diff --git a/Roslyn.sln b/Roslyn.sln
index 07332ef370408..c49637445381e 100644
--- a/Roslyn.sln
+++ b/Roslyn.sln
@@ -205,7 +205,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Expr
EndProject
Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.ResultProvider.UnitTests", "src\ExpressionEvaluator\VisualBasic\Test\ResultProvider\Microsoft.CodeAnalysis.VisualBasic.ResultProvider.UnitTests.vbproj", "{ACE53515-482C-4C6A-E2D2-4242A687DFEE}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.ExpressionCompiler.Utilities", "src\ExpressionEvaluator\Core\Test\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.Utilities.csproj", "{21B80A31-8FF9-4E3A-8403-AABD635AEED9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.ExpressionCompiler.Test.Utilities", "src\ExpressionEvaluator\Core\Test\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.Test.Utilities.csproj", "{21B80A31-8FF9-4E3A-8403-AABD635AEED9}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.ResultProvider.Utilities", "src\ExpressionEvaluator\Core\Test\ResultProvider\Microsoft.CodeAnalysis.ResultProvider.Utilities.csproj", "{ABDBAC1E-350E-4DC3-BB45-3504404545EE}"
EndProject
diff --git a/azure-pipelines-pr-validation.yml b/azure-pipelines-pr-validation.yml
index 2b8394f1b5d82..5399ec92521dc 100644
--- a/azure-pipelines-pr-validation.yml
+++ b/azure-pipelines-pr-validation.yml
@@ -33,8 +33,6 @@ variables:
value: false
- name: Codeql.SkipTaskAutoInjection
value: true
- - name: SignType
- value: ''
# To retrieve OptProf data we need to authenticate to the VS drop storage.
# If the pipeline is running in DevDiv, the account has access to the VS drop storage.
diff --git a/docs/Language Feature Status.md b/docs/Language Feature Status.md
index 014b3e5977d38..7061a36461d67 100644
--- a/docs/Language Feature Status.md
+++ b/docs/Language Feature Status.md
@@ -10,8 +10,8 @@ efforts behind them.
| Feature | Branch | State | Developer | Reviewer | IDE Buddy | LDM Champ |
| ------- | ------ | ----- | --------- | -------- | --------- | --------- |
+| [Partial Events and Constructors](https://github.com/dotnet/csharplang/issues/9058) | [features/PartialEventsCtors](https://github.com/dotnet/roslyn/tree/features/PartialEventsCtors) | [In Progress](https://github.com/dotnet/roslyn/issues/76859) | [jjonescz](https://github.com/jjonescz) | [cston](https://github.com/cston), [RikkiGibson](https://github.com/RikkiGibson) | | |
| Runtime Async | [features/runtime-async](https://github.com/dotnet/roslyn/tree/features/runtime-async) | [In Progress](https://github.com/dotnet/roslyn/issues/75960) | [333fred](https://github.com/333fred) | [jcouv](https://github.com/jcouv), [RikkiGibson](https://github.com/RikkiGibson) | | |
-| [Simple lambda parameters with modifiers](https://github.com/dotnet/csharplang/blob/main/proposals/simple-lambda-parameters-with-modifiers.md) | [PR](https://github.com/dotnet/roslyn/pull/75400) | [In Progress](https://github.com/dotnet/roslyn/issues/76298) | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) | [jjonescz](https://github.com/jjonescz), [cston](https://github.com/cston) | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) |
| [Null-conditional assignment](https://github.com/dotnet/csharplang/issues/6045) | [null-conditional-assignment](https://github.com/dotnet/roslyn/tree/features/null-conditional-assignment) | [In Progress](https://github.com/dotnet/roslyn/issues/75554) | [RikkiGibson](https://github.com/RikkiGibson) | [cston](https://github.com/cston), [jjonescz](https://github.com/jjonescz) | TBD | [RikkiGibson](https://github.com/RikkiGibson) |
| [Extensions](https://github.com/dotnet/csharplang/issues/8697) | [extensions](https://github.com/dotnet/roslyn/tree/features/extensions) | [In Progress](https://github.com/dotnet/roslyn/issues/76130) | [jcouv](https://github.com/jcouv), [AlekseyTs](https://github.com/AlekseyTs) | [jjonescz](https://github.com/jjonescz), TBD | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) | [MadsTorgersen](https://github.com/MadsTorgersen) |
| [Dictionary expressions](https://github.com/dotnet/csharplang/issues/8659) | [dictionary-expressions](https://github.com/dotnet/roslyn/tree/features/dictionary-expressions) | [In Progress](https://github.com/dotnet/roslyn/issues/76310) | [cston](https://github.com/cston), [CyrusNajmabadi](https://github.com/CyrusNajmabadi) | [333fred](https://github.com/333fred), [jcouv](https://github.com/jcouv) | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) |
@@ -19,6 +19,7 @@ efforts behind them.
| [First-class Span Types](https://github.com/dotnet/csharplang/issues/7905) | [FirstClassSpan](https://github.com/dotnet/roslyn/tree/features/FirstClassSpan) | [Merged into 17.13p1](https://github.com/dotnet/roslyn/issues/73445) | [jjonescz](https://github.com/jjonescz) | [cston](https://github.com/cston), [333fred](https://github.com/333fred) | | [333fred](https://github.com/333fred), [stephentoub](https://github.com/stephentoub) |
| [Unbound generic types in `nameof`](https://github.com/dotnet/csharplang/issues/8480) | [PR](https://github.com/dotnet/roslyn/pull/75368) | [Merged into 17.13p2](https://github.com/dotnet/roslyn/pull/75368) | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) | [jcouv](https://github.com/jcouv), [AlekseyTs](https://github.com/AlekseyTs) | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) |
| [String literals in data section as UTF8](https://github.com/dotnet/roslyn/blob/main/docs/features/string-literals-data-section.md) | [PR](https://github.com/dotnet/roslyn/pull/76036) | [Merged into 17.14p1](https://github.com/dotnet/roslyn/issues/76234) | [jjonescz](https://github.com/jjonescz) | [AlekseyTs](https://github.com/AlekseyTs), [cston](https://github.com/cston) | N/A | N/A |
+| [Simple lambda parameters with modifiers](https://github.com/dotnet/csharplang/blob/main/proposals/simple-lambda-parameters-with-modifiers.md) | [PR](https://github.com/dotnet/roslyn/pull/75400) | [Merged into 17.14p1](https://github.com/dotnet/roslyn/pull/75400) | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) | [jjonescz](https://github.com/jjonescz), [cston](https://github.com/cston) | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) |
# Working Set VB
diff --git a/eng/Signing.props b/eng/Signing.props
index 0bda27d7aa9f1..f1d94e766f317 100644
--- a/eng/Signing.props
+++ b/eng/Signing.props
@@ -61,19 +61,4 @@
-
-
-
-
-
-
-
-
-
- true
-
-
-
diff --git a/eng/config/PublishData.json b/eng/config/PublishData.json
index c53c5dc821844..3b859d2103fa7 100644
--- a/eng/config/PublishData.json
+++ b/eng/config/PublishData.json
@@ -281,6 +281,16 @@
"insertionTitlePrefix": "[Do not merge, please close me]",
"vsMajorVersion": 17,
"insertionCreateDraftPR": false
+ },
+ "features/vscode_net9": {
+ "nugetKind": [
+ "Shipping",
+ "NonShipping"
+ ],
+ "vsBranch": "main",
+ "insertionTitlePrefix": "[Do not merge, please close me]",
+ "vsMajorVersion": 17,
+ "insertionCreateDraftPR": true
}
}
}
diff --git a/eng/test-rebuild.ps1 b/eng/test-rebuild.ps1
index 68eeda7dfd6c9..ed0e3aa5c0273 100644
--- a/eng/test-rebuild.ps1
+++ b/eng/test-rebuild.ps1
@@ -67,7 +67,8 @@ try {
# Semantic Search reference assemblies can't be reconstructed from source.
# The assemblies are not marked with ReferenceAssemblyAttribute attribute.
- " --exclude net9.0\GeneratedRefAssemblies\Microsoft.CodeAnalysis.dll" +
+ " --exclude net8.0\GeneratedRefAssemblies\Microsoft.CodeAnalysis.dll" +
+ " --exclude net8.0\GeneratedRefAssemblies\Microsoft.CodeAnalysis.CSharp.dll" +
" --debugPath `"$ArtifactsDir/BuildValidator`"" +
" --sourcePath `"$RepoRoot/`"" +
diff --git a/src/Analyzers/CSharp/Analyzers/ConvertTypeofToNameof/CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/ConvertTypeofToNameof/CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.cs
index 59a110ab2350b..8beb2a5c885fb 100644
--- a/src/Analyzers/CSharp/Analyzers/ConvertTypeofToNameof/CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/ConvertTypeofToNameof/CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.cs
@@ -19,9 +19,6 @@ internal sealed class CSharpConvertTypeOfToNameOfDiagnosticAnalyzer()
{
private static readonly string s_title = CSharpAnalyzersResources.typeof_can_be_converted_to_nameof;
- protected override bool SupportsUnboundGenerics(ParseOptions options)
- => options.LanguageVersion().IsCSharp14OrAbove();
-
protected override bool IsValidTypeofAction(OperationAnalysisContext context)
{
var node = context.Operation.Syntax;
diff --git a/src/Analyzers/CSharp/Analyzers/UseAutoProperty/CSharpUseAutoPropertyAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseAutoProperty/CSharpUseAutoPropertyAnalyzer.cs
index f233637622a7f..ea3ff1d9974e4 100644
--- a/src/Analyzers/CSharp/Analyzers/UseAutoProperty/CSharpUseAutoPropertyAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseAutoProperty/CSharpUseAutoPropertyAnalyzer.cs
@@ -8,6 +8,7 @@
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
+using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Shared.Extensions;
@@ -41,23 +42,9 @@ protected override bool SupportsReadOnlyProperties(Compilation compilation)
protected override bool SupportsPropertyInitializer(Compilation compilation)
=> compilation.LanguageVersion() >= LanguageVersion.CSharp6;
- protected override bool SupportsFieldExpression(Compilation compilation)
- => compilation.LanguageVersion() >= LanguageVersion.Preview;
-
protected override ExpressionSyntax? GetFieldInitializer(VariableDeclaratorSyntax variable, CancellationToken cancellationToken)
=> variable.Initializer?.Value;
- protected override bool ContainsFieldExpression(PropertyDeclarationSyntax propertyDeclaration, CancellationToken cancellationToken)
- {
- foreach (var node in propertyDeclaration.DescendantNodes())
- {
- if (node.IsKind(SyntaxKind.FieldExpression))
- return true;
- }
-
- return false;
- }
-
protected override void RecordIneligibleFieldLocations(
HashSet fieldNames,
ConcurrentDictionary> ineligibleFieldUsageIfOutsideProperty,
diff --git a/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfTests.cs b/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfTests.cs
index 0c357404fdc9b..73bb70b099749 100644
--- a/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfTests.cs
+++ b/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfTests.cs
@@ -267,19 +267,7 @@ class Goo
{
void M()
{
- _ = [|typeof(Goo).Name|];
- }
- }
- }
- """,
- FixedCode = """
- class Test
- {
- class Goo
- {
- void M()
- {
- _ = nameof(Goo<>);
+ _ = typeof(Goo).Name;
}
}
}
@@ -321,19 +309,7 @@ class Goo
{
void M()
{
- _ = [|typeof(Goo<>).Name|];
- }
- }
- }
- """,
- FixedCode = """
- class Test
- {
- class Goo
- {
- void M()
- {
- _ = nameof(Goo<>);
+ _ = typeof(Goo<>).Name;
}
}
}
diff --git a/src/Analyzers/CSharp/Tests/ImplementInterface/ImplementInterfaceTests.cs b/src/Analyzers/CSharp/Tests/ImplementInterface/ImplementInterfaceTests.cs
index 4978cd0cbb9d0..1263931a130ca 100644
--- a/src/Analyzers/CSharp/Tests/ImplementInterface/ImplementInterfaceTests.cs
+++ b/src/Analyzers/CSharp/Tests/ImplementInterface/ImplementInterfaceTests.cs
@@ -7626,7 +7626,7 @@ public void M1()
[Fact, WorkItem("http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994328")]
public async Task TestDisposePatternWhenAdditionalUsingsAreIntroduced1()
{
-#if NET9_0_OR_GREATER
+#if NET
var extraUsing = """
using System.Diagnostics.CodeAnalysis;
diff --git a/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests_Field.cs b/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests_Field.cs
index 660f93366a5e9..24d1b83ee50e0 100644
--- a/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests_Field.cs
+++ b/src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests_Field.cs
@@ -4,6 +4,7 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
@@ -14,7 +15,7 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseAutoProperty;
public sealed partial class UseAutoPropertyTests
{
private static readonly ParseOptions CSharp13 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp13);
- private static readonly ParseOptions CSharp14 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview);
+ private static readonly ParseOptions CSharp14 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersionExtensions.CSharpNext);
[Fact]
public async Task TestNotInCSharp13()
@@ -1601,4 +1602,111 @@ void M()
}
""", new TestParameters(parseOptions: CSharp14));
}
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76901")]
+ public async Task TestReadAndWrite()
+ {
+ await TestInRegularAndScript1Async(
+ """
+ class C
+ {
+ private int [|_g|];
+
+ public int CustomGetter
+ {
+ get => _g < 0 ? 0 : _g; // Synthesized return value
+ set => _g = value;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ public int CustomGetter
+ {
+ get => field < 0 ? 0 : field; // Synthesized return value
+ set;
+ }
+ }
+ """, new TestParameters(parseOptions: CSharp14));
+ }
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76901")]
+ public async Task TestContractCall()
+ {
+ await TestInRegularAndScript1Async(
+ """
+ class C
+ {
+ private int [|_s|];
+
+ public int CustomSetter
+ {
+ get => _s;
+ set
+ {
+ Assumes.True(value >= 0); // Validation
+ _s = value;
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ public int CustomSetter
+ {
+ get;
+ set
+ {
+ Assumes.True(value >= 0); // Validation
+ field = value;
+ }
+ }
+ }
+ """, new TestParameters(parseOptions: CSharp14));
+ }
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76901")]
+ public async Task TestDelegateInvoke()
+ {
+ await TestInRegularAndScript1Async(
+ """
+ using System;
+
+ class C
+ {
+ private int [|_s|];
+ public event Action OnChanged;
+
+ public int ObservableProp
+ {
+ get => _s;
+ set
+ {
+ _s = value;
+ OnChanged.Invoke(nameof(ObservableProp));
+ }
+ }
+ }
+ """,
+ """
+ using System;
+
+ class C
+ {
+ public event Action OnChanged;
+
+ public int ObservableProp
+ {
+ get;
+ set
+ {
+ field = value;
+ OnChanged.Invoke(nameof(ObservableProp));
+ }
+ }
+ }
+ """, new TestParameters(parseOptions: CSharp14));
+ }
}
diff --git a/src/Analyzers/CSharp/Tests/UseImplicitlyTypedLambdaExpression/UseImplicitlyTypedLambdaExpressionTests.cs b/src/Analyzers/CSharp/Tests/UseImplicitlyTypedLambdaExpression/UseImplicitlyTypedLambdaExpressionTests.cs
index 437372cd52917..ea122efc4460d 100644
--- a/src/Analyzers/CSharp/Tests/UseImplicitlyTypedLambdaExpression/UseImplicitlyTypedLambdaExpressionTests.cs
+++ b/src/Analyzers/CSharp/Tests/UseImplicitlyTypedLambdaExpression/UseImplicitlyTypedLambdaExpressionTests.cs
@@ -4,6 +4,7 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.UseImplicitlyTypedLambdaExpression;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
@@ -18,7 +19,7 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseImplicitlyTypedLambd
[Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitObjectCreation)]
public sealed class UseImplicitlyTypedLambdaExpressionTests
{
- private static readonly LanguageVersion CSharp14 = LanguageVersion.Preview;
+ private static readonly LanguageVersion CSharp14 = LanguageVersionExtensions.CSharpNext;
[Fact]
public async Task TestAssignedToObject()
diff --git a/src/Analyzers/Core/Analyzers/ConvertTypeofToNameof/AbstractConvertTypeOfToNameOfDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/ConvertTypeofToNameof/AbstractConvertTypeOfToNameOfDiagnosticAnalyzer.cs
index 3e7664ae6bbdf..8db15069ba679 100644
--- a/src/Analyzers/Core/Analyzers/ConvertTypeofToNameof/AbstractConvertTypeOfToNameOfDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/ConvertTypeofToNameof/AbstractConvertTypeOfToNameOfDiagnosticAnalyzer.cs
@@ -20,12 +20,8 @@ public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
protected abstract bool IsValidTypeofAction(OperationAnalysisContext context);
- protected abstract bool SupportsUnboundGenerics(ParseOptions options);
-
protected override void InitializeWorker(AnalysisContext context)
- {
- context.RegisterOperationAction(AnalyzeAction, OperationKind.TypeOf);
- }
+ => context.RegisterOperationAction(AnalyzeAction, OperationKind.TypeOf);
protected void AnalyzeAction(OperationAnalysisContext context)
{
@@ -47,7 +43,7 @@ protected void AnalyzeAction(OperationAnalysisContext context)
}
- private bool IsValidOperation(IOperation operation)
+ private static bool IsValidOperation(IOperation operation)
{
// Cast to a typeof operation & check parent is a property reference and member access
var typeofOperation = (ITypeOfOperation)operation;
@@ -69,11 +65,10 @@ private bool IsValidOperation(IOperation operation)
if (typeofOperation.TypeOperand is not INamedTypeSymbol namedType)
return false;
- // Non-generic types are always convertible. typeof(X).Name can always be converted to nameof(X)
- if (namedType.TypeArguments.Length == 0)
- return true;
-
- // Generic types are convertible if the lang supports it. e.g. typeof(X).Name can be converted to nameof(X<>).
- return SupportsUnboundGenerics(operation.Syntax.SyntaxTree.Options);
+ // Note: generic names like `typeof(List)` are not convertible (since the name will be List`1). However,
+ // it's fine if an outer part of the name is generic (like `typeof(List.Enumerator)`). as that will be
+ // convertible to `nameof(List<>.Enumerator)`. So we only need to check the type arguments directly on the type
+ // here, not on any containing types.
+ return namedType.TypeArguments.Length == 0;
}
}
diff --git a/src/Analyzers/Core/Analyzers/UseAutoProperty/AbstractUseAutoPropertyAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseAutoProperty/AbstractUseAutoPropertyAnalyzer.cs
index 50584ae2493dc..ac98e5754cbaf 100644
--- a/src/Analyzers/Core/Analyzers/UseAutoProperty/AbstractUseAutoPropertyAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseAutoProperty/AbstractUseAutoPropertyAnalyzer.cs
@@ -82,9 +82,6 @@ public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
protected abstract bool SupportsReadOnlyProperties(Compilation compilation);
protected abstract bool SupportsPropertyInitializer(Compilation compilation);
- protected abstract bool SupportsFieldExpression(Compilation compilation);
-
- protected abstract bool ContainsFieldExpression(TPropertyDeclaration propertyDeclaration, CancellationToken cancellationToken);
protected abstract TExpression? GetFieldInitializer(TVariableDeclarator variable, CancellationToken cancellationToken);
protected abstract TExpression? GetGetterExpression(IMethodSymbol getMethod, CancellationToken cancellationToken);
@@ -265,7 +262,7 @@ private AccessedFields GetGetterFields(
if (trivialFieldExpression != null)
return new(CheckFieldAccessExpression(semanticModel, trivialFieldExpression, fieldNames, cancellationToken));
- if (!this.SupportsFieldExpression(semanticModel.Compilation))
+ if (!this.SyntaxFacts.SupportsFieldExpression(semanticModel.SyntaxTree.Options))
return AccessedFields.Empty;
using var _ = PooledHashSet.GetInstance(out var set);
@@ -281,7 +278,7 @@ private AccessedFields GetSetterFields(
if (trivialFieldExpression != null)
return new(CheckFieldAccessExpression(semanticModel, trivialFieldExpression, fieldNames, cancellationToken));
- if (!this.SupportsFieldExpression(semanticModel.Compilation))
+ if (!this.SyntaxFacts.SupportsFieldExpression(semanticModel.SyntaxTree.Options))
return AccessedFields.Empty;
using var _ = PooledHashSet.GetInstance(out var set);
@@ -381,8 +378,11 @@ private void AnalyzePropertyDeclaration(
return;
// If the property already contains a `field` expression, then we can't do anything more here.
- if (SupportsFieldExpression(compilation) && ContainsFieldExpression(propertyDeclaration, cancellationToken))
+ if (this.SyntaxFacts.SupportsFieldExpression(propertyDeclaration.SyntaxTree.Options) &&
+ propertyDeclaration.DescendantNodes().Any(this.SyntaxFacts.IsFieldExpression))
+ {
return;
+ }
var getterFields = GetGetterFields(semanticModel, property.GetMethod, fieldNames, cancellationToken);
getterFields = getterFields.Where(
@@ -550,7 +550,7 @@ private void Process(
// All the usages were inside the property. This is ok if we support the `field` keyword as those
// usages will be updated to that form.
- if (!this.SupportsFieldExpression(context.Compilation))
+ if (!this.SyntaxFacts.SupportsFieldExpression(result.PropertyDeclaration.SyntaxTree.Options))
continue;
}
diff --git a/src/Analyzers/VisualBasic/Analyzers/ConvertTypeofToNameof/VisualBasicConvertTypeOfToNameOfDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/ConvertTypeofToNameof/VisualBasicConvertTypeOfToNameOfDiagnosticAnalyzer.vb
index 3f2a092381028..03d6de10849ac 100644
--- a/src/Analyzers/VisualBasic/Analyzers/ConvertTypeofToNameof/VisualBasicConvertTypeOfToNameOfDiagnosticAnalyzer.vb
+++ b/src/Analyzers/VisualBasic/Analyzers/ConvertTypeofToNameof/VisualBasicConvertTypeOfToNameOfDiagnosticAnalyzer.vb
@@ -18,10 +18,6 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertTypeOfToNameOf
MyBase.New(s_title)
End Sub
- Protected Overrides Function SupportsUnboundGenerics(options As ParseOptions) As Boolean
- Return False
- End Function
-
Protected Overrides Function IsValidTypeofAction(context As OperationAnalysisContext) As Boolean
Dim node = context.Operation.Syntax
Dim compilation = context.Compilation
diff --git a/src/Analyzers/VisualBasic/Analyzers/UseAutoProperty/VisualBasicUseAutoPropertyAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/UseAutoProperty/VisualBasicUseAutoPropertyAnalyzer.vb
index a11a47261b69b..ce00c2434f568 100644
--- a/src/Analyzers/VisualBasic/Analyzers/UseAutoProperty/VisualBasicUseAutoPropertyAnalyzer.vb
+++ b/src/Analyzers/VisualBasic/Analyzers/UseAutoProperty/VisualBasicUseAutoPropertyAnalyzer.vb
@@ -34,18 +34,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UseAutoProperty
Return DirectCast(compilation, VisualBasicCompilation).LanguageVersion >= LanguageVersion.VisualBasic10
End Function
- Protected Overrides Function SupportsFieldExpression(compilation As Compilation) As Boolean
- ' 'field' keyword not supported in VB.
- Return False
- End Function
-
Protected Overrides ReadOnly Property CanExplicitInterfaceImplementationsBeFixed As Boolean = True
Protected Overrides ReadOnly Property SupportsFieldAttributesOnProperties As Boolean = False
- Protected Overrides Function ContainsFieldExpression(propertyDeclaration As PropertyBlockSyntax, cancellationToken As CancellationToken) As Boolean
- Return False
- End Function
-
Protected Overrides Sub RecordIneligibleFieldLocations(
fieldNames As HashSet(Of String),
ineligibleFieldUsageIfOutsideProperty As ConcurrentDictionary(Of IFieldSymbol, ConcurrentSet(Of SyntaxNode)),
diff --git a/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/UserDefinedExplicitConversions.cs b/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/UserDefinedExplicitConversions.cs
index caa4fa8c59f79..32db5df21b27e 100644
--- a/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/UserDefinedExplicitConversions.cs
+++ b/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/UserDefinedExplicitConversions.cs
@@ -222,29 +222,28 @@ private void AddUserDefinedConversionsToExplicitCandidateSet(
isExplicit ? (isChecked ? WellKnownMemberNames.CheckedExplicitConversionName : WellKnownMemberNames.ExplicitConversionName) : WellKnownMemberNames.ImplicitConversionName,
operators);
- var candidates = ArrayBuilder.GetInstance(operators.Count);
- candidates.AddRange(operators);
-
if (isExplicit && isChecked)
{
- var operators2 = ArrayBuilder.GetInstance();
- declaringType.AddOperators(WellKnownMemberNames.ExplicitConversionName, operators2);
-
// Add regular operators as well.
if (operators.IsEmpty)
{
- candidates.AddRange(operators2);
+ declaringType.AddOperators(WellKnownMemberNames.ExplicitConversionName, operators);
}
else
{
+ var originalOperatorCount = operators.Count;
+
+ var operators2 = ArrayBuilder.GetInstance();
+ declaringType.AddOperators(WellKnownMemberNames.ExplicitConversionName, operators2);
+
foreach (MethodSymbol op2 in operators2)
{
// Drop operators that have a match among the checked ones.
bool add = true;
- foreach (MethodSymbol op in operators)
+ for (var i = 0; i < originalOperatorCount; i++)
{
- if (SourceMemberContainerTypeSymbol.DoOperatorsPair(op, op2))
+ if (SourceMemberContainerTypeSymbol.DoOperatorsPair(operators[i], op2))
{
add = false;
break;
@@ -253,15 +252,15 @@ private void AddUserDefinedConversionsToExplicitCandidateSet(
if (add)
{
- candidates.Add(op2);
+ operators.Add(op2);
}
}
- }
- operators2.Free();
+ operators2.Free();
+ }
}
- foreach (MethodSymbol op in candidates)
+ foreach (MethodSymbol op in operators)
{
// We might have a bad operator and be in an error recovery situation. Ignore it.
if (op.ReturnsVoid || op.ParameterCount != 1 || op.ReturnType.TypeKind == TypeKind.Error)
@@ -365,7 +364,6 @@ private void AddUserDefinedConversionsToExplicitCandidateSet(
}
operators.Free();
- candidates.Free();
}
private TypeSymbol MostSpecificSourceTypeForExplicitUserDefinedConversion(
diff --git a/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/PEDeltaAssemblyBuilder.cs b/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/PEDeltaAssemblyBuilder.cs
index 636dd4a119a61..c565c056a507c 100644
--- a/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/PEDeltaAssemblyBuilder.cs
+++ b/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/PEDeltaAssemblyBuilder.cs
@@ -112,7 +112,7 @@ internal static EmitBaseline.MetadataSymbols GetOrCreateMetadataSymbols(EmitBase
internal static SynthesizedTypeMaps GetSynthesizedTypesFromMetadata(MetadataReader reader, MetadataDecoder metadataDecoder)
{
var anonymousTypes = ImmutableSegmentedDictionary.CreateBuilder();
- var anonymousDelegatesWithIndexedNames = new Dictionary>();
+ var anonymousDelegatesWithIndexedNames = PooledDictionary>.GetInstance();
var anonymousDelegates = ImmutableSegmentedDictionary.CreateBuilder();
foreach (var handle in reader.TypeDefinitions)
diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs
index bb3ec749a0ffc..abb58e2d51de5 100644
--- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs
+++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs
@@ -1695,6 +1695,11 @@ internal void AssertMemberExposure(Symbol member, bool forDiagnostics = false)
// Backing fields for field-like events are not added to the members list.
member = e;
}
+ else if (member is FieldSymbol { AssociatedSymbol: SourcePropertySymbolBase { PartialDefinitionPart: PropertySymbol definition } implementation } &&
+ definition.PartialImplementationPart == (object)implementation && implementation.BackingField != (object)member)
+ {
+ member = implementation; // This is a workaround for https://github.com/dotnet/roslyn/issues/76870, remove once the issue is addressed.
+ }
var membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers);
@@ -1716,7 +1721,7 @@ internal void AssertMemberExposure(Symbol member, bool forDiagnostics = false)
if (declared is object)
{
- if (declared.NonTypeMembers.Contains(m => m == (object)member) || declared.PrimaryConstructor == (object)member)
+ if (declared.NonTypeMembersWithPartialImplementations.Contains(m => m == (object)member) || declared.PrimaryConstructor == (object)member)
{
return;
}
@@ -1738,6 +1743,16 @@ internal void AssertMemberExposure(Symbol member, bool forDiagnostics = false)
static bool isMemberInCompleteMemberList(MembersAndInitializers? membersAndInitializers, Symbol member)
{
+ switch (member)
+ {
+ case MethodSymbol method:
+ member = method.PartialDefinitionPart ?? method;
+ break;
+ case PropertySymbol property:
+ member = property.PartialDefinitionPart ?? property;
+ break;
+ }
+
return membersAndInitializers?.NonTypeMembers.Contains(m => m == (object)member) == true;
}
}
@@ -1756,16 +1771,12 @@ private Dictionary, ImmutableArray> GetMembersByNam
{
if (_lazyMembersDictionary == null)
{
- var diagnostics = BindingDiagnosticBag.GetInstance();
- var membersDictionary = MakeAllMembers(diagnostics);
+ var membersDictionary = MakeAllMembers();
if (Interlocked.CompareExchange(ref _lazyMembersDictionary, membersDictionary, null) == null)
{
- AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.Members);
}
-
- diagnostics.Free();
}
state.SpinWaitComplete(CompletionPart.Members, default(CancellationToken));
@@ -2840,7 +2851,7 @@ private static bool ContainsModifier(SyntaxTokenList modifiers, SyntaxKind modif
return false;
}
- private Dictionary, ImmutableArray> MakeAllMembers(BindingDiagnosticBag diagnostics)
+ private Dictionary, ImmutableArray> MakeAllMembers()
{
Dictionary, ImmutableArray> membersByName;
var membersAndInitializers = GetMembersAndInitializers();
@@ -2860,8 +2871,6 @@ private Dictionary, ImmutableArray> MakeAllMembers(
AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary());
}
- MergePartialMembers(ref membersByName, diagnostics);
-
return membersByName;
}
@@ -2887,7 +2896,7 @@ private static void AddNestedTypesToDictionary(
private sealed class DeclaredMembersAndInitializersBuilder
{
- public ArrayBuilder NonTypeMembers = ArrayBuilder.GetInstance();
+ public ArrayBuilder NonTypeMembersWithPartialImplementations = ArrayBuilder.GetInstance();
public readonly ArrayBuilder> StaticInitializers = ArrayBuilder>.GetInstance();
public readonly ArrayBuilder> InstanceInitializers = ArrayBuilder>.GetInstance();
public bool HaveIndexers;
@@ -2900,7 +2909,7 @@ private sealed class DeclaredMembersAndInitializersBuilder
public DeclaredMembersAndInitializers ToReadOnlyAndFree(CSharpCompilation compilation)
{
return new DeclaredMembersAndInitializers(
- NonTypeMembers.ToImmutableAndFree(),
+ NonTypeMembersWithPartialImplementations.ToImmutableAndFree(),
MembersAndInitializersBuilder.ToReadOnlyAndFree(StaticInitializers),
MembersAndInitializersBuilder.ToReadOnlyAndFree(InstanceInitializers),
HaveIndexers,
@@ -2930,7 +2939,7 @@ private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic)
public void Free()
{
- NonTypeMembers.Free();
+ NonTypeMembersWithPartialImplementations.Free();
foreach (var group in StaticInitializers)
{
@@ -2948,7 +2957,7 @@ public void Free()
protected sealed class DeclaredMembersAndInitializers
{
- public readonly ImmutableArray NonTypeMembers;
+ public readonly ImmutableArray NonTypeMembersWithPartialImplementations;
public readonly ImmutableArray> StaticInitializers;
public readonly ImmutableArray> InstanceInitializers;
public readonly bool HaveIndexers;
@@ -2957,6 +2966,8 @@ protected sealed class DeclaredMembersAndInitializers
public readonly bool IsNullableEnabledForInstanceConstructorsAndFields;
public readonly bool IsNullableEnabledForStaticConstructorsAndFields;
+ private ImmutableArray _lazyNonTypeMembers;
+
public static readonly DeclaredMembersAndInitializers UninitializedSentinel = new DeclaredMembersAndInitializers();
private DeclaredMembersAndInitializers()
@@ -2964,7 +2975,7 @@ private DeclaredMembersAndInitializers()
}
public DeclaredMembersAndInitializers(
- ImmutableArray nonTypeMembers,
+ ImmutableArray nonTypeMembersWithPartialImplementations,
ImmutableArray> staticInitializers,
ImmutableArray> instanceInitializers,
bool haveIndexers,
@@ -2974,14 +2985,14 @@ public DeclaredMembersAndInitializers(
bool isNullableEnabledForStaticConstructorsAndFields,
CSharpCompilation compilation)
{
- Debug.Assert(!nonTypeMembers.IsDefault);
+ Debug.Assert(!nonTypeMembersWithPartialImplementations.IsDefault);
AssertInitializers(staticInitializers, compilation);
AssertInitializers(instanceInitializers, compilation);
- Debug.Assert(!nonTypeMembers.Any(static s => s is TypeSymbol));
+ Debug.Assert(!nonTypeMembersWithPartialImplementations.Any(static s => s is TypeSymbol));
Debug.Assert(declarationWithParameters is object == primaryConstructor is object);
- this.NonTypeMembers = nonTypeMembers;
+ this.NonTypeMembersWithPartialImplementations = nonTypeMembersWithPartialImplementations;
this.StaticInitializers = staticInitializers;
this.InstanceInitializers = instanceInitializers;
this.HaveIndexers = haveIndexers;
@@ -3023,6 +3034,16 @@ public static void AssertInitializers(ImmutableArray GetNonTypeMembers(SourceMemberContainerTypeSymbol container)
+ {
+ if (_lazyNonTypeMembers.IsDefault)
+ {
+ container.MergePartialMembersAndInitializeNonTypeMembers(NonTypeMembersWithPartialImplementations, ref _lazyNonTypeMembers);
+ }
+
+ return _lazyNonTypeMembers;
+ }
}
private sealed class MembersAndInitializersBuilder
@@ -3040,9 +3061,9 @@ public MembersAndInitializersBuilder(DeclaredMembersAndInitializers declaredMemb
this.IsNullableEnabledForStaticConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields;
}
- public MembersAndInitializers ToReadOnlyAndFree(DeclaredMembersAndInitializers declaredMembers)
+ public MembersAndInitializers ToReadOnlyAndFree(SourceMemberContainerTypeSymbol container, DeclaredMembersAndInitializers declaredMembers)
{
- var nonTypeMembers = NonTypeMembers?.ToImmutableAndFree() ?? declaredMembers.NonTypeMembers;
+ var nonTypeMembers = NonTypeMembers?.ToImmutableAndFree() ?? declaredMembers.GetNonTypeMembers(container);
var instanceInitializers = InstanceInitializersForPositionalMembers is null
? declaredMembers.InstanceInitializers
@@ -3136,17 +3157,18 @@ public void AddInstanceInitializerForPositionalMembers(FieldOrPropertyInitialize
InstanceInitializersForPositionalMembers.Add(initializer);
}
- public IReadOnlyCollection GetNonTypeMembers(DeclaredMembersAndInitializers declaredMembers)
+ public IReadOnlyCollection GetNonTypeMembers(SourceMemberContainerTypeSymbol container, DeclaredMembersAndInitializers declaredMembers)
{
- return NonTypeMembers ?? (IReadOnlyCollection)declaredMembers.NonTypeMembers;
+ return NonTypeMembers ?? (IReadOnlyCollection)declaredMembers.GetNonTypeMembers(container);
}
- public void AddNonTypeMember(Symbol member, DeclaredMembersAndInitializers declaredMembers)
+ public void AddNonTypeMember(SourceMemberContainerTypeSymbol container, Symbol member, DeclaredMembersAndInitializers declaredMembers)
{
if (NonTypeMembers is null)
{
- NonTypeMembers = ArrayBuilder.GetInstance(declaredMembers.NonTypeMembers.Length + 1);
- NonTypeMembers.AddRange(declaredMembers.NonTypeMembers);
+ var declaredNonTypeMembers = declaredMembers.GetNonTypeMembers(container);
+ NonTypeMembers = ArrayBuilder.GetInstance(declaredNonTypeMembers.Length + 1);
+ NonTypeMembers.AddRange(declaredNonTypeMembers);
}
NonTypeMembers.Add(member);
@@ -3213,7 +3235,7 @@ public void Free()
return null;
}
- return membersAndInitializersBuilder.ToReadOnlyAndFree(declaredMembersAndInitializers);
+ return membersAndInitializersBuilder.ToReadOnlyAndFree(this, declaredMembersAndInitializers);
DeclaredMembersAndInitializers? getDeclaredMembersAndInitializers()
{
@@ -3259,11 +3281,11 @@ public void Free()
{
case TypeKind.Struct:
CheckForStructBadInitializers(builder, diagnostics);
- CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: false, diagnostics: diagnostics);
+ CheckForStructDefaultConstructors(builder.NonTypeMembersWithPartialImplementations, isEnum: false, diagnostics: diagnostics);
break;
case TypeKind.Enum:
- CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: true, diagnostics: diagnostics);
+ CheckForStructDefaultConstructors(builder.NonTypeMembersWithPartialImplementations, isEnum: true, diagnostics: diagnostics);
break;
case TypeKind.Class:
@@ -3287,6 +3309,43 @@ public void Free()
}
}
+ private void MergePartialMembersAndInitializeNonTypeMembers(ImmutableArray nonTypeMembersWithPartialImplementations, ref ImmutableArray nonTypeMembers)
+ {
+ PooledDictionary, object>? partialMembersToMerge = null;
+
+ foreach (Symbol member in nonTypeMembersWithPartialImplementations)
+ {
+ if (member.IsPartialMember())
+ {
+ ImmutableArrayExtensions.AddToMultiValueDictionaryBuilder(
+ partialMembersToMerge ??= s_nameToObjectPool.Allocate(),
+ (member.IsIndexer() ? WellKnownMemberNames.Indexer : member.Name).AsMemory(),
+ member);
+ }
+ }
+
+ if (partialMembersToMerge is null)
+ {
+ ImmutableInterlocked.InterlockedInitialize(ref nonTypeMembers, nonTypeMembersWithPartialImplementations);
+ return;
+ }
+
+ Debug.Assert(partialMembersToMerge.Count != 0);
+
+ var diagnostics = BindingDiagnosticBag.GetInstance();
+ var nonTypeMembersBuilder = ArrayBuilder.GetInstance(nonTypeMembersWithPartialImplementations.Length);
+ nonTypeMembersBuilder.AddRange(nonTypeMembersWithPartialImplementations);
+ MergePartialMembers(partialMembersToMerge, nonTypeMembersBuilder, diagnostics);
+ partialMembersToMerge.Free();
+
+ if (ImmutableInterlocked.InterlockedInitialize(ref nonTypeMembers, nonTypeMembersBuilder.ToImmutableAndFree()))
+ {
+ AddDeclarationDiagnostics(diagnostics);
+ }
+
+ diagnostics.Free();
+ }
+
internal ImmutableArray GetSimpleProgramEntryPoints()
{
@@ -3375,7 +3434,7 @@ internal IEnumerable GetMethodsPossiblyCapturingPrimar
var declared = Volatile.Read(ref _lazyDeclaredMembersAndInitializers);
if (declared is not null && declared != DeclaredMembersAndInitializers.UninitializedSentinel)
{
- nonTypeMembersToCheck = declared.NonTypeMembers;
+ nonTypeMembersToCheck = declared.GetNonTypeMembers(this);
primaryConstructor = declared.PrimaryConstructor;
}
else
@@ -3421,7 +3480,7 @@ internal ImmutableArray GetMembersToMatchAgainstDeclarationSpan()
if (declared is not null && declared != DeclaredMembersAndInitializers.UninitializedSentinel)
{
Debug.Assert(declared.PrimaryConstructor is not null);
- return declared.NonTypeMembers;
+ return declared.GetNonTypeMembers(this);
}
else
{
@@ -3445,7 +3504,7 @@ internal ImmutableArray GetCandidateMembersForLookup(string name)
var declared = Volatile.Read(ref _lazyDeclaredMembersAndInitializers);
if (declared is not null && declared != DeclaredMembersAndInitializers.UninitializedSentinel)
{
- nonTypeMembersToCheck = declared.NonTypeMembers;
+ nonTypeMembersToCheck = declared.GetNonTypeMembers(this);
primaryConstructor = declared.PrimaryConstructor;
}
else
@@ -3537,7 +3596,7 @@ private void AddDeclaredNontypeMembers(DeclaredMembersAndInitializersBuilder bui
break;
case SyntaxKind.DelegateDeclaration:
- SourceDelegateMethodSymbol.AddDelegateMembers(this, builder.NonTypeMembers, (DelegateDeclarationSyntax)syntax, diagnostics);
+ SourceDelegateMethodSymbol.AddDelegateMembers(this, builder.NonTypeMembersWithPartialImplementations, (DelegateDeclarationSyntax)syntax, diagnostics);
break;
case SyntaxKind.NamespaceDeclaration:
@@ -3608,53 +3667,58 @@ internal Binder GetBinder(CSharpSyntaxNode syntaxNode)
return this.DeclaringCompilation.GetBinder(syntaxNode);
}
- private void MergePartialMembers(
- ref Dictionary, ImmutableArray> membersByName,
+ private static void MergePartialMembers(
+ Dictionary, object> membersByName,
+ ArrayBuilder nonTypeMembers,
BindingDiagnosticBag diagnostics)
{
- var memberNames = ArrayBuilder>.GetInstance(membersByName.Count);
- memberNames.AddRange(membersByName.Keys);
-
//key and value will be the same object
var membersBySignature = new Dictionary(MemberSignatureComparer.PartialMethodsComparer);
- foreach (var name in memberNames)
+ foreach (var pair in membersByName)
{
membersBySignature.Clear();
- foreach (var symbol in membersByName[name])
- {
- if (!symbol.IsPartialMember())
- {
- continue;
- }
-
- if (!membersBySignature.TryGetValue(symbol, out var prev))
- {
- membersBySignature.Add(symbol, symbol);
- continue;
- }
- switch (symbol, prev)
+ if (pair.Value is ArrayBuilder arrayBuilder)
+ {
+ foreach (var symbol in arrayBuilder)
{
- case (SourceOrdinaryMethodSymbol currentMethod, SourceOrdinaryMethodSymbol prevMethod):
- mergePartialMethods(ref membersByName, name, currentMethod, prevMethod, diagnostics);
- break;
-
- case (SourcePropertySymbol currentProperty, SourcePropertySymbol prevProperty):
- mergePartialProperties(ref membersByName, name, currentProperty, prevProperty, diagnostics);
- break;
+ Debug.Assert(symbol.IsPartialMember());
- case (SourcePropertyAccessorSymbol, SourcePropertyAccessorSymbol):
- break; // accessor symbols and their diagnostics are handled by processing the associated property
+ if (!membersBySignature.TryGetValue(symbol, out var prev))
+ {
+ membersBySignature.Add(symbol, symbol);
+ continue;
+ }
- default:
- // This is an error scenario. We simply don't merge the symbols in this case and a duplicate name diagnostic is reported separately.
- // One way this case can be reached is if type contains both `public partial int P { get; }` and `public partial int P_get();`.
- Debug.Assert(symbol is SourceOrdinaryMethodSymbol or SourcePropertySymbol or SourcePropertyAccessorSymbol);
- Debug.Assert(prev is SourceOrdinaryMethodSymbol or SourcePropertySymbol or SourcePropertyAccessorSymbol);
- break;
+ switch (symbol, prev)
+ {
+ case (SourceOrdinaryMethodSymbol currentMethod, SourceOrdinaryMethodSymbol prevMethod):
+ mergePartialMethods(nonTypeMembers, currentMethod, prevMethod, diagnostics);
+ break;
+
+ case (SourcePropertySymbol currentProperty, SourcePropertySymbol prevProperty):
+ mergePartialProperties(nonTypeMembers, currentProperty, prevProperty, diagnostics);
+ break;
+
+ case (SourcePropertyAccessorSymbol, SourcePropertyAccessorSymbol):
+ break; // accessor symbols and their diagnostics are handled by processing the associated property
+
+ default:
+ // This is an error scenario. We simply don't merge the symbols in this case and a duplicate name diagnostic is reported separately.
+ // One way this case can be reached is if type contains both `public partial int P { get; }` and `public partial int P_get();`.
+ Debug.Assert(symbol is SourceOrdinaryMethodSymbol or SourcePropertySymbol or SourcePropertyAccessorSymbol);
+ Debug.Assert(prev is SourceOrdinaryMethodSymbol or SourcePropertySymbol or SourcePropertyAccessorSymbol);
+ break;
+ }
}
}
+ else
+ {
+ var symbol = (Symbol)pair.Value;
+ Debug.Assert(symbol.IsPartialMember());
+ membersBySignature.Add(symbol, symbol);
+ }
foreach (var symbol in membersBySignature.Values)
{
@@ -3691,9 +3755,31 @@ private void MergePartialMembers(
}
}
- memberNames.Free();
+ foreach (var pair in membersByName)
+ {
+ if (pair.Value is ArrayBuilder arrayBuilder)
+ {
+ foreach (var symbol in arrayBuilder)
+ {
+ fixupNotMergedPartialProperty(symbol);
+ }
+ }
+ else
+ {
+ fixupNotMergedPartialProperty((Symbol)pair.Value);
+ }
+ }
- void mergePartialMethods(ref Dictionary, ImmutableArray> membersByName, ReadOnlyMemory name, SourceOrdinaryMethodSymbol currentMethod, SourceOrdinaryMethodSymbol prevMethod, BindingDiagnosticBag diagnostics)
+ static void fixupNotMergedPartialProperty(Symbol symbol)
+ {
+ Debug.Assert(symbol.IsPartialMember());
+ if (symbol is SourcePropertySymbol { OtherPartOfPartial: null } property)
+ {
+ property.SetMergedBackingField(property.DeclaredBackingField);
+ }
+ }
+
+ static void mergePartialMethods(ArrayBuilder nonTypeMembers, SourceOrdinaryMethodSymbol currentMethod, SourceOrdinaryMethodSymbol prevMethod, BindingDiagnosticBag diagnostics)
{
if (currentMethod.IsPartialImplementation &&
(prevMethod.IsPartialImplementation || (prevMethod.OtherPartOfPartial is MethodSymbol otherImplementation && (object)otherImplementation != currentMethod)))
@@ -3709,12 +3795,11 @@ void mergePartialMethods(ref Dictionary, ImmutableArray, ImmutableArray> membersByName, ReadOnlyMemory name, SourcePropertySymbol currentProperty, SourcePropertySymbol prevProperty, BindingDiagnosticBag diagnostics)
+ static void mergePartialProperties(ArrayBuilder nonTypeMembers, SourcePropertySymbol currentProperty, SourcePropertySymbol prevProperty, BindingDiagnosticBag diagnostics)
{
if (currentProperty.IsPartialImplementation &&
(prevProperty.IsPartialImplementation || (prevProperty.OtherPartOfPartial is SourcePropertySymbol otherImplementation && (object)otherImplementation != currentProperty)))
@@ -3733,19 +3818,17 @@ void mergePartialProperties(ref Dictionary, ImmutableArray<
diagnostics.Add(ErrorCode.ERR_PartialPropertyDuplicateInitializer, currentProperty.GetFirstLocation());
}
- DuplicateMembersByNameIfCached(ref membersByName);
- mergeAccessors(ref membersByName, (SourcePropertyAccessorSymbol?)currentProperty.GetMethod, (SourcePropertyAccessorSymbol?)prevProperty.GetMethod);
- mergeAccessors(ref membersByName, (SourcePropertyAccessorSymbol?)currentProperty.SetMethod, (SourcePropertyAccessorSymbol?)prevProperty.SetMethod);
- FixPartialProperty(ref membersByName, name, prevProperty, currentProperty);
+ mergeAccessors(nonTypeMembers, (SourcePropertyAccessorSymbol?)currentProperty.GetMethod, (SourcePropertyAccessorSymbol?)prevProperty.GetMethod);
+ mergeAccessors(nonTypeMembers, (SourcePropertyAccessorSymbol?)currentProperty.SetMethod, (SourcePropertyAccessorSymbol?)prevProperty.SetMethod);
+ FixPartialProperty(nonTypeMembers, prevProperty, currentProperty);
}
- void mergeAccessors(ref Dictionary, ImmutableArray> membersByName, SourcePropertyAccessorSymbol? currentAccessor, SourcePropertyAccessorSymbol? prevAccessor)
+ void mergeAccessors(ArrayBuilder nonTypeMembers, SourcePropertyAccessorSymbol? currentAccessor, SourcePropertyAccessorSymbol? prevAccessor)
{
if (currentAccessor is { } && prevAccessor is { })
{
- var name = currentAccessor.Name.AsMemory();
var implementationAccessor = currentProperty.IsPartialDefinition ? prevAccessor : currentAccessor;
- membersByName[name] = Remove(membersByName[name], implementationAccessor);
+ Remove(nonTypeMembers, implementationAccessor);
}
else if (currentAccessor is { } || prevAccessor is { })
{
@@ -3766,17 +3849,8 @@ static bool hasInitializer(SourcePropertySymbol property)
}
}
- private void DuplicateMembersByNameIfCached(ref Dictionary, ImmutableArray> membersByName)
- {
- if ((object)membersByName == _lazyEarlyAttributeDecodingMembersDictionary)
- {
- // Avoid mutating the cached dictionary and especially avoid doing this possibly on multiple threads in parallel.
- membersByName = new Dictionary, ImmutableArray>(membersByName, ReadOnlyMemoryOfCharComparer.Instance);
- }
- }
-
- /// Links together the definition and implementation parts of a partial method. Returns a member list which has the implementation part removed.
- private static ImmutableArray FixPartialMethod(ImmutableArray symbols, SourceOrdinaryMethodSymbol part1, SourceOrdinaryMethodSymbol part2)
+ /// Links together the definition and implementation parts of a partial method. Removes implementation part from .
+ private static void FixPartialMethod(ArrayBuilder nonTypeMembers, SourceOrdinaryMethodSymbol part1, SourceOrdinaryMethodSymbol part2)
{
SourceOrdinaryMethodSymbol definition;
SourceOrdinaryMethodSymbol implementation;
@@ -3794,11 +3868,11 @@ private static ImmutableArray FixPartialMethod(ImmutableArray sy
SourceOrdinaryMethodSymbol.InitializePartialMethodParts(definition, implementation);
// a partial method is represented in the member list by its definition part:
- return Remove(symbols, implementation);
+ Remove(nonTypeMembers, implementation);
}
- /// Links together the definition and implementation parts of a partial property. Returns a member list which has the implementation part removed.
- private static void FixPartialProperty(ref Dictionary, ImmutableArray> membersByName, ReadOnlyMemory name, SourcePropertySymbol part1, SourcePropertySymbol part2)
+ /// Links together the definition and implementation parts of a partial property. Removes implementation part from
+ private static void FixPartialProperty(ArrayBuilder nonTypeMembers, SourcePropertySymbol part1, SourcePropertySymbol part2)
{
SourcePropertySymbol definition;
SourcePropertySymbol implementation;
@@ -3816,27 +3890,28 @@ private static void FixPartialProperty(ref Dictionary, Immu
if (implementation.DeclaredBackingField is { } implementationField &&
definition.DeclaredBackingField is { })
{
- var fieldName = implementationField.Name.AsMemory();
- membersByName[fieldName] = Remove(membersByName[fieldName], implementationField);
+ Remove(nonTypeMembers, implementationField);
}
SourcePropertySymbol.InitializePartialPropertyParts(definition, implementation);
// a partial property is represented in the member list by its definition part:
- membersByName[name] = Remove(membersByName[name], implementation);
+ Remove(nonTypeMembers, implementation);
}
- private static ImmutableArray Remove(ImmutableArray symbols, Symbol symbol)
+ private static void Remove(ArrayBuilder symbols, Symbol symbol)
{
- var builder = ArrayBuilder.GetInstance();
- foreach (var s in symbols)
+ for (int i = 0; i < symbols.Count; i++)
{
- if (!ReferenceEquals(s, symbol))
+ Symbol s = symbols[i];
+ if (ReferenceEquals(s, symbol))
{
- builder.Add(s);
+ symbols.RemoveAt(i);
+ return;
}
}
- return builder.ToImmutableAndFree();
+
+ throw ExceptionUtilities.Unreachable();
}
///
@@ -4008,7 +4083,7 @@ private void AddEnumMembers(DeclaredMembersAndInitializersBuilder result, EnumDe
symbol = SourceEnumConstantSymbol.CreateImplicitValuedConstant(this, member, otherSymbol, otherSymbolOffset, diagnostics);
}
- result.NonTypeMembers.Add(symbol);
+ result.NonTypeMembersWithPartialImplementations.Add(symbol);
if (valueOpt != null || otherSymbol is null)
{
@@ -4155,7 +4230,7 @@ private void CheckForStructBadInitializers(DeclaredMembersAndInitializersBuilder
}
}
- if (hasInitializers && !builder.NonTypeMembers.Any(member => member is MethodSymbol { MethodKind: MethodKind.Constructor }))
+ if (hasInitializers && !builder.NonTypeMembersWithPartialImplementations.Any(member => member is MethodSymbol { MethodKind: MethodKind.Constructor }))
{
diagnostics.Add(ErrorCode.ERR_StructHasInitializersAndNoDeclaredConstructor, GetFirstLocation());
}
@@ -4166,7 +4241,7 @@ private void AddSynthesizedSimpleProgramEntryPointIfNecessary(MembersAndInitiali
var simpleProgramEntryPoints = GetSimpleProgramEntryPoints();
foreach (var member in simpleProgramEntryPoints)
{
- builder.AddNonTypeMember(member, declaredMembersAndInitializers);
+ builder.AddNonTypeMember(this, member, declaredMembersAndInitializers);
}
}
@@ -4177,7 +4252,7 @@ private void AddSynthesizedTypeMembersIfNecessary(MembersAndInitializersBuilder
return;
}
- var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers);
+ var membersSoFar = builder.GetNonTypeMembers(this, declaredMembersAndInitializers);
var members = ArrayBuilder.GetInstance(membersSoFar.Count + 1);
if (declaration.Kind is not (DeclarationKind.Record or DeclarationKind.RecordStruct))
@@ -4805,7 +4880,7 @@ private void AddSynthesizedConstructorsIfNecessary(MembersAndInitializersBuilder
// CONSIDER: if this traversal becomes a bottleneck, the flags could be made outputs of the
// dictionary construction process. For now, this is more encapsulated.
- var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers);
+ var membersSoFar = builder.GetNonTypeMembers(this, declaredMembersAndInitializers);
foreach (var member in membersSoFar)
{
if (member.Kind == SymbolKind.Method)
@@ -4844,7 +4919,7 @@ private void AddSynthesizedConstructorsIfNecessary(MembersAndInitializersBuilder
if ((!hasParameterlessInstanceConstructor && this.IsStructType()) ||
(!hasInstanceConstructor && !this.IsStatic && !this.IsInterface))
{
- builder.AddNonTypeMember((this.TypeKind == TypeKind.Submission) ?
+ builder.AddNonTypeMember(this, (this.TypeKind == TypeKind.Submission) ?
new SynthesizedSubmissionConstructor(this, diagnostics) :
new SynthesizedInstanceConstructor(this),
declaredMembersAndInitializers);
@@ -4858,15 +4933,15 @@ private void AddSynthesizedConstructorsIfNecessary(MembersAndInitializersBuilder
{
// Note: we don't have to put anything in the method - the binder will
// do that when processing field initializers.
- builder.AddNonTypeMember(new SynthesizedStaticConstructor(this), declaredMembersAndInitializers);
+ builder.AddNonTypeMember(this, new SynthesizedStaticConstructor(this), declaredMembersAndInitializers);
}
if (this.IsScriptClass)
{
var scriptInitializer = new SynthesizedInteractiveInitializerMethod(this, diagnostics);
- builder.AddNonTypeMember(scriptInitializer, declaredMembersAndInitializers);
+ builder.AddNonTypeMember(this, scriptInitializer, declaredMembersAndInitializers);
var scriptEntryPoint = SynthesizedEntryPointSymbol.Create(scriptInitializer, diagnostics);
- builder.AddNonTypeMember(scriptEntryPoint, declaredMembersAndInitializers);
+ builder.AddNonTypeMember(this, scriptEntryPoint, declaredMembersAndInitializers);
}
static bool hasNonConstantInitializer(ImmutableArray> initializers)
@@ -4882,7 +4957,7 @@ private void AddSynthesizedTupleMembersIfNecessary(MembersAndInitializersBuilder
return;
}
- var synthesizedMembers = this.MakeSynthesizedTupleMembers(declaredMembersAndInitializers.NonTypeMembers);
+ var synthesizedMembers = this.MakeSynthesizedTupleMembers(declaredMembersAndInitializers.GetNonTypeMembers(this));
if (synthesizedMembers is null)
{
return;
@@ -4890,7 +4965,7 @@ private void AddSynthesizedTupleMembersIfNecessary(MembersAndInitializersBuilder
foreach (var synthesizedMember in synthesizedMembers)
{
- builder.AddNonTypeMember(synthesizedMember, declaredMembersAndInitializers);
+ builder.AddNonTypeMember(this, synthesizedMember, declaredMembersAndInitializers);
}
synthesizedMembers.Free();
@@ -4945,7 +5020,7 @@ private void AddNonTypeMembers(
var fieldSymbol = (modifiers & DeclarationModifiers.Fixed) == 0
? new SourceMemberFieldSymbolFromDeclarator(this, variable, modifiers, modifierErrors, diagnostics)
: new SourceFixedFieldSymbol(this, variable, modifiers, modifierErrors, diagnostics);
- builder.NonTypeMembers.Add(fieldSymbol);
+ builder.NonTypeMembersWithPartialImplementations.Add(fieldSymbol);
// All fields are included in the nullable context for constructors and initializers, even fields without
// initializers, to ensure warnings are reported for uninitialized non-nullable fields in NullableWalker.
builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: fieldSymbol.IsStatic, compilation, variable);
@@ -4953,7 +5028,7 @@ private void AddNonTypeMembers(
if (IsScriptClass)
{
// also gather expression-declared variables from the bracketed argument lists and the initializers
- ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, variable, this,
+ ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembersWithPartialImplementations, variable, this,
DeclarationModifiers.Private | (modifiers & DeclarationModifiers.Static),
fieldSymbol);
}
@@ -4983,7 +5058,7 @@ private void AddNonTypeMembers(
}
var method = SourceOrdinaryMethodSymbol.CreateMethodSymbol(this, bodyBinder, methodSyntax, compilation.IsNullableAnalysisEnabledIn(methodSyntax), diagnostics);
- builder.NonTypeMembers.Add(method);
+ builder.NonTypeMembersWithPartialImplementations.Add(method);
}
break;
@@ -4998,7 +5073,7 @@ private void AddNonTypeMembers(
bool isNullableEnabled = compilation.IsNullableAnalysisEnabledIn(constructorSyntax);
var constructor = SourceConstructorSymbol.CreateConstructorSymbol(this, constructorSyntax, isNullableEnabled, diagnostics);
- builder.NonTypeMembers.Add(constructor);
+ builder.NonTypeMembersWithPartialImplementations.Add(constructor);
if (constructorSyntax.Initializer?.Kind() != SyntaxKind.ThisConstructorInitializer)
{
builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: constructor.IsStatic, isNullableEnabled);
@@ -5020,7 +5095,7 @@ private void AddNonTypeMembers(
// when it is loaded from metadata. Perhaps we should just treat it as an Ordinary
// method in such cases?
var destructor = new SourceDestructorSymbol(this, destructorSyntax, compilation.IsNullableAnalysisEnabledIn(destructorSyntax), diagnostics);
- builder.NonTypeMembers.Add(destructor);
+ builder.NonTypeMembersWithPartialImplementations.Add(destructor);
}
break;
@@ -5034,10 +5109,10 @@ private void AddNonTypeMembers(
}
var property = SourcePropertySymbol.Create(this, bodyBinder, propertySyntax, diagnostics);
- builder.NonTypeMembers.Add(property);
+ builder.NonTypeMembersWithPartialImplementations.Add(property);
- AddAccessorIfAvailable(builder.NonTypeMembers, property.GetMethod);
- AddAccessorIfAvailable(builder.NonTypeMembers, property.SetMethod);
+ AddAccessorIfAvailable(builder.NonTypeMembersWithPartialImplementations, property.GetMethod);
+ AddAccessorIfAvailable(builder.NonTypeMembersWithPartialImplementations, property.SetMethod);
FieldSymbol? backingField = property.DeclaredBackingField;
// TODO: can we leave this out of the member list?
@@ -5046,7 +5121,7 @@ private void AddNonTypeMembers(
// a similar manner and make the autoproperty fields private.
if (backingField is { })
{
- builder.NonTypeMembers.Add(backingField);
+ builder.NonTypeMembersWithPartialImplementations.Add(backingField);
builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: backingField.IsStatic, compilation, propertySyntax);
var initializer = propertySyntax.Initializer;
@@ -5055,7 +5130,7 @@ private void AddNonTypeMembers(
if (IsScriptClass)
{
// also gather expression-declared variables from the initializer
- ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers,
+ ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembersWithPartialImplementations,
initializer,
this,
DeclarationModifiers.Private | (property.IsStatic ? DeclarationModifiers.Static : 0),
@@ -5088,14 +5163,14 @@ private void AddNonTypeMembers(
foreach (VariableDeclaratorSyntax declarator in eventFieldSyntax.Declaration.Variables)
{
SourceFieldLikeEventSymbol @event = new SourceFieldLikeEventSymbol(this, bodyBinder, eventFieldSyntax.Modifiers, declarator, diagnostics);
- builder.NonTypeMembers.Add(@event);
+ builder.NonTypeMembersWithPartialImplementations.Add(@event);
FieldSymbol? associatedField = @event.AssociatedField;
if (IsScriptClass)
{
// also gather expression-declared variables from the bracketed argument lists and the initializers
- ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, declarator, this,
+ ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembersWithPartialImplementations, declarator, this,
DeclarationModifiers.Private | (@event.IsStatic ? DeclarationModifiers.Static : 0),
associatedField);
}
@@ -5123,8 +5198,8 @@ private void AddNonTypeMembers(
Debug.Assert((object)@event.AddMethod != null);
Debug.Assert((object)@event.RemoveMethod != null);
- AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod);
- AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod);
+ AddAccessorIfAvailable(builder.NonTypeMembersWithPartialImplementations, @event.AddMethod);
+ AddAccessorIfAvailable(builder.NonTypeMembersWithPartialImplementations, @event.RemoveMethod);
}
}
break;
@@ -5140,10 +5215,10 @@ private void AddNonTypeMembers(
var @event = new SourceCustomEventSymbol(this, bodyBinder, eventSyntax, diagnostics);
- builder.NonTypeMembers.Add(@event);
+ builder.NonTypeMembersWithPartialImplementations.Add(@event);
- AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod);
- AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod);
+ AddAccessorIfAvailable(builder.NonTypeMembersWithPartialImplementations, @event.AddMethod);
+ AddAccessorIfAvailable(builder.NonTypeMembersWithPartialImplementations, @event.RemoveMethod);
Debug.Assert(@event.AssociatedField is null);
}
@@ -5160,9 +5235,9 @@ private void AddNonTypeMembers(
var indexer = SourcePropertySymbol.Create(this, bodyBinder, indexerSyntax, diagnostics);
builder.HaveIndexers = true;
- builder.NonTypeMembers.Add(indexer);
- AddAccessorIfAvailable(builder.NonTypeMembers, indexer.GetMethod);
- AddAccessorIfAvailable(builder.NonTypeMembers, indexer.SetMethod);
+ builder.NonTypeMembersWithPartialImplementations.Add(indexer);
+ AddAccessorIfAvailable(builder.NonTypeMembersWithPartialImplementations, indexer.GetMethod);
+ AddAccessorIfAvailable(builder.NonTypeMembersWithPartialImplementations, indexer.SetMethod);
}
break;
@@ -5177,7 +5252,7 @@ private void AddNonTypeMembers(
var method = SourceUserDefinedConversionSymbol.CreateUserDefinedConversionSymbol(
this, bodyBinder, conversionOperatorSyntax, compilation.IsNullableAnalysisEnabledIn(conversionOperatorSyntax), diagnostics);
- builder.NonTypeMembers.Add(method);
+ builder.NonTypeMembersWithPartialImplementations.Add(method);
}
break;
@@ -5192,7 +5267,7 @@ private void AddNonTypeMembers(
var method = SourceUserDefinedOperatorSymbol.CreateUserDefinedOperatorSymbol(
this, bodyBinder, operatorSyntax, compilation.IsNullableAnalysisEnabledIn(operatorSyntax), diagnostics);
- builder.NonTypeMembers.Add(method);
+ builder.NonTypeMembersWithPartialImplementations.Add(method);
}
break;
@@ -5219,7 +5294,7 @@ private void AddNonTypeMembers(
foreach (var vdecl in decl.Declaration.Variables)
{
// also gather expression-declared variables from the bracketed argument lists and the initializers
- ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, vdecl, this, DeclarationModifiers.Private,
+ ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembersWithPartialImplementations, vdecl, this, DeclarationModifiers.Private,
containingFieldOpt: null);
}
break;
@@ -5231,7 +5306,7 @@ private void AddNonTypeMembers(
case SyntaxKind.ThrowStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.LockStatement:
- ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers,
+ ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembersWithPartialImplementations,
innerStatement,
this,
DeclarationModifiers.Private,
diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbolBase.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbolBase.cs
index ddb22a7995cba..d3fa761b0baee 100644
--- a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbolBase.cs
+++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbolBase.cs
@@ -9,6 +9,7 @@
using System.Diagnostics;
using System.Globalization;
using System.Linq;
+using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -74,7 +75,7 @@ private enum Flags : ushort
#nullable enable
private SynthesizedBackingFieldSymbol? _lazyDeclaredBackingField;
- private SynthesizedBackingFieldSymbol? _lazyMergedBackingField;
+ private StrongBox? _lazyMergedBackingField;
protected SourcePropertySymbolBase(
SourceMemberContainerTypeSymbol containingType,
@@ -756,19 +757,11 @@ internal SynthesizedBackingFieldSymbol BackingField
if (_lazyMergedBackingField is null)
{
var backingField = DeclaredBackingField;
- // The property should only be used after members in the containing
- // type are complete, and partial members have been merged.
- if (!_containingType.AreMembersComplete)
- {
- // When calling through the SemanticModel, partial members are not
- // necessarily merged when the containing type includes a primary
- // constructor - see https://github.com/dotnet/roslyn/issues/75002.
- Debug.Assert(_containingType.PrimaryConstructor is { });
- return backingField;
- }
- Interlocked.CompareExchange(ref _lazyMergedBackingField, backingField, null);
+ // The property should only be used after partial members have been merged.
+ Debug.Assert(!IsPartial);
+ Interlocked.CompareExchange(ref _lazyMergedBackingField, new StrongBox(backingField), null);
}
- return _lazyMergedBackingField;
+ return _lazyMergedBackingField.Value;
}
}
@@ -787,8 +780,8 @@ internal SynthesizedBackingFieldSymbol? DeclaredBackingField
internal void SetMergedBackingField(SynthesizedBackingFieldSymbol? backingField)
{
- Interlocked.CompareExchange(ref _lazyMergedBackingField, backingField, null);
- Debug.Assert((object?)_lazyMergedBackingField == backingField);
+ Interlocked.CompareExchange(ref _lazyMergedBackingField, new StrongBox(backingField), null);
+ Debug.Assert((object?)_lazyMergedBackingField.Value == backingField);
}
private SynthesizedBackingFieldSymbol CreateBackingField()
diff --git a/src/Compilers/CSharp/Test/Emit3/Semantics/PrimaryConstructorTests.cs b/src/Compilers/CSharp/Test/Emit3/Semantics/PrimaryConstructorTests.cs
index 623a2f0f15f6b..b6c2778c94988 100644
--- a/src/Compilers/CSharp/Test/Emit3/Semantics/PrimaryConstructorTests.cs
+++ b/src/Compilers/CSharp/Test/Emit3/Semantics/PrimaryConstructorTests.cs
@@ -19791,6 +19791,7 @@ class C(int p)
}
[WorkItem("https://github.com/dotnet/roslyn/issues/75002")]
+ [WorkItem("https://github.com/dotnet/roslyn/issues/76651")]
[Fact]
public void PartialMembers_01()
{
@@ -19812,14 +19813,49 @@ public partial void M() { }
var comp = CreateCompilation([source1, source2]);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
- // https://github.com/dotnet/roslyn/issues/75002: SemanticModel.GetDiagnostics() does not merge partial members.
+ model.GetDiagnostics().Verify();
+ }
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76651")]
+ public void PartialMembers_02()
+ {
+ var source1 = """
+[System.Diagnostics.CodeAnalysis.Experimental(C.P)]
+class Repro
+{
+}
+""";
+
+ var source2 = """
+partial class C
+{
+ public static partial string P {get=>"";set{}}
+ public static partial string P {get;set;}
+}
+
+namespace System.Diagnostics.CodeAnalysis
+{
+ [AttributeUsage(AttributeTargets.All, Inherited = false)]
+ public sealed class ExperimentalAttribute : Attribute
+ {
+ public ExperimentalAttribute(string diagnosticId) { }
+
+ public string UrlFormat { get; set; }
+
+ public string Message { get; set; }
+ }
+}
+""";
+ var comp = CreateCompilation([source1, source2]);
+
+ var tree = comp.SyntaxTrees[0];
+ var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
+
model.GetDiagnostics().Verify(
- // (2,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M()' and 'C.M()'
- // c.M();
- Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M()", "C.M()").WithLocation(2, 3),
- // (3,7): error CS0229: Ambiguity between 'C.P' and 'C.P'
- // _ = c.P;
- Diagnostic(ErrorCode.ERR_AmbigMember, "P").WithArguments("C.P", "C.P").WithLocation(3, 7));
+ // (1,47): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
+ // [System.Diagnostics.CodeAnalysis.Experimental(C.P)]
+ Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.P").WithLocation(1, 47)
+ );
}
[Fact]
@@ -19880,14 +19916,14 @@ partial class C(int p)
var comp = CreateCompilation([source1, source2], targetFramework: TargetFramework.Net80);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
- // https://github.com/dotnet/roslyn/issues/75002: SemanticModel.GetDiagnostics() does not merge partial members.
model.GetDiagnostics().Verify(
- // (4,7): error CS0121: The call is ambiguous between the following methods or properties: 'C.M()' and 'C.M()'
+ // (4,5): warning CS8600: Converting null literal or possible null value to non-nullable type.
// o = c.M();
- Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M()", "C.M()").WithLocation(4, 7),
- // (5,7): error CS0229: Ambiguity between 'C.P' and 'C.P'
+ Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M()").WithLocation(4, 5),
+ // (5,5): warning CS8600: Converting null literal or possible null value to non-nullable type.
// o = c.P;
- Diagnostic(ErrorCode.ERR_AmbigMember, "P").WithArguments("C.P", "C.P").WithLocation(5, 7));
+ Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P").WithLocation(5, 5)
+ );
}
[WorkItem("https://github.com/dotnet/roslyn/issues/75002")]
@@ -19916,14 +19952,14 @@ partial class C(int p)
var comp = CreateCompilation([source1, source2], targetFramework: TargetFramework.Net80);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
- // https://github.com/dotnet/roslyn/issues/75002: SemanticModel.GetDiagnostics() does not merge partial members.
model.GetDiagnostics().Verify(
- // (4,7): error CS0121: The call is ambiguous between the following methods or properties: 'C.M()' and 'C.M()'
+ // (4,5): warning CS8600: Converting null literal or possible null value to non-nullable type.
// o = c.M();
- Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M()", "C.M()").WithLocation(4, 7),
- // (5,7): error CS0229: Ambiguity between 'C.P' and 'C.P'
+ Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M()").WithLocation(4, 5),
+ // (5,5): warning CS8600: Converting null literal or possible null value to non-nullable type.
// o = c.P;
- Diagnostic(ErrorCode.ERR_AmbigMember, "P").WithArguments("C.P", "C.P").WithLocation(5, 7));
+ Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P").WithLocation(5, 5)
+ );
}
[Fact]
diff --git a/src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs b/src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs
index c1633ff05187d..58d7a89a0ae22 100644
--- a/src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs
+++ b/src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs
@@ -1525,6 +1525,54 @@ [Attr] class D { }
Assert.Equal(e, runResults.Results.Single().Exception);
}
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76765")]
+ public void Incremental_Generators_Exception_In_DefaultComparer()
+ {
+ var source = """
+ class C { }
+ """;
+ var parseOptions = TestOptions.RegularPreview;
+ Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDllThrowing, parseOptions: parseOptions);
+ compilation.VerifyDiagnostics();
+
+ var syntaxTree = compilation.SyntaxTrees.Single();
+
+ var e = new InvalidOperationException("abc");
+ var generator = new PipelineCallbackGenerator((ctx) =>
+ {
+ var name = ctx.CompilationProvider.Select((c, _) => new ThrowWhenEqualsItem(e));
+ ctx.RegisterSourceOutput(name, (spc, n) => spc.AddSource("item.cs", "// generated"));
+ });
+
+ GeneratorDriver driver = CSharpGeneratorDriver.Create([generator.AsSourceGenerator()], parseOptions: parseOptions);
+ driver = driver.RunGenerators(compilation);
+ var runResults = driver.GetRunResult();
+
+ Assert.Empty(runResults.Diagnostics);
+ Assert.Equal("// generated", runResults.Results.Single().GeneratedSources.Single().SourceText.ToString());
+
+ compilation = compilation.ReplaceSyntaxTree(syntaxTree, CSharpSyntaxTree.ParseText("""
+ class D { }
+ """, parseOptions));
+ compilation.VerifyDiagnostics();
+
+ driver = driver.RunGenerators(compilation);
+ runResults = driver.GetRunResult();
+
+ VerifyGeneratorExceptionDiagnostic(runResults.Diagnostics.Single(), nameof(PipelineCallbackGenerator), "abc");
+ Assert.Empty(runResults.GeneratedTrees);
+ Assert.Equal(e, runResults.Results.Single().Exception);
+ }
+
+ class ThrowWhenEqualsItem(Exception toThrow)
+ {
+ readonly Exception _toThrow = toThrow;
+
+ public override bool Equals(object? obj) => throw _toThrow;
+
+ public override int GetHashCode() => throw new NotImplementedException();
+ }
+
[Fact]
public void Incremental_Generators_Exception_During_Execution_Doesnt_Produce_AnySource()
{
diff --git a/src/Compilers/CSharp/Test/Semantic/SourceGeneration/StateTableTests.cs b/src/Compilers/CSharp/Test/Semantic/SourceGeneration/StateTableTests.cs
index bb887e87ce6ec..e075bce56677d 100644
--- a/src/Compilers/CSharp/Test/Semantic/SourceGeneration/StateTableTests.cs
+++ b/src/Compilers/CSharp/Test/Semantic/SourceGeneration/StateTableTests.cs
@@ -82,9 +82,9 @@ public void Node_Builder_Can_Add_Entries_From_Previous_Table()
var previousTable = builder.ToImmutableAndFree();
builder = previousTable.ToBuilder(stepName: null, false);
- builder.TryModifyEntries(ImmutableArray.Create(10, 11), EqualityComparer.Default, TimeSpan.Zero, default, EntryState.Modified);
+ builder.TryModifyEntries(ImmutableArray.Create(10, 11), TimeSpan.Zero, default, EntryState.Modified);
builder.TryUseCachedEntries(TimeSpan.Zero, default, out var cachedEntries); // ((2, EntryState.Cached), (3, EntryState.Cached))
- builder.TryModifyEntries(ImmutableArray.Create(20, 21, 22), EqualityComparer.Default, TimeSpan.Zero, default, EntryState.Modified);
+ builder.TryModifyEntries(ImmutableArray.Create(20, 21, 22), TimeSpan.Zero, default, EntryState.Modified);
bool didRemoveEntries = builder.TryRemoveEntries(TimeSpan.Zero, default, out var removedEntries); //((6, EntryState.Removed))
var newTable = builder.ToImmutableAndFree();
@@ -185,9 +185,9 @@ public void Node_Builder_Handles_Modification_When_Both_Tables_Have_Empty_Entrie
AssertTableEntries(previousTable, expected);
builder = previousTable.ToBuilder(stepName: null, false);
- Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 2), EqualityComparer.Default, TimeSpan.Zero, default, EntryState.Modified));
- Assert.True(builder.TryModifyEntries(ImmutableArray.Empty, EqualityComparer.Default, TimeSpan.Zero, default, EntryState.Modified));
- Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 5), EqualityComparer.Default, TimeSpan.Zero, default, EntryState.Modified));
+ Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 2), TimeSpan.Zero, default, EntryState.Modified));
+ Assert.True(builder.TryModifyEntries(ImmutableArray.Empty, TimeSpan.Zero, default, EntryState.Modified));
+ Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 5), TimeSpan.Zero, default, EntryState.Modified));
var newTable = builder.ToImmutableAndFree();
@@ -209,10 +209,10 @@ public void Node_Table_Doesnt_Modify_Single_Item_Multiple_Times_When_Same()
AssertTableEntries(previousTable, expected);
builder = previousTable.ToBuilder(stepName: null, false);
- Assert.True(builder.TryModifyEntry(1, EqualityComparer.Default, TimeSpan.Zero, default, EntryState.Modified));
- Assert.True(builder.TryModifyEntry(2, EqualityComparer.Default, TimeSpan.Zero, default, EntryState.Modified));
- Assert.True(builder.TryModifyEntry(5, EqualityComparer.Default, TimeSpan.Zero, default, EntryState.Modified));
- Assert.True(builder.TryModifyEntry(4, EqualityComparer.Default, TimeSpan.Zero, default, EntryState.Modified));
+ Assert.True(builder.TryModifyEntry(1, TimeSpan.Zero, default, EntryState.Modified));
+ Assert.True(builder.TryModifyEntry(2, TimeSpan.Zero, default, EntryState.Modified));
+ Assert.True(builder.TryModifyEntry(5, TimeSpan.Zero, default, EntryState.Modified));
+ Assert.True(builder.TryModifyEntry(4, TimeSpan.Zero, default, EntryState.Modified));
var newTable = builder.ToImmutableAndFree();
@@ -232,10 +232,10 @@ public void Node_Table_Caches_Previous_Object_When_Modification_Considered_Cache
var expected = ImmutableArray.Create((1, EntryState.Added, 0), (2, EntryState.Added, 0), (3, EntryState.Added, 0));
AssertTableEntries(previousTable, expected);
- builder = previousTable.ToBuilder(stepName: null, false);
- Assert.True(builder.TryModifyEntry(1, EqualityComparer.Default, TimeSpan.Zero, default, EntryState.Modified)); // ((1, EntryState.Cached))
- Assert.True(builder.TryModifyEntry(4, EqualityComparer.Default, TimeSpan.Zero, default, EntryState.Modified)); // ((4, EntryState.Modified))
- Assert.True(builder.TryModifyEntry(5, new LambdaComparer((i, j) => true), TimeSpan.Zero, default, EntryState.Modified)); // ((3, EntryState.Cached))
+ builder = previousTable.ToBuilder(stepName: null, false, new LambdaComparer((i, j) => i == 3 || i == j));
+ Assert.True(builder.TryModifyEntry(1, TimeSpan.Zero, default, EntryState.Modified)); // ((1, EntryState.Cached))
+ Assert.True(builder.TryModifyEntry(4, TimeSpan.Zero, default, EntryState.Modified)); // ((4, EntryState.Modified))
+ Assert.True(builder.TryModifyEntry(5, TimeSpan.Zero, default, EntryState.Modified)); // ((3, EntryState.Cached))
var newTable = builder.ToImmutableAndFree();
expected = ImmutableArray.Create((1, EntryState.Cached, 0), (4, EntryState.Modified, 0), (3, EntryState.Cached, 0));
diff --git a/src/Compilers/CSharp/Test/Symbol/Symbols/PartialPropertiesTests.cs b/src/Compilers/CSharp/Test/Symbol/Symbols/PartialPropertiesTests.cs
index eaa4ca1a170a9..6673e386e5806 100644
--- a/src/Compilers/CSharp/Test/Symbol/Symbols/PartialPropertiesTests.cs
+++ b/src/Compilers/CSharp/Test/Symbol/Symbols/PartialPropertiesTests.cs
@@ -5090,5 +5090,43 @@ partial struct S
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics();
}
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76842")]
+ public void IndexerWithName_01()
+ {
+ var source = """
+ using System.Runtime.CompilerServices;
+
+ partial struct S1
+ {
+ public partial int this[int x] {get=>x;}
+
+ [IndexerName("MyName")]
+ public partial int this[int x] {get;}
+ }
+ """;
+
+ var comp = CreateCompilation(source);
+ comp.VerifyEmitDiagnostics();
+ }
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76842")]
+ public void IndexerWithName_02()
+ {
+ var source = """
+ using System.Runtime.CompilerServices;
+
+ partial struct S1
+ {
+ [IndexerName("MyName")]
+ public partial int this[int x] {get=>x;}
+
+ public partial int this[int x] {get;}
+ }
+ """;
+
+ var comp = CreateCompilation(source);
+ comp.VerifyEmitDiagnostics();
+ }
}
}
diff --git a/src/Compilers/Core/Portable/Collections/DictionaryExtensions.cs b/src/Compilers/Core/Portable/Collections/DictionaryExtensions.cs
index cb74f75739217..f3f6f224cfa57 100644
--- a/src/Compilers/Core/Portable/Collections/DictionaryExtensions.cs
+++ b/src/Compilers/Core/Portable/Collections/DictionaryExtensions.cs
@@ -76,7 +76,7 @@ public static bool TryAdd(
}
#endif
- public static void AddPooled(this IDictionary> dictionary, K key, V value)
+ public static void AddPooled(this Dictionary> dictionary, K key, V value)
where K : notnull
{
if (!dictionary.TryGetValue(key, out var values))
@@ -88,15 +88,22 @@ public static void AddPooled(this IDictionary> dictiona
values.Add(value);
}
- public static ImmutableSegmentedDictionary> ToImmutableSegmentedDictionaryAndFree(this IReadOnlyDictionary> builder)
+ ///
+ /// Converts the passed in dictionary to an , where all
+ /// the values in the passed builder will be converted to an using . The will be freed at the end of
+ /// this method as well, and should not be used afterwards.
+ ///
+ public static ImmutableSegmentedDictionary> ToImmutableSegmentedDictionaryAndFree(this PooledDictionary> dictionary)
where K : notnull
{
var result = ImmutableSegmentedDictionary.CreateBuilder>();
- foreach (var (key, values) in builder)
+ foreach (var (key, values) in dictionary)
{
result.Add(key, values.ToImmutableAndFree());
}
+ dictionary.Free();
return result.ToImmutable();
}
}
diff --git a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.GroupedAnalyzerActions.cs b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.GroupedAnalyzerActions.cs
index 04132ae8fafbe..521c4437f1a98 100644
--- a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.GroupedAnalyzerActions.cs
+++ b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.GroupedAnalyzerActions.cs
@@ -5,6 +5,7 @@
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
+using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
@@ -17,16 +18,25 @@ internal partial class AnalyzerDriver : AnalyzerDriver where
///
private sealed class GroupedAnalyzerActions : IGroupedAnalyzerActions
{
- public static readonly GroupedAnalyzerActions Empty = new GroupedAnalyzerActions(ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Empty, AnalyzerActions.Empty);
+ public static readonly GroupedAnalyzerActions Empty = new GroupedAnalyzerActions(
+ ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Empty,
+ ImmutableSegmentedDictionary>.Empty,
+ AnalyzerActions.Empty);
- private GroupedAnalyzerActions(ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)> groupedActionsAndAnalyzers, in AnalyzerActions analyzerActions)
+ private GroupedAnalyzerActions(
+ ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)> groupedActionsAndAnalyzers,
+ ImmutableSegmentedDictionary> analyzersByKind,
+ in AnalyzerActions analyzerActions)
{
GroupedActionsByAnalyzer = groupedActionsAndAnalyzers;
AnalyzerActions = analyzerActions;
+ AnalyzersByKind = analyzersByKind;
}
public ImmutableArray<(DiagnosticAnalyzer analyzer, GroupedAnalyzerActionsForAnalyzer groupedActions)> GroupedActionsByAnalyzer { get; }
+ public ImmutableSegmentedDictionary> AnalyzersByKind { get; }
+
public AnalyzerActions AnalyzerActions { get; }
public bool IsEmpty
@@ -48,7 +58,8 @@ public static GroupedAnalyzerActions Create(DiagnosticAnalyzer analyzer, in Anal
var groupedActions = new GroupedAnalyzerActionsForAnalyzer(analyzer, analyzerActions, analyzerActionsNeedFiltering: false);
var groupedActionsAndAnalyzers = ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Empty.Add((analyzer, groupedActions));
- return new GroupedAnalyzerActions(groupedActionsAndAnalyzers, in analyzerActions);
+ var analyzersByKind = CreateAnalyzersByKind(groupedActionsAndAnalyzers);
+ return new GroupedAnalyzerActions(groupedActionsAndAnalyzers, analyzersByKind, in analyzerActions);
}
public static GroupedAnalyzerActions Create(ImmutableArray analyzers, in AnalyzerActions analyzerActions)
@@ -58,7 +69,8 @@ public static GroupedAnalyzerActions Create(ImmutableArray a
var groups = analyzers.SelectAsArray(
(analyzer, analyzerActions) => (analyzer, new GroupedAnalyzerActionsForAnalyzer(analyzer, analyzerActions, analyzerActionsNeedFiltering: true)),
analyzerActions);
- return new GroupedAnalyzerActions(groups, in analyzerActions);
+ var analyzersByKind = CreateAnalyzersByKind(groups);
+ return new GroupedAnalyzerActions(groups, analyzersByKind, in analyzerActions);
}
IGroupedAnalyzerActions IGroupedAnalyzerActions.Append(IGroupedAnalyzerActions igroupedAnalyzerActions)
@@ -74,7 +86,22 @@ IGroupedAnalyzerActions IGroupedAnalyzerActions.Append(IGroupedAnalyzerActions i
var newGroupedActions = GroupedActionsByAnalyzer.AddRange(groupedAnalyzerActions.GroupedActionsByAnalyzer);
var newAnalyzerActions = AnalyzerActions.Append(groupedAnalyzerActions.AnalyzerActions);
- return new GroupedAnalyzerActions(newGroupedActions, newAnalyzerActions);
+ var analyzersByKind = CreateAnalyzersByKind(newGroupedActions);
+ return new GroupedAnalyzerActions(newGroupedActions, analyzersByKind, newAnalyzerActions);
+ }
+
+ private static ImmutableSegmentedDictionary> CreateAnalyzersByKind(ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)> groupedActionsAndAnalyzers)
+ {
+ var analyzersByKind = PooledDictionary>.GetInstance();
+ foreach (var (analyzer, groupedActionsForAnalyzer) in groupedActionsAndAnalyzers)
+ {
+ foreach (var (kind, _) in groupedActionsForAnalyzer.NodeActionsByAnalyzerAndKind)
+ {
+ analyzersByKind.AddPooled(kind, analyzer);
+ }
+ }
+
+ return analyzersByKind.ToImmutableSegmentedDictionaryAndFree();
}
}
}
diff --git a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.cs b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.cs
index f3f942d2d1cfc..fa01b2f7f0e9f 100644
--- a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.cs
+++ b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.cs
@@ -2611,10 +2611,26 @@ void executeNodeActions()
void executeNodeActionsByKind(ArrayBuilder nodesToAnalyze, GroupedAnalyzerActions groupedActions, bool arePerSymbolActions)
{
+ if (groupedActions.GroupedActionsByAnalyzer.Length == 0)
+ {
+ return;
+ }
+
+ var analyzersForNodes = PooledHashSet.GetInstance();
+ foreach (var node in nodesToAnalyze)
+ {
+ if (groupedActions.AnalyzersByKind.TryGetValue(_getKind(node), out var analyzersForKind))
+ {
+ foreach (var analyzer in analyzersForKind)
+ {
+ analyzersForNodes.Add(analyzer);
+ }
+ }
+ }
+
foreach (var (analyzer, groupedActionsForAnalyzer) in groupedActions.GroupedActionsByAnalyzer)
{
- var nodeActionsByKind = groupedActionsForAnalyzer.NodeActionsByAnalyzerAndKind;
- if (nodeActionsByKind.IsEmpty || !analysisScope.Contains(analyzer))
+ if (!analyzersForNodes.Contains(analyzer) || !analysisScope.Contains(analyzer))
{
continue;
}
@@ -2642,6 +2658,8 @@ void executeNodeActionsByKind(ArrayBuilder nodesToAnalyze, GroupedAn
}
}
+ analyzersForNodes.Free();
+
void executeSyntaxNodeActions(
DiagnosticAnalyzer analyzer,
GroupedAnalyzerActionsForAnalyzer groupedActionsForAnalyzer,
diff --git a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerExecutor.cs b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerExecutor.cs
index 17eeeb262d9b7..4b0acdd04c7d9 100644
--- a/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerExecutor.cs
+++ b/src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerExecutor.cs
@@ -932,19 +932,11 @@ internal static ImmutableSegmentedDictionary>.GetInstance());
- }
-
- actionsForKind.Add(nodeAction);
+ nodeActionsByKind.AddPooled(kind, nodeAction);
}
}
- var tuples = nodeActionsByKind.Select(kvp => KeyValuePairUtil.Create(kvp.Key, kvp.Value.ToImmutableAndFree()));
- var map = ImmutableSegmentedDictionary.CreateRange(tuples);
- nodeActionsByKind.Free();
- return map;
+ return nodeActionsByKind.ToImmutableSegmentedDictionaryAndFree();
}
///
@@ -1031,19 +1023,11 @@ internal static ImmutableSegmentedDictionary.GetInstance());
- }
-
- actionsForKind.Add(operationAction);
+ operationActionsByKind.AddPooled(kind, operationAction);
}
}
- var tuples = operationActionsByKind.Select(kvp => KeyValuePairUtil.Create(kvp.Key, kvp.Value.ToImmutableAndFree()));
- var map = ImmutableSegmentedDictionary.CreateRange(tuples);
- operationActionsByKind.Free();
- return map;
+ return operationActionsByKind.ToImmutableSegmentedDictionaryAndFree();
}
///
diff --git a/src/Compilers/Core/Portable/MetadataReference/ModuleMetadata.cs b/src/Compilers/Core/Portable/MetadataReference/ModuleMetadata.cs
index 58d64292d8f73..ab9a5f805e3dd 100644
--- a/src/Compilers/Core/Portable/MetadataReference/ModuleMetadata.cs
+++ b/src/Compilers/Core/Portable/MetadataReference/ModuleMetadata.cs
@@ -240,13 +240,6 @@ public static ModuleMetadata CreateFromStream(Stream peStream, PEStreamOptions o
}
}
- // Workaround of issue https://github.com/dotnet/corefx/issues/1815:
- if (peStream.Length == 0 && (options & PEStreamOptions.PrefetchEntireImage) != 0 && (options & PEStreamOptions.PrefetchMetadata) != 0)
- {
- // throws BadImageFormatException:
- new PEHeaders(peStream);
- }
-
// ownership of the stream is passed on PEReader:
return new ModuleMetadata(new PEReader(peStream, options), onDispose: null);
}
diff --git a/src/Compilers/Core/Portable/SourceGeneration/Nodes/BatchNode.cs b/src/Compilers/Core/Portable/SourceGeneration/Nodes/BatchNode.cs
index 3b803f961498b..f8c92b1791cde 100644
--- a/src/Compilers/Core/Portable/SourceGeneration/Nodes/BatchNode.cs
+++ b/src/Compilers/Core/Portable/SourceGeneration/Nodes/BatchNode.cs
@@ -16,13 +16,13 @@ internal sealed class BatchNode : IIncrementalGeneratorNode).FullName;
private readonly IIncrementalGeneratorNode _sourceNode;
- private readonly IEqualityComparer> _comparer;
+ private readonly IEqualityComparer>? _comparer;
private readonly string? _name;
public BatchNode(IIncrementalGeneratorNode sourceNode, IEqualityComparer>? comparer = null, string? name = null)
{
_sourceNode = sourceNode;
- _comparer = comparer ?? EqualityComparer>.Default;
+ _comparer = comparer;
_name = name;
}
@@ -136,7 +136,7 @@ public NodeStateTable> UpdateStateTable(DriverStateTable.
}
else if (!sourceTable.IsCached || !tableBuilder.TryUseCachedEntries(stopwatch.Elapsed, sourceInputs))
{
- if (!tableBuilder.TryModifyEntry(sourceValues, _comparer, stopwatch.Elapsed, sourceInputs, EntryState.Modified))
+ if (!tableBuilder.TryModifyEntry(sourceValues, stopwatch.Elapsed, sourceInputs, EntryState.Modified))
{
tableBuilder.AddEntry(sourceValues, EntryState.Added, stopwatch.Elapsed, sourceInputs, EntryState.Added);
}
diff --git a/src/Compilers/Core/Portable/SourceGeneration/Nodes/CombineNode.cs b/src/Compilers/Core/Portable/SourceGeneration/Nodes/CombineNode.cs
index bd4c0d4c489c5..67795541805fb 100644
--- a/src/Compilers/Core/Portable/SourceGeneration/Nodes/CombineNode.cs
+++ b/src/Compilers/Core/Portable/SourceGeneration/Nodes/CombineNode.cs
@@ -72,7 +72,7 @@ public CombineNode(IIncrementalGeneratorNode input1, IIncrementalGenera
};
var entry = (entry1.Item, input2);
- if (state != EntryState.Modified || _comparer is null || !tableBuilder.TryModifyEntry(entry, _comparer, stopwatch.Elapsed, stepInputs, state))
+ if (state != EntryState.Modified || _comparer is null || !tableBuilder.TryModifyEntry(entry, stopwatch.Elapsed, stepInputs, state))
{
tableBuilder.AddEntry(entry, state, stopwatch.Elapsed, stepInputs, state);
}
diff --git a/src/Compilers/Core/Portable/SourceGeneration/Nodes/InputNode.cs b/src/Compilers/Core/Portable/SourceGeneration/Nodes/InputNode.cs
index 2e7205b08793e..66b8cfe04e012 100644
--- a/src/Compilers/Core/Portable/SourceGeneration/Nodes/InputNode.cs
+++ b/src/Compilers/Core/Portable/SourceGeneration/Nodes/InputNode.cs
@@ -24,7 +24,7 @@ internal sealed class InputNode : IIncrementalGeneratorNode
private readonly Func> _getInput;
private readonly Action _registerOutput;
private readonly IEqualityComparer _inputComparer;
- private readonly IEqualityComparer _comparer;
+ private readonly IEqualityComparer? _comparer;
private readonly string? _name;
public InputNode(Func> getInput, IEqualityComparer? inputComparer = null)
@@ -35,7 +35,7 @@ public InputNode(Func> getInput, IEq
private InputNode(Func> getInput, Action? registerOutput, IEqualityComparer? inputComparer = null, IEqualityComparer? comparer = null, string? name = null)
{
_getInput = getInput;
- _comparer = comparer ?? EqualityComparer.Default;
+ _comparer = comparer;
_inputComparer = inputComparer ?? EqualityComparer.Default;
_registerOutput = registerOutput ?? (o => throw ExceptionUtilities.Unreachable());
_name = name;
@@ -83,7 +83,7 @@ public NodeStateTable UpdateStateTable(DriverStateTable.Builder graphState, N
// This allows us to correctly 'replace' items even when they aren't actually the same. In the case that the
// item really isn't modified, but a new item, we still function correctly as we mostly treat them the same,
// but will perform an extra comparison that is omitted in the pure 'added' case.
- var modified = tableBuilder.TryModifyEntry(inputItems[itemIndex], _comparer, elapsedTime, noInputStepsStepInfo, EntryState.Modified);
+ var modified = tableBuilder.TryModifyEntry(inputItems[itemIndex], elapsedTime, noInputStepsStepInfo, EntryState.Modified);
Debug.Assert(modified);
itemsSet.Remove(inputItems[itemIndex]);
}
diff --git a/src/Compilers/Core/Portable/SourceGeneration/Nodes/NodeStateTable.cs b/src/Compilers/Core/Portable/SourceGeneration/Nodes/NodeStateTable.cs
index 8758c9302a75a..d166d64ec62ff 100644
--- a/src/Compilers/Core/Portable/SourceGeneration/Nodes/NodeStateTable.cs
+++ b/src/Compilers/Core/Portable/SourceGeneration/Nodes/NodeStateTable.cs
@@ -183,7 +183,7 @@ public NodeStateTable AsCached()
public Builder ToBuilder(string? stepName, bool stepTrackingEnabled, IEqualityComparer? equalityComparer = null, int? tableCapacity = null)
=> new(this, stepName, stepTrackingEnabled, equalityComparer, tableCapacity);
- public NodeStateTable CreateCachedTableWithUpdatedSteps(NodeStateTable inputTable, string? stepName, IEqualityComparer equalityComparer)
+ public NodeStateTable CreateCachedTableWithUpdatedSteps(NodeStateTable inputTable, string? stepName, IEqualityComparer? equalityComparer)
{
Debug.Assert(inputTable.HasTrackedSteps && inputTable.IsCached);
NodeStateTable.Builder builder = ToBuilder(stepName, stepTrackingEnabled: true, equalityComparer);
@@ -256,7 +256,7 @@ internal Builder(
_states = ArrayBuilder.GetInstance(tableCapacity ?? previous.GetTotalEntryItemCount());
_previous = previous;
_name = name;
- _equalityComparer = equalityComparer ?? EqualityComparer.Default;
+ _equalityComparer = equalityComparer ?? WrappedUserComparer.Default;
if (stepTrackingEnabled)
{
_steps = ArrayBuilder.GetInstance();
@@ -320,7 +320,7 @@ internal bool TryUseCachedEntries(TimeSpan elapsedTime, ImmutableArray<(Incremen
return true;
}
- public bool TryModifyEntry(T value, IEqualityComparer comparer, TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, EntryState overallInputState)
+ public bool TryModifyEntry(T value, TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, EntryState overallInputState)
{
if (!TryGetPreviousEntry(out var previousEntry))
{
@@ -335,13 +335,13 @@ public bool TryModifyEntry(T value, IEqualityComparer comparer, TimeSpan elap
}
Debug.Assert(previousEntry.Count == 1);
- var (chosen, state, _) = GetModifiedItemAndState(previousEntry.GetItem(0), value, comparer);
+ var (chosen, state, _) = GetModifiedItemAndState(previousEntry.GetItem(0), value);
_states.Add(new TableEntry(OneOrMany.Create(chosen), state));
RecordStepInfoForLastEntry(elapsedTime, stepInputs, overallInputState);
return true;
}
- public bool TryModifyEntries(ImmutableArray outputs, IEqualityComparer comparer, TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, EntryState overallInputState)
+ public bool TryModifyEntries(ImmutableArray outputs, TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, EntryState overallInputState)
{
// Semantics:
// For each item in the row, we compare with the new matching new value.
@@ -384,7 +384,7 @@ public bool TryModifyEntries(ImmutableArray outputs, IEqualityComparer com
var previousState = previousEntry.GetState(i);
var replacementItem = outputs[i];
- var (chosenItem, state, chosePrevious) = GetModifiedItemAndState(previousItem, replacementItem, comparer);
+ var (chosenItem, state, chosePrevious) = GetModifiedItemAndState(previousItem, replacementItem);
if (builder != null)
{
@@ -433,9 +433,9 @@ public bool TryModifyEntries(ImmutableArray outputs, IEqualityComparer com
return true;
}
- public bool TryModifyEntries(ImmutableArray outputs, IEqualityComparer comparer, TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, EntryState overallInputState, out TableEntry entry)
+ public bool TryModifyEntries(ImmutableArray outputs, TimeSpan elapsedTime, ImmutableArray<(IncrementalGeneratorRunStep InputStep, int OutputIndex)> stepInputs, EntryState overallInputState, out TableEntry entry)
{
- if (!TryModifyEntries(outputs, comparer, elapsedTime, stepInputs, overallInputState))
+ if (!TryModifyEntries(outputs, elapsedTime, stepInputs, overallInputState))
{
entry = default;
return false;
@@ -554,11 +554,11 @@ public NodeStateTable ToImmutableAndFree()
isCached: finalStates.All(static s => s.IsCached) && _previous.GetTotalEntryItemCount() == finalStates.Sum(static s => s.Count));
}
- private static (T chosen, EntryState state, bool chosePrevious) GetModifiedItemAndState(T previous, T replacement, IEqualityComparer comparer)
+ private (T chosen, EntryState state, bool chosePrevious) GetModifiedItemAndState(T previous, T replacement)
{
// when comparing an item to check if its modified we explicitly cache the *previous* item in the case where its
// considered to be equal. This ensures that subsequent comparisons are stable across future generation passes.
- return comparer.Equals(previous, replacement)
+ return _equalityComparer.Equals(previous, replacement)
? (previous, EntryState.Cached, chosePrevious: true)
: (replacement, EntryState.Modified, chosePrevious: false);
}
diff --git a/src/Compilers/Core/Portable/SourceGeneration/Nodes/PredicateSyntaxStrategy.cs b/src/Compilers/Core/Portable/SourceGeneration/Nodes/PredicateSyntaxStrategy.cs
index 540902c29ac9e..e6fc120ee48bd 100644
--- a/src/Compilers/Core/Portable/SourceGeneration/Nodes/PredicateSyntaxStrategy.cs
+++ b/src/Compilers/Core/Portable/SourceGeneration/Nodes/PredicateSyntaxStrategy.cs
@@ -30,7 +30,7 @@ internal PredicateSyntaxStrategy(
_filterFunc = filterFunc;
}
- public ISyntaxInputBuilder GetBuilder(StateTableStore table, object key, bool trackIncrementalSteps, string? name, IEqualityComparer? comparer) => new Builder(this, key, table, trackIncrementalSteps, name, comparer ?? EqualityComparer.Default);
+ public ISyntaxInputBuilder GetBuilder(StateTableStore table, object key, bool trackIncrementalSteps, string? name, IEqualityComparer comparer) => new Builder(this, key, table, trackIncrementalSteps, name, comparer);
private sealed class Builder : ISyntaxInputBuilder
{
@@ -48,7 +48,7 @@ public Builder(PredicateSyntaxStrategy owner, object key, StateTableStore tab
_name = name;
_comparer = comparer;
_key = key;
- _filterTable = table.GetStateTableOrEmpty(_owner._filterKey).ToBuilder(stepName: null, trackIncrementalSteps);
+ _filterTable = table.GetStateTableOrEmpty(_owner._filterKey).ToBuilder(stepName: null, trackIncrementalSteps, equalityComparer: Roslyn.Utilities.ReferenceEqualityComparer.Instance);
_transformTable = table.GetStateTableOrEmpty(_key).ToBuilder(_name, trackIncrementalSteps, _comparer);
}
@@ -85,7 +85,7 @@ public void VisitTree(
var stopwatch = SharedStopwatch.StartNew();
var nodes = getFilteredNodes(root.Value, _owner._filterFunc, cancellationToken);
- if (state != EntryState.Modified || !_filterTable.TryModifyEntries(nodes, Roslyn.Utilities.ReferenceEqualityComparer.Instance, stopwatch.Elapsed, noInputStepsStepInfo, state, out entry))
+ if (state != EntryState.Modified || !_filterTable.TryModifyEntries(nodes, stopwatch.Elapsed, noInputStepsStepInfo, state, out entry))
{
entry = _filterTable.AddEntries(nodes, state, stopwatch.Elapsed, noInputStepsStepInfo, state);
}
@@ -108,7 +108,7 @@ public void VisitTree(
// so we never consider the input to the transform as cached.
var transformInputState = state == EntryState.Cached ? EntryState.Modified : state;
- if (transformInputState == EntryState.Added || !_transformTable.TryModifyEntry(transformed, _comparer, stopwatch.Elapsed, noInputStepsStepInfo, transformInputState))
+ if (transformInputState == EntryState.Added || !_transformTable.TryModifyEntry(transformed, stopwatch.Elapsed, noInputStepsStepInfo, transformInputState))
{
_transformTable.AddEntry(transformed, EntryState.Added, stopwatch.Elapsed, noInputStepsStepInfo, EntryState.Added);
}
diff --git a/src/Compilers/Core/Portable/SourceGeneration/Nodes/SourceOutputNode.cs b/src/Compilers/Core/Portable/SourceGeneration/Nodes/SourceOutputNode.cs
index 79a71f0e2e17a..028a4764d3c66 100644
--- a/src/Compilers/Core/Portable/SourceGeneration/Nodes/SourceOutputNode.cs
+++ b/src/Compilers/Core/Portable/SourceGeneration/Nodes/SourceOutputNode.cs
@@ -46,12 +46,12 @@ public NodeStateTable UpdateStateTable(DriverStateTable.Builder graphSt
this.LogTables(stepName, s_tableType, previousTable, previousTable, sourceTable);
if (graphState.DriverState.TrackIncrementalSteps)
{
- return previousTable.CreateCachedTableWithUpdatedSteps(sourceTable, stepName, EqualityComparer.Default);
+ return previousTable.CreateCachedTableWithUpdatedSteps(sourceTable, stepName, equalityComparer: null);
}
return previousTable;
}
- var tableBuilder = graphState.CreateTableBuilder(previousTable, stepName, EqualityComparer.Default);
+ var tableBuilder = graphState.CreateTableBuilder(previousTable, stepName, equalityComparer: null);
foreach (var entry in sourceTable)
{
var inputs = tableBuilder.TrackIncrementalSteps ? ImmutableArray.Create((entry.Step!, entry.OutputIndex)) : default;
@@ -71,7 +71,7 @@ public NodeStateTable UpdateStateTable(DriverStateTable.Builder graphSt
_action(context, entry.Item, cancellationToken);
var sourcesAndDiagnostics = (sourcesBuilder.ToImmutable(), diagnostics.ToReadOnly());
- if (entry.State != EntryState.Modified || !tableBuilder.TryModifyEntry(sourcesAndDiagnostics, EqualityComparer.Default, stopwatch.Elapsed, inputs, entry.State))
+ if (entry.State != EntryState.Modified || !tableBuilder.TryModifyEntry(sourcesAndDiagnostics, stopwatch.Elapsed, inputs, entry.State))
{
tableBuilder.AddEntry(sourcesAndDiagnostics, EntryState.Added, stopwatch.Elapsed, inputs, EntryState.Added);
}
diff --git a/src/Compilers/Core/Portable/SourceGeneration/Nodes/SyntaxReceiverStrategy.cs b/src/Compilers/Core/Portable/SourceGeneration/Nodes/SyntaxReceiverStrategy.cs
index 63b7be100b588..d969dc80a4c90 100644
--- a/src/Compilers/Core/Portable/SourceGeneration/Nodes/SyntaxReceiverStrategy.cs
+++ b/src/Compilers/Core/Portable/SourceGeneration/Nodes/SyntaxReceiverStrategy.cs
@@ -27,7 +27,7 @@ public SyntaxReceiverStrategy(
_syntaxHelper = syntaxHelper;
}
- public ISyntaxInputBuilder GetBuilder(StateTableStore table, object key, bool trackIncrementalSteps, string? name, IEqualityComparer? comparer) => new Builder(this, key, table, trackIncrementalSteps);
+ public ISyntaxInputBuilder GetBuilder(StateTableStore table, object key, bool trackIncrementalSteps, string? name, IEqualityComparer comparer) => new Builder(this, key, table, trackIncrementalSteps);
private sealed class Builder : ISyntaxInputBuilder
{
diff --git a/src/Compilers/Core/Portable/SourceGeneration/Nodes/TransformNode.cs b/src/Compilers/Core/Portable/SourceGeneration/Nodes/TransformNode.cs
index d63edba0ce260..1ff2adb1f2640 100644
--- a/src/Compilers/Core/Portable/SourceGeneration/Nodes/TransformNode.cs
+++ b/src/Compilers/Core/Portable/SourceGeneration/Nodes/TransformNode.cs
@@ -18,7 +18,7 @@ internal sealed class TransformNode : IIncrementalGeneratorNode
private static readonly string? s_tableType = typeof(TOutput).FullName;
private readonly Func> _func;
- private readonly IEqualityComparer _comparer;
+ private readonly IEqualityComparer? _comparer;
private readonly IIncrementalGeneratorNode _sourceNode;
private readonly string? _name;
private readonly bool _wrapUserFunc;
@@ -33,7 +33,7 @@ public TransformNode(IIncrementalGeneratorNode sourceNode, Func.Default;
+ _comparer = comparer;
_name = name;
}
@@ -87,7 +87,7 @@ public NodeStateTable UpdateStateTable(DriverStateTable.Builder builder
throw new UserFunctionException(e);
}
- if (entry.State != EntryState.Modified || !tableBuilder.TryModifyEntries(newOutputs, _comparer, stopwatch.Elapsed, inputs, entry.State))
+ if (entry.State != EntryState.Modified || !tableBuilder.TryModifyEntries(newOutputs, stopwatch.Elapsed, inputs, entry.State))
{
tableBuilder.AddEntries(newOutputs, EntryState.Added, stopwatch.Elapsed, inputs, entry.State);
}
diff --git a/src/Compilers/Core/Portable/SourceGeneration/UserFunction.cs b/src/Compilers/Core/Portable/SourceGeneration/UserFunction.cs
index 6aedc61bc6130..64d1588f2955e 100644
--- a/src/Compilers/Core/Portable/SourceGeneration/UserFunction.cs
+++ b/src/Compilers/Core/Portable/SourceGeneration/UserFunction.cs
@@ -25,6 +25,8 @@ internal sealed class WrappedUserComparer : IEqualityComparer
{
private readonly IEqualityComparer _inner;
+ public static WrappedUserComparer Default { get; } = new WrappedUserComparer(EqualityComparer.Default);
+
public WrappedUserComparer(IEqualityComparer inner)
{
_inner = inner;
diff --git a/src/EditorFeatures/CSharpTest/Structure/BlockSyntaxStructureTests.cs b/src/EditorFeatures/CSharpTest/Structure/BlockSyntaxStructureTests.cs
index a6d5fc0d3b6c2..1d4feb02e239b 100644
--- a/src/EditorFeatures/CSharpTest/Structure/BlockSyntaxStructureTests.cs
+++ b/src/EditorFeatures/CSharpTest/Structure/BlockSyntaxStructureTests.cs
@@ -13,7 +13,7 @@
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure;
[Trait(Traits.Feature, Traits.Features.Outlining)]
-public class BlockSyntaxStructureTests : AbstractCSharpSyntaxNodeStructureTests
+public sealed class BlockSyntaxStructureTests : AbstractCSharpSyntaxNodeStructureTests
{
internal override AbstractSyntaxStructureProvider CreateProvider() => new BlockSyntaxStructureProvider();
@@ -464,12 +464,13 @@ public async Task LocalFunctionInTopLevelStatement_AutoCollapse()
{|hint:static void Goo(){|textspan:
{$$
- // ...
+ {|hint2:{|textspan2:// comment|}|}
}|}|}
""";
await VerifyBlockSpansAsync(code,
- Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
+ Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true),
+ Region("textspan2", "hint2", "// comment ...", autoCollapse: true));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68513")]
@@ -480,16 +481,17 @@ class C
{
void M()
{
- {|hint:static void Goo(){|textspan:
+ {|hint1:static void Goo(){|textspan1:
{$$
- // ...
+ {|hint2:{|textspan2:// comment|}|}
}|}|}
}
}
""";
await VerifyBlockSpansAsync(code,
- Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
+ Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false),
+ Region("textspan2", "hint2", "// comment ...", autoCollapse: true));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68513")]
@@ -502,7 +504,7 @@ void M()
{
{|hint:static void Goo(){|textspan:
{$$
- // ...
+ {|hint2:{|textspan2:// comment|}|}
}|}|}
}
}
@@ -511,6 +513,7 @@ void M()
await VerifyBlockSpansAsync(code, GetDefaultOptions() with
{
CollapseLocalFunctionsWhenCollapsingToDefinitions = true,
- }, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
+ }, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true),
+ Region("textspan2", "hint2", "// comment ...", autoCollapse: true));
}
}
diff --git a/src/EditorFeatures/Core.Wpf/InlineDiagnostics/AbstractDiagnosticsTaggerProvider.SingleDiagnosticKindPullTaggerProvider.cs b/src/EditorFeatures/Core.Wpf/InlineDiagnostics/AbstractDiagnosticsTaggerProvider.SingleDiagnosticKindPullTaggerProvider.cs
index e56886d8cdcad..d38f7a89b74eb 100644
--- a/src/EditorFeatures/Core.Wpf/InlineDiagnostics/AbstractDiagnosticsTaggerProvider.SingleDiagnosticKindPullTaggerProvider.cs
+++ b/src/EditorFeatures/Core.Wpf/InlineDiagnostics/AbstractDiagnosticsTaggerProvider.SingleDiagnosticKindPullTaggerProvider.cs
@@ -128,7 +128,6 @@ private async Task ProduceTagsAsync(
document,
requestedSpan.Span.ToTextSpan(),
diagnosticKind: _diagnosticKind,
- includeSuppressedDiagnostics: true,
cancellationToken: cancellationToken).ConfigureAwait(false);
// Copilot code analysis is a special analyzer that reports semantic correctness
diff --git a/src/EditorFeatures/Core.Wpf/QuickInfo/OnTheFlyDocsView.xaml.cs b/src/EditorFeatures/Core.Wpf/QuickInfo/OnTheFlyDocsView.xaml.cs
index f2ab905041903..424d1c8c775d2 100644
--- a/src/EditorFeatures/Core.Wpf/QuickInfo/OnTheFlyDocsView.xaml.cs
+++ b/src/EditorFeatures/Core.Wpf/QuickInfo/OnTheFlyDocsView.xaml.cs
@@ -3,8 +3,11 @@
// See the LICENSE file in the project root for more information.
using System;
+using System.Collections.Generic;
using System.ComponentModel;
+using System.Diagnostics;
using System.Runtime.CompilerServices;
+using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
@@ -20,6 +23,9 @@
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.PlatformUI;
+using Microsoft.VisualStudio.Shell;
+using Microsoft.VisualStudio.Shell.Interop;
+using Microsoft.VisualStudio.Telemetry;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
@@ -40,6 +46,8 @@ internal sealed partial class OnTheFlyDocsView : UserControl, INotifyPropertyCha
private readonly OnTheFlyDocsInfo _onTheFlyDocsInfo;
private readonly ContentControl _responseControl = new();
private readonly CancellationTokenSource _cancellationTokenSource = new();
+ private readonly List quotaExceededContent;
+ private readonly IServiceProvider _serviceProvider;
private OnTheFlyDocsState _currentState = OnTheFlyDocsState.OnDemandLink;
@@ -51,6 +59,11 @@ internal sealed partial class OnTheFlyDocsView : UserControl, INotifyPropertyCha
///
public event EventHandler ResultsRequested;
+ ///
+ /// Event that fires when the user requests to upgrade their Copilot plan.
+ ///
+ public event EventHandler? PlanUpgradeRequested;
+
#pragma warning disable CA1822 // Mark members as static
///
/// Used to display the "On the fly documentation" directly in the associated XAML file.
@@ -58,7 +71,9 @@ internal sealed partial class OnTheFlyDocsView : UserControl, INotifyPropertyCha
public string OnTheFlyDocumentation => EditorFeaturesResources.On_the_fly_documentation;
#pragma warning restore CA1822 // Mark members as static
- public OnTheFlyDocsView(ITextView textView, IViewElementFactoryService viewElementFactoryService, IAsynchronousOperationListenerProvider listenerProvider, IAsyncQuickInfoSession asyncQuickInfoSession, IThreadingContext threadingContext, QuickInfoOnTheFlyDocsElement onTheFlyDocsElement)
+ public OnTheFlyDocsView(ITextView textView, IViewElementFactoryService viewElementFactoryService,
+ IAsynchronousOperationListenerProvider listenerProvider, IAsyncQuickInfoSession asyncQuickInfoSession,
+ IThreadingContext threadingContext, QuickInfoOnTheFlyDocsElement onTheFlyDocsElement, IServiceProvider serviceProvider)
{
_textView = textView;
_viewElementFactoryService = viewElementFactoryService;
@@ -67,6 +82,7 @@ public OnTheFlyDocsView(ITextView textView, IViewElementFactoryService viewEleme
_threadingContext = threadingContext;
_onTheFlyDocsInfo = onTheFlyDocsElement.Info;
_document = onTheFlyDocsElement.Document;
+ _serviceProvider = serviceProvider;
var sparkle = new ImageElement(new VisualStudio.Core.Imaging.ImageId(CopilotConstants.CopilotIconMonikerGuid, CopilotConstants.CopilotIconSparkleId));
object onDemandLinkText = _onTheFlyDocsInfo.IsContentExcluded
@@ -111,6 +127,34 @@ public OnTheFlyDocsView(ITextView textView, IViewElementFactoryService viewEleme
_responseControl,
]));
+ // Locates the "upgrade now" link in the localized text, surrounded by square brackets.
+ var quotaExceededMatch = Regex.Match(
+ EditorFeaturesResources.Chat_limit_reached_upgrade_now_or_wait_for_the_limit_to_reset,
+ @"^(.*)\[(.*)\](.*)$");
+ if (quotaExceededMatch == null)
+ {
+ // The text wasn't localized correctly. Assert and fallback to showing it verbatim.
+ Debug.Fail("Copilot Hover quota exceeded message was not correctly localized.");
+ quotaExceededContent = [new ClassifiedTextRun(
+ ClassifiedTextElement.TextClassificationTypeName,
+ EditorFeaturesResources.Chat_limit_reached_upgrade_now_or_wait_for_the_limit_to_reset)];
+ }
+ else
+ {
+ quotaExceededContent = [
+ new ClassifiedTextRun(
+ ClassifiedTextElement.TextClassificationTypeName,
+ quotaExceededMatch.Groups[1].Value),
+ new ClassifiedTextRun(
+ ClassifiedTextElement.TextClassificationTypeName,
+ quotaExceededMatch.Groups[2].Value,
+ () => this.PlanUpgradeRequested?.Invoke(this, EventArgs.Empty)),
+ new ClassifiedTextRun(
+ ClassifiedTextElement.TextClassificationTypeName,
+ quotaExceededMatch.Groups[3].Value),
+ ];
+ }
+
ResultsRequested += (_, _) => PopulateAIDocumentationElements(_cancellationTokenSource.Token);
_asyncQuickInfoSession.StateChanged += (_, _) => OnQuickInfoSessionChanged();
InitializeComponent();
@@ -135,31 +179,61 @@ private async Task SetResultTextAsync(ICopilotCodeAnalysisService copilotService
try
{
- var response = await copilotService.GetOnTheFlyDocsAsync(_onTheFlyDocsInfo.SymbolSignature, _onTheFlyDocsInfo.DeclarationCode, _onTheFlyDocsInfo.Language, cancellationToken).ConfigureAwait(false);
+ var (responseString, isQuotaExceeded) = await copilotService.GetOnTheFlyDocsAsync(_onTheFlyDocsInfo.SymbolSignature, _onTheFlyDocsInfo.DeclarationCode, _onTheFlyDocsInfo.Language, cancellationToken).ConfigureAwait(false);
var copilotRequestTime = stopwatch.Elapsed;
await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
- if (response is null || response.Length == 0)
+ if (string.IsNullOrEmpty(responseString))
{
- SetResultText(EditorFeaturesResources.An_error_occurred_while_generating_documentation_for_this_code);
- CurrentState = OnTheFlyDocsState.Finished;
- Logger.Log(FunctionId.Copilot_On_The_Fly_Docs_Error_Displayed, KeyValueLogMessage.Create(m =>
+ // If the responseStatus is 8, then that means the quota has been exceeded.
+ if (isQuotaExceeded)
{
- m["ElapsedTime"] = copilotRequestTime;
- }, LogLevel.Information));
+ this.PlanUpgradeRequested += (_, _) =>
+ {
+ // GUID and command ID from
+ // https://dev.azure.com/devdiv/DevDiv/_wiki/wikis/DevDiv.wiki/45121/Free-SKU-Handling-Guidance-and-Recommendations
+ var uiShell = _serviceProvider.GetServiceOnMainThread();
+ uiShell.PostExecCommand(
+ new Guid("39B0DEDE-D931-4A92-9AA2-3447BC4998DC"),
+ 0x3901,
+ nCmdexecopt: 0,
+ pvaIn: null);
+
+ _asyncQuickInfoSession.DismissAsync();
+
+ // Telemetry to track when users reach the quota of the Copilot Free plan.
+ var telemetryEvent = new OperationEvent(
+ "vs/copilot/showcopilotfreestatus",
+ TelemetryResult.Success);
+ telemetryEvent.Properties["vs.copilot.source"] = "CSharpOnTheFlyDocs";
+ TelemetryService.DefaultSession.PostEvent(telemetryEvent);
+ };
+
+ ShowQuotaExceededResult();
+ }
+ else
+ {
+ SetResultText(EditorFeaturesResources.An_error_occurred_while_generating_documentation_for_this_code);
+ Logger.Log(FunctionId.Copilot_On_The_Fly_Docs_Error_Displayed, KeyValueLogMessage.Create(m =>
+ {
+ m["ElapsedTime"] = copilotRequestTime;
+ }, LogLevel.Information));
+ }
+
+ CurrentState = OnTheFlyDocsState.Finished;
}
else
{
- SetResultText(response);
+ SetResultText(responseString);
CurrentState = OnTheFlyDocsState.Finished;
Logger.Log(FunctionId.Copilot_On_The_Fly_Docs_Results_Displayed, KeyValueLogMessage.Create(m =>
{
m["ElapsedTime"] = copilotRequestTime;
- m["ResponseLength"] = response.Length;
+ m["ResponseLength"] = responseString.Length;
}, LogLevel.Information));
}
}
@@ -222,6 +296,15 @@ public void SetResultText(string text)
new ContainerElement(ContainerElementStyle.Wrapped, new ClassifiedTextElement([new ClassifiedTextRun(ClassificationTypeNames.Text, text)])));
}
+ ///
+ /// Shows a result message for exceeding the quota of the Copilot Free plan.
+ ///
+ public void ShowQuotaExceededResult()
+ {
+ _responseControl.Content = ToUIElement(new ContainerElement(ContainerElementStyle.Stacked,
+ [new ContainerElement(ContainerElementStyle.Wrapped, new ClassifiedTextElement(this.quotaExceededContent))]));
+ }
+
private void OnPropertyChanged(ref T member, T value, [CallerMemberName] string? name = null)
{
member = value;
diff --git a/src/EditorFeatures/Core.Wpf/QuickInfo/OnTheFlyDocsViewFactory.cs b/src/EditorFeatures/Core.Wpf/QuickInfo/OnTheFlyDocsViewFactory.cs
index 35ee7beb5349d..c0b96f3cf63ea 100644
--- a/src/EditorFeatures/Core.Wpf/QuickInfo/OnTheFlyDocsViewFactory.cs
+++ b/src/EditorFeatures/Core.Wpf/QuickInfo/OnTheFlyDocsViewFactory.cs
@@ -12,6 +12,7 @@
using Microsoft.CodeAnalysis.QuickInfo.Presentation;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Language.Intellisense;
+using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
@@ -28,15 +29,18 @@ internal sealed class OnTheFlyDocsViewFactory : IViewElementFactory
private readonly IAsynchronousOperationListenerProvider _listenerProvider;
private readonly IAsyncQuickInfoBroker _asyncQuickInfoBroker;
private readonly IThreadingContext _threadingContext;
+ private readonly IServiceProvider _serviceProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public OnTheFlyDocsViewFactory(IViewElementFactoryService factoryService, IAsynchronousOperationListenerProvider listenerProvider, IAsyncQuickInfoBroker asyncQuickInfoBroker, IThreadingContext threadingContext)
+ public OnTheFlyDocsViewFactory(IViewElementFactoryService factoryService, IAsynchronousOperationListenerProvider listenerProvider,
+ IAsyncQuickInfoBroker asyncQuickInfoBroker, IThreadingContext threadingContext, SVsServiceProvider serviceProvider)
{
_factoryService = factoryService;
_listenerProvider = listenerProvider;
_asyncQuickInfoBroker = asyncQuickInfoBroker;
_threadingContext = threadingContext;
+ _serviceProvider = serviceProvider;
}
public TView? CreateViewElement(ITextView textView, object model) where TView : class
@@ -64,6 +68,6 @@ public OnTheFlyDocsViewFactory(IViewElementFactoryService factoryService, IAsync
OnTheFlyDocsLogger.LogShowedOnTheFlyDocsLinkWithDocComments();
}
- return new OnTheFlyDocsView(textView, _factoryService, _listenerProvider, quickInfoSession, _threadingContext, onTheFlyDocsElement) as TView;
+ return new OnTheFlyDocsView(textView, _factoryService, _listenerProvider, quickInfoSession, _threadingContext, onTheFlyDocsElement, _serviceProvider) as TView;
}
}
diff --git a/src/EditorFeatures/Core/EditAndContinue/EditAndContinueLanguageService.cs b/src/EditorFeatures/Core/EditAndContinue/EditAndContinueLanguageService.cs
index c4d3dd98990c0..74948a69c5ad0 100644
--- a/src/EditorFeatures/Core/EditAndContinue/EditAndContinueLanguageService.cs
+++ b/src/EditorFeatures/Core/EditAndContinue/EditAndContinueLanguageService.cs
@@ -9,14 +9,12 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.BrokeredServices;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Debugger.Contracts.HotReload;
using Roslyn.Utilities;
@@ -31,13 +29,12 @@ namespace Microsoft.CodeAnalysis.EditAndContinue;
[method: ImportingConstructor]
[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
internal sealed class EditAndContinueLanguageService(
- IServiceBrokerProvider serviceBrokerProvider,
EditAndContinueSessionState sessionState,
Lazy workspaceProvider,
Lazy debuggerService,
PdbMatchingSourceTextProvider sourceTextProvider,
- IDiagnosticsRefresher diagnosticRefresher,
- IAsynchronousOperationListenerProvider listenerProvider) : IManagedHotReloadLanguageService2, IEditAndContinueSolutionProvider
+ IEditAndContinueLogReporter logReporter,
+ IDiagnosticsRefresher diagnosticRefresher) : IManagedHotReloadLanguageService2, IEditAndContinueSolutionProvider
{
private sealed class NoSessionException : InvalidOperationException
{
@@ -49,9 +46,6 @@ public NoSessionException()
}
}
- private readonly IAsynchronousOperationListener _asyncListener = listenerProvider.GetListener(FeatureAttribute.EditAndContinue);
- private readonly HotReloadLoggerProxy _logger = new(serviceBrokerProvider.ServiceBroker);
-
private bool _disabled;
private RemoteDebuggingSessionProxy? _debuggingSession;
@@ -94,11 +88,7 @@ private IActiveStatementTrackingService GetActiveStatementTrackingService()
internal void Disable(Exception e)
{
_disabled = true;
-
- var token = _asyncListener.BeginAsyncOperation(nameof(EditAndContinueLanguageService) + ".LogToOutput");
-
- _ = _logger.LogAsync(new HotReloadLogMessage(HotReloadVerbosity.Diagnostic, e.ToString(), errorLevel: HotReloadDiagnosticErrorLevel.Error), CancellationToken.None).AsTask()
- .ReportNonFatalErrorAsync().CompletesAsyncOperation(token);
+ logReporter.Report(e.ToString(), LogMessageSeverity.Error);
}
private void UpdateApplyChangesDiagnostics(ImmutableArray diagnostics)
@@ -265,7 +255,7 @@ public async ValueTask UpdateBaselinesAsync(ImmutableArray projectPaths,
}
_committedDesignTimeSolution = currentDesignTimeSolution;
- var projectIds = await GetProjectIdsAsync(projectPaths, currentCompileTimeSolution, cancellationToken).ConfigureAwait(false);
+ var projectIds = GetProjectIds(projectPaths, currentCompileTimeSolution);
try
{
@@ -281,7 +271,7 @@ public async ValueTask UpdateBaselinesAsync(ImmutableArray projectPaths,
}
}
- private async ValueTask> GetProjectIdsAsync(ImmutableArray projectPaths, Solution solution, CancellationToken cancellationToken)
+ private ImmutableArray GetProjectIds(ImmutableArray projectPaths, Solution solution)
{
using var _ = ArrayBuilder.GetInstance(out var projectIds);
foreach (var path in projectPaths)
@@ -293,11 +283,7 @@ private async ValueTask> GetProjectIdsAsync(ImmutableA
}
else
{
- await _logger.LogAsync(new HotReloadLogMessage(
- HotReloadVerbosity.Diagnostic,
- $"Project with path '{path}' not found in the current solution.",
- errorLevel: HotReloadDiagnosticErrorLevel.Warning),
- cancellationToken).ConfigureAwait(false);
+ logReporter.Report($"Project with path '{path}' not found in the current solution.", LogMessageSeverity.Info);
}
}
diff --git a/src/EditorFeatures/Core/EditorFeaturesResources.resx b/src/EditorFeatures/Core/EditorFeaturesResources.resx
index 0d2ddf466abbc..42d5a9f806b9d 100644
--- a/src/EditorFeatures/Core/EditorFeaturesResources.resx
+++ b/src/EditorFeatures/Core/EditorFeaturesResources.resx
@@ -950,4 +950,8 @@ Do you want to proceed?
'Describe with Copilot' is unavailable since the referenced document is excluded by your organization.
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
\ No newline at end of file
diff --git a/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj b/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj
index 0d1bf87e852d7..2ffdb061e7ab2 100644
--- a/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj
+++ b/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj
@@ -36,6 +36,8 @@
+
+
diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.cs.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.cs.xlf
index deadfb68a2575..cda4910f11c0d 100644
--- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.cs.xlf
+++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.cs.xlf
@@ -17,6 +17,11 @@
Aplikují se změny.
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
Computing 'Encapsulate Field' information
Výpočet informací Encapsulate Field
diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.de.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.de.xlf
index 7c5542620b5d3..223527ee2ae83 100644
--- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.de.xlf
+++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.de.xlf
@@ -17,6 +17,11 @@
Änderungen werden übernommen
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
Computing 'Encapsulate Field' information
Berechnen von "Kapselungsfeld"-Informationen
diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.es.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.es.xlf
index 7def27cefa87b..8f96fcc9c21d7 100644
--- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.es.xlf
+++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.es.xlf
@@ -17,6 +17,11 @@
Aplicando cambios
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
Computing 'Encapsulate Field' information
Calculando información de "Encapsular campo"
diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.fr.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.fr.xlf
index 77e83a00bb46b..cd4dc9731af30 100644
--- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.fr.xlf
+++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.fr.xlf
@@ -17,6 +17,11 @@
Application des changements
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
Computing 'Encapsulate Field' information
Calcul des informations « Encapsuler le champ »
diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.it.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.it.xlf
index 494d58240b5f9..264651a81a1d2 100644
--- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.it.xlf
+++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.it.xlf
@@ -17,6 +17,11 @@
Applicazione delle modifiche in corso
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
Computing 'Encapsulate Field' information
Calcolo delle informazioni su 'Incapsula campo'
diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ja.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ja.xlf
index 173a32b73c844..162b9ff3a5da9 100644
--- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ja.xlf
+++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ja.xlf
@@ -17,6 +17,11 @@
変更の適用
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
Computing 'Encapsulate Field' information
'フィールドのカプセル化' 情報を計算中
diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ko.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ko.xlf
index 6af82a2e1d86a..967a8c3d65f76 100644
--- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ko.xlf
+++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ko.xlf
@@ -17,6 +17,11 @@
변경 내용 적용
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
Computing 'Encapsulate Field' information
'Encapsulate Field' 정보 계산
diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pl.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pl.xlf
index db20f5ea0e5ab..13c31e460e558 100644
--- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pl.xlf
+++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pl.xlf
@@ -17,6 +17,11 @@
Stosowanie zmian
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
Computing 'Encapsulate Field' information
Obliczanie informacji „Hermetyzuj pole”
diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pt-BR.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pt-BR.xlf
index 3106e84c43329..f0b76297e818e 100644
--- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pt-BR.xlf
+++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pt-BR.xlf
@@ -17,6 +17,11 @@
Aplicando mudanças
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
Computing 'Encapsulate Field' information
Computando informações de 'Encapsular Campo'
diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ru.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ru.xlf
index 159f84ac42a3b..882882e284155 100644
--- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ru.xlf
+++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ru.xlf
@@ -17,6 +17,11 @@
Применение изменений
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
Computing 'Encapsulate Field' information
Вычисление сведений "Инкапсуляция поля"
diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.tr.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.tr.xlf
index 98f893e21b5cc..6aff6dc59e379 100644
--- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.tr.xlf
+++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.tr.xlf
@@ -17,6 +17,11 @@
Değişiklikler uygulanıyor
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
Computing 'Encapsulate Field' information
'Alanı Kapsülle' bilgileri hesaplanıyor
diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hans.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hans.xlf
index e626b6675a912..0bed7187047f0 100644
--- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hans.xlf
+++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hans.xlf
@@ -17,6 +17,11 @@
应用更改
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
Computing 'Encapsulate Field' information
计算“封装字段”信息
diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hant.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hant.xlf
index 3ef849680bea5..7daf637ef2194 100644
--- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hant.xlf
+++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hant.xlf
@@ -17,6 +17,11 @@
正在套用變更
+
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ Chat limit reached, [upgrade now] or wait for the limit to reset.
+ The text surrounded by "[" and "]" characters will be hyperlinked. Please ensure the localized text still has "[" and "]" characters.
+
Computing 'Encapsulate Field' information
正在計算 [封裝欄位] 資訊
diff --git a/src/EditorFeatures/ExternalAccess/Copilot/Analyzer/IExternalCSharpCopilotCodeAnalysisService.cs b/src/EditorFeatures/ExternalAccess/Copilot/Analyzer/IExternalCSharpCopilotCodeAnalysisService.cs
index 3a8485c1f14b2..1a0fed9bd383b 100644
--- a/src/EditorFeatures/ExternalAccess/Copilot/Analyzer/IExternalCSharpCopilotCodeAnalysisService.cs
+++ b/src/EditorFeatures/ExternalAccess/Copilot/Analyzer/IExternalCSharpCopilotCodeAnalysisService.cs
@@ -18,6 +18,6 @@ internal interface IExternalCSharpCopilotCodeAnalysisService
Task> AnalyzeDocumentAsync(Document document, TextSpan? span, string promptTitle, CancellationToken cancellationToken);
Task> GetCachedDiagnosticsAsync(Document document, string promptTitle, CancellationToken cancellationToken);
Task StartRefinementSessionAsync(Document oldDocument, Document newDocument, Diagnostic? primaryDiagnostic, CancellationToken cancellationToken);
- Task GetOnTheFlyDocsAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken);
+ Task<(string responseString, bool isQuotaExceeded)> GetOnTheFlyDocsAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken);
Task IsFileExcludedAsync(string filePath, CancellationToken cancellationToken);
}
diff --git a/src/EditorFeatures/ExternalAccess/Copilot/Internal/Analyzer/AbstractCopilotCodeAnalysisService.cs b/src/EditorFeatures/ExternalAccess/Copilot/Internal/Analyzer/AbstractCopilotCodeAnalysisService.cs
index 1c0353b079b42..a75f5e8f6f026 100644
--- a/src/EditorFeatures/ExternalAccess/Copilot/Internal/Analyzer/AbstractCopilotCodeAnalysisService.cs
+++ b/src/EditorFeatures/ExternalAccess/Copilot/Internal/Analyzer/AbstractCopilotCodeAnalysisService.cs
@@ -39,7 +39,7 @@ internal abstract class AbstractCopilotCodeAnalysisService(IDiagnosticsRefresher
protected abstract Task> AnalyzeDocumentCoreAsync(Document document, TextSpan? span, string promptTitle, CancellationToken cancellationToken);
protected abstract Task> GetCachedDiagnosticsCoreAsync(Document document, string promptTitle, CancellationToken cancellationToken);
protected abstract Task StartRefinementSessionCoreAsync(Document oldDocument, Document newDocument, Diagnostic? primaryDiagnostic, CancellationToken cancellationToken);
- protected abstract Task GetOnTheFlyDocsCoreAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken);
+ protected abstract Task<(string responseString, bool isQuotaExceeded)> GetOnTheFlyDocsCoreAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken);
protected abstract Task IsFileExcludedCoreAsync(string filePath, CancellationToken cancellationToken);
public Task IsAvailableAsync(CancellationToken cancellationToken)
@@ -173,10 +173,10 @@ public async Task StartRefinementSessionAsync(Document oldDocument, Document new
await StartRefinementSessionCoreAsync(oldDocument, newDocument, primaryDiagnostic, cancellationToken).ConfigureAwait(false);
}
- public async Task GetOnTheFlyDocsAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken)
+ public async Task<(string responseString, bool isQuotaExceeded)> GetOnTheFlyDocsAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken)
{
if (!await IsAvailableAsync(cancellationToken).ConfigureAwait(false))
- return string.Empty;
+ return (string.Empty, false);
return await GetOnTheFlyDocsCoreAsync(symbolSignature, declarationCode, language, cancellationToken).ConfigureAwait(false);
}
diff --git a/src/EditorFeatures/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.ReflectionWrapper.cs b/src/EditorFeatures/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.ReflectionWrapper.cs
index 7b3b41c63c1c6..6f33ec3b27cf8 100644
--- a/src/EditorFeatures/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.ReflectionWrapper.cs
+++ b/src/EditorFeatures/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.ReflectionWrapper.cs
@@ -19,7 +19,7 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.Copilot.Internal.Analyzer.CSharp
using GetCachedDiagnosticsAsyncDelegateType = Func>>;
using IsAvailableAsyncDelegateType = Func>;
using StartRefinementSessionAsyncDelegateType = Func;
-using GetOnTheFlyDocsAsyncDelegateType = Func, string, CancellationToken, Task>;
+using GetOnTheFlyDocsAsyncDelegateType = Func, string, CancellationToken, Task<(string responseString, bool isQuotaExceeded)>>;
using IsAnyExclusionAsyncDelegateType = Func>;
using IsFileExcludedAsyncDelegateType = Func>;
@@ -159,10 +159,10 @@ public Task StartRefinementSessionAsync(Document oldDocument, Document newDocume
return _lazyStartRefinementSessionAsyncDelegate.Value(oldDocument, newDocument, primaryDiagnostic, cancellationToken);
}
- public async Task GetOnTheFlyDocsAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken)
+ public async Task<(string responseString, bool isQuotaExceeded)> GetOnTheFlyDocsAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken)
{
if (_lazyGetOnTheFlyDocsAsyncDelegate.Value is null)
- return string.Empty;
+ return (string.Empty, false);
return await _lazyGetOnTheFlyDocsAsyncDelegate.Value(symbolSignature, declarationCode, language, cancellationToken).ConfigureAwait(false);
}
diff --git a/src/EditorFeatures/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.cs b/src/EditorFeatures/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.cs
index 317a234a68c11..8d5a5a91088af 100644
--- a/src/EditorFeatures/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.cs
+++ b/src/EditorFeatures/ExternalAccess/Copilot/Internal/Analyzer/CSharp/CSharpCopilotCodeAnalysisService.cs
@@ -57,7 +57,7 @@ protected override Task IsAvailableCoreAsync(CancellationToken cancellatio
protected override Task StartRefinementSessionCoreAsync(Document oldDocument, Document newDocument, Diagnostic? primaryDiagnostic, CancellationToken cancellationToken)
=> _lazyExternalCopilotService.Value.StartRefinementSessionAsync(oldDocument, newDocument, primaryDiagnostic, cancellationToken);
- protected override Task GetOnTheFlyDocsCoreAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken)
+ protected override Task<(string responseString, bool isQuotaExceeded)> GetOnTheFlyDocsCoreAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken)
=> _lazyExternalCopilotService.Value.GetOnTheFlyDocsAsync(symbolSignature, declarationCode, language, cancellationToken);
protected override async Task> GetDiagnosticsIntersectWithSpanAsync(
diff --git a/src/EditorFeatures/ExternalAccess/Copilot/InternalAPI.Unshipped.txt b/src/EditorFeatures/ExternalAccess/Copilot/InternalAPI.Unshipped.txt
index 9f06d5d62b1b3..546acd188e8fa 100644
--- a/src/EditorFeatures/ExternalAccess/Copilot/InternalAPI.Unshipped.txt
+++ b/src/EditorFeatures/ExternalAccess/Copilot/InternalAPI.Unshipped.txt
@@ -8,7 +8,7 @@ Microsoft.CodeAnalysis.ExternalAccess.Copilot.IExternalCSharpCopilotCodeAnalysis
Microsoft.CodeAnalysis.ExternalAccess.Copilot.IExternalCSharpCopilotCodeAnalysisService.AnalyzeDocumentAsync(Microsoft.CodeAnalysis.Document! document, Microsoft.CodeAnalysis.Text.TextSpan? span, string! promptTitle, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task>!
Microsoft.CodeAnalysis.ExternalAccess.Copilot.IExternalCSharpCopilotCodeAnalysisService.GetAvailablePromptTitlesAsync(Microsoft.CodeAnalysis.Document! document, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task>!
Microsoft.CodeAnalysis.ExternalAccess.Copilot.IExternalCSharpCopilotCodeAnalysisService.GetCachedDiagnosticsAsync(Microsoft.CodeAnalysis.Document! document, string! promptTitle, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task>!
-Microsoft.CodeAnalysis.ExternalAccess.Copilot.IExternalCSharpCopilotCodeAnalysisService.GetOnTheFlyDocsAsync(string! symbolSignature, System.Collections.Immutable.ImmutableArray declarationCode, string! language, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task!
+Microsoft.CodeAnalysis.ExternalAccess.Copilot.IExternalCSharpCopilotCodeAnalysisService.GetOnTheFlyDocsAsync(string! symbolSignature, System.Collections.Immutable.ImmutableArray declarationCode, string! language, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<(string! responseString, bool isQuotaExceeded)>!
Microsoft.CodeAnalysis.ExternalAccess.Copilot.IExternalCSharpCopilotCodeAnalysisService.IsAvailableAsync(System.Threading.CancellationToken cancellation) -> System.Threading.Tasks.Task!
Microsoft.CodeAnalysis.ExternalAccess.Copilot.IExternalCSharpCopilotCodeAnalysisService.IsFileExcludedAsync(string! filePath, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task!
Microsoft.CodeAnalysis.ExternalAccess.Copilot.IExternalCSharpCopilotCodeAnalysisService.StartRefinementSessionAsync(Microsoft.CodeAnalysis.Document! oldDocument, Microsoft.CodeAnalysis.Document! newDocument, Microsoft.CodeAnalysis.Diagnostic? primaryDiagnostic, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task!
diff --git a/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs b/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs
index 5d9394ee00cb2..1b777a72a585c 100644
--- a/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs
+++ b/src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs
@@ -1078,7 +1078,7 @@ void M()
await diagnosticIncrementalAnalyzer.GetDiagnosticsForIdsAsync(
sourceDocument.Project.Solution, sourceDocument.Project.Id, sourceDocument.Id, diagnosticIds: null, shouldIncludeAnalyzer: null, getDocuments: null,
- includeSuppressedDiagnostics: true, includeLocalDocumentDiagnostics: true, includeNonLocalDocumentDiagnostics: true, CancellationToken.None);
+ includeLocalDocumentDiagnostics: true, includeNonLocalDocumentDiagnostics: true, CancellationToken.None);
await diagnosticIncrementalAnalyzer.GetTestAccessor().TextDocumentOpenAsync(sourceDocument);
var lowPriorityAnalyzerData = new SuggestedActionPriorityProvider.LowPriorityAnalyzersAndDiagnosticIds();
@@ -1142,7 +1142,9 @@ static bool GetExpectDeprioritization(
static async Task VerifyCachedDiagnosticsAsync(Document sourceDocument, bool expectedCachedDiagnostic, TextSpan testSpan, DiagnosticIncrementalAnalyzer diagnosticIncrementalAnalyzer)
{
var cachedDiagnostics = await diagnosticIncrementalAnalyzer.GetCachedDiagnosticsAsync(sourceDocument.Project.Solution, sourceDocument.Project.Id, sourceDocument.Id,
- includeSuppressedDiagnostics: false, includeLocalDocumentDiagnostics: true, includeNonLocalDocumentDiagnostics: true, CancellationToken.None);
+ includeLocalDocumentDiagnostics: true, includeNonLocalDocumentDiagnostics: true, CancellationToken.None);
+ cachedDiagnostics = cachedDiagnostics.WhereAsArray(d => !d.IsSuppressed);
+
if (!expectedCachedDiagnostic)
{
Assert.Empty(cachedDiagnostics);
diff --git a/src/EditorFeatures/Test/Collections/Immutable/Maps/MapTests.cs b/src/EditorFeatures/Test/Collections/Immutable/Maps/MapTests.cs
index 94f2d5822f574..11a1d52fdbfd1 100644
--- a/src/EditorFeatures/Test/Collections/Immutable/Maps/MapTests.cs
+++ b/src/EditorFeatures/Test/Collections/Immutable/Maps/MapTests.cs
@@ -76,7 +76,7 @@ public void TestRemove()
Assert.Equal(1, map.Count);
map = map.Remove("5");
- Assert.Equal(0, map.Count);
+ Assert.Empty(map);
}
[Fact]
@@ -116,7 +116,7 @@ public void TestPathology()
Assert.Equal(1, map.Count);
map = map.Remove("5");
- Assert.Equal(0, map.Count);
+ Assert.Empty(map);
}
private class PathologicalComparer : IEqualityComparer
diff --git a/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs b/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs
index 204f0c4473ba7..000c997aa4adf 100644
--- a/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs
+++ b/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs
@@ -69,7 +69,7 @@ public async Task TestHasSuccessfullyLoadedBeingFalse()
var diagnostics = await analyzer.GetDiagnosticsForIdsAsync(
workspace.CurrentSolution, projectId: null, documentId: null, diagnosticIds: null, shouldIncludeAnalyzer: null, getDocuments: null,
- includeSuppressedDiagnostics: false, includeLocalDocumentDiagnostics: true, includeNonLocalDocumentDiagnostics: false, CancellationToken.None);
+ includeLocalDocumentDiagnostics: true, includeNonLocalDocumentDiagnostics: false, CancellationToken.None);
Assert.NotEmpty(diagnostics);
}
@@ -705,7 +705,7 @@ internal async Task TestOnlyRequiredAnalyzerExecutedDuringDiagnosticComputation(
var diagnosticsMapResults = await DiagnosticComputer.GetDiagnosticsAsync(
document, project, Checksum.Null, span: null, projectAnalyzerIds: [], analyzerIdsToRequestDiagnostics,
AnalysisKind.Semantic, new DiagnosticAnalyzerInfoCache(), workspace.Services,
- isExplicit: false, reportSuppressedDiagnostics: false, logPerformanceInfo: false, getTelemetryInfo: false,
+ isExplicit: false, logPerformanceInfo: false, getTelemetryInfo: false,
cancellationToken: CancellationToken.None);
Assert.False(analyzer2.ReceivedSymbolCallback);
@@ -773,7 +773,7 @@ async Task VerifyCallbackSpanAsync(TextSpan? filterSpan)
_ = await DiagnosticComputer.GetDiagnosticsAsync(
documentToAnalyze, project, Checksum.Null, filterSpan, analyzerIdsToRequestDiagnostics, hostAnalyzerIds: [],
analysisKind, new DiagnosticAnalyzerInfoCache(), workspace.Services,
- isExplicit: false, reportSuppressedDiagnostics: false, logPerformanceInfo: false, getTelemetryInfo: false,
+ isExplicit: false, logPerformanceInfo: false, getTelemetryInfo: false,
CancellationToken.None);
Assert.Equal(filterSpan, analyzer.CallbackFilterSpan);
if (kind == FilterSpanTestAnalyzer.AnalysisKind.AdditionalFile)
@@ -827,7 +827,7 @@ void M()
try
{
_ = await DiagnosticComputer.GetDiagnosticsAsync(document, project, Checksum.Null, span: null,
- projectAnalyzerIds: [], analyzerIds, kind, diagnosticAnalyzerInfoCache, workspace.Services, isExplicit: false, reportSuppressedDiagnostics: false,
+ projectAnalyzerIds: [], analyzerIds, kind, diagnosticAnalyzerInfoCache, workspace.Services, isExplicit: false,
logPerformanceInfo: false, getTelemetryInfo: false, cancellationToken: analyzer.CancellationToken);
throw ExceptionUtilities.Unreachable();
@@ -840,7 +840,7 @@ void M()
// Then invoke analysis without cancellation token, and verify non-cancelled diagnostic.
var diagnosticsMap = await DiagnosticComputer.GetDiagnosticsAsync(document, project, Checksum.Null, span: null,
- projectAnalyzerIds: [], analyzerIds, kind, diagnosticAnalyzerInfoCache, workspace.Services, isExplicit: false, reportSuppressedDiagnostics: false,
+ projectAnalyzerIds: [], analyzerIds, kind, diagnosticAnalyzerInfoCache, workspace.Services, isExplicit: false,
logPerformanceInfo: false, getTelemetryInfo: false, cancellationToken: CancellationToken.None);
var builder = diagnosticsMap.Diagnostics.Single().diagnosticMap;
var diagnostic = kind == AnalysisKind.Syntax ? builder.Syntax.Single().Item2.Single() : builder.Semantic.Single().Item2.Single();
diff --git a/src/EditorFeatures/Test/Extensions/CollectionExtensionsTest.cs b/src/EditorFeatures/Test/Extensions/CollectionExtensionsTest.cs
index cc184d27aaac6..6a4dfe5942975 100644
--- a/src/EditorFeatures/Test/Extensions/CollectionExtensionsTest.cs
+++ b/src/EditorFeatures/Test/Extensions/CollectionExtensionsTest.cs
@@ -21,7 +21,7 @@ public void PushReverse1()
Assert.Equal(1, stack.Pop());
Assert.Equal(2, stack.Pop());
Assert.Equal(3, stack.Pop());
- Assert.Equal(0, stack.Count);
+ Assert.Empty(stack);
}
[Fact]
@@ -29,7 +29,7 @@ public void PushReverse2()
{
var stack = new Stack();
stack.PushReverse(Array.Empty());
- Assert.Equal(0, stack.Count);
+ Assert.Empty(stack);
}
[Fact]
@@ -41,6 +41,6 @@ public void PushReverse3()
Assert.Equal(1, stack.Pop());
Assert.Equal(2, stack.Pop());
Assert.Equal(3, stack.Pop());
- Assert.Equal(0, stack.Count);
+ Assert.Empty(stack);
}
}
diff --git a/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.cs b/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.cs
index d0686f539086b..8e00e418bd095 100644
--- a/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.cs
+++ b/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.cs
@@ -104,7 +104,7 @@ public async Task GenerateSourceAsync(
// Get an ISymbol corresponding to the metadata name
var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None);
var diagnostics = compilation.GetDiagnostics().ToArray();
- Assert.Equal(0, diagnostics.Length);
+ Assert.Empty(diagnostics);
var symbol = await ResolveSymbolAsync(symbolMetadataName, compilation);
Contract.ThrowIfNull(symbol);
@@ -172,7 +172,7 @@ public void Dispose()
{
compilation = await this.DefaultProject.GetRequiredCompilationAsync(CancellationToken.None);
var diagnostics = compilation.GetDiagnostics().ToArray();
- Assert.Equal(0, diagnostics.Length);
+ Assert.Empty(diagnostics);
}
foreach (var reference in compilation.References)
diff --git a/src/EditorFeatures/Test2/CodeFixes/CodeFixServiceTests.vb b/src/EditorFeatures/Test2/CodeFixes/CodeFixServiceTests.vb
index 5b996eecaa62c..f2daa492cf9c6 100644
--- a/src/EditorFeatures/Test2/CodeFixes/CodeFixServiceTests.vb
+++ b/src/EditorFeatures/Test2/CodeFixes/CodeFixServiceTests.vb
@@ -68,7 +68,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.CodeFixes.UnitTests
' Verify available diagnostics
Dim document = project.Documents.Single()
Dim diagnostics = Await diagnosticService.GetDiagnosticsForSpanAsync(document,
- range:=(Await document.GetSyntaxRootAsync()).FullSpan, DiagnosticKind.All, includeSuppressedDiagnostics:=False, CancellationToken.None)
+ range:=(Await document.GetSyntaxRootAsync()).FullSpan, DiagnosticKind.All, CancellationToken.None)
Assert.Equal(1, diagnostics.Length)
@@ -78,7 +78,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.CodeFixes.UnitTests
(Await document.GetSyntaxRootAsync()).FullSpan,
CancellationToken.None)
- Assert.Equal(0, fixes.Length)
+ Assert.Empty(fixes)
' Verify available codefix with a global fixer + a project fixer
' We will use this assembly as a project fixer provider.
@@ -102,7 +102,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.CodeFixes.UnitTests
(Await document.GetSyntaxRootAsync()).FullSpan,
CancellationToken.None)
- Assert.Equal(0, fixes.Length)
+ Assert.Empty(fixes)
End Using
End Function
@@ -140,7 +140,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.CodeFixes.UnitTests
' Verify available diagnostics
Dim document = project.Documents.Single()
Dim diagnostics = Await diagnosticService.GetDiagnosticsForSpanAsync(document,
- range:=(Await document.GetSyntaxRootAsync()).FullSpan, DiagnosticKind.All, includeSuppressedDiagnostics:=False, CancellationToken.None)
+ range:=(Await document.GetSyntaxRootAsync()).FullSpan, DiagnosticKind.All, CancellationToken.None)
Assert.Equal(1, diagnostics.Length)
@@ -150,7 +150,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.CodeFixes.UnitTests
(Await document.GetSyntaxRootAsync()).FullSpan,
CancellationToken.None)
- Assert.Equal(0, fixes.Length)
+ Assert.Empty(fixes)
' Verify no codefix with a global fixer + a project fixer
' We will use this assembly as a project fixer provider.
@@ -165,7 +165,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.CodeFixes.UnitTests
(Await document.GetSyntaxRootAsync()).FullSpan,
CancellationToken.None)
- Assert.Equal(0, fixes.Length)
+ Assert.Empty(fixes)
End Using
End Function
@@ -351,8 +351,8 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.CodeFixes.UnitTests
Return Task.CompletedTask
End Function
- Public Function GetOnTheFlyDocsAsync(symbolSignature As String, declarationCode As ImmutableArray(Of String), language As String, cancellationToken As CancellationToken) As Task(Of String) Implements ICopilotCodeAnalysisService.GetOnTheFlyDocsAsync
- Return Task.FromResult("")
+ Public Function GetOnTheFlyDocsAsync(symbolSignature As String, declarationCode As ImmutableArray(Of String), language As String, cancellationToken As CancellationToken) As Task(Of (responseString As String, isQuotaExceeded As Boolean)) Implements ICopilotCodeAnalysisService.GetOnTheFlyDocsAsync
+ Return Task.FromResult(("", False))
End Function
Public Function IsFileExcludedAsync(filePath As String, cancellationToken As CancellationToken) As Task(Of Boolean) Implements ICopilotCodeAnalysisService.IsFileExcludedAsync
diff --git a/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb b/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb
index 088b930be272f..6f7c36018d869 100644
--- a/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb
+++ b/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb
@@ -263,10 +263,10 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests
Dim diagnosticProvider = GetDiagnosticProvider(workspace)
Dim actualDiagnostics = diagnosticProvider.GetDiagnosticsForIdsAsync(
workspace.CurrentSolution, projectId:=Nothing, documentId:=Nothing, diagnosticIds:=Nothing, shouldIncludeAnalyzer:=Nothing,
- includeSuppressedDiagnostics:=False, includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None).Result
+ includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None).Result
If diagnostics Is Nothing Then
- Assert.Equal(0, actualDiagnostics.Length)
+ Assert.Empty(actualDiagnostics)
Else
Dim expectedDiagnostics = GetExpectedDiagnostics(workspace, diagnostics)
diff --git a/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb b/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb
index 3a9f4c2a0ec60..aa4ecdbe70240 100644
--- a/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb
+++ b/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb
@@ -7,17 +7,12 @@ Imports System.IO
Imports System.Reflection
Imports System.Threading
Imports Microsoft.CodeAnalysis
-Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers
Imports Microsoft.CodeAnalysis.CSharp
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Diagnostics.CSharp
Imports Microsoft.CodeAnalysis.Editor.UnitTests
-Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
-Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Host.Mef
-Imports Microsoft.CodeAnalysis.Options
-Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.SolutionCrawler
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.UnitTests.Diagnostics
@@ -65,7 +60,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests
End Function
Private Shared Async Function GetDiagnosticsForSpanAsync(diagnosticService As IDiagnosticAnalyzerService, document As Document, range As TextSpan, diagnosticKind As DiagnosticKind) As Task(Of ImmutableArray(Of DiagnosticData))
- Return Await diagnosticService.GetDiagnosticsForSpanAsync(document, range, diagnosticKind, includeSuppressedDiagnostics:=False, CancellationToken.None)
+ Return Await diagnosticService.GetDiagnosticsForSpanAsync(document, range, diagnosticKind, CancellationToken.None)
End Function
@@ -300,7 +295,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests
project = project.WithCompilationOptions(newCompilationOptions)
document = project.Documents.Single()
diagnostics = Await GetDiagnosticsForSpanAsync(diagnosticService, document, span)
- Assert.Equal(0, diagnostics.Length)
+ Assert.Empty(diagnostics)
Dim changeSeverityDiagOptions = New Dictionary(Of String, ReportDiagnostic)
changeSeverityDiagOptions.Add(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, ReportDiagnostic.Error)
@@ -350,7 +345,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests
Dim hostAnalyzers = solution.SolutionState.Analyzers
Dim workspaceDescriptors = hostAnalyzers.GetDiagnosticDescriptorsPerReference(diagnosticService.AnalyzerInfoCache)
- Assert.Equal(0, workspaceDescriptors.Count)
+ Assert.Empty(workspaceDescriptors)
Dim descriptors1 = hostAnalyzers.GetDiagnosticDescriptorsPerReference(diagnosticService.AnalyzerInfoCache, p1)
Assert.Equal("XX0001", descriptors1.Single().Value.Single().Id)
@@ -494,14 +489,14 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests
Dim descriptorsMap = solution.SolutionState.Analyzers.GetDiagnosticDescriptorsPerReference(diagnosticService.AnalyzerInfoCache, project)
Assert.Equal(1, descriptorsMap.Count)
Dim descriptors = descriptorsMap.First().Value
- Assert.Equal(0, descriptors.Length)
+ Assert.Empty(descriptors)
Dim document = project.Documents.Single()
Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace)
Dim diagnostics = Await GetDiagnosticsForDocumentAsync(diagnosticService, document)
- Assert.Equal(0, diagnostics.Length)
+ Assert.Empty(diagnostics)
End Using
End Function
@@ -534,11 +529,11 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests
Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace)
Dim root = Await document.GetSyntaxRootAsync().ConfigureAwait(False)
Dim diagnostics = Await GetDiagnosticsForSpanAsync(diagnosticService, document, root.FullSpan)
- Assert.Equal(0, diagnostics.Length)
+ Assert.Empty(diagnostics)
diagnostics = Await diagnosticService.GetDiagnosticsForIdsAsync(
project.Solution, projectId:=Nothing, documentId:=Nothing, diagnosticIds:=Nothing, shouldIncludeAnalyzer:=Nothing,
- includeSuppressedDiagnostics:=False, includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)
+ includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)
Dim diagnostic = diagnostics.First()
Assert.True(diagnostic.Id = "AD0001")
Assert.Contains("CodeBlockStartedAnalyzer", diagnostic.Message, StringComparison.Ordinal)
@@ -609,7 +604,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests
Dim document = project.Documents.Single()
Dim diagnostics = Await diagnosticService.GetDiagnosticsForIdsAsync(
project.Solution, project.Id, documentId:=Nothing, diagnosticIds:=Nothing, shouldIncludeAnalyzer:=Nothing,
- includeSuppressedDiagnostics:=False, includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)
+ includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)
Assert.Equal(1, diagnostics.Length)
Dim diagnostic = diagnostics.First()
Assert.Equal(OperationAnalyzer.Descriptor.Id, diagnostic.Id)
@@ -805,9 +800,10 @@ class AnonymousFunctions
' Test "GetDiagnosticsForIdsAsync" does force computation of compilation end diagnostics.
' Verify compilation diagnostics are reported with correct location info when asked for project diagnostics.
- Dim projectDiagnostics = Await diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, documentId:=Nothing,
- diagnosticIds:=Nothing, shouldIncludeAnalyzer:=Nothing, includeSuppressedDiagnostics:=False,
- includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)
+ Dim projectDiagnostics = Await diagnosticService.GetDiagnosticsForIdsAsync(
+ project.Solution, project.Id, documentId:=Nothing,
+ diagnosticIds:=Nothing, shouldIncludeAnalyzer:=Nothing,
+ includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)
Assert.Equal(2, projectDiagnostics.Length)
Dim noLocationDiagnostic = projectDiagnostics.First(Function(d) d.DataLocation.DocumentId Is Nothing)
@@ -951,7 +947,7 @@ class AnonymousFunctions
Dim document = project.Documents.Single()
Dim diagnostics = (Await diagnosticService.GetDiagnosticsForIdsAsync(
project.Solution, project.Id, documentId:=Nothing, diagnosticIds:=Nothing, shouldIncludeAnalyzer:=Nothing,
- includeSuppressedDiagnostics:=False, includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)).
+ includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)).
Select(Function(d) d.Id = NamedTypeAnalyzer.DiagDescriptor.Id)
Assert.Equal(1, diagnostics.Count)
@@ -1046,7 +1042,7 @@ class AnonymousFunctions
Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace)
Dim diagnostics = Await diagnosticService.GetDiagnosticsForIdsAsync(
project.Solution, project.Id, documentId:=Nothing, diagnosticIds:=Nothing, shouldIncludeAnalyzer:=Nothing,
- includeSuppressedDiagnostics:=False, includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)
+ includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)
Assert.Equal(2, diagnostics.Length)
Dim file1HasDiag = False, file2HasDiag = False
For Each diagnostic In diagnostics
@@ -2096,7 +2092,7 @@ class MyClass
Dim document = project.Documents.Single()
Dim diagnostics = Await GetDiagnosticsForDocumentAsync(diagnosticService, document)
- Assert.Equal(0, diagnostics.Length)
+ Assert.Empty(diagnostics)
End Using
End Function
@@ -2135,11 +2131,11 @@ class MyClass
Assert.Equal(analyzer.Descriptor.Id, descriptors.Single().Id)
' Get cached project diagnostics.
- Dim diagnostics = Await diagnosticService.GetCachedDiagnosticsAsync(workspace, project.Id, documentId:=Nothing,
- includeSuppressedDiagnostics:=False,
- includeLocalDocumentDiagnostics:=True,
- includeNonLocalDocumentDiagnostics:=True,
- CancellationToken.None)
+ Dim diagnostics = Await diagnosticService.GetCachedDiagnosticsAsync(
+ workspace, project.Id, documentId:=Nothing,
+ includeLocalDocumentDiagnostics:=True,
+ includeNonLocalDocumentDiagnostics:=True,
+ CancellationToken.None)
' in v2, solution crawler never creates non-local hidden diagnostics.
' v2 still creates those for LB and explicit queries such as FixAll.
@@ -2149,7 +2145,7 @@ class MyClass
' Get diagnostics explicitly
Dim hiddenDiagnostics = Await diagnosticService.GetDiagnosticsForIdsAsync(
project.Solution, project.Id, documentId:=Nothing, diagnosticIds:=Nothing, shouldIncludeAnalyzer:=Nothing,
- includeSuppressedDiagnostics:=False, includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)
+ includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)
Assert.Equal(1, hiddenDiagnostics.Length)
Assert.Equal(analyzer.Descriptor.Id, hiddenDiagnostics.Single().Id)
End Using
@@ -2236,8 +2232,8 @@ class C
Dim incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace)
Dim diagnostics = Await diagnosticService.GetDiagnosticsForIdsAsync(
project.Solution, project.Id, documentId:=Nothing, diagnosticIds:=Nothing, shouldIncludeAnalyzer:=Nothing,
- includeSuppressedDiagnostics:=False, includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)
- Assert.Equal(0, diagnostics.Length)
+ includeLocalDocumentDiagnostics:=True, includeNonLocalDocumentDiagnostics:=True, CancellationToken.None)
+ Assert.Empty(diagnostics)
End Using
End Function
diff --git a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb
index 93e3d6a1af72e..3c9256fba03e2 100644
--- a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb
+++ b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb
@@ -12753,5 +12753,72 @@ internal class Program
Await state.AssertSelectedCompletionItem("Create")
End Using
End Function
+
+
+
+ Public Async Function TestFilterOutOwnTypeInBaseList1(showCompletionInArgumentLists As Boolean) As Task
+ Using state = TestStateFactory.CreateCSharpTestState(
+
+ class C : $$
+ {
+ }
+ ,
+ showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp12)
+
+ state.SendInvokeCompletionList()
+ Await state.AssertCompletionItemsDoNotContainAny("C")
+ End Using
+ End Function
+
+
+
+ Public Async Function TestFilterOutOwnTypeInBaseList2(showCompletionInArgumentLists As Boolean) As Task
+ Using state = TestStateFactory.CreateCSharpTestState(
+
+ class C : $$
+ {
+ interface IGoo
+ {
+ }
+ }
+ ,
+ showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp12)
+
+ state.SendInvokeCompletionList()
+ Await state.AssertCompletionItemsContain("C", displayTextSuffix:="")
+ End Using
+ End Function
+
+
+
+ Public Async Function TestFilterOutOwnTypeInBaseList3(showCompletionInArgumentLists As Boolean) As Task
+ Using state = TestStateFactory.CreateCSharpTestState(
+
+ class C : IComparable<$$>
+ {
+ }
+ ,
+ showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp12)
+
+ state.SendInvokeCompletionList()
+ Await state.AssertCompletionItemsContain("C", displayTextSuffix:="")
+ End Using
+ End Function
+
+
+
+ Public Async Function TestFilterOutOwnTypeInBaseList4(showCompletionInArgumentLists As Boolean) As Task
+ Using state = TestStateFactory.CreateCSharpTestState(
+
+ class C : BaseType($$);
+ {
+ }
+ ,
+ showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp12)
+
+ state.SendInvokeCompletionList()
+ Await state.AssertCompletionItemsContain("C", displayTextSuffix:="")
+ End Using
+ End Function
End Class
End Namespace
diff --git a/src/EditorFeatures/TestUtilities/Diagnostics/MockDiagnosticAnalyzerService.cs b/src/EditorFeatures/TestUtilities/Diagnostics/MockDiagnosticAnalyzerService.cs
index 1d58ca00a5b09..7c4baeeb75e67 100644
--- a/src/EditorFeatures/TestUtilities/Diagnostics/MockDiagnosticAnalyzerService.cs
+++ b/src/EditorFeatures/TestUtilities/Diagnostics/MockDiagnosticAnalyzerService.cs
@@ -55,19 +55,19 @@ public bool ContainsDiagnostics(Workspace workspace, ProjectId projectId)
public Task ForceAnalyzeProjectAsync(Project project, CancellationToken cancellationToken)
=> throw new NotImplementedException();
- public Task> GetCachedDiagnosticsAsync(Workspace workspace, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics, bool includeLocalDocumentDiagnostics, bool includeNonLocalDocumentDiagnostics, CancellationToken cancellationToken)
+ public Task> GetCachedDiagnosticsAsync(Workspace workspace, ProjectId? projectId, DocumentId? documentId, bool includeLocalDocumentDiagnostics, bool includeNonLocalDocumentDiagnostics, CancellationToken cancellationToken)
=> throw new NotImplementedException();
- public Task> GetDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics, bool includeNonLocalDocumentDiagnostics, CancellationToken cancellationToken)
+ public Task> GetDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeNonLocalDocumentDiagnostics, CancellationToken cancellationToken)
=> throw new NotImplementedException();
- public Task> GetDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet? diagnosticIds, Func? shouldIncludeAnalyzer, Func>? getDocuments, bool includeSuppressedDiagnostics, bool includeLocalDocumentDiagnostics, bool includeNonLocalDocumentDiagnostics, CancellationToken cancellationToken)
+ public Task> GetDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet? diagnosticIds, Func? shouldIncludeAnalyzer, Func>? getDocuments, bool includeLocalDocumentDiagnostics, bool includeNonLocalDocumentDiagnostics, CancellationToken cancellationToken)
=> throw new NotImplementedException();
- public Task> GetDiagnosticsForSpanAsync(TextDocument document, TextSpan? range, Func? shouldIncludeDiagnostic, bool includeCompilerDiagnostics, bool includeSuppressedDiagnostics, ICodeActionRequestPriorityProvider priorityProvider, DiagnosticKind diagnosticKind, bool isExplicit, CancellationToken cancellationToken)
+ public Task> GetDiagnosticsForSpanAsync(TextDocument document, TextSpan? range, Func? shouldIncludeDiagnostic, bool includeCompilerDiagnostics, ICodeActionRequestPriorityProvider priorityProvider, DiagnosticKind diagnosticKind, bool isExplicit, CancellationToken cancellationToken)
=> Task.FromResult(_diagnosticsWithKindFilter.Where(d => diagnosticKind == d.KindFilter).Select(d => d.Diagnostic).ToImmutableArray());
- public Task> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, ImmutableHashSet? diagnosticIds, Func? shouldIncludeAnalyzer, bool includeSuppressedDiagnostics, bool includeNonLocalDocumentDiagnostics, CancellationToken cancellationToken)
+ public Task> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, ImmutableHashSet? diagnosticIds, Func? shouldIncludeAnalyzer, bool includeNonLocalDocumentDiagnostics, CancellationToken cancellationToken)
=> throw new NotImplementedException();
}
}
diff --git a/src/EditorFeatures/TestUtilities/Rename/RenamerTests.cs b/src/EditorFeatures/TestUtilities/Rename/RenamerTests.cs
index 3b70d661c01e3..d628c3bfc5e96 100644
--- a/src/EditorFeatures/TestUtilities/Rename/RenamerTests.cs
+++ b/src/EditorFeatures/TestUtilities/Rename/RenamerTests.cs
@@ -99,7 +99,7 @@ protected async Task TestRenameDocument(
}
AssertEx.EqualOrDiff(endDocument.Text, (await updatedDocument.GetTextAsync()).ToString());
- Assert.Equal(0, remainingErrors.Count);
+ Assert.Empty(remainingErrors);
}
}
diff --git a/src/EditorFeatures/VisualBasicTest/Recommendations/RecommendationTestHelpers.vb b/src/EditorFeatures/VisualBasicTest/Recommendations/RecommendationTestHelpers.vb
index 15f02976ee58c..d9e46a4ee0d3a 100644
--- a/src/EditorFeatures/VisualBasicTest/Recommendations/RecommendationTestHelpers.vb
+++ b/src/EditorFeatures/VisualBasicTest/Recommendations/RecommendationTestHelpers.vb
@@ -147,7 +147,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations
.OrderBy(Function(recommendation) recommendation) _
.ToArray()
- Assert.Equal(0, recommendedKeywords.Length)
+ Assert.Empty(recommendedKeywords)
End Sub
Private Function GetSourceCodeKind(testSource As XElement) As SourceCodeKind
diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpExpressionCompiler.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpExpressionCompiler.cs
index d69d5dd1828ad..312654b1db780 100644
--- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpExpressionCompiler.cs
+++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpExpressionCompiler.cs
@@ -33,10 +33,11 @@ internal override DkmCompilerId CompilerId
internal delegate MetadataContext GetMetadataContextDelegate(TAppDomain appDomain);
internal delegate void SetMetadataContextDelegate(TAppDomain appDomain, MetadataContext metadataContext, bool report);
+ /// Module wasn't included in the compilation due to bad metadata.
internal override EvaluationContextBase CreateTypeContext(
DkmClrAppDomain appDomain,
ImmutableArray metadataBlocks,
- Guid moduleVersionId,
+ ModuleId moduleId,
int typeToken,
bool useReferencedModulesOnly)
{
@@ -44,16 +45,17 @@ internal override EvaluationContextBase CreateTypeContext(
appDomain,
ad => ad.GetMetadataContext(),
metadataBlocks,
- moduleVersionId,
+ moduleId,
typeToken,
GetMakeAssemblyReferencesKind(useReferencedModulesOnly));
}
+ /// Module wasn't included in the compilation due to bad metadata.
internal static EvaluationContext CreateTypeContext(
TAppDomain appDomain,
GetMetadataContextDelegate getMetadataContext,
ImmutableArray metadataBlocks,
- Guid moduleVersionId,
+ ModuleId moduleId,
int typeToken,
MakeAssemblyReferencesKind kind)
{
@@ -63,14 +65,14 @@ internal static EvaluationContext CreateTypeContext(
{
// Avoid using the cache for referenced assemblies only
// since this should be the exceptional case.
- compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId);
+ compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleId);
return EvaluationContext.CreateTypeContext(
compilation,
- moduleVersionId,
+ moduleId,
typeToken);
}
- var contextId = MetadataContextId.GetContextId(moduleVersionId, kind);
+ var contextId = MetadataContextId.GetContextId(moduleId, kind);
var previous = getMetadataContext(appDomain);
CSharpMetadataContext previousMetadataContext = default;
if (previous.Matches(metadataBlocks))
@@ -80,11 +82,11 @@ internal static EvaluationContext CreateTypeContext(
// Re-use the previous compilation if possible.
compilation = previousMetadataContext.Compilation;
- compilation ??= metadataBlocks.ToCompilation(moduleVersionId, kind);
+ compilation ??= metadataBlocks.ToCompilation(moduleId, kind);
var context = EvaluationContext.CreateTypeContext(
compilation,
- moduleVersionId,
+ moduleId,
typeToken);
// New type context is not attached to the AppDomain since it is less
@@ -101,7 +103,7 @@ internal override EvaluationContextBase CreateMethodContext(
ImmutableArray metadataBlocks,
Lazy> unusedLazyAssemblyReaders,
object? symReader,
- Guid moduleVersionId,
+ ModuleId moduleId,
int methodToken,
int methodVersion,
uint ilOffset,
@@ -114,7 +116,7 @@ internal override EvaluationContextBase CreateMethodContext(
(ad, mc, report) => ad.SetMetadataContext(mc, report),
metadataBlocks,
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
ilOffset,
@@ -128,7 +130,7 @@ internal static EvaluationContext CreateMethodContext(
SetMetadataContextDelegate setMetadataContext,
ImmutableArray metadataBlocks,
object? symReader,
- Guid moduleVersionId,
+ ModuleId moduleId,
int methodToken,
int methodVersion,
uint ilOffset,
@@ -142,18 +144,18 @@ internal static EvaluationContext CreateMethodContext(
{
// Avoid using the cache for referenced assemblies only
// since this should be the exceptional case.
- compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId);
+ compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleId);
return EvaluationContext.CreateMethodContext(
compilation,
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
offset,
localSignatureToken);
}
- var contextId = MetadataContextId.GetContextId(moduleVersionId, kind);
+ var contextId = MetadataContextId.GetContextId(moduleId, kind);
var previous = getMetadataContext(appDomain);
var assemblyContexts = previous.Matches(metadataBlocks) ? previous.AssemblyContexts : ImmutableDictionary.Empty;
CSharpMetadataContext previousMetadataContext;
@@ -167,20 +169,20 @@ internal static EvaluationContext CreateMethodContext(
var previousContext = previousMetadataContext.EvaluationContext;
if (previousContext != null &&
previousContext.MethodContextReuseConstraints.HasValue &&
- previousContext.MethodContextReuseConstraints.GetValueOrDefault().AreSatisfied(moduleVersionId, methodToken, methodVersion, offset))
+ previousContext.MethodContextReuseConstraints.GetValueOrDefault().AreSatisfied(moduleId, methodToken, methodVersion, offset))
{
return previousContext;
}
}
else
{
- compilation = metadataBlocks.ToCompilation(moduleVersionId, kind);
+ compilation = metadataBlocks.ToCompilation(moduleId, kind);
}
var context = EvaluationContext.CreateMethodContext(
compilation,
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
offset,
diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpInstructionDecoder.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpInstructionDecoder.cs
index bd7334fbd67cf..f401de6dea6b4 100644
--- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpInstructionDecoder.cs
+++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpInstructionDecoder.cs
@@ -151,12 +151,12 @@ internal override ImmutableArray GetAllTypeParameters(Metho
internal override CSharpCompilation GetCompilation(DkmClrModuleInstance moduleInstance)
{
var appDomain = moduleInstance.AppDomain;
- var moduleVersionId = moduleInstance.Mvid;
+ var moduleId = moduleInstance.GetModuleId();
var previous = appDomain.GetMetadataContext();
var metadataBlocks = moduleInstance.RuntimeInstance.GetMetadataBlocks(appDomain, previous.MetadataBlocks);
var kind = GetMakeAssemblyReferencesKind();
- var contextId = MetadataContextId.GetContextId(moduleVersionId, kind);
+ var contextId = MetadataContextId.GetContextId(moduleId, kind);
var assemblyContexts = previous.Matches(metadataBlocks) ? previous.AssemblyContexts : ImmutableDictionary.Empty;
CSharpMetadataContext previousContext;
assemblyContexts.TryGetValue(contextId, out previousContext);
@@ -164,7 +164,7 @@ internal override CSharpCompilation GetCompilation(DkmClrModuleInstance moduleIn
var compilation = previousContext.Compilation;
if (compilation == null)
{
- compilation = metadataBlocks.ToCompilation(moduleVersionId, kind);
+ compilation = metadataBlocks.ToCompilation(moduleId, kind);
appDomain.SetMetadataContext(
new MetadataContext(
metadataBlocks,
@@ -178,7 +178,7 @@ internal override CSharpCompilation GetCompilation(DkmClrModuleInstance moduleIn
internal override MethodSymbol GetMethod(CSharpCompilation compilation, DkmClrInstructionAddress instructionAddress)
{
var methodHandle = (MethodDefinitionHandle)MetadataTokens.Handle(instructionAddress.MethodId.Token);
- return compilation.GetSourceMethod(instructionAddress.ModuleInstance.Mvid, methodHandle);
+ return compilation.GetSourceMethod(instructionAddress.ModuleInstance.GetModuleId(), methodHandle);
}
internal override TypeNameDecoder GetTypeNameDecoder(CSharpCompilation compilation, MethodSymbol method)
diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationExtensions.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationExtensions.cs
index 66a924a798140..226b7413c3c22 100644
--- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationExtensions.cs
+++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationExtensions.cs
@@ -24,14 +24,15 @@ private static PENamedTypeSymbol GetType(PEModuleSymbol module, TypeDefinitionHa
return (PENamedTypeSymbol)metadataDecoder.GetTypeOfToken(typeHandle);
}
- internal static PENamedTypeSymbol GetType(this CSharpCompilation compilation, Guid moduleVersionId, int typeToken)
+ /// Module wasn't included in the compilation due to bad metadata.
+ internal static PENamedTypeSymbol GetType(this CSharpCompilation compilation, ModuleId moduleId, int typeToken)
{
- return GetType(compilation.GetModule(moduleVersionId), (TypeDefinitionHandle)MetadataTokens.Handle(typeToken));
+ return GetType(compilation.GetModule(moduleId), (TypeDefinitionHandle)MetadataTokens.Handle(typeToken));
}
- internal static PEMethodSymbol GetSourceMethod(this CSharpCompilation compilation, Guid moduleVersionId, MethodDefinitionHandle methodHandle)
+ internal static PEMethodSymbol GetSourceMethod(this CSharpCompilation compilation, ModuleId moduleId, MethodDefinitionHandle methodHandle)
{
- var method = GetMethod(compilation, moduleVersionId, methodHandle);
+ var method = GetMethod(compilation, moduleId, methodHandle);
var metadataDecoder = new MetadataDecoder((PEModuleSymbol)method.ContainingModule);
var containingType = method.ContainingType;
if (GeneratedNameParser.TryParseSourceMethodNameFromGeneratedName(containingType.Name, GeneratedNameKind.StateMachineType, out var sourceMethodName))
@@ -49,9 +50,10 @@ internal static PEMethodSymbol GetSourceMethod(this CSharpCompilation compilatio
return method;
}
- internal static PEMethodSymbol GetMethod(this CSharpCompilation compilation, Guid moduleVersionId, MethodDefinitionHandle methodHandle)
+ /// Module wasn't included in the compilation due to bad metadata.
+ internal static PEMethodSymbol GetMethod(this CSharpCompilation compilation, ModuleId moduleId, MethodDefinitionHandle methodHandle)
{
- var module = compilation.GetModule(moduleVersionId);
+ var module = compilation.GetModule(moduleId);
var reader = module.Module.MetadataReader;
var typeHandle = reader.GetMethodDefinition(methodHandle).GetDeclaringType();
var type = GetType(module, typeHandle);
@@ -59,7 +61,8 @@ internal static PEMethodSymbol GetMethod(this CSharpCompilation compilation, Gui
return method;
}
- internal static PEModuleSymbol GetModule(this CSharpCompilation compilation, Guid moduleVersionId)
+ /// Module wasn't included in the compilation due to bad metadata.
+ internal static PEModuleSymbol GetModule(this CSharpCompilation compilation, ModuleId moduleId)
{
foreach (var pair in compilation.GetBoundReferenceManager().GetReferencedAssemblies())
{
@@ -68,24 +71,24 @@ internal static PEModuleSymbol GetModule(this CSharpCompilation compilation, Gui
{
var m = (PEModuleSymbol)module;
var id = m.Module.GetModuleVersionIdOrThrow();
- if (id == moduleVersionId)
+ if (id == moduleId.Id)
{
return m;
}
}
}
- throw new ArgumentException($"No module found with MVID '{moduleVersionId}'", nameof(moduleVersionId));
+ throw new BadMetadataModuleException(moduleId);
}
- internal static CSharpCompilation ToCompilationReferencedModulesOnly(this ImmutableArray metadataBlocks, Guid moduleVersionId)
+ internal static CSharpCompilation ToCompilationReferencedModulesOnly(this ImmutableArray metadataBlocks, ModuleId moduleId)
{
- return ToCompilation(metadataBlocks, moduleVersionId, kind: MakeAssemblyReferencesKind.DirectReferencesOnly);
+ return ToCompilation(metadataBlocks, moduleId, kind: MakeAssemblyReferencesKind.DirectReferencesOnly);
}
- internal static CSharpCompilation ToCompilation(this ImmutableArray metadataBlocks, Guid moduleVersionId, MakeAssemblyReferencesKind kind)
+ internal static CSharpCompilation ToCompilation(this ImmutableArray metadataBlocks, ModuleId moduleId, MakeAssemblyReferencesKind kind)
{
- var references = metadataBlocks.MakeAssemblyReferences(moduleVersionId, IdentityComparer, kind, out var referencesBySimpleName);
+ var references = metadataBlocks.MakeAssemblyReferences(moduleId, IdentityComparer, kind, out var referencesBySimpleName);
var options = s_compilationOptions;
if (referencesBySimpleName != null)
{
diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/EvaluationContext.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/EvaluationContext.cs
index 7e32529042d3b..d074738506645 100644
--- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/EvaluationContext.cs
+++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/EvaluationContext.cs
@@ -64,20 +64,21 @@ private EvaluationContext(
/// Create a context for evaluating expressions at a type scope.
///
/// Compilation.
- /// Module containing type
+ /// Module containing type
/// Type metadata token
/// Evaluation context
///
/// No locals since locals are associated with methods, not types.
///
+ /// Module wasn't included in the compilation due to bad metadata.
internal static EvaluationContext CreateTypeContext(
CSharpCompilation compilation,
- Guid moduleVersionId,
+ ModuleId moduleId,
int typeToken)
{
Debug.Assert(MetadataTokens.Handle(typeToken).Kind == HandleKind.TypeDefinition);
- var currentType = compilation.GetType(moduleVersionId, typeToken);
+ var currentType = compilation.GetType(moduleId, typeToken);
RoslynDebug.Assert(currentType is object);
var currentFrame = new SynthesizedContextMethodSymbol(currentType);
return new EvaluationContext(
@@ -90,13 +91,23 @@ internal static EvaluationContext CreateTypeContext(
methodDebugInfo: MethodDebugInfo.None);
}
+ // Used by VS debugger (/src/debugger/ProductionDebug/CodeAnalysis/CodeAnalysis/ExpressionEvaluator.cs)
+ internal static EvaluationContext CreateMethodContext(
+ ImmutableArray metadataBlocks,
+ object symReader,
+ Guid moduleId,
+ int methodToken,
+ int methodVersion,
+ uint ilOffset,
+ int localSignatureToken)
+ => CreateMethodContext(metadataBlocks, symReader, new ModuleId(moduleId, ""), methodToken, methodVersion, ilOffset, localSignatureToken);
+
///
/// Create a context for evaluating expressions within a method scope.
///
/// Module metadata
- /// for PDB associated with
- /// Module containing method
- /// Method metadata token
+ /// for PDB associated with
+ /// Module containing method
/// Method version.
/// IL offset of instruction pointer in method
/// Method local signature token
@@ -104,7 +115,7 @@ internal static EvaluationContext CreateTypeContext(
internal static EvaluationContext CreateMethodContext(
ImmutableArray metadataBlocks,
object symReader,
- Guid moduleVersionId,
+ ModuleId moduleId,
int methodToken,
int methodVersion,
uint ilOffset,
@@ -112,12 +123,12 @@ internal static EvaluationContext CreateMethodContext(
{
var offset = NormalizeILOffset(ilOffset);
- var compilation = metadataBlocks.ToCompilation(moduleVersionId: default, MakeAssemblyReferencesKind.AllAssemblies);
+ var compilation = metadataBlocks.ToCompilation(moduleId: default, MakeAssemblyReferencesKind.AllAssemblies);
return CreateMethodContext(
compilation,
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
offset,
@@ -128,8 +139,8 @@ internal static EvaluationContext CreateMethodContext(
/// Create a context for evaluating expressions within a method scope.
///
/// Compilation.
- /// for PDB associated with
- /// Module containing method
+ /// for PDB associated with
+ /// Module containing method
/// Method metadata token
/// Method version.
/// IL offset of instruction pointer in method
@@ -138,17 +149,17 @@ internal static EvaluationContext CreateMethodContext(
internal static EvaluationContext CreateMethodContext(
CSharpCompilation compilation,
object? symReader,
- Guid moduleVersionId,
+ ModuleId moduleId,
int methodToken,
int methodVersion,
int ilOffset,
int localSignatureToken)
{
var methodHandle = (MethodDefinitionHandle)MetadataTokens.Handle(methodToken);
- var currentSourceMethod = compilation.GetSourceMethod(moduleVersionId, methodHandle);
+ var currentSourceMethod = compilation.GetSourceMethod(moduleId, methodHandle);
var localSignatureHandle = (localSignatureToken != 0) ? (StandaloneSignatureHandle)MetadataTokens.Handle(localSignatureToken) : default;
- var currentFrame = compilation.GetMethod(moduleVersionId, methodHandle);
+ var currentFrame = compilation.GetMethod(moduleId, methodHandle);
RoslynDebug.AssertNotNull(currentFrame);
var symbolProvider = new CSharpEESymbolProvider(compilation.SourceAssembly, (PEModuleSymbol)currentFrame.ContainingModule, currentFrame);
@@ -174,7 +185,7 @@ internal static EvaluationContext CreateMethodContext(
localsBuilder.AddRange(debugInfo.LocalConstants);
return new EvaluationContext(
- new MethodContextReuseConstraints(moduleVersionId, methodToken, methodVersion, reuseSpan),
+ new MethodContextReuseConstraints(moduleId, methodToken, methodVersion, reuseSpan),
compilation,
currentFrame,
currentSourceMethod,
diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTestBase.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTestBase.cs
index 5f42d90e82458..230bf3926c994 100644
--- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTestBase.cs
+++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTestBase.cs
@@ -136,7 +136,7 @@ internal void RemoveMetadataContext()
internal static EvaluationContext CreateTypeContext(
AppDomain appDomain,
ImmutableArray blocks,
- Guid moduleVersionId,
+ ModuleId moduleId,
int typeToken,
MakeAssemblyReferencesKind kind = MakeAssemblyReferencesKind.AllAssemblies)
{
@@ -144,7 +144,7 @@ internal static EvaluationContext CreateTypeContext(
appDomain,
ad => ad.GetMetadataContext(),
blocks,
- moduleVersionId,
+ moduleId,
typeToken,
kind);
}
@@ -153,7 +153,7 @@ internal static EvaluationContext CreateMethodContext(
AppDomain appDomain,
ImmutableArray blocks,
ISymUnmanagedReader symReader,
- Guid moduleVersionId,
+ ModuleId moduleId,
int methodToken,
int methodVersion,
uint ilOffset,
@@ -166,7 +166,7 @@ internal static EvaluationContext CreateMethodContext(
(ad, mc, report) => ad.SetMetadataContext(mc),
blocks,
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
ilOffset,
@@ -177,14 +177,14 @@ internal static EvaluationContext CreateMethodContext(
internal static EvaluationContext CreateMethodContext(
AppDomain appDomain,
ImmutableArray blocks,
- (Guid ModuleVersionId, ISymUnmanagedReader SymReader, int MethodToken, int LocalSignatureToken, uint ILOffset) state,
+ (ModuleId ModuleId, ISymUnmanagedReader SymReader, int MethodToken, int LocalSignatureToken, uint ILOffset) state,
MakeAssemblyReferencesKind kind = MakeAssemblyReferencesKind.AllReferences)
{
return CreateMethodContext(
appDomain,
blocks,
state.SymReader,
- state.ModuleVersionId,
+ state.ModuleId,
state.MethodToken,
methodVersion: 1,
state.ILOffset,
@@ -192,10 +192,10 @@ internal static EvaluationContext CreateMethodContext(
kind);
}
- internal static CSharpMetadataContext GetMetadataContext(MetadataContext appDomainContext, Guid mvid = default)
+ internal static CSharpMetadataContext GetMetadataContext(MetadataContext appDomainContext, ModuleId moduleId = default)
{
var assemblyContexts = appDomainContext.AssemblyContexts;
- return assemblyContexts != null && assemblyContexts.TryGetValue(new MetadataContextId(mvid), out CSharpMetadataContext context)
+ return assemblyContexts != null && assemblyContexts.TryGetValue(new MetadataContextId(moduleId.Id), out CSharpMetadataContext context)
? context
: default;
}
@@ -207,9 +207,9 @@ internal static MetadataContext SetMetadataContext(Metada
appDomainContext.AssemblyContexts.SetItem(new MetadataContextId(mvid), context));
}
- internal static (Guid ModuleVersionId, ISymUnmanagedReader SymReader, int MethodToken, int LocalSignatureToken, uint ILOffset) GetContextState(RuntimeInstance runtime, string methodName)
+ internal static (ModuleId ModuleId, ISymUnmanagedReader SymReader, int MethodToken, int LocalSignatureToken, uint ILOffset) GetContextState(RuntimeInstance runtime, string methodName)
{
- Guid moduleVersionId;
+ ModuleId moduleId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
@@ -217,19 +217,19 @@ internal static (Guid ModuleVersionId, ISymUnmanagedReader SymReader, int Method
runtime,
methodName,
out _,
- out moduleVersionId,
+ out moduleId,
out symReader,
out methodToken,
out localSignatureToken);
uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader);
- return (moduleVersionId, symReader, methodToken, localSignatureToken, ilOffset);
+ return (moduleId, symReader, methodToken, localSignatureToken, ilOffset);
}
internal static void GetContextState(
RuntimeInstance runtime,
string methodOrTypeName,
out ImmutableArray blocks,
- out Guid moduleVersionId,
+ out ModuleId moduleId,
out ISymUnmanagedReader symReader,
out int methodOrTypeToken,
out int localSignatureToken)
@@ -237,15 +237,15 @@ internal static void GetContextState(
var moduleInstances = runtime.Modules;
blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock);
- var compilation = blocks.ToCompilation(default(Guid), MakeAssemblyReferencesKind.AllAssemblies);
+ var compilation = blocks.ToCompilation(new ModuleId(id: default, "test"), MakeAssemblyReferencesKind.AllAssemblies);
var methodOrType = GetMethodOrTypeBySignature(compilation, methodOrTypeName);
var module = (PEModuleSymbol)methodOrType.ContainingModule;
- var id = module.Module.GetModuleVersionIdOrThrow();
- var moduleInstance = moduleInstances.First(m => m.ModuleVersionId == id);
+ var mvid = module.Module.GetModuleVersionIdOrThrow();
+ var moduleInstance = moduleInstances.First(m => m.Id.Id == mvid);
- moduleVersionId = id;
+ moduleId = moduleInstance.Id;
symReader = (ISymUnmanagedReader)moduleInstance.SymReader;
EntityHandle methodOrTypeHandle;
@@ -270,11 +270,11 @@ internal static EvaluationContext CreateMethodContext(
int atLineNumber = -1)
{
ImmutableArray blocks;
- Guid moduleVersionId;
+ ModuleId moduleId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
- GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
+ GetContextState(runtime, methodName, out blocks, out moduleId, out symReader, out methodToken, out localSignatureToken);
uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber);
@@ -282,7 +282,7 @@ internal static EvaluationContext CreateMethodContext(
new AppDomain(),
blocks,
symReader,
- moduleVersionId,
+ moduleId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: ilOffset,
@@ -295,15 +295,15 @@ internal static EvaluationContext CreateTypeContext(
string typeName)
{
ImmutableArray blocks;
- Guid moduleVersionId;
+ ModuleId moduleId;
ISymUnmanagedReader symReader;
int typeToken;
int localSignatureToken;
- GetContextState(runtime, typeName, out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
+ GetContextState(runtime, typeName, out blocks, out moduleId, out symReader, out typeToken, out localSignatureToken);
return CreateTypeContext(
new AppDomain(),
blocks,
- moduleVersionId,
+ moduleId,
typeToken,
kind: MakeAssemblyReferencesKind.AllAssemblies);
}
@@ -508,11 +508,11 @@ internal static Alias Alias(DkmClrAliasKind kind, string name, string fullName,
internal static MethodDebugInfo GetMethodDebugInfo(RuntimeInstance runtime, string qualifiedMethodName, int ilOffset = 0)
{
- var peCompilation = runtime.Modules.SelectAsArray(m => m.MetadataBlock).ToCompilation(default(Guid), MakeAssemblyReferencesKind.AllAssemblies);
+ var peCompilation = runtime.Modules.SelectAsArray(m => m.MetadataBlock).ToCompilation(moduleId: default, MakeAssemblyReferencesKind.AllAssemblies);
var peMethod = peCompilation.GlobalNamespace.GetMember(qualifiedMethodName);
var peModule = (PEModuleSymbol)peMethod.ContainingModule;
- var symReader = runtime.Modules.Single(mi => mi.ModuleVersionId == peModule.Module.GetModuleVersionIdOrThrow()).SymReader;
+ var symReader = runtime.Modules.Single(mi => mi.Id.Id == peModule.Module.GetModuleVersionIdOrThrow()).SymReader;
var symbolProvider = new CSharpEESymbolProvider(peCompilation.SourceAssembly, peModule, peMethod);
return MethodDebugInfo.ReadMethodDebugInfo((ISymUnmanagedReader3)symReader, symbolProvider, MetadataTokens.GetToken(peMethod.Handle), methodVersion: 1, ilOffset: ilOffset, isVisualBasicMethod: false);
diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs
index 704fe62aeb1f5..5ed458adb7962 100644
--- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs
+++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs
@@ -46,12 +46,7 @@ static void M()
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
- ImmutableArray blocks;
- Guid moduleVersionId;
- ISymUnmanagedReader symReader;
- int methodToken;
- int localSignatureToken;
- GetContextState(runtime, "C.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
+ GetContextState(runtime, "C.M", out var blocks, out var moduleVersionId, out var symReader, out var methodToken, out var localSignatureToken);
var appDomain = new AppDomain();
uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader);
@@ -341,13 +336,13 @@ static void G()
var runtime = CreateRuntimeInstance(moduleB, referencesB);
ImmutableArray typeBlocks;
ImmutableArray methodBlocks;
- Guid moduleVersionId;
+ ModuleId moduleId;
ISymUnmanagedReader symReader;
int typeToken;
int methodToken;
int localSignatureToken;
- GetContextState(runtime, "C", out typeBlocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
- GetContextState(runtime, "C.F", out methodBlocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
+ GetContextState(runtime, "C", out typeBlocks, out moduleId, out symReader, out typeToken, out localSignatureToken);
+ GetContextState(runtime, "C.F", out methodBlocks, out moduleId, out symReader, out methodToken, out localSignatureToken);
// Get non-empty scopes.
var scopes = symReader.GetScopes(methodToken, methodVersion, EvaluationContext.IsLocalScopeEndInclusive).WhereAsArray(s => s.Locals.Length > 0);
@@ -358,16 +353,16 @@ static void G()
endOffset = outerScope.EndOffset - 1;
// At start of outer scope.
- var context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, (uint)startOffset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies);
+ var context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleId, methodToken, methodVersion, (uint)startOffset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies);
// At end of outer scope - not reused because of the nested scope.
var previous = appDomain.GetMetadataContext();
- context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, (uint)endOffset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies);
+ context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleId, methodToken, methodVersion, (uint)endOffset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies);
Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext); // Not required, just documentary.
// At type context.
previous = appDomain.GetMetadataContext();
- context = CreateTypeContext(appDomain, typeBlocks, moduleVersionId, typeToken, MakeAssemblyReferencesKind.AllAssemblies);
+ context = CreateTypeContext(appDomain, typeBlocks, moduleId, typeToken, MakeAssemblyReferencesKind.AllAssemblies);
Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext);
Assert.Null(context.MethodContextReuseConstraints);
Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation);
@@ -381,10 +376,10 @@ static void G()
var constraints = GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints;
if (constraints.HasValue)
{
- Assert.Equal(scope == previousScope, constraints.GetValueOrDefault().AreSatisfied(moduleVersionId, methodToken, methodVersion, offset));
+ Assert.Equal(scope == previousScope, constraints.GetValueOrDefault().AreSatisfied(moduleId, methodToken, methodVersion, offset));
}
- context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, (uint)offset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies);
+ context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleId, methodToken, methodVersion, (uint)offset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies);
var previousEvaluationContext = GetMetadataContext(previous).EvaluationContext;
if (scope == previousScope)
{
@@ -407,20 +402,20 @@ static void G()
// With different references.
var fewerReferences = new[] { MscorlibRef };
runtime = CreateRuntimeInstance(moduleB, fewerReferences);
- GetContextState(runtime, "C.F", out methodBlocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
+ GetContextState(runtime, "C.F", out methodBlocks, out moduleId, out symReader, out methodToken, out localSignatureToken);
// Different references. No reuse.
- context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, (uint)endOffset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies);
+ context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleId, methodToken, methodVersion, (uint)endOffset, localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies);
Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext);
- Assert.True(GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints.Value.AreSatisfied(moduleVersionId, methodToken, methodVersion, endOffset));
+ Assert.True(GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints.Value.AreSatisfied(moduleId, methodToken, methodVersion, endOffset));
Assert.NotEqual(context.Compilation, GetMetadataContext(previous).Compilation);
previous = appDomain.GetMetadataContext();
// Different method. Should reuse Compilation.
- GetContextState(runtime, "C.G", out methodBlocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
- context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, ilOffset: 0, localSignatureToken: localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies);
+ GetContextState(runtime, "C.G", out methodBlocks, out moduleId, out symReader, out methodToken, out localSignatureToken);
+ context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleId, methodToken, methodVersion, ilOffset: 0, localSignatureToken: localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies);
Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext);
- Assert.False(GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints.Value.AreSatisfied(moduleVersionId, methodToken, methodVersion, 0));
+ Assert.False(GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints.Value.AreSatisfied(moduleId, methodToken, methodVersion, 0));
Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation);
// No EvaluationContext. Should reuse Compilation
@@ -428,7 +423,7 @@ static void G()
previous = appDomain.GetMetadataContext();
Assert.Null(GetMetadataContext(previous).EvaluationContext);
Assert.NotNull(GetMetadataContext(previous).Compilation);
- context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleVersionId, methodToken, methodVersion, ilOffset: 0, localSignatureToken: localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies);
+ context = CreateMethodContext(appDomain, methodBlocks, symReader, moduleId, methodToken, methodVersion, ilOffset: 0, localSignatureToken: localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies);
Assert.Null(GetMetadataContext(previous).EvaluationContext);
Assert.NotNull(context);
Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation);
@@ -5602,7 +5597,7 @@ static void M()
using (var pinnedMetadata = new PinnedBlob(TestResources.ExpressionCompiler.NoValidTables))
{
- var corruptMetadata = ModuleInstance.Create(pinnedMetadata.Pointer, pinnedMetadata.Size, default(Guid));
+ var corruptMetadata = ModuleInstance.Create(pinnedMetadata.Pointer, pinnedMetadata.Size, id: default);
var runtime = RuntimeInstance.Create(new[] { corruptMetadata, comp.ToModuleInstance(), MscorlibRef.ToModuleInstance() });
var context = CreateMethodContext(runtime, "C.M");
@@ -6032,11 +6027,11 @@ public static void M()
var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef, ExpressionCompilerTestHelpers.IntrinsicAssemblyReference });
ImmutableArray blocks;
- Guid moduleVersionId;
+ ModuleId moduleId;
ISymUnmanagedReader symReader2;
int methodToken;
int localSignatureToken;
- GetContextState(runtime, "C.M", out blocks, out moduleVersionId, out symReader2, out methodToken, out localSignatureToken);
+ GetContextState(runtime, "C.M", out blocks, out moduleId, out symReader2, out methodToken, out localSignatureToken);
Assert.Same(symReader, symReader2);
@@ -6047,7 +6042,7 @@ public static void M()
new AppDomain(),
blocks,
symReader,
- moduleVersionId,
+ moduleId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: 0,
@@ -6067,7 +6062,7 @@ public static void M()
new AppDomain(),
blocks,
symReader,
- moduleVersionId,
+ moduleId,
methodToken: methodToken,
methodVersion: 2,
ilOffset: 0,
@@ -6265,18 +6260,18 @@ static void M(int x)
WithRuntimeInstance(compilation0, runtime =>
{
ImmutableArray blocks;
- Guid moduleVersionId;
+ ModuleId moduleId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
- GetContextState(runtime, "C.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
+ GetContextState(runtime, "C.M", out blocks, out moduleId, out symReader, out methodToken, out localSignatureToken);
var appDomain = new AppDomain();
var context = CreateMethodContext(
appDomain,
blocks,
symReader,
- moduleVersionId,
+ moduleId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: ExpressionCompilerTestHelpers.NoILOffset,
@@ -6302,7 +6297,7 @@ .locals init (int V_0) //y
appDomain,
blocks,
symReader,
- moduleVersionId,
+ moduleId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: 0,
@@ -6315,7 +6310,7 @@ .locals init (int V_0) //y
appDomain,
blocks,
symReader,
- moduleVersionId,
+ moduleId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: ExpressionCompilerTestHelpers.NoILOffset,
diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/HoistedStateMachineLocalTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/HoistedStateMachineLocalTests.cs
index dea8f37c45f2b..8b28a453aa30b 100644
--- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/HoistedStateMachineLocalTests.cs
+++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/HoistedStateMachineLocalTests.cs
@@ -1343,11 +1343,11 @@ static IEnumerable M()
WithRuntimeInstance(compilation0, runtime =>
{
ImmutableArray blocks;
- Guid moduleVersionId;
+ ModuleId moduleId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
- GetContextState(runtime, "C.d__0.MoveNext", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
+ GetContextState(runtime, "C.d__0.MoveNext", out blocks, out moduleId, out symReader, out methodToken, out localSignatureToken);
var appDomain = new AppDomain();
uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber: 100);
@@ -1355,7 +1355,7 @@ static IEnumerable M()
appDomain,
blocks,
symReader,
- moduleVersionId,
+ moduleId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: ilOffset,
@@ -1373,7 +1373,7 @@ static IEnumerable M()
appDomain,
blocks,
symReader,
- moduleVersionId,
+ moduleId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: ilOffset,
diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/InstructionDecoderTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/InstructionDecoderTests.cs
index 296b53939144b..b08988356335a 100644
--- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/InstructionDecoderTests.cs
+++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/InstructionDecoderTests.cs
@@ -594,7 +594,7 @@ private CSharpCompilation CreateCompilation(string source)
var runtime = CreateRuntimeInstance(compilation);
var moduleInstances = runtime.Modules;
var blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock);
- return blocks.ToCompilation(default(Guid), MakeAssemblyReferencesKind.AllAssemblies);
+ return blocks.ToCompilation(new ModuleId(id: default, compilation.AssemblyName), MakeAssemblyReferencesKind.AllAssemblies);
}
private MethodSymbol GetConstructedMethod(CSharpCompilation compilation, PEMethodSymbol frame, string[] serializedTypeArgumentNames, CSharpInstructionDecoder instructionDecoder)
@@ -603,8 +603,9 @@ private MethodSymbol GetConstructedMethod(CSharpCompilation compilation, PEMetho
// using the same helper as the product code. This helper will also map
// async/iterator "MoveNext" methods to the original source method.
MethodSymbol method = compilation.GetSourceMethod(
- ((PEModuleSymbol)frame.ContainingModule).Module.GetModuleVersionIdOrThrow(),
+ new ModuleId(((PEModuleSymbol)frame.ContainingModule).Module.GetModuleVersionIdOrThrow(), compilation.AssemblyName),
frame.Handle);
+
if (serializedTypeArgumentNames != null)
{
Assert.NotEmpty(serializedTypeArgumentNames);
diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalFunctionTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalFunctionTests.cs
index e81aed85b3051..6e768a7bc4c8e 100644
--- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalFunctionTests.cs
+++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalFunctionTests.cs
@@ -41,8 +41,8 @@ int G()
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.NotNull(assembly);
- Assert.Equal(0, assembly.Count);
- Assert.Equal(0, locals.Count);
+ Assert.Empty(assembly);
+ Assert.Empty(locals);
locals.Free();
});
}
diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalsTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalsTests.cs
index 288b380a00f08..b79db1b87fdbe 100644
--- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalsTests.cs
+++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalsTests.cs
@@ -46,8 +46,8 @@ static void M()
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.NotNull(assembly);
- Assert.Equal(0, assembly.Count);
- Assert.Equal(0, locals.Count);
+ Assert.Empty(assembly);
+ Assert.Empty(locals);
locals.Free();
});
}
@@ -2491,7 +2491,7 @@ static void M(A a, B b, C c)
Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("A", "Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1)
]);
- Assert.Equal(0, locals.Count);
+ Assert.Empty(locals);
locals.Free();
});
}
@@ -2535,7 +2535,7 @@ static void M(object o) where T : I
Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("I", "Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1)
]);
- Assert.Equal(0, locals.Count);
+ Assert.Empty(locals);
locals.Free();
});
}
@@ -5116,7 +5116,7 @@ private static void GetLocals(RuntimeInstance runtime, string methodName, bool a
Assert.NotNull(assembly);
if (count == 0)
{
- Assert.Equal(0, assembly.Count);
+ Assert.Empty(assembly);
}
else
{
@@ -5128,11 +5128,11 @@ private static void GetLocals(RuntimeInstance runtime, string methodName, bool a
private static void GetLocals(RuntimeInstance runtime, string methodName, MethodDebugInfoBytes debugInfo, ArrayBuilder locals, int count)
{
ImmutableArray blocks;
- Guid moduleVersionId;
+ ModuleId moduleId;
ISymUnmanagedReader unused;
int methodToken;
int localSignatureToken;
- GetContextState(runtime, methodName, out blocks, out moduleVersionId, out unused, out methodToken, out localSignatureToken);
+ GetContextState(runtime, methodName, out blocks, out moduleId, out unused, out methodToken, out localSignatureToken);
var symReader = new MockSymUnmanagedReader(
new Dictionary()
@@ -5143,7 +5143,7 @@ private static void GetLocals(RuntimeInstance runtime, string methodName, Method
new AppDomain(),
blocks,
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion: 1,
ilOffset: 0,
@@ -5156,7 +5156,7 @@ private static void GetLocals(RuntimeInstance runtime, string methodName, Method
Assert.NotNull(assembly);
if (count == 0)
{
- Assert.Equal(0, assembly.Count);
+ Assert.Empty(assembly);
}
else
{
diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MethodContextReuseConstraintsTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MethodContextReuseConstraintsTests.cs
index e3dd509f76a46..85d0197eb3df1 100644
--- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MethodContextReuseConstraintsTests.cs
+++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MethodContextReuseConstraintsTests.cs
@@ -16,26 +16,26 @@ public class MethodContextReuseConstraintsTests : ExpressionCompilerTestBase
[Fact]
public void AreSatisfied()
{
- var moduleVersionId = Guid.NewGuid();
+ var moduleId = new ModuleId(Guid.NewGuid(), "module");
const int methodToken = 0x06000001;
const int methodVersion = 1;
const uint startOffset = 1;
const uint endOffsetExclusive = 3;
var constraints = new MethodContextReuseConstraints(
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
new ILSpan(startOffset, endOffsetExclusive));
- Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset));
- Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive - 1));
+ Assert.True(constraints.AreSatisfied(moduleId, methodToken, methodVersion, (int)startOffset));
+ Assert.True(constraints.AreSatisfied(moduleId, methodToken, methodVersion, (int)endOffsetExclusive - 1));
- Assert.False(constraints.AreSatisfied(Guid.NewGuid(), methodToken, methodVersion, (int)startOffset));
- Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken + 1, methodVersion, (int)startOffset));
- Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion + 1, (int)startOffset));
- Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset - 1));
- Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive));
+ Assert.False(constraints.AreSatisfied(new ModuleId(Guid.NewGuid(), "module"), methodToken, methodVersion, (int)startOffset));
+ Assert.False(constraints.AreSatisfied(moduleId, methodToken + 1, methodVersion, (int)startOffset));
+ Assert.False(constraints.AreSatisfied(moduleId, methodToken, methodVersion + 1, (int)startOffset));
+ Assert.False(constraints.AreSatisfied(moduleId, methodToken, methodVersion, (int)startOffset - 1));
+ Assert.False(constraints.AreSatisfied(moduleId, methodToken, methodVersion, (int)endOffsetExclusive));
}
[Fact]
diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.UnitTests.csproj b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.UnitTests.csproj
index e38edfef0f10b..ba668ee2a1d90 100644
--- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.UnitTests.csproj
+++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.UnitTests.csproj
@@ -14,7 +14,7 @@
-
+
diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MissingAssemblyTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MissingAssemblyTests.cs
index 1b0cce7b9beb0..2a1b5564ebd61 100644
--- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MissingAssemblyTests.cs
+++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MissingAssemblyTests.cs
@@ -663,6 +663,7 @@ void M()
uSize = (uint)missingModule.MetadataLength;
return missingModule.MetadataAddress;
},
+ out _,
out errorMessage);
Assert.Equal(2, numRetries); // Ensure that we actually retried and that we bailed out on the second retry if the same identity was seen in the diagnostics.
@@ -690,7 +691,7 @@ void M()
var shouldSucceed = false;
string errorMessage;
- var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
+ ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(),
context,
(_, diagnostics) =>
@@ -711,6 +712,7 @@ void M()
uSize = (uint)missingModule.MetadataLength;
return missingModule.MetadataAddress;
},
+ out var compileResult,
out errorMessage);
Assert.Same(TestCompileResult.Instance, compileResult);
@@ -902,11 +904,11 @@ private static void TupleContextNoSystemRuntime(string source, string methodName
WithRuntimeInstance(comp, [Net461.References.mscorlib, ValueTupleLegacyRef], runtime =>
{
ImmutableArray blocks;
- Guid moduleVersionId;
+ ModuleId moduleId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
- GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
+ GetContextState(runtime, methodName, out blocks, out moduleId, out symReader, out methodToken, out localSignatureToken);
string errorMessage;
CompilationTestData testData;
int retryCount = 0;
@@ -915,9 +917,9 @@ private static void TupleContextNoSystemRuntime(string source, string methodName
expression,
ImmutableArray.Empty,
(b, u) => EvaluationContext.CreateMethodContext(
- b.ToCompilation(default(Guid), MakeAssemblyReferencesKind.AllAssemblies),
+ b.ToCompilation(moduleId: default, MakeAssemblyReferencesKind.AllAssemblies),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion: 1,
ilOffset: 0,
diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ReferencedModulesTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ReferencedModulesTests.cs
index 9b86934ebdc21..733ed84419182 100644
--- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ReferencedModulesTests.cs
+++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ReferencedModulesTests.cs
@@ -164,7 +164,7 @@ .maxstack 1
context = EvaluationContext.CreateMethodContext(
allBlocks,
stateA1.SymReader,
- stateA1.ModuleVersionId,
+ stateA1.ModuleId,
stateA1.MethodToken,
methodVersion: 1,
stateA1.ILOffset,
@@ -185,7 +185,7 @@ .maxstack 1
context = EvaluationContext.CreateMethodContext(
allBlocks,
stateA1.SymReader,
- stateA1.ModuleVersionId,
+ stateA1.ModuleId,
stateA1.MethodToken,
methodVersion: 1,
uint.MaxValue,
@@ -371,10 +371,10 @@ public void ReuseCompilation()
var stateB1 = GetContextState(runtime, "B1.M");
var stateB2 = GetContextState(runtime, "B2.M");
- var mvidA1 = stateA1.ModuleVersionId;
- var mvidA2 = stateA2.ModuleVersionId;
- var mvidB1 = stateB1.ModuleVersionId;
- Assert.Equal(mvidB1, stateB2.ModuleVersionId);
+ var mvidA1 = stateA1.ModuleId;
+ var mvidA2 = stateA2.ModuleId;
+ var mvidB1 = stateB1.ModuleId;
+ Assert.Equal(mvidB1, stateB2.ModuleId);
EvaluationContext context;
MetadataContext previous;
@@ -452,9 +452,9 @@ public void ReuseCompilation()
}
}
- private static void VerifyAppDomainMetadataContext(AppDomain appDomain, params Guid[] moduleVersionIds)
+ private static void VerifyAppDomainMetadataContext(AppDomain appDomain, params ModuleId[] moduleIds)
{
- ExpressionCompilerTestHelpers.VerifyAppDomainMetadataContext(appDomain.GetMetadataContext(), moduleVersionIds);
+ ExpressionCompilerTestHelpers.VerifyAppDomainMetadataContext(appDomain.GetMetadataContext(), moduleIds);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/26159")]
@@ -630,13 +630,13 @@ static void M()
{
ImmutableArray typeBlocks;
ImmutableArray methodBlocks;
- Guid moduleVersionId;
+ ModuleId moduleId;
ISymUnmanagedReader symReader;
int typeToken;
int methodToken;
int localSignatureToken;
- GetContextState(runtime, "C", out typeBlocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
- GetContextState(runtime, "C.M", out methodBlocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
+ GetContextState(runtime, "C", out typeBlocks, out moduleId, out symReader, out typeToken, out localSignatureToken);
+ GetContextState(runtime, "C.M", out methodBlocks, out moduleId, out symReader, out methodToken, out localSignatureToken);
uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader);
// Compile expression with type context with all modules.
@@ -644,7 +644,7 @@ static void M()
var context = CreateTypeContext(
appDomain,
typeBlocks,
- moduleVersionId,
+ moduleId,
typeToken,
MakeAssemblyReferencesKind.AllAssemblies);
@@ -670,7 +670,7 @@ static void M()
context = CreateTypeContext(
appDomain,
typeBlocks,
- moduleVersionId,
+ moduleId,
typeToken,
MakeAssemblyReferencesKind.DirectReferencesOnly);
// A is unrecognized since there were no direct references to AS1 or AS2.
@@ -711,7 +711,7 @@ .maxstack 1
appDomain,
methodBlocks,
symReader,
- moduleVersionId,
+ moduleId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: ilOffset,
@@ -734,7 +734,7 @@ .maxstack 1
appDomain,
methodBlocks,
symReader,
- moduleVersionId,
+ moduleId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: ilOffset,
@@ -797,11 +797,11 @@ private static void VerifyAssemblyReferences(
var modules = references.SelectAsArray(r => r.ToModuleInstance());
using (var runtime = new RuntimeInstance(modules, DebugInformationFormat.Pdb))
{
- var moduleVersionId = target.GetModuleVersionId();
+ var moduleId = new ModuleId(target.GetModuleVersionId(), target.Display ?? "");
var blocks = runtime.Modules.SelectAsArray(m => m.MetadataBlock);
IReadOnlyDictionary> referencesBySimpleName;
- var actualReferences = blocks.MakeAssemblyReferences(moduleVersionId, CompilationExtensions.IdentityComparer, MakeAssemblyReferencesKind.DirectReferencesOnly, out referencesBySimpleName);
+ var actualReferences = blocks.MakeAssemblyReferences(moduleId, CompilationExtensions.IdentityComparer, MakeAssemblyReferencesKind.DirectReferencesOnly, out referencesBySimpleName);
Assert.Null(referencesBySimpleName);
// Verify identities.
var actualIdentities = actualReferences.SelectAsArray(r => r.GetAssemblyIdentity());
@@ -810,9 +810,9 @@ private static void VerifyAssemblyReferences(
var uniqueIdentities = actualIdentities.Distinct();
Assert.Equal(actualIdentities.Length, uniqueIdentities.Length);
- actualReferences = blocks.MakeAssemblyReferences(moduleVersionId, CompilationExtensions.IdentityComparer, MakeAssemblyReferencesKind.AllReferences, out referencesBySimpleName);
+ actualReferences = blocks.MakeAssemblyReferences(moduleId, CompilationExtensions.IdentityComparer, MakeAssemblyReferencesKind.AllReferences, out referencesBySimpleName);
Assert.Equal(2, actualReferences.Length);
- Assert.Equal(moduleVersionId, actualReferences[1].GetModuleVersionId());
+ Assert.Equal(moduleId.Id, actualReferences[1].GetModuleVersionId());
foreach (var reference in references)
{
var identity = reference.GetAssemblyIdentity();
@@ -879,15 +879,15 @@ static void M()
var runtime = CreateRuntimeInstance(new[] { MscorlibRef.ToModuleInstance(), SystemCoreRef.ToModuleInstance(), moduleA, moduleB });
ImmutableArray blocks;
- Guid moduleVersionId;
+ ModuleId moduleId;
ISymUnmanagedReader symReader;
int typeToken;
int methodToken;
int localSignatureToken;
- GetContextState(runtime, "B", out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
+ GetContextState(runtime, "B", out blocks, out moduleId, out symReader, out typeToken, out localSignatureToken);
string errorMessage;
CompilationTestData testData;
- var contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken);
+ var contextFactory = CreateTypeContextFactory(moduleId, typeToken);
// Duplicate type in namespace, at type scope.
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new N.C1()", ImmutableArray.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData);
@@ -899,8 +899,8 @@ IEnumerable CS0433Messages(string type)
}
Assert.Contains(errorMessage, CS0433Messages("C1"));
- GetContextState(runtime, "B.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
- contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken);
+ GetContextState(runtime, "B.M", out blocks, out moduleId, out symReader, out methodToken, out localSignatureToken);
+ contextFactory = CreateMethodContextFactory(moduleId, symReader, methodToken, localSignatureToken);
// Duplicate type in namespace, at method scope.
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new C1()", ImmutableArray.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData);
@@ -915,8 +915,8 @@ IEnumerable CS0433Messages(string type)
Assert.Equal($"error CS0121: {string.Format(CSharpResources.ERR_AmbigCall, "N.E.F(A)", "N.E.F(A)")}", errorMessage);
// Same tests as above but in library that does not directly reference duplicates.
- GetContextState(runtime, "A", out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
- contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken);
+ GetContextState(runtime, "A", out blocks, out moduleId, out symReader, out typeToken, out localSignatureToken);
+ contextFactory = CreateTypeContextFactory(moduleId, typeToken);
// Duplicate type in namespace, at type scope.
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new N.C1()", ImmutableArray.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData);
@@ -931,8 +931,8 @@ .maxstack 1
}");
Assert.Equal(((MethodSymbol)methodData.Method).ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName());
- GetContextState(runtime, "A.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
- contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken);
+ GetContextState(runtime, "A.M", out blocks, out moduleId, out symReader, out methodToken, out localSignatureToken);
+ contextFactory = CreateMethodContextFactory(moduleId, symReader, methodToken, localSignatureToken);
// Duplicate type in global namespace, at method scope.
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new C2()", ImmutableArray.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData);
@@ -1013,11 +1013,11 @@ class C
});
ImmutableArray blocks;
- Guid moduleVersionId;
+ ModuleId moduleId;
ISymUnmanagedReader symReader;
int typeToken;
int localSignatureToken;
- GetContextState(runtime, "C", out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
+ GetContextState(runtime, "C", out blocks, out moduleId, out symReader, out typeToken, out localSignatureToken);
string errorMessage;
CompilationTestData testData;
int attempts = 0;
@@ -1025,8 +1025,8 @@ EvaluationContextBase contextFactory(ImmutableArray b, bool u)
{
attempts++;
return EvaluationContext.CreateTypeContext(
- ToCompilation(b, u, moduleVersionId),
- moduleVersionId,
+ ToCompilation(b, u, moduleId),
+ moduleId,
typeToken);
}
@@ -1178,11 +1178,11 @@ static void M(A a)
});
ImmutableArray blocks;
- Guid moduleVersionId;
+ ModuleId moduleId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
- GetContextState(runtime, "B.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
+ GetContextState(runtime, "B.M", out blocks, out moduleId, out symReader, out methodToken, out localSignatureToken);
var aliases = ImmutableArray.Create(
ExceptionAlias(typeof(ArgumentException)),
@@ -1194,9 +1194,9 @@ EvaluationContextBase contextFactory(ImmutableArray b, bool u)
{
attempts++;
return EvaluationContext.CreateMethodContext(
- ToCompilation(b, u, moduleVersionId),
+ ToCompilation(b, u, moduleId),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion: 1,
ilOffset: 0,
@@ -1296,7 +1296,7 @@ public class Void : Object { }
var metadata = reader.GetMetadata();
var module = metadata.ToModuleMetadata(ignoreAssemblyRefs: true);
var metadataReader = metadata.ToMetadataReader();
- var moduleInstance = ModuleInstance.Create(metadata, metadataReader.GetModuleVersionIdOrThrow());
+ var moduleInstance = ModuleInstance.Create(metadata, new ModuleId(metadataReader.GetModuleVersionIdOrThrow(), module.Name));
// Verify the module declares System.Object.
Assert.True(metadataReader.DeclaresTheObjectClass());
@@ -1416,7 +1416,7 @@ public class Void : Object { }
var metadata = reader.GetMetadata();
var module = metadata.ToModuleMetadata(ignoreAssemblyRefs: true);
var metadataReader = metadata.ToMetadataReader();
- var moduleInstance = ModuleInstance.Create(metadata, metadataReader.GetModuleVersionIdOrThrow(), symReader);
+ var moduleInstance = ModuleInstance.Create(metadata, new ModuleId(metadataReader.GetModuleVersionIdOrThrow(), module.Name), symReader);
// Verify the module declares System.Object.
Assert.True(metadataReader.DeclaresTheObjectClass());
@@ -1488,25 +1488,25 @@ .maxstack 1
}
private static ExpressionCompiler.CreateContextDelegate CreateTypeContextFactory(
- Guid moduleVersionId,
+ ModuleId moduleId,
int typeToken)
{
return (blocks, useReferencedModulesOnly) => EvaluationContext.CreateTypeContext(
- ToCompilation(blocks, useReferencedModulesOnly, moduleVersionId),
- moduleVersionId,
+ ToCompilation(blocks, useReferencedModulesOnly, moduleId),
+ moduleId,
typeToken);
}
private static ExpressionCompiler.CreateContextDelegate CreateMethodContextFactory(
- Guid moduleVersionId,
+ ModuleId moduleId,
ISymUnmanagedReader symReader,
int methodToken,
int localSignatureToken)
{
return (blocks, useReferencedModulesOnly) => EvaluationContext.CreateMethodContext(
- ToCompilation(blocks, useReferencedModulesOnly, moduleVersionId),
+ ToCompilation(blocks, useReferencedModulesOnly, moduleId),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion: 1,
ilOffset: 0,
@@ -1516,9 +1516,9 @@ private static ExpressionCompiler.CreateContextDelegate CreateMethodContextFacto
private static CSharpCompilation ToCompilation(
ImmutableArray blocks,
bool useReferencedModulesOnly,
- Guid moduleVersionId)
+ ModuleId moduleId)
{
- return blocks.ToCompilation(moduleVersionId, useReferencedModulesOnly ? MakeAssemblyReferencesKind.DirectReferencesOnly : MakeAssemblyReferencesKind.AllAssemblies);
+ return blocks.ToCompilation(moduleId, useReferencedModulesOnly ? MakeAssemblyReferencesKind.DirectReferencesOnly : MakeAssemblyReferencesKind.AllAssemblies);
}
private sealed class PEAssemblyBuilderWithAdditionalReferences : PEModuleBuilder, IAssemblyReference
diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/UsingDebugInfoTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/UsingDebugInfoTests.cs
index 27a7d762f5b1c..1bdf2288df498 100644
--- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/UsingDebugInfoTests.cs
+++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/UsingDebugInfoTests.cs
@@ -405,11 +405,11 @@ public void BadPdb_ForwardChain()
importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken2, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings);
Assert.Equal(importString, importStrings.Single().Single());
- Assert.Equal(0, externAliasStrings.Length);
+ Assert.Empty(externAliasStrings);
importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken2, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings);
Assert.Equal(importString, importStrings.Single().Single());
- Assert.Equal(0, externAliasStrings.Length);
+ Assert.Empty(externAliasStrings);
}
[Fact]
diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/BadMetadataModuleException.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/BadMetadataModuleException.cs
new file mode 100644
index 0000000000000..a6eca0167dbfc
--- /dev/null
+++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/BadMetadataModuleException.cs
@@ -0,0 +1,16 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// 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.ExpressionEvaluator;
+
+///
+/// Thrown when trying to evaluate within a module that was not loaded due to bad metadata.
+///
+internal sealed class BadMetadataModuleException(ModuleId moduleId)
+ : Exception($"Unable to evaluate within module '{moduleId.DisplayName}' ({moduleId.Id}): the module metadata is invalid.")
+{
+ public ModuleId ModuleId { get; } = moduleId;
+}
diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs
index d74d15bdb955e..38639903bc862 100644
--- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs
+++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs
@@ -86,7 +86,7 @@ internal static ImmutableArray GetMetadataBlocks(
continue;
}
- Debug.Assert(block.ModuleVersionId == module.Mvid);
+ Debug.Assert(block.ModuleId.Id == module.Mvid);
builder.Add(block);
index++;
}
@@ -177,9 +177,10 @@ private static unsafe bool TryGetMetadataBlock(IntPtr ptr, uint size, out Metada
{
var reader = new MetadataReader((byte*)ptr, (int)size);
var moduleDef = reader.GetModuleDefinition();
- var moduleVersionId = reader.GetGuid(moduleDef.Mvid);
+ var name = reader.GetString(moduleDef.Name);
+ var mvid = reader.GetGuid(moduleDef.Mvid);
var generationId = reader.GetGuid(moduleDef.GenerationId);
- block = new MetadataBlock(moduleVersionId, generationId, ptr, (int)size);
+ block = new MetadataBlock(new ModuleId(mvid, name), generationId, ptr, (int)size);
return true;
}
catch (BadImageFormatException)
@@ -217,17 +218,12 @@ private static bool TryGetMetadataBlock(ImmutableArray previousMe
return clrModule.GetSymUnmanagedReader();
}
- internal static DkmCompiledClrInspectionQuery? ToQueryResult(
- this CompileResult? compResult,
+ internal static DkmCompiledClrInspectionQuery ToQueryResult(
+ this CompileResult compResult,
DkmCompilerId languageId,
ResultProperties resultProperties,
DkmClrRuntimeInstance runtimeInstance)
{
- if (compResult == null)
- {
- return null;
- }
-
Debug.Assert(compResult.Assembly != null);
ReadOnlyCollection? customTypeInfo;
diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/ExpressionCompiler.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/ExpressionCompiler.cs
index 8eed0705b271a..efc3d3308e14d 100644
--- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/ExpressionCompiler.cs
+++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/ExpressionCompiler.cs
@@ -6,6 +6,7 @@
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
@@ -53,8 +54,8 @@ DkmCompiledClrLocalsQuery IDkmClrExpressionCompiler.GetClrLocalVariableQuery(
var aliases = argumentsOnly
? ImmutableArray.Empty
: GetAliases(runtimeInstance, inspectionContext); // NB: Not affected by retrying.
- string? error;
- var r = CompileWithRetry(
+
+ if (TryCompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
@@ -73,8 +74,14 @@ DkmCompiledClrLocalsQuery IDkmClrExpressionCompiler.GetClrLocalVariableQuery(
builder.Free();
return new GetLocalsResult(typeName, locals, assembly);
},
- out error);
- return DkmCompiledClrLocalsQuery.Create(runtimeInstance, null, CompilerId, r.Assembly, r.TypeName, r.Locals);
+ out var result,
+ out var error))
+ {
+ return DkmCompiledClrLocalsQuery.Create(runtimeInstance, null, CompilerId, result.Assembly, result.TypeName, result.Locals);
+ }
+
+ // TODO: better error reporting to the debugger (https://github.com/dotnet/roslyn/issues/76887)
+ throw new BadImageFormatException(error);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
@@ -116,7 +123,8 @@ void IDkmClrExpressionCompiler.CompileExpression(
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = GetAliases(runtimeInstance, inspectionContext); // NB: Not affected by retrying.
- var r = CompileWithRetry(
+
+ if (TryCompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
@@ -131,8 +139,15 @@ void IDkmClrExpressionCompiler.CompileExpression(
testData: null);
return new CompileExpressionResult(compileResult, resultProperties);
},
- out error);
- result = r.CompileResult.ToQueryResult(CompilerId, r.ResultProperties, runtimeInstance);
+ out var r,
+ out error))
+ {
+ result = r.CompileResult?.ToQueryResult(CompilerId, r.ResultProperties, runtimeInstance);
+ }
+ else
+ {
+ result = null;
+ }
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
@@ -152,7 +167,8 @@ void IDkmClrExpressionCompiler.CompileAssignment(
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = GetAliases(runtimeInstance, lValue.InspectionContext); // NB: Not affected by retrying.
- var r = CompileWithRetry(
+
+ if (TryCompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
@@ -170,13 +186,19 @@ void IDkmClrExpressionCompiler.CompileAssignment(
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);
+ out var r,
+ 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);
+ result = r.CompileResult?.ToQueryResult(CompilerId, r.ResultProperties, runtimeInstance);
+ }
+ else
+ {
+ result = null;
+ }
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
@@ -195,11 +217,12 @@ void IDkmClrExpressionCompilerCallback.CompileDisplayAttribute(
{
var runtimeInstance = moduleInstance.RuntimeInstance;
var appDomain = moduleInstance.AppDomain;
- var compileResult = CompileWithRetry(
+
+ if (TryCompileWithRetry(
appDomain,
runtimeInstance,
- (blocks, useReferencedModulesOnly) => CreateTypeContext(appDomain, blocks, moduleInstance.Mvid, token, useReferencedModulesOnly),
- (context, diagnostics) =>
+ createContext: (blocks, useReferencedModulesOnly) => CreateTypeContext(appDomain, blocks, moduleInstance.GetModuleId(), token, useReferencedModulesOnly),
+ compile: (context, diagnostics) =>
{
return context.CompileExpression(
expression.Text,
@@ -209,8 +232,15 @@ void IDkmClrExpressionCompilerCallback.CompileDisplayAttribute(
out var unusedResultProperties,
testData: null);
},
- out error);
- result = compileResult.ToQueryResult(CompilerId, resultProperties: default, runtimeInstance);
+ out var r,
+ out error))
+ {
+ result = r.ToQueryResult(CompilerId, resultProperties: default, runtimeInstance);
+ }
+ else
+ {
+ result = null;
+ }
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
@@ -301,7 +331,7 @@ private void RemoveDataItemIfNecessary(DkmModuleInstance moduleInstance)
internal abstract EvaluationContextBase CreateTypeContext(
DkmClrAppDomain appDomain,
ImmutableArray metadataBlocks,
- Guid moduleVersionId,
+ ModuleId moduleId,
int typeToken,
bool useReferencedModulesOnly);
@@ -310,7 +340,7 @@ internal abstract EvaluationContextBase CreateMethodContext(
ImmutableArray metadataBlocks,
Lazy> lazyAssemblyReaders,
object? symReader,
- Guid moduleVersionId,
+ ModuleId moduleId,
int methodToken,
int methodVersion,
uint ilOffset,
@@ -348,9 +378,9 @@ private EvaluationContextBase CreateMethodContext(
return CreateMethodContext(
moduleInstance.AppDomain,
metadataBlocks,
- new Lazy>(() => instructionAddress.MakeAssemblyReaders(), LazyThreadSafetyMode.None),
+ new Lazy>(instructionAddress.MakeAssemblyReaders, LazyThreadSafetyMode.None),
symReader: moduleInstance.GetSymReader(),
- moduleVersionId: moduleInstance.Mvid,
+ moduleId: moduleInstance.GetModuleId(),
methodToken: methodToken,
methodVersion: (int)instructionAddress.MethodId.Version,
ilOffset: instructionAddress.ILOffset,
@@ -361,41 +391,53 @@ private EvaluationContextBase CreateMethodContext(
internal delegate EvaluationContextBase CreateContextDelegate(ImmutableArray metadataBlocks, bool useReferencedModulesOnly);
internal delegate TResult CompileDelegate(EvaluationContextBase context, DiagnosticBag diagnostics);
- private TResult CompileWithRetry(
+ private bool TryCompileWithRetry(
DkmClrAppDomain appDomain,
DkmClrRuntimeInstance runtimeInstance,
CreateContextDelegate createContext,
CompileDelegate compile,
- out string? errorMessage)
+ [NotNullWhen(true)] out TResult? result,
+ [NotNullWhen(false)] out string? errorMessage)
{
var metadataBlocks = GetMetadataBlocks(appDomain, runtimeInstance);
- return CompileWithRetry(
+ return TryCompileWithRetry(
metadataBlocks,
DiagnosticFormatter,
createContext,
compile,
(AssemblyIdentity assemblyIdentity, out uint size) => appDomain.GetMetaDataBytesPtr(assemblyIdentity.GetDisplayName(), out size),
+ out result,
out errorMessage);
}
- internal static TResult CompileWithRetry(
+ internal static bool TryCompileWithRetry(
ImmutableArray metadataBlocks,
DiagnosticFormatter formatter,
CreateContextDelegate createContext,
CompileDelegate compile,
DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr,
- out string? errorMessage)
+ [NotNullWhen(true)] out TResult? compileResult,
+ [NotNullWhen(false)] out string? errorMessage)
{
- TResult compileResult;
-
PooledHashSet? assembliesLoadedInRetryLoop = null;
bool tryAgain;
var linqLibrary = EvaluationContextBase.SystemLinqIdentity;
do
{
+ EvaluationContextBase context;
+ try
+ {
+ context = createContext(metadataBlocks, useReferencedModulesOnly: false);
+ }
+ catch (BadMetadataModuleException e)
+ {
+ compileResult = default;
+ errorMessage = e.Message;
+ return false;
+ }
+
errorMessage = null;
- var context = createContext(metadataBlocks, useReferencedModulesOnly: false);
var diagnostics = DiagnosticBag.GetInstance();
compileResult = compile(context, diagnostics);
tryAgain = false;
@@ -445,7 +487,7 @@ internal static TResult CompileWithRetry(
} while (tryAgain);
assembliesLoadedInRetryLoop?.Free();
- return compileResult;
+ return errorMessage == null;
}
private static DkmClrLocalVariableInfo ToLocalVariableInfo(LocalAndMethod local)
diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/FrameDecoder.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/FrameDecoder.cs
index c21fff40eeb11..aa1f81e2180fe 100644
--- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/FrameDecoder.cs
+++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/FrameDecoder.cs
@@ -98,7 +98,18 @@ private void GetNameWithGenericTypeArguments(
RoslynDebug.AssertNotNull(frame.InstructionAddress);
var instructionAddress = (DkmClrInstructionAddress)frame.InstructionAddress;
var compilation = _instructionDecoder.GetCompilation(instructionAddress.ModuleInstance);
- var method = _instructionDecoder.GetMethod(compilation, instructionAddress);
+
+ TMethodSymbol? method;
+ try
+ {
+ method = _instructionDecoder.GetMethod(compilation, instructionAddress);
+ }
+ catch (BadMetadataModuleException e)
+ {
+ onFailure(e);
+ return;
+ }
+
var typeParameters = _instructionDecoder.GetAllTypeParameters(method);
if (!typeParameters.IsEmpty)
{
diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LanguageInstructionDecoder.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LanguageInstructionDecoder.cs
index e8a401155f8ca..8e0cc0dc871ea 100644
--- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LanguageInstructionDecoder.cs
+++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LanguageInstructionDecoder.cs
@@ -57,7 +57,7 @@ string IDkmLanguageInstructionDecoder.GetMethodName(DkmLanguageInstructionAddres
return _instructionDecoder.GetName(method, includeParameterTypes, includeParameterNames);
}
}
- catch (NotImplementedMetadataException)
+ catch (Exception e) when (e is NotImplementedMetadataException or BadMetadataModuleException)
{
return languageInstructionAddress.GetMethodName(argumentFlags);
}
diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataBlock.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataBlock.cs
index d2fac14a6d6c4..8d5f4a684eb8b 100644
--- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataBlock.cs
+++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataBlock.cs
@@ -12,41 +12,39 @@ namespace Microsoft.CodeAnalysis.ExpressionEvaluator
/// Module metadata block
///
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
- internal readonly struct MetadataBlock : IEquatable
+ internal readonly struct MetadataBlock(ModuleId moduleId, Guid generationId, IntPtr pointer, int size) : IEquatable
{
///
- /// Module version id.
+ /// Module id.
///
- internal readonly Guid ModuleVersionId;
+ internal readonly ModuleId ModuleId = moduleId;
///
/// Module generation id.
///
- internal readonly Guid GenerationId;
+ internal readonly Guid GenerationId = generationId;
///
/// Pointer to memory block managed by the caller.
///
- internal readonly IntPtr Pointer;
+ internal readonly IntPtr Pointer = pointer;
///
/// Size of memory block.
///
- internal readonly int Size;
+ internal readonly int Size = size;
- internal MetadataBlock(Guid moduleVersionId, Guid generationId, IntPtr pointer, int size)
+ // Used by VS debugger (/src/debugger/ProductionDebug/CodeAnalysis/CodeAnalysis/ExpressionEvaluator.cs)
+ internal MetadataBlock(Guid moduleId, Guid generationId, IntPtr pointer, int size)
+ : this(new ModuleId(moduleId, ""), generationId, pointer, size)
{
- ModuleVersionId = moduleVersionId;
- GenerationId = generationId;
- Pointer = pointer;
- Size = size;
}
public bool Equals(MetadataBlock other)
{
return Pointer == other.Pointer &&
Size == other.Size &&
- ModuleVersionId == other.ModuleVersionId &&
+ ModuleId.Id == other.ModuleId.Id &&
GenerationId == other.GenerationId;
}
@@ -63,12 +61,12 @@ public override int GetHashCode()
{
return Hash.Combine(
Hash.Combine(Pointer.GetHashCode(), Size),
- Hash.Combine(ModuleVersionId.GetHashCode(), GenerationId.GetHashCode()));
+ Hash.Combine(ModuleId.GetHashCode(), GenerationId.GetHashCode()));
}
private string GetDebuggerDisplay()
{
- return string.Format("MetadataBlock {{ Mvid = {{{0}}}, Address = {1}, Size = {2} }}", ModuleVersionId, Pointer, Size);
+ return string.Format("MetadataBlock {{ Mvid = {{{0}}}, Address = {1}, Size = {2} }}", ModuleId, Pointer, Size);
}
}
}
diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataContextId.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataContextId.cs
index 787990c7176a6..b4d15d2bce5f2 100644
--- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataContextId.cs
+++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataContextId.cs
@@ -28,12 +28,12 @@ public override bool Equals(object obj)
public override int GetHashCode()
=> ModuleVersionId.GetHashCode();
- internal static MetadataContextId GetContextId(Guid moduleVersionId, MakeAssemblyReferencesKind kind)
+ internal static MetadataContextId GetContextId(ModuleId moduleId, MakeAssemblyReferencesKind kind)
{
return kind switch
{
MakeAssemblyReferencesKind.AllAssemblies => default,
- MakeAssemblyReferencesKind.AllReferences => new MetadataContextId(moduleVersionId),
+ MakeAssemblyReferencesKind.AllReferences => new MetadataContextId(moduleId.Id),
_ => throw ExceptionUtilities.UnexpectedValue(kind),
};
}
diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataUtilities.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataUtilities.cs
index 3fb1d95d561a1..71dde6191b484 100644
--- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataUtilities.cs
+++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataUtilities.cs
@@ -20,18 +20,18 @@ internal static partial class MetadataUtilities
{
///
/// Group module metadata into assemblies.
- /// If is set, the
+ /// If is set, the
/// assemblies are limited to those referenced by that module.
///
internal static ImmutableArray MakeAssemblyReferences(
this ImmutableArray metadataBlocks,
- Guid moduleVersionId,
+ ModuleId moduleId,
AssemblyIdentityComparer identityComparer,
MakeAssemblyReferencesKind kind,
out IReadOnlyDictionary>? referencesBySimpleName)
{
- RoslynDebug.Assert(kind == MakeAssemblyReferencesKind.AllAssemblies || moduleVersionId != Guid.Empty);
- RoslynDebug.Assert(moduleVersionId == Guid.Empty || identityComparer != null);
+ RoslynDebug.Assert(kind == MakeAssemblyReferencesKind.AllAssemblies || moduleId.Id != Guid.Empty);
+ RoslynDebug.Assert(moduleId.Id == Guid.Empty || identityComparer != null);
// Get metadata for each module.
var metadataBuilder = ArrayBuilder.GetInstance();
@@ -141,7 +141,7 @@ internal static ImmutableArray MakeAssemblyReferences(
refsBySimpleName[identity.Name] = refs.Add((identity, reference));
if (targetReference == null &&
- reader.GetModuleVersionIdOrThrow() == moduleVersionId)
+ reader.GetModuleVersionIdOrThrow() == moduleId.Id)
{
targetReference = reference;
}
@@ -191,7 +191,7 @@ internal static ImmutableArray MakeAssemblyReferences(
identitiesBuilder.Add(identity);
if (targetModule == null &&
- reader.GetModuleVersionIdOrThrow() == moduleVersionId)
+ reader.GetModuleVersionIdOrThrow() == moduleId.Id)
{
targetModule = metadata;
}
diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MethodContextReuseConstraints.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MethodContextReuseConstraints.cs
index bfa603f101369..300ec9f622811 100644
--- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MethodContextReuseConstraints.cs
+++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MethodContextReuseConstraints.cs
@@ -7,37 +7,36 @@
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
-using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal readonly struct MethodContextReuseConstraints
{
- private readonly Guid _moduleVersionId;
+ private readonly ModuleId _moduleId;
private readonly int _methodToken;
private readonly int _methodVersion;
private readonly ILSpan _span;
- internal MethodContextReuseConstraints(Guid moduleVersionId, int methodToken, int methodVersion, ILSpan span)
+ internal MethodContextReuseConstraints(ModuleId moduleId, int methodToken, int methodVersion, ILSpan span)
{
- Debug.Assert(moduleVersionId != Guid.Empty);
+ Debug.Assert(moduleId.Id != Guid.Empty);
Debug.Assert(MetadataTokens.Handle(methodToken).Kind == HandleKind.MethodDefinition);
Debug.Assert(methodVersion >= 1);
- _moduleVersionId = moduleVersionId;
+ _moduleId = moduleId;
_methodToken = methodToken;
_methodVersion = methodVersion;
_span = span;
}
- public bool AreSatisfied(Guid moduleVersionId, int methodToken, int methodVersion, int ilOffset)
+ public bool AreSatisfied(ModuleId moduleId, int methodToken, int methodVersion, int ilOffset)
{
- Debug.Assert(moduleVersionId != Guid.Empty);
+ Debug.Assert(moduleId.Id != Guid.Empty);
Debug.Assert(MetadataTokens.Handle(methodToken).Kind == HandleKind.MethodDefinition);
Debug.Assert(methodVersion >= 1);
Debug.Assert(ilOffset >= 0);
- return moduleVersionId == _moduleVersionId &&
+ return moduleId.Id == _moduleId.Id &&
methodToken == _methodToken &&
methodVersion == _methodVersion &&
_span.Contains(ilOffset);
@@ -45,7 +44,7 @@ public bool AreSatisfied(Guid moduleVersionId, int methodToken, int methodVersio
public override string ToString()
{
- return $"0x{_methodToken:x8}v{_methodVersion} from {_moduleVersionId} {_span}";
+ return $"0x{_methodToken:x8}v{_methodVersion} from {_moduleId.Id} {_span}";
}
///
diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/ModuleId.cs b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/ModuleId.cs
new file mode 100644
index 0000000000000..6f5589aa1771c
--- /dev/null
+++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/ModuleId.cs
@@ -0,0 +1,20 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using Microsoft.VisualStudio.Debugger.Clr;
+
+namespace Microsoft.CodeAnalysis.ExpressionEvaluator;
+
+internal readonly struct ModuleId(Guid id, string displayName)
+{
+ public Guid Id { get; } = id;
+ public string DisplayName { get; } = displayName;
+}
+
+internal static class Extensions
+{
+ public static ModuleId GetModuleId(this DkmClrModuleInstance module)
+ => new(module.Mvid, module.FullName);
+}
diff --git a/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/ExpressionCompilerTestHelpers.cs b/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/ExpressionCompilerTestHelpers.cs
index 7838bdea83a01..03f09c05baa73 100644
--- a/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/ExpressionCompilerTestHelpers.cs
+++ b/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/ExpressionCompilerTestHelpers.cs
@@ -241,19 +241,21 @@ internal static CompileResult CompileExpression(
return result;
}
- internal static CompileResult CompileExpressionWithRetry(
+ internal static bool CompileExpressionWithRetry(
ImmutableArray metadataBlocks,
EvaluationContextBase context,
ExpressionCompiler.CompileDelegate compile,
DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr,
+ out CompileResult compileResult,
out string errorMessage)
{
- return ExpressionCompiler.CompileWithRetry(
+ return ExpressionCompiler.TryCompileWithRetry(
metadataBlocks,
DebuggerDiagnosticFormatter.Instance,
(blocks, useReferencedModulesOnly) => context,
compile,
getMetaDataBytesPtr,
+ out compileResult,
out errorMessage);
}
@@ -266,7 +268,7 @@ internal static CompileResult CompileExpressionWithRetry(
out string errorMessage,
out CompilationTestData testData)
{
- var r = ExpressionCompiler.CompileWithRetry(
+ ExpressionCompiler.TryCompileWithRetry(
metadataBlocks,
DebuggerDiagnosticFormatter.Instance,
createContext,
@@ -284,6 +286,7 @@ internal static CompileResult CompileExpressionWithRetry(
return new CompileExpressionResult(compileResult, td);
},
getMetaDataBytesPtr,
+ out var r,
out errorMessage);
testData = r.TestData;
return r.CompileResult;
@@ -554,12 +557,12 @@ static void sort(ArrayBuilder<(AssemblyIdentity, AssemblyIdentity, int)> builder
#endif
}
- internal static void VerifyAppDomainMetadataContext(MetadataContext metadataContext, Guid[] moduleVersionIds)
+ internal static void VerifyAppDomainMetadataContext(MetadataContext metadataContext, ModuleId[] moduleIds)
where TAssemblyContext : struct
{
var actualIds = metadataContext.AssemblyContexts.Keys.Select(key => key.ModuleVersionId.ToString()).ToArray();
Array.Sort(actualIds);
- var expectedIds = moduleVersionIds.Select(mvid => mvid.ToString()).ToArray();
+ var expectedIds = moduleIds.Select(mvid => mvid.Id.ToString()).ToArray();
Array.Sort(expectedIds);
AssertEx.Equal(expectedIds, actualIds);
}
diff --git a/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/Microsoft.CodeAnalysis.ExpressionCompiler.Utilities.csproj b/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/Microsoft.CodeAnalysis.ExpressionCompiler.Test.Utilities.csproj
similarity index 100%
rename from src/ExpressionEvaluator/Core/Test/ExpressionCompiler/Microsoft.CodeAnalysis.ExpressionCompiler.Utilities.csproj
rename to src/ExpressionEvaluator/Core/Test/ExpressionCompiler/Microsoft.CodeAnalysis.ExpressionCompiler.Test.Utilities.csproj
diff --git a/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/ModuleInstance.cs b/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/ModuleInstance.cs
index 71b52f06663aa..8625983ecad6e 100644
--- a/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/ModuleInstance.cs
+++ b/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/ModuleInstance.cs
@@ -21,20 +21,20 @@ internal sealed class ModuleInstance : IDisposable
internal readonly int MetadataLength;
internal readonly IntPtr MetadataAddress;
- internal readonly Guid ModuleVersionId;
+ internal readonly ModuleId Id;
internal readonly object SymReader;
private readonly bool _includeLocalSignatures;
private ModuleInstance(
Metadata metadata,
- Guid moduleVersionId,
+ ModuleId id,
int metadataLength,
IntPtr metadataAddress,
object symReader,
bool includeLocalSignatures)
{
_metadataOpt = metadata;
- ModuleVersionId = moduleVersionId;
+ Id = id;
MetadataLength = metadataLength;
MetadataAddress = metadataAddress;
SymReader = symReader; // should be non-null if and only if there are symbols
@@ -43,21 +43,21 @@ private ModuleInstance(
public static unsafe ModuleInstance Create(
PEMemoryBlock metadata,
- Guid moduleVersionId,
+ ModuleId id,
ISymUnmanagedReader symReader = null)
{
- return Create((IntPtr)metadata.Pointer, metadata.Length, moduleVersionId, symReader);
+ return Create((IntPtr)metadata.Pointer, metadata.Length, id, symReader);
}
public static ModuleInstance Create(
IntPtr metadataAddress,
int metadataLength,
- Guid moduleVersionId,
+ ModuleId id,
ISymUnmanagedReader symReader = null)
{
return new ModuleInstance(
metadata: null,
- moduleVersionId: moduleVersionId,
+ id: id,
metadataLength: metadataLength,
metadataAddress: metadataAddress,
symReader: symReader,
@@ -84,12 +84,12 @@ private static unsafe ModuleInstance Create(
var assemblyMetadata = metadata as AssemblyMetadata;
var moduleMetadata = (assemblyMetadata == null) ? (ModuleMetadata)metadata : assemblyMetadata.GetModules()[0];
- var moduleId = moduleMetadata.Module.GetModuleVersionIdOrThrow();
+ var mvid = moduleMetadata.Module.GetModuleVersionIdOrThrow();
var metadataBlock = moduleMetadata.Module.PEReaderOpt.GetMetadata();
return new ModuleInstance(
metadata,
- moduleId,
+ new ModuleId(mvid, moduleMetadata.Module.Name),
metadataBlock.Length,
(IntPtr)metadataBlock.Pointer,
symReader,
@@ -100,7 +100,7 @@ private static unsafe ModuleInstance Create(
public MetadataReference GetReference() => (_metadataOpt as AssemblyMetadata)?.GetReference() ?? ((ModuleMetadata)_metadataOpt).GetReference();
- internal MetadataBlock MetadataBlock => new MetadataBlock(ModuleVersionId, Guid.Empty, MetadataAddress, MetadataLength);
+ internal MetadataBlock MetadataBlock => new MetadataBlock(Id, Guid.Empty, MetadataAddress, MetadataLength);
internal unsafe MetadataReader GetMetadataReader() => new MetadataReader((byte*)MetadataAddress, MetadataLength);
diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/CompilationExtensions.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/CompilationExtensions.vb
index 78ac4b0404922..a3c4a78c35992 100644
--- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/CompilationExtensions.vb
+++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/CompilationExtensions.vb
@@ -21,13 +21,13 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
End Function
- Friend Function [GetType](compilation As VisualBasicCompilation, moduleVersionId As Guid, typeToken As Integer) As PENamedTypeSymbol
- Return [GetType](compilation.GetModule(moduleVersionId), CType(MetadataTokens.Handle(typeToken), TypeDefinitionHandle))
+ Friend Function [GetType](compilation As VisualBasicCompilation, moduleId As ModuleId, typeToken As Integer) As PENamedTypeSymbol
+ Return [GetType](compilation.GetModule(moduleId), CType(MetadataTokens.Handle(typeToken), TypeDefinitionHandle))
End Function
- Friend Function GetSourceMethod(compilation As VisualBasicCompilation, moduleVersionId As Guid, methodHandle As MethodDefinitionHandle) As PEMethodSymbol
- Dim method = GetMethod(compilation, moduleVersionId, methodHandle)
+ Friend Function GetSourceMethod(compilation As VisualBasicCompilation, moduleId As ModuleId, methodHandle As MethodDefinitionHandle) As PEMethodSymbol
+ Dim method = GetMethod(compilation, moduleId, methodHandle)
Dim metadataDecoder = New MetadataDecoder(DirectCast(method.ContainingModule, PEModuleSymbol))
Dim containingType = method.ContainingType
Dim sourceMethodName As String = Nothing
@@ -47,8 +47,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
End Function
- Friend Function GetMethod(compilation As VisualBasicCompilation, moduleVersionId As Guid, methodHandle As MethodDefinitionHandle) As PEMethodSymbol
- Dim [module] = compilation.GetModule(moduleVersionId)
+ Friend Function GetMethod(compilation As VisualBasicCompilation, moduleId As ModuleId, methodHandle As MethodDefinitionHandle) As PEMethodSymbol
+ Dim [module] = compilation.GetModule(moduleId)
Dim reader = [module].Module.MetadataReader
Dim typeHandle = reader.GetMethodDefinition(methodHandle).GetDeclaringType()
Dim type = [GetType]([module], typeHandle)
@@ -57,35 +57,35 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
End Function
- Friend Function GetModule(compilation As VisualBasicCompilation, moduleVersionId As Guid) As PEModuleSymbol
+ Friend Function GetModule(compilation As VisualBasicCompilation, moduleId As ModuleId) As PEModuleSymbol
For Each pair In compilation.GetBoundReferenceManager().GetReferencedAssemblies()
Dim assembly = DirectCast(pair.Value, AssemblySymbol)
For Each [module] In assembly.Modules
Dim m = DirectCast([module], PEModuleSymbol)
Dim id = m.Module.GetModuleVersionIdOrThrow()
- If id = moduleVersionId Then
+ If id = moduleId.Id Then
Return m
End If
Next
Next
- Throw New ArgumentException($"No module found with MVID '{moduleVersionId}'", NameOf(moduleVersionId))
+ Throw New BadMetadataModuleException(moduleId)
End Function
Friend Function ToCompilation(metadataBlocks As ImmutableArray(Of MetadataBlock)) As VisualBasicCompilation
- Return ToCompilation(metadataBlocks, moduleVersionId:=Nothing, MakeAssemblyReferencesKind.AllAssemblies)
+ Return ToCompilation(metadataBlocks, moduleId:=Nothing, MakeAssemblyReferencesKind.AllAssemblies)
End Function
- Friend Function ToCompilationReferencedModulesOnly(metadataBlocks As ImmutableArray(Of MetadataBlock), moduleVersionId As Guid) As VisualBasicCompilation
- Return ToCompilation(metadataBlocks, moduleVersionId, MakeAssemblyReferencesKind.DirectReferencesOnly)
+ Friend Function ToCompilationReferencedModulesOnly(metadataBlocks As ImmutableArray(Of MetadataBlock), moduleId As ModuleId) As VisualBasicCompilation
+ Return ToCompilation(metadataBlocks, moduleId, MakeAssemblyReferencesKind.DirectReferencesOnly)
End Function
- Friend Function ToCompilation(metadataBlocks As ImmutableArray(Of MetadataBlock), moduleVersionId As Guid, kind As MakeAssemblyReferencesKind) As VisualBasicCompilation
+ Friend Function ToCompilation(metadataBlocks As ImmutableArray(Of MetadataBlock), moduleId As ModuleId, kind As MakeAssemblyReferencesKind) As VisualBasicCompilation
Dim referencesBySimpleName As IReadOnlyDictionary(Of String, ImmutableArray(Of (AssemblyIdentity, MetadataReference))) = Nothing
- Dim references = metadataBlocks.MakeAssemblyReferences(moduleVersionId, IdentityComparer, kind, referencesBySimpleName)
+ Dim references = metadataBlocks.MakeAssemblyReferences(moduleId, IdentityComparer, kind, referencesBySimpleName)
Dim options = s_compilationOptions
If referencesBySimpleName IsNot Nothing Then
Debug.Assert(kind = MakeAssemblyReferencesKind.AllReferences)
diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EvaluationContext.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EvaluationContext.vb
index eeeb6b15beb10..7512de0a950fd 100644
--- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EvaluationContext.vb
+++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EvaluationContext.vb
@@ -65,7 +65,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
''' Create a context for evaluating expressions at a type scope.
'''
''' Compilation.
- ''' Module containing type.
+ ''' Module containing type.
''' Type metadata token.
''' Evaluation context.
'''
@@ -73,12 +73,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
'''
Friend Shared Function CreateTypeContext(
compilation As VisualBasicCompilation,
- moduleVersionId As Guid,
+ moduleId As ModuleId,
typeToken As Integer) As EvaluationContext
Debug.Assert(MetadataTokens.Handle(typeToken).Kind = HandleKind.TypeDefinition)
- Dim currentType = compilation.GetType(moduleVersionId, typeToken)
+ Dim currentType = compilation.GetType(moduleId, typeToken)
Debug.Assert(currentType IsNot Nothing)
Dim currentFrame = New SynthesizedContextMethodSymbol(currentType)
@@ -97,8 +97,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
'''
''' Previous context, if any, for possible re-use.
''' Module metadata.
- ''' for PDB associated with .
- ''' Module containing method.
+ ''' for PDB associated with .
+ ''' Module containing method.
''' Method metadata token.
''' Method version.
''' IL offset of instruction pointer in method.
@@ -109,7 +109,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
metadataBlocks As ImmutableArray(Of MetadataBlock),
lazyAssemblyReaders As Lazy(Of ImmutableArray(Of AssemblyReaders)),
symReader As Object,
- moduleVersionId As Guid,
+ moduleId As ModuleId,
methodToken As Integer,
methodVersion As Integer,
ilOffset As UInteger,
@@ -123,7 +123,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
compilation,
lazyAssemblyReaders,
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
offset,
@@ -134,8 +134,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
''' Create a context for evaluating expressions within a method scope.
'''
''' Compilation.
- ''' for PDB associated with .
- ''' Module containing method.
+ ''' for PDB associated with .
+ ''' Module containing method.
''' Method metadata token.
''' Method version.
''' IL offset of instruction pointer in method.
@@ -145,17 +145,17 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
compilation As VisualBasicCompilation,
lazyAssemblyReaders As Lazy(Of ImmutableArray(Of AssemblyReaders)),
symReader As Object,
- moduleVersionId As Guid,
+ moduleId As ModuleId,
methodToken As Integer,
methodVersion As Integer,
ilOffset As Integer,
localSignatureToken As Integer) As EvaluationContext
Dim methodHandle = CType(MetadataTokens.Handle(methodToken), MethodDefinitionHandle)
- Dim currentSourceMethod = compilation.GetSourceMethod(moduleVersionId, methodHandle)
+ Dim currentSourceMethod = compilation.GetSourceMethod(moduleId, methodHandle)
Dim localSignatureHandle = If(localSignatureToken <> 0, CType(MetadataTokens.Handle(localSignatureToken), StandaloneSignatureHandle), Nothing)
- Dim currentFrame = compilation.GetMethod(moduleVersionId, methodHandle)
+ Dim currentFrame = compilation.GetMethod(moduleId, methodHandle)
Debug.Assert(currentFrame IsNot Nothing)
Dim symbolProvider = New VisualBasicEESymbolProvider(DirectCast(currentFrame.ContainingModule, PEModuleSymbol), currentFrame)
@@ -190,7 +190,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
localsBuilder.AddRange(debugInfo.LocalConstants)
Return New EvaluationContext(
- New MethodContextReuseConstraints(moduleVersionId, methodToken, methodVersion, reuseSpan),
+ New MethodContextReuseConstraints(moduleId, methodToken, methodVersion, reuseSpan),
compilation,
currentFrame,
currentSourceMethod,
diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicExpressionCompiler.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicExpressionCompiler.vb
index 2bcfa8361a131..899797768e5d8 100644
--- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicExpressionCompiler.vb
+++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicExpressionCompiler.vb
@@ -38,7 +38,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend Overrides Function CreateTypeContext(
appDomain As DkmClrAppDomain,
metadataBlocks As ImmutableArray(Of MetadataBlock),
- moduleVersionId As Guid,
+ moduleId As ModuleId,
typeToken As Integer,
useReferencedModulesOnly As Boolean) As EvaluationContextBase
@@ -46,7 +46,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
appDomain,
Function(ad) ad.GetMetadataContext(Of VisualBasicMetadataContext)(),
metadataBlocks,
- moduleVersionId,
+ moduleId,
typeToken,
GetMakeAssemblyReferencesKind(useReferencedModulesOnly))
End Function
@@ -55,7 +55,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
appDomain As TAppDomain,
getMetadataContext As GetMetadataContextDelegate(Of TAppDomain),
metadataBlocks As ImmutableArray(Of MetadataBlock),
- moduleVersionId As Guid,
+ moduleId As ModuleId,
typeToken As Integer,
kind As MakeAssemblyReferencesKind) As EvaluationContext
@@ -64,14 +64,14 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
If kind = MakeAssemblyReferencesKind.DirectReferencesOnly Then
' Avoid using the cache for referenced assemblies only
' since this should be the exceptional case.
- compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId)
+ compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleId)
Return EvaluationContext.CreateTypeContext(
compilation,
- moduleVersionId,
+ moduleId,
typeToken)
End If
- Dim contextId = MetadataContextId.GetContextId(moduleVersionId, kind)
+ Dim contextId = MetadataContextId.GetContextId(moduleId, kind)
Dim previous = getMetadataContext(appDomain)
Dim previousMetadataContext As VisualBasicMetadataContext = Nothing
If previous.Matches(metadataBlocks) Then
@@ -80,11 +80,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
' Re-use the previous compilation if possible.
compilation = If(previousMetadataContext.Compilation,
- metadataBlocks.ToCompilation(moduleVersionId, kind))
+ metadataBlocks.ToCompilation(moduleId, kind))
Dim context = EvaluationContext.CreateTypeContext(
compilation,
- moduleVersionId,
+ moduleId,
typeToken)
' New type context is not attached to the AppDomain since it is less
@@ -101,7 +101,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
metadataBlocks As ImmutableArray(Of MetadataBlock),
lazyAssemblyReaders As Lazy(Of ImmutableArray(Of AssemblyReaders)),
symReader As Object,
- moduleVersionId As Guid,
+ moduleId As ModuleId,
methodToken As Integer,
methodVersion As Integer,
ilOffset As UInteger,
@@ -115,7 +115,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
metadataBlocks,
lazyAssemblyReaders,
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
ilOffset,
@@ -130,7 +130,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
metadataBlocks As ImmutableArray(Of MetadataBlock),
lazyAssemblyReaders As Lazy(Of ImmutableArray(Of AssemblyReaders)),
symReader As Object,
- moduleVersionId As Guid,
+ moduleId As ModuleId,
methodToken As Integer,
methodVersion As Integer,
ilOffset As UInteger,
@@ -143,19 +143,19 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
If kind = MakeAssemblyReferencesKind.DirectReferencesOnly Then
' Avoid using the cache for referenced assemblies only
' since this should be the exceptional case.
- compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId)
+ compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleId)
Return EvaluationContext.CreateMethodContext(
compilation,
lazyAssemblyReaders,
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
offset,
localSignatureToken)
End If
- Dim contextId = MetadataContextId.GetContextId(moduleVersionId, kind)
+ Dim contextId = MetadataContextId.GetContextId(moduleId, kind)
Dim previous = getMetadataContext(appDomain)
Dim assemblyContexts = If(previous.Matches(metadataBlocks), previous.AssemblyContexts, ImmutableDictionary(Of MetadataContextId, VisualBasicMetadataContext).Empty)
Dim previousMetadataContext As VisualBasicMetadataContext = Nothing
@@ -168,18 +168,18 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Dim previousContext = previousMetadataContext.EvaluationContext
If previousContext IsNot Nothing AndAlso
previousContext.MethodContextReuseConstraints.HasValue AndAlso
- previousContext.MethodContextReuseConstraints.GetValueOrDefault().AreSatisfied(moduleVersionId, methodToken, methodVersion, offset) Then
+ previousContext.MethodContextReuseConstraints.GetValueOrDefault().AreSatisfied(moduleId, methodToken, methodVersion, offset) Then
Return previousContext
End If
Else
- compilation = metadataBlocks.ToCompilation(moduleVersionId, kind)
+ compilation = metadataBlocks.ToCompilation(moduleId, kind)
End If
Dim context = EvaluationContext.CreateMethodContext(
compilation,
lazyAssemblyReaders,
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
offset,
diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicInstructionDecoder.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicInstructionDecoder.vb
index f4e8c8f128f3e..d36a4d64168fe 100644
--- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicInstructionDecoder.vb
+++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicInstructionDecoder.vb
@@ -90,19 +90,19 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend Overrides Function GetCompilation(moduleInstance As DkmClrModuleInstance) As VisualBasicCompilation
Dim appDomain = moduleInstance.AppDomain
- Dim moduleVersionId = moduleInstance.Mvid
+ Dim moduleId = moduleInstance.GetModuleId()
Dim previous = appDomain.GetMetadataContext(Of VisualBasicMetadataContext)()
Dim metadataBlocks = moduleInstance.RuntimeInstance.GetMetadataBlocks(appDomain, previous.MetadataBlocks)
Dim kind = GetMakeAssemblyReferencesKind()
- Dim contextId = MetadataContextId.GetContextId(moduleVersionId, kind)
+ Dim contextId = MetadataContextId.GetContextId(moduleId, kind)
Dim assemblyContexts = If(previous.Matches(metadataBlocks), previous.AssemblyContexts, ImmutableDictionary(Of MetadataContextId, VisualBasicMetadataContext).Empty)
Dim previousContext As VisualBasicMetadataContext = Nothing
assemblyContexts.TryGetValue(contextId, previousContext)
Dim compilation = previousContext.Compilation
If compilation Is Nothing Then
- compilation = metadataBlocks.ToCompilation(moduleVersionId, kind)
+ compilation = metadataBlocks.ToCompilation(moduleId, kind)
appDomain.SetMetadataContext(
New MetadataContext(Of VisualBasicMetadataContext)(
metadataBlocks,
@@ -115,7 +115,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend Overrides Function GetMethod(compilation As VisualBasicCompilation, instructionAddress As DkmClrInstructionAddress) As MethodSymbol
Dim methodHandle = CType(MetadataTokens.Handle(instructionAddress.MethodId.Token), MethodDefinitionHandle)
- Return compilation.GetSourceMethod(instructionAddress.ModuleInstance.Mvid, methodHandle)
+ Return compilation.GetSourceMethod(instructionAddress.ModuleInstance.GetModuleId(), methodHandle)
End Function
Friend Overrides Function GetTypeNameDecoder(compilation As VisualBasicCompilation, method As MethodSymbol) As TypeNameDecoder(Of PEModuleSymbol, TypeSymbol)
diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTestBase.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTestBase.vb
index 59d89d033e287..dc6c949e11817 100644
--- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTestBase.vb
+++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTestBase.vb
@@ -98,23 +98,23 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Friend Shared Function GetContextState(
runtime As RuntimeInstance,
- methodName As String) As (ModuleVersionId As Guid, SymReader As ISymUnmanagedReader, MethodToken As Integer, LocalSignatureToken As Integer, ILOffset As UInteger)
+ methodName As String) As (ModuleId As ModuleId, SymReader As ISymUnmanagedReader, MethodToken As Integer, LocalSignatureToken As Integer, ILOffset As UInteger)
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim methodToken As Integer
Dim localSignatureToken As Integer
- GetContextState(runtime, methodName, blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, methodName, blocks, moduleId, symReader, methodToken, localSignatureToken)
Dim ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader)
- Return (moduleVersionId, symReader, methodToken, localSignatureToken, ilOffset)
+ Return (moduleId, symReader, methodToken, localSignatureToken, ilOffset)
End Function
Friend Shared Sub GetContextState(
runtime As RuntimeInstance,
methodOrTypeName As String,
ByRef blocks As ImmutableArray(Of MetadataBlock),
- ByRef moduleVersionId As Guid,
+ ByRef moduleId As ModuleId,
ByRef symReader As ISymUnmanagedReader,
ByRef methodOrTypeToken As Integer,
ByRef localSignatureToken As Integer)
@@ -125,10 +125,10 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Dim compilation = blocks.ToCompilation()
Dim methodOrType = GetMethodOrTypeBySignature(compilation, methodOrTypeName)
Dim [module] = DirectCast(methodOrType.ContainingModule, PEModuleSymbol)
- Dim id = [module].Module.GetModuleVersionIdOrThrow()
- Dim moduleInstance = moduleInstances.First(Function(m) m.ModuleVersionId = id)
+ Dim mvid = [module].Module.GetModuleVersionIdOrThrow()
+ Dim moduleInstance = moduleInstances.First(Function(m) m.Id.Id = mvid)
- moduleVersionId = id
+ moduleId = moduleInstance.Id
symReader = DirectCast(moduleInstance.SymReader, ISymUnmanagedReader)
Dim methodOrTypeHandle As EntityHandle
@@ -163,7 +163,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Friend Shared Function CreateTypeContext(
appDomain As AppDomain,
metadataBlocks As ImmutableArray(Of MetadataBlock),
- moduleVersionId As Guid,
+ moduleId As ModuleId,
typeToken As Integer,
kind As MakeAssemblyReferencesKind) As EvaluationContext
@@ -171,7 +171,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
appDomain,
Function(ad) ad.GetMetadataContext(),
metadataBlocks,
- moduleVersionId,
+ moduleId,
typeToken,
kind)
End Function
@@ -181,7 +181,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
metadataBlocks As ImmutableArray(Of MetadataBlock),
lazyAssemblyReaders As Lazy(Of ImmutableArray(Of AssemblyReaders)),
symReader As Object,
- moduleVersionId As Guid,
+ moduleId As ModuleId,
methodToken As Integer,
methodVersion As Integer,
ilOffset As UInteger,
@@ -195,7 +195,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
metadataBlocks,
lazyAssemblyReaders,
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
ilOffset,
@@ -206,14 +206,14 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Friend Shared Function CreateMethodContext(
appDomain As AppDomain,
blocks As ImmutableArray(Of MetadataBlock),
- state As (ModuleVersionId As Guid, SymReader As ISymUnmanagedReader, MethodToken As Integer, LocalSignatureToken As Integer, ILOffset As UInteger)) As EvaluationContext
+ state As (ModuleId As ModuleId, SymReader As ISymUnmanagedReader, MethodToken As Integer, LocalSignatureToken As Integer, ILOffset As UInteger)) As EvaluationContext
Return CreateMethodContext(
appDomain,
blocks,
MakeDummyLazyAssemblyReaders(),
state.SymReader,
- state.ModuleVersionId,
+ state.ModuleId,
state.MethodToken,
methodVersion:=1,
state.ILOffset,
@@ -221,13 +221,13 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
MakeAssemblyReferencesKind.AllReferences)
End Function
- Friend Shared Function GetMetadataContext(appDomainContext As MetadataContext(Of VisualBasicMetadataContext), Optional mvid As Guid = Nothing) As VisualBasicMetadataContext
+ Friend Shared Function GetMetadataContext(appDomainContext As MetadataContext(Of VisualBasicMetadataContext), Optional moduleId As ModuleId = Nothing) As VisualBasicMetadataContext
Dim assemblyContexts = appDomainContext.AssemblyContexts
If assemblyContexts Is Nothing Then
Return Nothing
End If
Dim context As VisualBasicMetadataContext = Nothing
- assemblyContexts.TryGetValue(New MetadataContextId(mvid), context)
+ assemblyContexts.TryGetValue(New MetadataContextId(moduleId.Id), context)
Return context
End Function
@@ -244,11 +244,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Optional lazyAssemblyReaders As Lazy(Of ImmutableArray(Of AssemblyReaders)) = Nothing) As EvaluationContext
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim methodToken = 0
Dim localSignatureToken = 0
- GetContextState(runtime, methodName, blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, methodName, blocks, moduleId, symReader, methodToken, localSignatureToken)
Const methodVersion = 1
Dim ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber)
@@ -258,7 +258,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
blocks,
If(lazyAssemblyReaders, MakeDummyLazyAssemblyReaders()),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
ilOffset,
@@ -280,16 +280,16 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
typeName As String) As EvaluationContext
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim typeToken = 0
Dim localSignatureToken = 0
- GetContextState(runtime, typeName, blocks, moduleVersionId, symReader, typeToken, localSignatureToken)
+ GetContextState(runtime, typeName, blocks, moduleId, symReader, typeToken, localSignatureToken)
Return VisualBasicExpressionCompiler.CreateTypeContextHelper(
New AppDomain(),
Function(ad) ad.GetMetadataContext(),
blocks,
- moduleVersionId,
+ moduleId,
typeToken,
MakeAssemblyReferencesKind.AllAssemblies)
End Function
@@ -465,7 +465,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Dim peCompilation = runtime.Modules.SelectAsArray(Function(m) m.MetadataBlock).ToCompilation()
Dim peMethod = peCompilation.GlobalNamespace.GetMember(Of PEMethodSymbol)(qualifiedMethodName)
Dim peModule = DirectCast(peMethod.ContainingModule, PEModuleSymbol)
- Dim symReader = runtime.Modules.Single(Function(mi) mi.ModuleVersionId = peModule.Module.GetModuleVersionIdOrThrow()).SymReader
+ Dim symReader = runtime.Modules.Single(Function(mi) mi.Id.Id = peModule.Module.GetModuleVersionIdOrThrow()).SymReader
Dim symbolProvider = New VisualBasicEESymbolProvider(peModule, peMethod)
Return MethodDebugInfo(Of TypeSymbol, LocalSymbol).ReadMethodDebugInfo(DirectCast(symReader, ISymUnmanagedReader3), symbolProvider, MetadataTokens.GetToken(peMethod.Handle), methodVersion:=1, ilOffset:=ilOffset, isVisualBasicMethod:=True)
End Function
diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTests.vb
index fdc9a9d470428..568aa79b5bdc4 100644
--- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTests.vb
+++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ExpressionCompilerTests.vb
@@ -42,11 +42,11 @@ End Class
Sub(runtime)
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim methodToken = 0
Dim localSignatureToken = 0
- GetContextState(runtime, "C.M", blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, "C.M", blocks, moduleId, symReader, methodToken, localSignatureToken)
Const methodVersion = 1
Dim appDomain = New AppDomain()
@@ -56,7 +56,7 @@ End Class
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
ilOffset,
@@ -74,7 +74,7 @@ End Class
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
ilOffset,
@@ -317,13 +317,13 @@ End Class"
Dim typeBlocks As ImmutableArray(Of MetadataBlock) = Nothing
Dim methodBlocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim typeToken = 0
Dim methodToken = 0
Dim localSignatureToken = 0
- GetContextState(runtime, "C", typeBlocks, moduleVersionId, symReader, typeToken, localSignatureToken)
- GetContextState(runtime, "C.F", methodBlocks, moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, "C", typeBlocks, moduleId, symReader, typeToken, localSignatureToken)
+ GetContextState(runtime, "C.F", methodBlocks, moduleId, symReader, methodToken, localSignatureToken)
' Get non-empty scopes.
Dim scopes = symReader.GetScopes(methodToken, methodVersion, isEndInclusive:=True).WhereAsArray(Function(s) s.Locals.Length > 0)
@@ -334,15 +334,15 @@ End Class"
endOffset = outerScope.EndOffset
' At start of outer scope.
- Dim context = CreateMethodContext(appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleVersionId, methodToken, methodVersion, CType(startOffset, UInteger), localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies)
+ Dim context = CreateMethodContext(appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleId, methodToken, methodVersion, CType(startOffset, UInteger), localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies)
' At end of outer scope - not reused because of the nested scope.
Dim previous = appDomain.GetMetadataContext()
- context = CreateMethodContext(appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleVersionId, methodToken, methodVersion, CType(endOffset, UInteger), localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies)
+ context = CreateMethodContext(appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleId, methodToken, methodVersion, CType(endOffset, UInteger), localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies)
Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext) ' Not required, just documentary.
' At type context.
- context = CreateTypeContext(appDomain, typeBlocks, moduleVersionId, typeToken, MakeAssemblyReferencesKind.AllAssemblies)
+ context = CreateTypeContext(appDomain, typeBlocks, moduleId, typeToken, MakeAssemblyReferencesKind.AllAssemblies)
Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext)
Assert.Null(context.MethodContextReuseConstraints)
Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation)
@@ -354,10 +354,10 @@ End Class"
Dim scope = scopes.GetInnermostScope(offset)
Dim constraints = GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints
If constraints.HasValue Then
- Assert.Equal(scope Is previousScope, constraints.GetValueOrDefault().AreSatisfied(moduleVersionId, methodToken, methodVersion, offset))
+ Assert.Equal(scope Is previousScope, constraints.GetValueOrDefault().AreSatisfied(moduleId, methodToken, methodVersion, offset))
End If
- context = CreateMethodContext(appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleVersionId, methodToken, methodVersion, CType(offset, UInteger), localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies)
+ context = CreateMethodContext(appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleId, methodToken, methodVersion, CType(offset, UInteger), localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies)
If scope Is previousScope Then
Assert.Equal(context, GetMetadataContext(previous).EvaluationContext)
Else
@@ -376,24 +376,24 @@ End Class"
Dim fewerReferences = {MscorlibRef}
runtime = CreateRuntimeInstance(moduleB, fewerReferences)
methodBlocks = Nothing
- moduleVersionId = Nothing
+ moduleId = Nothing
symReader = Nothing
methodToken = 0
localSignatureToken = 0
- GetContextState(runtime, "C.F", methodBlocks, moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, "C.F", methodBlocks, moduleId, symReader, methodToken, localSignatureToken)
' Different references. No reuse.
- context = CreateMethodContext(appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleVersionId, methodToken, methodVersion, CType(endOffset - 1, UInteger), localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies)
+ context = CreateMethodContext(appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleId, methodToken, methodVersion, CType(endOffset - 1, UInteger), localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies)
Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext)
- Assert.True(GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints.Value.AreSatisfied(moduleVersionId, methodToken, methodVersion, endOffset - 1))
+ Assert.True(GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints.Value.AreSatisfied(moduleId, methodToken, methodVersion, endOffset - 1))
Assert.NotEqual(context.Compilation, GetMetadataContext(previous).Compilation)
previous = appDomain.GetMetadataContext()
' Different method. Should reuse Compilation.
- GetContextState(runtime, "C.G", methodBlocks, moduleVersionId, symReader, methodToken, localSignatureToken)
- context = CreateMethodContext(appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleVersionId, methodToken, methodVersion, ilOffset:=0, localSignatureToken:=localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies)
+ GetContextState(runtime, "C.G", methodBlocks, moduleId, symReader, methodToken, localSignatureToken)
+ context = CreateMethodContext(appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleId, methodToken, methodVersion, ilOffset:=0, localSignatureToken:=localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies)
Assert.NotEqual(context, GetMetadataContext(previous).EvaluationContext)
- Assert.False(GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints.Value.AreSatisfied(moduleVersionId, methodToken, methodVersion, 0))
+ Assert.False(GetMetadataContext(previous).EvaluationContext.MethodContextReuseConstraints.Value.AreSatisfied(moduleId, methodToken, methodVersion, 0))
Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation)
' No EvaluationContext. Should reuse Compilation
@@ -401,7 +401,7 @@ End Class"
previous = appDomain.GetMetadataContext()
Assert.Null(GetMetadataContext(previous).EvaluationContext)
Assert.NotNull(GetMetadataContext(previous).Compilation)
- context = CreateMethodContext(appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleVersionId, methodToken, methodVersion, ilOffset:=0, localSignatureToken:=localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies)
+ context = CreateMethodContext(appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleId, methodToken, methodVersion, ilOffset:=0, localSignatureToken:=localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies)
Assert.Null(GetMetadataContext(previous).EvaluationContext)
Assert.NotNull(context)
Assert.Equal(context.Compilation, GetMetadataContext(previous).Compilation)
@@ -3690,7 +3690,7 @@ End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName())
Using pinnedMetadata = New PinnedBlob(TestResources.ExpressionCompiler.NoValidTables)
- Dim corruptMetadata = ModuleInstance.Create(pinnedMetadata.Pointer, pinnedMetadata.Size, moduleVersionId:=Nothing)
+ Dim corruptMetadata = ModuleInstance.Create(pinnedMetadata.Pointer, pinnedMetadata.Size, id:=Nothing)
Dim runtime = CreateRuntimeInstance({corruptMetadata, comp.ToModuleInstance(), MscorlibRef.ToModuleInstance()})
Dim context = CreateMethodContext(runtime, "C.M")
@@ -4126,11 +4126,11 @@ End Class
Dim runtime = CreateRuntimeInstance(module2, {MscorlibRef, ExpressionCompilerTestHelpers.IntrinsicAssemblyReference})
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim symReader2 As ISymUnmanagedReader = Nothing
Dim methodToken As Integer = Nothing
Dim localSignatureToken As Integer = Nothing
- GetContextState(runtime, "C.M", blocks, moduleVersionId, symReader2, methodToken, localSignatureToken)
+ GetContextState(runtime, "C.M", blocks, moduleId, symReader2, methodToken, localSignatureToken)
Assert.Same(symReader, symReader2)
@@ -4142,7 +4142,7 @@ End Class
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken:=methodToken,
methodVersion:=1,
ilOffset:=0,
@@ -4163,7 +4163,7 @@ End Class
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken:=methodToken,
methodVersion:=2,
ilOffset:=0,
@@ -4538,11 +4538,11 @@ End Class"
Sub(runtime)
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim methodToken = 0
Dim localSignatureToken = 0
- GetContextState(runtime, "C.M", blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, "C.M", blocks, moduleId, symReader, methodToken, localSignatureToken)
Dim appDomain = New AppDomain()
Dim context = CreateMethodContext(
@@ -4550,7 +4550,7 @@ End Class"
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion:=1,
ilOffset:=ExpressionCompilerTestHelpers.NoILOffset,
@@ -4578,7 +4578,7 @@ End Class"
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion:=1,
ilOffset:=0,
@@ -4593,7 +4593,7 @@ End Class"
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion:=1,
ilOffset:=ExpressionCompilerTestHelpers.NoILOffset,
diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/HoistedStateMachineLocalTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/HoistedStateMachineLocalTests.vb
index 218e9771e51ac..6a59f8947a0e2 100644
--- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/HoistedStateMachineLocalTests.vb
+++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/HoistedStateMachineLocalTests.vb
@@ -1419,11 +1419,11 @@ End Class
WithRuntimeInstance(comp,
Sub(runtime)
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim methodToken = 0
Dim localSignatureToken = 0
- GetContextState(runtime, "C.VB$StateMachine_1_M.MoveNext", blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, "C.VB$StateMachine_1_M.MoveNext", blocks, moduleId, symReader, methodToken, localSignatureToken)
Const methodVersion = 1
Dim appDomain = New AppDomain()
@@ -1433,7 +1433,7 @@ End Class
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
ilOffset,
@@ -1452,7 +1452,7 @@ End Class
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion,
ilOffset,
diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/InstructionDecoderTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/InstructionDecoderTests.vb
index 97f7db63389c2..e23059f839fb2 100644
--- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/InstructionDecoderTests.vb
+++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/InstructionDecoderTests.vb
@@ -653,7 +653,7 @@ End Class"
' using the same helper as the product code. This helper will also map
' async/ iterator "MoveNext" methods to the original source method.
Dim method As MethodSymbol = compilation.GetSourceMethod(
- DirectCast(frame.ContainingModule, PEModuleSymbol).Module.GetModuleVersionIdOrThrow(),
+ New ModuleId(DirectCast(frame.ContainingModule, PEModuleSymbol).Module.GetModuleVersionIdOrThrow(), frame.ContainingModule.Name),
frame.Handle)
If serializedTypeArgumentNames IsNot Nothing Then
Assert.NotEmpty(serializedTypeArgumentNames)
diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/LocalsTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/LocalsTests.vb
index 06b0ccd3d7737..8ed7524cf3bbc 100644
--- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/LocalsTests.vb
+++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/LocalsTests.vb
@@ -36,8 +36,8 @@ End Class"
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.NotNull(assembly)
- Assert.Equal(0, assembly.Count)
- Assert.Equal(0, locals.Count)
+ Assert.Empty(assembly)
+ Assert.Empty(locals)
locals.Free()
End Sub)
End Sub
@@ -1789,7 +1789,7 @@ End Class"
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "a").WithArguments("A", "Test.dll").WithLocation(1, 1)
})
- Assert.Equal(0, locals.Count)
+ Assert.Empty(locals)
locals.Free()
End Sub)
End Sub
@@ -3373,7 +3373,7 @@ End Class"
Assert.NotNull(assembly)
If count = 0 Then
- Assert.Equal(0, assembly.Count)
+ Assert.Empty(assembly)
Else
Assert.InRange(assembly.Count, 0, Integer.MaxValue)
End If
@@ -3382,10 +3382,10 @@ End Class"
Private Shared Sub GetLocals(runtime As RuntimeInstance, methodName As String, debugInfo As MethodDebugInfoBytes, locals As ArrayBuilder(Of LocalAndMethod), count As Integer)
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim methodToken = 0
Dim localSignatureToken = 0
- GetContextState(runtime, methodName, blocks, moduleVersionId, symReader:=Nothing, methodOrTypeToken:=methodToken, localSignatureToken:=localSignatureToken)
+ GetContextState(runtime, methodName, blocks, moduleId, symReader:=Nothing, methodOrTypeToken:=methodToken, localSignatureToken:=localSignatureToken)
Dim symReader = New MockSymUnmanagedReader(
New Dictionary(Of Integer, MethodDebugInfoBytes)() From
@@ -3397,7 +3397,7 @@ End Class"
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion:=1,
ilOffset:=0,
@@ -3408,7 +3408,7 @@ End Class"
Assert.NotNull(assembly)
If count = 0 Then
- Assert.Equal(0, assembly.Count)
+ Assert.Empty(assembly)
Else
Assert.InRange(assembly.Count, 0, Integer.MaxValue)
End If
diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.UnitTests.vbproj b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.UnitTests.vbproj
index 09fc271070543..1b91ac618bbb1 100644
--- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.UnitTests.vbproj
+++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.UnitTests.vbproj
@@ -16,7 +16,7 @@
-
+
diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/MissingAssemblyTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/MissingAssemblyTests.vb
index 9a76d1d8ab6c1..5b6bd8eeb95f3 100644
--- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/MissingAssemblyTests.vb
+++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/MissingAssemblyTests.vb
@@ -521,6 +521,7 @@ End Class
Dim numRetries = 0
Dim errorMessage As String = Nothing
+ Dim compileResult As CompileResult = Nothing
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
runtime.Modules.Select(Function(m) m.MetadataBlock).ToImmutableArray(),
context,
@@ -534,6 +535,7 @@ End Class
uSize = CUInt(missingModule.MetadataLength)
Return missingModule.MetadataAddress
End Function,
+ compileResult,
errorMessage)
Assert.Equal(2, numRetries) ' Ensure that we actually retried and that we bailed out on the second retry if the same identity was seen in the diagnostics.
@@ -675,12 +677,12 @@ End Class"
WithRuntimeInstance(comp, {Net461.References.mscorlib, ValueTupleLegacyRef},
Sub(runtime)
Dim methodBlocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim typeToken = 0
Dim methodToken = 0
Dim localSignatureToken = 0
- GetContextState(runtime, "C.M", methodBlocks, moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, "C.M", methodBlocks, moduleId, symReader, methodToken, localSignatureToken)
Dim errorMessage As String = Nothing
Dim testData As CompilationTestData = Nothing
Dim retryCount = 0
@@ -688,7 +690,7 @@ End Class"
runtime.Modules.Select(Function(m) m.MetadataBlock).ToImmutableArray(),
expression,
ImmutableArray(Of [Alias]).Empty,
- Function(b, u) EvaluationContext.CreateMethodContext(b.ToCompilation(), MakeDummyLazyAssemblyReaders(), symReader, moduleVersionId, methodToken, methodVersion:=1, ilOffset:=0, localSignatureToken:=localSignatureToken),
+ Function(b, u) EvaluationContext.CreateMethodContext(b.ToCompilation(), MakeDummyLazyAssemblyReaders(), symReader, moduleId, methodToken, methodVersion:=1, ilOffset:=0, localSignatureToken:=localSignatureToken),
Function(assemblyIdentity As AssemblyIdentity, ByRef uSize As UInteger)
retryCount += 1
Assert.Equal("System.Runtime", assemblyIdentity.Name)
diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ReferencedModulesTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ReferencedModulesTests.vb
index 73177efc24708..035e5a7d149dc 100644
--- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ReferencedModulesTests.vb
+++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/ReferencedModulesTests.vb
@@ -191,7 +191,7 @@ End Class"
allBlocks,
MakeDummyLazyAssemblyReaders(),
stateA1.SymReader,
- stateA1.ModuleVersionId,
+ stateA1.ModuleId,
stateA1.MethodToken,
methodVersion:=1,
stateA1.ILOffset,
@@ -213,7 +213,7 @@ End Class"
allBlocks,
MakeDummyLazyAssemblyReaders(),
stateA1.SymReader,
- stateA1.ModuleVersionId,
+ stateA1.ModuleId,
stateA1.MethodToken,
methodVersion:=1,
UInteger.MaxValue,
@@ -275,9 +275,9 @@ End Class"
Dim stateB1 = GetContextState(runtime, "B1.M")
Dim stateB2 = GetContextState(runtime, "B2.M")
- Dim mvidA1 = stateA1.ModuleVersionId
- Dim mvidA2 = stateA2.ModuleVersionId
- Dim mvidB1 = stateB1.ModuleVersionId
+ Dim mvidA1 = stateA1.ModuleId
+ Dim mvidA2 = stateA2.ModuleId
+ Dim mvidB1 = stateB1.ModuleId
Dim context As EvaluationContext
Dim previous As MetadataContext(Of VisualBasicMetadataContext)
@@ -357,8 +357,8 @@ End Class"
End Using
End Sub
- Private Shared Sub VerifyAppDomainMetadataContext(appDomain As AppDomain, ParamArray moduleVersionIds As Guid())
- ExpressionCompilerTestHelpers.VerifyAppDomainMetadataContext(appDomain.GetMetadataContext(), moduleVersionIds)
+ Private Shared Sub VerifyAppDomainMetadataContext(appDomain As AppDomain, ParamArray moduleIds As ModuleId())
+ ExpressionCompilerTestHelpers.VerifyAppDomainMetadataContext(appDomain.GetMetadataContext(), moduleIds)
End Sub
@@ -424,20 +424,20 @@ End Class"
Sub(runtime)
Dim typeBlocks As ImmutableArray(Of MetadataBlock) = Nothing
Dim methodBlocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim typeToken = 0
Dim methodToken = 0
Dim localSignatureToken = 0
- GetContextState(runtime, "C", typeBlocks, moduleVersionId, symReader, typeToken, localSignatureToken)
- GetContextState(runtime, "C.M", methodBlocks, moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, "C", typeBlocks, moduleId, symReader, typeToken, localSignatureToken)
+ GetContextState(runtime, "C.M", methodBlocks, moduleId, symReader, methodToken, localSignatureToken)
' Compile expression with type context.
Dim appDomain = New AppDomain()
Dim context = CreateTypeContext(
appDomain,
typeBlocks,
- moduleVersionId,
+ moduleId,
typeToken,
MakeAssemblyReferencesKind.AllAssemblies)
@@ -464,7 +464,7 @@ End Class"
methodBlocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion:=1,
ilOffset:=0,
@@ -561,13 +561,13 @@ End Class"
})
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim typeToken = 0
Dim methodToken = 0
Dim localSignatureToken = 0
- GetContextState(runtime, "B", blocks, moduleVersionId, symReader, typeToken, localSignatureToken)
- Dim contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken)
+ GetContextState(runtime, "B", blocks, moduleId, symReader, typeToken, localSignatureToken)
+ Dim contextFactory = CreateTypeContextFactory(moduleId, typeToken)
' Duplicate type in namespace, at type scope.
Dim testData As CompilationTestData = Nothing
@@ -575,8 +575,8 @@ End Class"
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New N.C1()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData)
Assert.Equal($"error BC30560: { String.Format(VBResources.ERR_AmbiguousInNamespace2, "C1", "N") }", errorMessage)
- GetContextState(runtime, "B.Main", blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
- contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, "B.Main", blocks, moduleId, symReader, methodToken, localSignatureToken)
+ contextFactory = CreateMethodContextFactory(moduleId, symReader, methodToken, localSignatureToken)
' Duplicate type in namespace, at method scope.
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New C1()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData)
@@ -591,8 +591,8 @@ End Class"
Assert.True(errorMessage.StartsWith($"error BC30521: { String.Format(VBResources.ERR_NoMostSpecificOverload2, "F", "") }"))
' Same tests as above but in library that does not directly reference duplicates.
- GetContextState(runtime, "A", blocks, moduleVersionId, symReader, typeToken, localSignatureToken)
- contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken)
+ GetContextState(runtime, "A", blocks, moduleId, symReader, typeToken, localSignatureToken)
+ contextFactory = CreateTypeContextFactory(moduleId, typeToken)
' Duplicate type in namespace, at type scope.
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New N.C1()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData)
@@ -607,8 +607,8 @@ IL_0005: ret
}")
Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName())
- GetContextState(runtime, "A.M", blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
- contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, "A.M", blocks, moduleId, symReader, methodToken, localSignatureToken)
+ contextFactory = CreateMethodContextFactory(moduleId, symReader, methodToken, localSignatureToken)
' Duplicate type in global namespace, at method scope.
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New C2()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData)
@@ -681,19 +681,19 @@ End Class"
Sub(runtime)
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim typeToken = 0
Dim methodToken = 0
Dim localSignatureToken = 0
- GetContextState(runtime, "C.M", blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, "C.M", blocks, moduleId, symReader, methodToken, localSignatureToken)
Dim context = CreateMethodContext(
New AppDomain(),
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion:=1,
ilOffset:=0,
@@ -704,7 +704,7 @@ End Class"
Assert.Equal(errorMessage, "error BC30562: 'F' is ambiguous between declarations in Modules 'N.M, N.M'.")
Dim testData As New CompilationTestData()
- Dim contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken)
+ Dim contextFactory = CreateMethodContextFactory(moduleId, symReader, methodToken, localSignatureToken)
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "F()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(
@@ -852,7 +852,7 @@ End Namespace"
Dim metadata = reader.GetMetadata()
Dim [module] = metadata.ToModuleMetadata(ignoreAssemblyRefs:=True)
Dim metadataReader = metadata.ToMetadataReader()
- Dim moduleInstance = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.ModuleInstance.Create(metadata, metadataReader.GetModuleVersionIdOrThrow())
+ Dim moduleInstance = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.ModuleInstance.Create(metadata, New ModuleId(metadataReader.GetModuleVersionIdOrThrow(), [module].Name))
' Verify the module declares System.Object.
Assert.True(metadataReader.DeclaresTheObjectClass())
@@ -909,31 +909,31 @@ End Class"
End Sub
Private Shared Function CreateTypeContextFactory(
- moduleVersionId As Guid,
+ moduleId As ModuleId,
typeToken As Integer) As ExpressionCompiler.CreateContextDelegate
Return Function(blocks, useReferencedModulesOnly)
- Dim compilation = If(useReferencedModulesOnly, blocks.ToCompilationReferencedModulesOnly(moduleVersionId), blocks.ToCompilation())
+ Dim compilation = If(useReferencedModulesOnly, blocks.ToCompilationReferencedModulesOnly(moduleId), blocks.ToCompilation())
Return EvaluationContext.CreateTypeContext(
compilation,
- moduleVersionId,
+ moduleId,
typeToken)
End Function
End Function
Private Shared Function CreateMethodContextFactory(
- moduleVersionId As Guid,
+ moduleId As ModuleId,
symReader As ISymUnmanagedReader,
methodToken As Integer,
localSignatureToken As Integer) As ExpressionCompiler.CreateContextDelegate
Return Function(blocks, useReferencedModulesOnly)
- Dim compilation = If(useReferencedModulesOnly, blocks.ToCompilationReferencedModulesOnly(moduleVersionId), blocks.ToCompilation())
+ Dim compilation = If(useReferencedModulesOnly, blocks.ToCompilationReferencedModulesOnly(moduleId), blocks.ToCompilation())
Return EvaluationContext.CreateMethodContext(
compilation,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion:=1,
ilOffset:=0,
diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/StaticLocalsTests.vb b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/StaticLocalsTests.vb
index 97a688fcf41da..24bbc046eb7e8 100644
--- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/StaticLocalsTests.vb
+++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/StaticLocalsTests.vb
@@ -186,17 +186,17 @@ End Class"
WithRuntimeInstance(comp,
Sub(runtime)
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
- Dim moduleVersionId As Guid = Nothing
+ Dim moduleId As ModuleId = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim methodToken = 0
Dim localSignatureToken = 0
- GetContextState(runtime, "C.F(Boolean)", blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, "C.F(Boolean)", blocks, moduleId, symReader, methodToken, localSignatureToken)
Dim context = CreateMethodContext(
New AppDomain(),
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion:=1,
ilOffset:=0,
@@ -233,13 +233,13 @@ End Class"
}")
locals.Free()
- GetContextState(runtime, "C.F(Int32)", blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
+ GetContextState(runtime, "C.F(Int32)", blocks, moduleId, symReader, methodToken, localSignatureToken)
context = CreateMethodContext(
New AppDomain(),
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
- moduleVersionId,
+ moduleId,
methodToken,
methodVersion:=1,
ilOffset:=0,
diff --git a/src/Features/CSharp/Portable/ConvertAutoPropertyToFullProperty/CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/ConvertAutoPropertyToFullProperty/CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider.cs
index 363f5336084e2..c238e4b2dd533 100644
--- a/src/Features/CSharp/Portable/ConvertAutoPropertyToFullProperty/CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider.cs
+++ b/src/Features/CSharp/Portable/ConvertAutoPropertyToFullProperty/CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider.cs
@@ -9,6 +9,7 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.ConvertAutoPropertyToFullProperty;
@@ -24,6 +25,7 @@
namespace Microsoft.CodeAnalysis.CSharp.ConvertAutoPropertyToFullProperty;
using static CSharpSyntaxTokens;
+using static SyntaxFactory;
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertAutoPropertyToFullProperty), Shared]
[method: ImportingConstructor]
@@ -44,73 +46,81 @@ protected override async Task GetFieldNameAsync(Document document, IProp
}
protected override (SyntaxNode newGetAccessor, SyntaxNode newSetAccessor) GetNewAccessors(
- CSharpCodeGenerationContextInfo info, PropertyDeclarationSyntax property,
- string fieldName, SyntaxGenerator generator, CancellationToken cancellationToken)
+ CSharpCodeGenerationContextInfo info,
+ PropertyDeclarationSyntax property,
+ string fieldName,
+ CancellationToken cancellationToken)
+ {
+ // Replace the bodies with bodies that reference the new field name.
+ return GetNewAccessors(info, property, fieldName.ToIdentifierName(), cancellationToken);
+ }
+
+ private static (SyntaxNode newGetAccessor, SyntaxNode newSetAccessor) GetNewAccessors(
+ CSharpCodeGenerationContextInfo info,
+ PropertyDeclarationSyntax property,
+ ExpressionSyntax backingFieldExpression,
+ CancellationToken cancellationToken)
{
// C# might have trivia with the accessors that needs to be preserved.
// so we will update the existing accessors instead of creating new ones
var accessorListSyntax = property.AccessorList;
var (getAccessor, setAccessor) = GetExistingAccessors(accessorListSyntax);
- var getAccessorStatement = generator.ReturnStatement(generator.IdentifierName(fieldName));
- var newGetter = GetUpdatedAccessor(info, getAccessor, getAccessorStatement, cancellationToken);
+ var getAccessorStatement = ReturnStatement(backingFieldExpression);
+ var newGetter = GetUpdatedAccessor(getAccessor, getAccessorStatement);
var newSetter = setAccessor;
if (newSetter != null)
{
- var setAccessorStatement = generator.ExpressionStatement(generator.AssignmentStatement(
- generator.IdentifierName(fieldName),
- generator.IdentifierName("value")));
- newSetter = GetUpdatedAccessor(info, setAccessor, setAccessorStatement, cancellationToken);
+ var setAccessorStatement = ExpressionStatement(AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ backingFieldExpression,
+ IdentifierName("value")));
+ newSetter = GetUpdatedAccessor(setAccessor, setAccessorStatement);
}
return (newGetter, newSetter);
- }
- private static (AccessorDeclarationSyntax getAccessor, AccessorDeclarationSyntax setAccessor)
- GetExistingAccessors(AccessorListSyntax accessorListSyntax)
- => (accessorListSyntax.Accessors.FirstOrDefault(a => a.IsKind(SyntaxKind.GetAccessorDeclaration)),
- accessorListSyntax.Accessors.FirstOrDefault(a => a.Kind() is SyntaxKind.SetAccessorDeclaration or SyntaxKind.InitAccessorDeclaration));
+ AccessorDeclarationSyntax GetUpdatedAccessor(AccessorDeclarationSyntax accessor, StatementSyntax statement)
+ {
+ if (accessor.Body != null || accessor.ExpressionBody != null)
+ return ReplaceFieldExpression(accessor);
- private static AccessorDeclarationSyntax GetUpdatedAccessor(CSharpCodeGenerationContextInfo info,
- AccessorDeclarationSyntax accessor, SyntaxNode statement, CancellationToken cancellationToken)
- {
- if (accessor.Body != null || accessor.ExpressionBody != null)
- return accessor;
+ var accessorDeclarationSyntax = accessor.WithBody(Block(
+ OpenBraceToken.WithLeadingTrivia(ElasticCarriageReturnLineFeed),
+ [statement],
+ CloseBraceToken.WithTrailingTrivia(accessor.SemicolonToken.TrailingTrivia)));
- var newAccessor = AddStatement(accessor, statement);
- var accessorDeclarationSyntax = (AccessorDeclarationSyntax)newAccessor;
+ var preference = info.Options.PreferExpressionBodiedAccessors.Value;
+ if (preference == ExpressionBodyPreference.Never)
+ return accessorDeclarationSyntax.WithSemicolonToken(default);
- var preference = info.Options.PreferExpressionBodiedAccessors.Value;
- if (preference == ExpressionBodyPreference.Never)
- {
- return accessorDeclarationSyntax.WithSemicolonToken(default);
+ if (!accessorDeclarationSyntax.Body.TryConvertToArrowExpressionBody(
+ accessorDeclarationSyntax.Kind(), info.LanguageVersion, preference, cancellationToken,
+ out var arrowExpression, out _))
+ {
+ return accessorDeclarationSyntax.WithSemicolonToken(default);
+ }
+
+ return accessorDeclarationSyntax
+ .WithExpressionBody(arrowExpression)
+ .WithBody(null)
+ .WithSemicolonToken(accessorDeclarationSyntax.SemicolonToken)
+ .WithAdditionalAnnotations(Formatter.Annotation);
}
- if (!accessorDeclarationSyntax.Body.TryConvertToArrowExpressionBody(
- accessorDeclarationSyntax.Kind(), info.LanguageVersion, preference, cancellationToken,
- out var arrowExpression, out _))
+ AccessorDeclarationSyntax ReplaceFieldExpression(AccessorDeclarationSyntax accessor)
{
- return accessorDeclarationSyntax.WithSemicolonToken(default);
+ return accessor.ReplaceNodes(
+ accessor.DescendantNodes().OfType(),
+ (oldNode, _) => backingFieldExpression.WithTriviaFrom(oldNode));
}
-
- return accessorDeclarationSyntax
- .WithExpressionBody(arrowExpression)
- .WithBody(null)
- .WithSemicolonToken(accessorDeclarationSyntax.SemicolonToken)
- .WithAdditionalAnnotations(Formatter.Annotation);
}
- internal static SyntaxNode AddStatement(SyntaxNode accessor, SyntaxNode statement)
- {
- var blockSyntax = SyntaxFactory.Block(
- OpenBraceToken.WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed),
- new SyntaxList((StatementSyntax)statement),
- CloseBraceToken
- .WithTrailingTrivia(((AccessorDeclarationSyntax)accessor).SemicolonToken.TrailingTrivia));
-
- return ((AccessorDeclarationSyntax)accessor).WithBody(blockSyntax);
- }
+ private static (AccessorDeclarationSyntax getAccessor, AccessorDeclarationSyntax setAccessor)
+ GetExistingAccessors(AccessorListSyntax accessorListSyntax)
+ => (accessorListSyntax.Accessors.FirstOrDefault(a => a.IsKind(SyntaxKind.GetAccessorDeclaration)),
+ accessorListSyntax.Accessors.FirstOrDefault(a => a.Kind() is SyntaxKind.SetAccessorDeclaration or SyntaxKind.InitAccessorDeclaration));
protected override SyntaxNode ConvertPropertyToExpressionBodyIfDesired(
CSharpCodeGenerationContextInfo info, SyntaxNode property)
@@ -142,9 +152,25 @@ protected override SyntaxNode ConvertPropertyToExpressionBodyIfDesired(
protected override SyntaxNode GetTypeBlock(SyntaxNode syntaxNode)
=> syntaxNode;
- protected override SyntaxNode GetInitializerValue(SyntaxNode property)
- => ((PropertyDeclarationSyntax)property).Initializer?.Value;
+ protected override SyntaxNode GetInitializerValue(PropertyDeclarationSyntax property)
+ => property.Initializer?.Value;
- protected override SyntaxNode GetPropertyWithoutInitializer(SyntaxNode property)
- => ((PropertyDeclarationSyntax)property).WithInitializer(null);
+ protected override PropertyDeclarationSyntax GetPropertyWithoutInitializer(PropertyDeclarationSyntax property)
+ => property.WithInitializer(null);
+
+ protected override async Task ExpandToFieldPropertyAsync(
+ Document document, PropertyDeclarationSyntax property, CancellationToken cancellationToken)
+ {
+ var info = (CSharpCodeGenerationContextInfo)await document.GetCodeGenerationInfoAsync(CodeGenerationContext.Default, cancellationToken).ConfigureAwait(false);
+
+ var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
+
+ // Update the getter/setter to reference the 'field' expression instead.
+ var (newGetAccessor, newSetAccessor) = GetNewAccessors(info, property, FieldExpression(), cancellationToken);
+
+ var finalProperty = CreateFinalProperty(document, property, info, newGetAccessor, newSetAccessor);
+ var finalRoot = root.ReplaceNode(property, finalProperty);
+
+ return document.WithSyntaxRoot(finalRoot);
+ }
}
diff --git a/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs b/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs
index 188db75a521b6..b15aa6882b6f9 100644
--- a/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs
+++ b/src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs
@@ -15,8 +15,6 @@
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Differencing;
using Microsoft.CodeAnalysis.EditAndContinue;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
@@ -26,17 +24,11 @@
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue;
-internal sealed class CSharpEditAndContinueAnalyzer(Action? testFaultInjector = null) : AbstractEditAndContinueAnalyzer(testFaultInjector)
+[ExportLanguageService(typeof(IEditAndContinueAnalyzer), LanguageNames.CSharp), Shared]
+[method: ImportingConstructor]
+[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
+internal sealed class CSharpEditAndContinueAnalyzer() : AbstractEditAndContinueAnalyzer
{
- [ExportLanguageServiceFactory(typeof(IEditAndContinueAnalyzer), LanguageNames.CSharp), Shared]
- [method: ImportingConstructor]
- [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- internal sealed class Factory() : ILanguageServiceFactory
- {
- public ILanguageService CreateLanguageService(HostLanguageServices languageServices)
- => new CSharpEditAndContinueAnalyzer(testFaultInjector: null);
- }
-
#region Syntax Analysis
private enum BlockPart
diff --git a/src/Features/CSharp/Portable/Structure/CSharpStructureHelpers.cs b/src/Features/CSharp/Portable/Structure/CSharpStructureHelpers.cs
index e7b9ea1f7f0b0..f32d1420cf2c7 100644
--- a/src/Features/CSharp/Portable/Structure/CSharpStructureHelpers.cs
+++ b/src/Features/CSharp/Portable/Structure/CSharpStructureHelpers.cs
@@ -187,14 +187,14 @@ public static void CollectCommentBlockSpans(
else if (trivia is not SyntaxTrivia(
SyntaxKind.WhitespaceTrivia or SyntaxKind.EndOfLineTrivia or SyntaxKind.EndOfFileToken))
{
- completeSingleLineCommentGroup(spans);
+ CompleteSingleLineCommentGroup(spans);
}
}
- completeSingleLineCommentGroup(spans);
+ CompleteSingleLineCommentGroup(spans);
return;
- void completeSingleLineCommentGroup(ArrayBuilder spans)
+ void CompleteSingleLineCommentGroup(ArrayBuilder spans)
{
if (startComment != null)
{
diff --git a/src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.cs
index 7b8d2062f5c84..5c96efa3c8be2 100644
--- a/src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.cs
+++ b/src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.cs
@@ -142,6 +142,9 @@ protected override void CollectBlockSpans(
type: type));
}
}
+
+ // Add any leading comments before the end of the block
+ CSharpStructureHelpers.CollectCommentBlockSpans(node.CloseBraceToken.LeadingTrivia, spans);
}
private static bool IsNonBlockStatement(SyntaxNode node)
diff --git a/src/Features/CSharp/Portable/Structure/Providers/TypeDeclarationStructureProvider.cs b/src/Features/CSharp/Portable/Structure/Providers/TypeDeclarationStructureProvider.cs
index 11ed11b058e17..f58c8340f1818 100644
--- a/src/Features/CSharp/Portable/Structure/Providers/TypeDeclarationStructureProvider.cs
+++ b/src/Features/CSharp/Portable/Structure/Providers/TypeDeclarationStructureProvider.cs
@@ -11,7 +11,7 @@
namespace Microsoft.CodeAnalysis.CSharp.Structure;
-internal class TypeDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider
+internal sealed class TypeDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider
{
protected override void CollectBlockSpans(
SyntaxToken previousToken,
diff --git a/src/Features/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.cs b/src/Features/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.cs
index 1b2b5314f5350..111cea0267bfa 100644
--- a/src/Features/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.cs
+++ b/src/Features/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.cs
@@ -6,6 +6,7 @@
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.ConvertAutoPropertyToFullProperty;
+using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
@@ -14,9 +15,9 @@
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertAutoPropertyToFullProperty;
[Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
-public partial class ConvertAutoPropertyToFullPropertyTests : AbstractCSharpCodeActionTest_NoEditor
+public sealed partial class ConvertAutoPropertyToFullPropertyTests : AbstractCSharpCodeActionTest_NoEditor
{
- private static readonly CSharpParseOptions s_preview = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview);
+ private static readonly CSharpParseOptions CSharp14 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersionExtensions.CSharpNext);
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(TestWorkspace workspace, TestParameters parameters)
=> new CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider();
@@ -762,6 +763,25 @@ class TestClass
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiesOnAccessorsAndMethods);
}
+ [Fact]
+ public async Task GetterOnlyExpressionBodies_Field()
+ {
+ var text = """
+ class TestClass
+ {
+ public int G[||]oo { get;}
+ }
+ """;
+ var expected = """
+ class TestClass
+ {
+ public int Goo => field;
+ }
+ """;
+ await TestInRegularAndScriptAsync(
+ text, expected, options: PreferExpressionBodiesOnAccessorsAndMethods, index: 1, parseOptions: CSharp14);
+ }
+
[Fact]
public async Task SetterOnly()
{
@@ -1384,14 +1404,44 @@ int [||]P
get => p;
set
{
- M(field);
- field = value;
+ M(p);
+ p = value;
}
}
void M(int i) { }
}
""",
- parseOptions: s_preview);
+ parseOptions: CSharp14);
+ }
+
+ [Theory]
+ [InlineData("set"), InlineData("init")]
+ [WorkItem("https://github.com/dotnet/roslyn/issues/76899")]
+ public async Task ProduceFieldBackedProperty(string setter)
+ {
+ var text = $$"""
+ class TestClass
+ {
+ public int G[||]oo { get; {{setter}}; }
+ }
+ """;
+ var expected = $$"""
+ class TestClass
+ {
+ public int Goo
+ {
+ get
+ {
+ return field;
+ }
+ {{setter}}
+ {
+ field = value;
+ }
+ }
+ }
+ """;
+ await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors, index: 1, parseOptions: CSharp14);
}
}
diff --git a/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTests.cs b/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTests.cs
index eafccb6be22a1..7d9906343d41b 100644
--- a/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTests.cs
+++ b/src/Features/CSharpTest/Diagnostics/Suppression/SuppressionTests.cs
@@ -458,7 +458,7 @@ void Method()
[suppressionProviderFactory]);
var document = GetDocumentAndSelectSpan(workspace, out var span);
var diagnostics = await diagnosticService.GetDiagnosticsForSpanAsync(
- document, span, DiagnosticKind.All, includeSuppressedDiagnostics: false, CancellationToken.None);
+ document, span, DiagnosticKind.All, CancellationToken.None);
Assert.Equal(2, diagnostics.Where(d => d.Id == "CS0219").Count());
var allFixes = (await fixService.GetFixesAsync(document, span, CancellationToken.None))
diff --git a/src/Features/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs b/src/Features/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs
index 292dd30d98dc6..84f7c5020d8ae 100644
--- a/src/Features/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs
+++ b/src/Features/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs
@@ -122,10 +122,11 @@ private static async Task AnalyzeDocumentAsync(
EditAndContinueCapabilities capabilities = EditAndContinueTestVerifier.Net5RuntimeCapabilities,
ImmutableArray newActiveStatementSpans = default)
{
- var analyzer = new CSharpEditAndContinueAnalyzer();
+ var analyzer = oldProject.Services.GetRequiredService();
var baseActiveStatements = AsyncLazy.Create(activeStatementMap ?? ActiveStatementsMap.Empty);
var lazyCapabilities = AsyncLazy.Create(capabilities);
- return await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newDocument, newActiveStatementSpans.NullToEmpty(), lazyCapabilities, CancellationToken.None);
+ var log = new TraceLog("Test");
+ return await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newDocument, newActiveStatementSpans.NullToEmpty(), lazyCapabilities, log, CancellationToken.None);
}
#endregion
@@ -749,15 +750,17 @@ public async Task AnalyzeDocumentAsync_InternalError(bool outOfMemory)
var baseActiveStatements = AsyncLazy.Create(ActiveStatementsMap.Empty);
var capabilities = AsyncLazy.Create(EditAndContinueTestVerifier.Net5RuntimeCapabilities);
- var analyzer = new CSharpEditAndContinueAnalyzer(node =>
+ var analyzer = Assert.IsType(oldProject.Services.GetRequiredService());
+ analyzer.GetTestAccessor().FaultInjector = node =>
{
if (node is CompilationUnitSyntax)
{
throw outOfMemory ? new OutOfMemoryException() : new NullReferenceException("NullRef!");
}
- });
+ };
- var result = await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newDocument, [], capabilities, CancellationToken.None);
+ var log = new TraceLog("Test");
+ var result = await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newDocument, [], capabilities, log, CancellationToken.None);
var expectedDiagnostic = outOfMemory
? $"ENC0089: {string.Format(FeaturesResources.Modifying_source_file_0_requires_restarting_the_application_because_the_file_is_too_big, filePath)}"
diff --git a/src/Features/CSharpTest/EditAndContinue/Helpers/CSharpEditAndContinueTestVerifier.cs b/src/Features/CSharpTest/EditAndContinue/Helpers/CSharpEditAndContinueTestVerifier.cs
index 2c38995e0dce1..8dcdd79f7b572 100644
--- a/src/Features/CSharpTest/EditAndContinue/Helpers/CSharpEditAndContinueTestVerifier.cs
+++ b/src/Features/CSharpTest/EditAndContinue/Helpers/CSharpEditAndContinueTestVerifier.cs
@@ -6,17 +6,13 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Differencing;
-using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.EditAndContinue.UnitTests;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests;
-internal sealed class CSharpEditAndContinueTestVerifier(Action? faultInjector = null) : EditAndContinueTestVerifier
+internal sealed class CSharpEditAndContinueTestVerifier(Action? faultInjector = null) : EditAndContinueTestVerifier(faultInjector)
{
- private readonly CSharpEditAndContinueAnalyzer _analyzer = new(faultInjector);
-
- public override AbstractEditAndContinueAnalyzer Analyzer => _analyzer;
public override string LanguageName => LanguageNames.CSharp;
public override string ProjectFileExtension => ".csproj";
public override TreeComparer TopSyntaxComparer => SyntaxComparer.TopLevel;
diff --git a/src/Features/CSharpTest/EditAndContinue/Helpers/EditAndContinueValidation.cs b/src/Features/CSharpTest/EditAndContinue/Helpers/EditAndContinueValidation.cs
index 252a5c1ec6764..0d8f89d47c2fa 100644
--- a/src/Features/CSharpTest/EditAndContinue/Helpers/EditAndContinueValidation.cs
+++ b/src/Features/CSharpTest/EditAndContinue/Helpers/EditAndContinueValidation.cs
@@ -2,9 +2,8 @@
// 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.Differencing;
-using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Contracts.EditAndContinue;
+using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.EditAndContinue.UnitTests;
using Roslyn.Test.Utilities;
using Xunit;
diff --git a/src/Features/CSharpTest/EditAndContinue/Helpers/EditingTestBase.cs b/src/Features/CSharpTest/EditAndContinue/Helpers/EditingTestBase.cs
index 89fe647d5c4fd..778bff54e0d09 100644
--- a/src/Features/CSharpTest/EditAndContinue/Helpers/EditingTestBase.cs
+++ b/src/Features/CSharpTest/EditAndContinue/Helpers/EditingTestBase.cs
@@ -5,14 +5,16 @@
using System;
using System.Collections.Generic;
using System.IO;
+using System.Linq;
+using Microsoft.CodeAnalysis.Contracts.EditAndContinue;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Differencing;
using Microsoft.CodeAnalysis.EditAndContinue;
-using Microsoft.CodeAnalysis.Contracts.EditAndContinue;
using Microsoft.CodeAnalysis.EditAndContinue.UnitTests;
using Microsoft.CodeAnalysis.Emit;
+using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
@@ -27,11 +29,6 @@ public abstract class EditingTestBase : CSharpTestBase
namespace System.Runtime.CompilerServices { class CreateNewOnMetadataUpdateAttribute : Attribute {} }
";
- internal static CSharpEditAndContinueAnalyzer CreateAnalyzer()
- {
- return new CSharpEditAndContinueAnalyzer(testFaultInjector: null);
- }
-
internal enum MethodKind
{
Regular,
@@ -184,7 +181,8 @@ internal static Match GetMethodMatch(string src1, string src2, Metho
internal static IEnumerable> GetMethodMatches(string src1, string src2, MethodKind kind = MethodKind.Regular)
{
var methodMatch = GetMethodMatch(src1, src2, kind);
- return EditAndContinueTestVerifier.GetMethodMatches(CreateAnalyzer(), methodMatch);
+ var analyzer = EditAndContinueTestVerifier.CreateAnalyzer(faultInjector: null, LanguageNames.CSharp);
+ return EditAndContinueTestVerifier.GetMethodMatches(analyzer, methodMatch);
}
public static MatchingPairs ToMatchingPairs(Match match)
diff --git a/src/Features/CSharpTest/EditAndContinue/StatementMatchingTests.cs b/src/Features/CSharpTest/EditAndContinue/StatementMatchingTests.cs
index 6e6ebef35347a..cc2bd04c9dc14 100644
--- a/src/Features/CSharpTest/EditAndContinue/StatementMatchingTests.cs
+++ b/src/Features/CSharpTest/EditAndContinue/StatementMatchingTests.cs
@@ -7,11 +7,13 @@
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.EditAndContinue.UnitTests;
+using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests;
+[UseExportProvider]
public class StatementMatchingTests : EditingTestBase
{
#region Known Matches
diff --git a/src/Features/CSharpTest/Microsoft.CodeAnalysis.CSharp.Features.UnitTests.csproj b/src/Features/CSharpTest/Microsoft.CodeAnalysis.CSharp.Features.UnitTests.csproj
index da6edb8aff9f5..9b2e042ff8414 100644
--- a/src/Features/CSharpTest/Microsoft.CodeAnalysis.CSharp.Features.UnitTests.csproj
+++ b/src/Features/CSharpTest/Microsoft.CodeAnalysis.CSharp.Features.UnitTests.csproj
@@ -3,7 +3,8 @@
Library
- $(NetRoslyn);net472
+
+ $(NetVSShared);net472
Microsoft.CodeAnalysis.CSharp.UnitTests
true
@@ -21,7 +22,7 @@
SemanticSearch_RefAssemblies
- TargetFramework=$(NetRoslyn)
+ TargetFramework=$(NetVS)
diff --git a/src/Features/Core/Portable/CodeRefactorings/ExtractMethod/AbstractExtractMethodCodeRefactoringProvider.cs b/src/Features/Core/Portable/CodeRefactorings/ExtractMethod/AbstractExtractMethodCodeRefactoringProvider.cs
index c6bac26aa5ebc..24ef70bf21c2a 100644
--- a/src/Features/Core/Portable/CodeRefactorings/ExtractMethod/AbstractExtractMethodCodeRefactoringProvider.cs
+++ b/src/Features/Core/Portable/CodeRefactorings/ExtractMethod/AbstractExtractMethodCodeRefactoringProvider.cs
@@ -25,6 +25,8 @@ namespace Microsoft.CodeAnalysis.CodeRefactorings.ExtractMethod;
[method: SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
internal sealed class ExtractMethodCodeRefactoringProvider() : CodeRefactoringProvider
{
+ internal override CodeRefactoringKind Kind => CodeRefactoringKind.Extract;
+
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
// Don't bother if there isn't a selection
diff --git a/src/Features/Core/Portable/ConvertAutoPropertyToFullProperty/AbstractConvertAutoPropertyToFullPropertyCodeRefactoringProvider.cs b/src/Features/Core/Portable/ConvertAutoPropertyToFullProperty/AbstractConvertAutoPropertyToFullPropertyCodeRefactoringProvider.cs
index 6001d0c2cc020..9fdb11ae24361 100644
--- a/src/Features/Core/Portable/ConvertAutoPropertyToFullProperty/AbstractConvertAutoPropertyToFullPropertyCodeRefactoringProvider.cs
+++ b/src/Features/Core/Portable/ConvertAutoPropertyToFullProperty/AbstractConvertAutoPropertyToFullPropertyCodeRefactoringProvider.cs
@@ -11,6 +11,7 @@
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
+using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
@@ -23,11 +24,12 @@ internal abstract class AbstractConvertAutoPropertyToFullPropertyCodeRefactoring
{
protected abstract Task GetFieldNameAsync(Document document, IPropertySymbol propertySymbol, CancellationToken cancellationToken);
protected abstract (SyntaxNode newGetAccessor, SyntaxNode? newSetAccessor) GetNewAccessors(
- TCodeGenerationContextInfo info, TPropertyDeclarationNode property, string fieldName, SyntaxGenerator generator, CancellationToken cancellationToken);
- protected abstract SyntaxNode GetPropertyWithoutInitializer(SyntaxNode property);
- protected abstract SyntaxNode GetInitializerValue(SyntaxNode property);
+ TCodeGenerationContextInfo info, TPropertyDeclarationNode property, string fieldName, CancellationToken cancellationToken);
+ protected abstract TPropertyDeclarationNode GetPropertyWithoutInitializer(TPropertyDeclarationNode property);
+ protected abstract SyntaxNode GetInitializerValue(TPropertyDeclarationNode property);
protected abstract SyntaxNode ConvertPropertyToExpressionBodyIfDesired(TCodeGenerationContextInfo info, SyntaxNode fullProperty);
protected abstract SyntaxNode GetTypeBlock(SyntaxNode syntaxNode);
+ protected abstract Task ExpandToFieldPropertyAsync(Document document, TPropertyDeclarationNode property, CancellationToken cancellationToken);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
@@ -45,12 +47,23 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte
if (!IsValidAutoProperty(propertySymbol))
return;
- context.RegisterRefactoring(
- CodeAction.Create(
+ context.RegisterRefactoring(CodeAction.Create(
FeaturesResources.Convert_to_full_property,
- cancellationToken => ExpandToFullPropertyAsync(document, property, propertySymbol, root, cancellationToken),
+ cancellationToken => ExpandToFullPropertyAsync(document, property, propertySymbol, cancellationToken),
nameof(FeaturesResources.Convert_to_full_property)),
property.Span);
+
+ // If supported, offer to convert auto-prop to use 'field' instead.
+ var syntaxFacts = document.GetRequiredLanguageService();
+ if (syntaxFacts.SupportsFieldExpression(semanticModel.SyntaxTree.Options) &&
+ !property.DescendantNodes().Any(syntaxFacts.IsFieldExpression))
+ {
+ context.RegisterRefactoring(CodeAction.Create(
+ FeaturesResources.Convert_to_field_property,
+ cancellationToken => ExpandToFieldPropertyAsync(document, property, cancellationToken),
+ nameof(FeaturesResources.Convert_to_field_property)),
+ property.Span);
+ }
}
internal static bool IsValidAutoProperty(IPropertySymbol propertySymbol)
@@ -73,29 +86,22 @@ private async Task ExpandToFullPropertyAsync(
Document document,
TPropertyDeclarationNode property,
IPropertySymbol propertySymbol,
- SyntaxNode root,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(document.DocumentState.ParseOptions);
+ var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var editor = new SyntaxEditor(root, document.Project.Solution.Services);
- var generator = editor.Generator;
var info = (TCodeGenerationContextInfo)await document.GetCodeGenerationInfoAsync(CodeGenerationContext.Default, cancellationToken).ConfigureAwait(false);
// Create full property. If the auto property had an initial value
// we need to remove it and later add it to the backing field
var fieldName = await GetFieldNameAsync(document, propertySymbol, cancellationToken).ConfigureAwait(false);
- var (newGetAccessor, newSetAccessor) = GetNewAccessors(info, property, fieldName, generator, cancellationToken);
- var fullProperty = generator
- .WithAccessorDeclarations(
- GetPropertyWithoutInitializer(property),
- newSetAccessor == null
- ? [newGetAccessor]
- : [newGetAccessor, newSetAccessor])
- .WithLeadingTrivia(property.GetLeadingTrivia());
- fullProperty = ConvertPropertyToExpressionBodyIfDesired(info, fullProperty);
+ var (newGetAccessor, newSetAccessor) = GetNewAccessors(info, property, fieldName, cancellationToken);
- editor.ReplaceNode(property, fullProperty.WithAdditionalAnnotations(Formatter.Annotation));
+ editor.ReplaceNode(
+ property,
+ CreateFinalProperty(document, property, info, newGetAccessor, newSetAccessor));
// add backing field, plus initializer if it exists
var newField = CodeGenerationSymbolFactory.CreateFieldSymbol(
@@ -119,4 +125,24 @@ private async Task ExpandToFullPropertyAsync(
var newRoot = editor.GetChangedRoot();
return document.WithSyntaxRoot(newRoot);
}
+
+ protected SyntaxNode CreateFinalProperty(
+ Document document,
+ TPropertyDeclarationNode property,
+ TCodeGenerationContextInfo info,
+ SyntaxNode newGetAccessor,
+ SyntaxNode? newSetAccessor)
+ {
+ var generator = document.GetRequiredLanguageService();
+
+ var fullProperty = generator
+ .WithAccessorDeclarations(
+ GetPropertyWithoutInitializer(property),
+ newSetAccessor == null
+ ? [newGetAccessor]
+ : [newGetAccessor, newSetAccessor])
+ .WithLeadingTrivia(property.GetLeadingTrivia());
+ fullProperty = ConvertPropertyToExpressionBodyIfDesired(info, fullProperty);
+ return fullProperty.WithAdditionalAnnotations(Formatter.Annotation);
+ }
}
diff --git a/src/Features/Core/Portable/Copilot/ICopilotCodeAnalysisService.cs b/src/Features/Core/Portable/Copilot/ICopilotCodeAnalysisService.cs
index 0bdd083ad9584..a4ce548bcfa7c 100644
--- a/src/Features/Core/Portable/Copilot/ICopilotCodeAnalysisService.cs
+++ b/src/Features/Core/Portable/Copilot/ICopilotCodeAnalysisService.cs
@@ -70,7 +70,7 @@ internal interface ICopilotCodeAnalysisService : ILanguageService
/// is the language of the originating .
///
///
- Task GetOnTheFlyDocsAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken);
+ Task<(string responseString, bool isQuotaExceeded)> GetOnTheFlyDocsAsync(string symbolSignature, ImmutableArray declarationCode, string language, CancellationToken cancellationToken);
///
/// Determines if the given is excluded in the workspace.
diff --git a/src/Features/Core/Portable/Diagnostics/CodeAnalysisDiagnosticAnalyzerService.cs b/src/Features/Core/Portable/Diagnostics/CodeAnalysisDiagnosticAnalyzerService.cs
index d215f1a95815a..cc52cd179ee96 100644
--- a/src/Features/Core/Portable/Diagnostics/CodeAnalysisDiagnosticAnalyzerService.cs
+++ b/src/Features/Core/Portable/Diagnostics/CodeAnalysisDiagnosticAnalyzerService.cs
@@ -134,25 +134,41 @@ private async ValueTask AnalyzeProjectCoreAsync(Project project, Action
}
///
- /// Running code analysis on the project force computes and caches the diagnostics on the DiagnosticAnalyzerService.
- /// We return these cached document diagnostics here, including both local and non-local document diagnostics.
+ /// Running code analysis on the project force computes and caches the diagnostics on the
+ /// DiagnosticAnalyzerService. We return these cached document diagnostics here, including both local and
+ /// non-local document diagnostics.
///
- public Task> GetLastComputedDocumentDiagnosticsAsync(DocumentId documentId, CancellationToken cancellationToken)
- => _clearedProjectIds.Contains(documentId.ProjectId)
- ? SpecializedTasks.EmptyImmutableArray()
- : _diagnosticAnalyzerService.GetCachedDiagnosticsAsync(_workspace, documentId.ProjectId,
- documentId, includeSuppressedDiagnostics: false, includeLocalDocumentDiagnostics: true,
- includeNonLocalDocumentDiagnostics: true, cancellationToken);
+ ///
+ /// Only returns non-suppressed diagnostics.
+ ///
+ public async Task> GetLastComputedDocumentDiagnosticsAsync(DocumentId documentId, CancellationToken cancellationToken)
+ {
+ if (_clearedProjectIds.Contains(documentId.ProjectId))
+ return [];
+
+ var diagnostics = await _diagnosticAnalyzerService.GetCachedDiagnosticsAsync(
+ _workspace, documentId.ProjectId, documentId, includeLocalDocumentDiagnostics: true,
+ includeNonLocalDocumentDiagnostics: true, cancellationToken).ConfigureAwait(false);
+ return diagnostics.WhereAsArray(d => !d.IsSuppressed);
+ }
///
- /// Running code analysis on the project force computes and caches the diagnostics on the DiagnosticAnalyzerService.
- /// We return these cached project diagnostics here, i.e. diagnostics with no location, by excluding all local and non-local document diagnostics.
+ /// Running code analysis on the project force computes and caches the diagnostics on the
+ /// DiagnosticAnalyzerService. We return these cached project diagnostics here, i.e. diagnostics with no
+ /// location, by excluding all local and non-local document diagnostics.
///
- public Task> GetLastComputedProjectDiagnosticsAsync(ProjectId projectId, CancellationToken cancellationToken)
- => _clearedProjectIds.Contains(projectId)
- ? SpecializedTasks.EmptyImmutableArray()
- : _diagnosticAnalyzerService.GetCachedDiagnosticsAsync(_workspace, projectId, documentId: null,
- includeSuppressedDiagnostics: false, includeLocalDocumentDiagnostics: false,
- includeNonLocalDocumentDiagnostics: false, cancellationToken);
+ ///
+ /// Only returns non-suppressed diagnostics.
+ ///
+ public async Task> GetLastComputedProjectDiagnosticsAsync(ProjectId projectId, CancellationToken cancellationToken)
+ {
+ if (_clearedProjectIds.Contains(projectId))
+ return [];
+
+ var diagnostics = await _diagnosticAnalyzerService.GetCachedDiagnosticsAsync(
+ _workspace, projectId, documentId: null, includeLocalDocumentDiagnostics: false,
+ includeNonLocalDocumentDiagnostics: false, cancellationToken).ConfigureAwait(false);
+ return diagnostics.WhereAsArray(d => !d.IsSuppressed);
+ }
}
}
diff --git a/src/Features/Core/Portable/Diagnostics/DiagnosticArguments.cs b/src/Features/Core/Portable/Diagnostics/DiagnosticArguments.cs
index fa573e85c5018..4108a704423ae 100644
--- a/src/Features/Core/Portable/Diagnostics/DiagnosticArguments.cs
+++ b/src/Features/Core/Portable/Diagnostics/DiagnosticArguments.cs
@@ -15,38 +15,32 @@ namespace Microsoft.CodeAnalysis.Diagnostics;
[DataContract]
internal sealed class DiagnosticArguments
{
- ///
- /// Flag indicating if suppressed diagnostics should be returned.
- ///
- [DataMember(Order = 0)]
- public bool ReportSuppressedDiagnostics;
-
///
/// Flag indicating if analyzer performance info, such as analyzer execution times,
/// should be logged as performance telemetry.
///
- [DataMember(Order = 1)]
+ [DataMember(Order = 0)]
public bool LogPerformanceInfo;
///
/// Flag indicating if the analyzer telemety info, such as registered analyzer action counts
/// and analyzer execution times, should be included in the computed result.
///
- [DataMember(Order = 2)]
+ [DataMember(Order = 1)]
public bool GetTelemetryInfo;
///
/// Optional document ID, if computing diagnostics for a specific document.
/// For example, diagnostic computation for open file analysis.
///
- [DataMember(Order = 3)]
+ [DataMember(Order = 2)]
public DocumentId? DocumentId;
///
/// Optional document text span, if computing diagnostics for a specific span for a document.
/// For example, diagnostic computation for light bulb invocation for a specific line in active document.
///
- [DataMember(Order = 4)]
+ [DataMember(Order = 3)]
public TextSpan? DocumentSpan;
///
@@ -54,36 +48,35 @@ internal sealed class DiagnosticArguments
/// i.e. must be non-null for a non-null analysis kind.
/// Only supported non-null values are and .
///
- [DataMember(Order = 5)]
+ [DataMember(Order = 4)]
public AnalysisKind? DocumentAnalysisKind;
///
/// Project ID for the document or project for which diagnostics need to be computed.
///
- [DataMember(Order = 6)]
+ [DataMember(Order = 5)]
public ProjectId ProjectId;
///
/// Array of analyzer IDs for analyzers that need to be executed for computing diagnostics.
///
- [DataMember(Order = 7)]
+ [DataMember(Order = 6)]
public ImmutableArray ProjectAnalyzerIds;
///
/// Array of analyzer IDs for analyzers that need to be executed for computing diagnostics.
///
- [DataMember(Order = 8)]
+ [DataMember(Order = 7)]
public ImmutableArray HostAnalyzerIds;
///
/// Indicates diagnostic computation for an explicit user-invoked request,
/// such as a user-invoked Ctrl + Dot operation to bring up the light bulb.
///
- [DataMember(Order = 9)]
+ [DataMember(Order = 8)]
public bool IsExplicit;
public DiagnosticArguments(
- bool reportSuppressedDiagnostics,
bool logPerformanceInfo,
bool getTelemetryInfo,
DocumentId? documentId,
@@ -100,7 +93,6 @@ public DiagnosticArguments(
(AnalysisKind?)AnalysisKind.Syntax or (AnalysisKind?)AnalysisKind.Semantic);
Debug.Assert(projectAnalyzerIds.Length > 0 || hostAnalyzerIds.Length > 0);
- ReportSuppressedDiagnostics = reportSuppressedDiagnostics;
LogPerformanceInfo = logPerformanceInfo;
GetTelemetryInfo = getTelemetryInfo;
DocumentId = documentId;
diff --git a/src/Features/Core/Portable/Diagnostics/IDiagnosticAnalyzerService.cs b/src/Features/Core/Portable/Diagnostics/IDiagnosticAnalyzerService.cs
index 0de170d0f25fb..406c168c5324e 100644
--- a/src/Features/Core/Portable/Diagnostics/IDiagnosticAnalyzerService.cs
+++ b/src/Features/Core/Portable/Diagnostics/IDiagnosticAnalyzerService.cs
@@ -33,7 +33,6 @@ internal interface IDiagnosticAnalyzerService
/// Workspace for the document/project/solution to compute diagnostics for.
/// Optional project to scope the returned diagnostics.
/// Optional document to scope the returned diagnostics.
- /// Indicates if diagnostics suppressed in source via pragmas and SuppressMessageAttributes should be returned.
///
/// Indicates if local document diagnostics must be returned.
/// Local diagnostics are the ones that are reported by analyzers on the same file for which the callback was received
@@ -46,7 +45,7 @@ internal interface IDiagnosticAnalyzerService
/// complete set of non-local document diagnostics.
///
/// Cancellation token.
- Task> GetCachedDiagnosticsAsync(Workspace workspace, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics, bool includeLocalDocumentDiagnostics, bool includeNonLocalDocumentDiagnostics, CancellationToken cancellationToken);
+ Task> GetCachedDiagnosticsAsync(Workspace workspace, ProjectId? projectId, DocumentId? documentId, bool includeLocalDocumentDiagnostics, bool includeNonLocalDocumentDiagnostics, CancellationToken cancellationToken);
///
/// Force analyzes the given project by running all applicable analyzers on the project and caching the reported analyzer diagnostics.
@@ -54,29 +53,29 @@ internal interface IDiagnosticAnalyzerService
Task ForceAnalyzeProjectAsync(Project project, CancellationToken cancellationToken);
///
- /// Get diagnostics of the given diagnostic ids and/or analyzers from the given solution. all diagnostics returned should be up-to-date with respect to the given solution.
- /// Note that for project case, this method returns diagnostics from all project documents as well. Use
- /// if you want to fetch only project diagnostics without source locations.
+ /// Get diagnostics of the given diagnostic ids and/or analyzers from the given solution. all diagnostics returned
+ /// should be up-to-date with respect to the given solution. Note that for project case, this method returns
+ /// diagnostics from all project documents as well. Use if you want
+ /// to fetch only project diagnostics without source locations.
///
/// Solution to fetch the diagnostics for.
/// Optional project to scope the returned diagnostics.
/// Optional document to scope the returned diagnostics.
/// Optional set of diagnostic IDs to scope the returned diagnostics.
/// Option callback to filter out analyzers to execute for computing diagnostics.
- /// Indicates if diagnostics suppressed in source via pragmas and SuppressMessageAttributes should be returned.
///
/// Indicates if local document diagnostics must be returned.
/// Local diagnostics are the ones that are reported by analyzers on the same file for which the callback was received
/// and hence can be computed by analyzing a single file in isolation.
///
///
- /// Indicates if non-local document diagnostics must be returned.
- /// Non-local diagnostics are the ones reported by analyzers either at compilation end callback OR
- /// in a different file from which the callback was made. Entire project must be analyzed to get the
- /// complete set of non-local document diagnostics.
+ /// Indicates if non-local document diagnostics must be returned. Non-local diagnostics are the ones reported by
+ /// analyzers either at compilation end callback OR in a different file from which the callback was made. Entire
+ /// project must be analyzed to get the complete set of non-local document diagnostics.
///
/// Cancellation token.
- Task> GetDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet? diagnosticIds, Func? shouldIncludeAnalyzer, Func>? getDocumentIds, bool includeSuppressedDiagnostics, bool includeLocalDocumentDiagnostics, bool includeNonLocalDocumentDiagnostics, CancellationToken cancellationToken);
+ Task> GetDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet? diagnosticIds, Func? shouldIncludeAnalyzer, Func>? getDocumentIds, bool includeLocalDocumentDiagnostics, bool includeNonLocalDocumentDiagnostics, CancellationToken cancellationToken);
///
/// Get project diagnostics (diagnostics with no source location) of the given diagnostic ids and/or analyzers from
@@ -88,14 +87,13 @@ internal interface IDiagnosticAnalyzerService
/// Optional project to scope the returned diagnostics.
/// Optional set of diagnostic IDs to scope the returned diagnostics.
/// Option callback to filter out analyzers to execute for computing diagnostics.
- /// Indicates if diagnostics suppressed in source via SuppressMessageAttributes should be returned.
///
/// Indicates if non-local document diagnostics must be returned.
/// Non-local diagnostics are the ones reported by analyzers either at compilation end callback.
/// Entire project must be analyzed to get the complete set of non-local diagnostics.
///
/// Cancellation token.
- Task> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, ImmutableHashSet? diagnosticIds, Func? shouldIncludeAnalyzer, bool includeSuppressedDiagnostics, bool includeNonLocalDocumentDiagnostics, CancellationToken cancellationToken);
+ Task> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, ImmutableHashSet? diagnosticIds, Func