repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.MetadataAsSource { /// <summary> /// Helpers shared by both the text service and the editor service /// </summary> internal class MetadataAsSourceHelpers { #if false public static void ValidateSymbolArgument(ISymbol symbol, string parameterName) { if (symbol == null) { throw new ArgumentNullException(parameterName); } else if (!MetadataAsSourceHelpers.ValidSymbolKinds.Contains(symbol.Kind)) { throw new ArgumentException(FeaturesResources.generating_source_for_symbols_of_this_type_is_not_supported, parameterName); } } #endif public static string GetAssemblyInfo(IAssemblySymbol assemblySymbol) { return string.Format( "{0} {1}", FeaturesResources.Assembly, assemblySymbol.Identity.GetDisplayName()); } public static string GetAssemblyDisplay(Compilation compilation, IAssemblySymbol assemblySymbol) { // This method is only used to generate a comment at the top of Metadata-as-Source documents and // previous submissions are never viewed as metadata (i.e. we always have compilations) so there's no // need to consume compilation.ScriptCompilationInfo.PreviousScriptCompilation. var assemblyReference = compilation.GetMetadataReference(assemblySymbol); return assemblyReference?.Display ?? FeaturesResources.location_unknown; } public static INamedTypeSymbol GetTopLevelContainingNamedType(ISymbol symbol) { // Traverse up until we find a named type that is parented by the namespace var topLevelNamedType = symbol; while (topLevelNamedType.ContainingSymbol != symbol.ContainingNamespace || topLevelNamedType.Kind != SymbolKind.NamedType) { topLevelNamedType = topLevelNamedType.ContainingSymbol; } return (INamedTypeSymbol)topLevelNamedType; } public static async Task<Location> GetLocationInGeneratedSourceAsync(SymbolKey symbolId, Document generatedDocument, CancellationToken cancellationToken) { var resolution = symbolId.Resolve( await generatedDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false), ignoreAssemblyKey: true, cancellationToken: cancellationToken); var location = GetFirstSourceLocation(resolution); if (location == null) { // If we cannot find the location of the symbol. Just put the caret at the // beginning of the file. var tree = await generatedDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); location = Location.Create(tree, new TextSpan(0, 0)); } return location; } private static Location GetFirstSourceLocation(SymbolKeyResolution resolution) { foreach (var symbol in resolution) { foreach (var location in symbol.Locations) { if (location.IsInSource) { return location; } } } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.MetadataAsSource { /// <summary> /// Helpers shared by both the text service and the editor service /// </summary> internal class MetadataAsSourceHelpers { #if false public static void ValidateSymbolArgument(ISymbol symbol, string parameterName) { if (symbol == null) { throw new ArgumentNullException(parameterName); } else if (!MetadataAsSourceHelpers.ValidSymbolKinds.Contains(symbol.Kind)) { throw new ArgumentException(FeaturesResources.generating_source_for_symbols_of_this_type_is_not_supported, parameterName); } } #endif public static string GetAssemblyInfo(IAssemblySymbol assemblySymbol) { return string.Format( "{0} {1}", FeaturesResources.Assembly, assemblySymbol.Identity.GetDisplayName()); } public static string GetAssemblyDisplay(Compilation compilation, IAssemblySymbol assemblySymbol) { // This method is only used to generate a comment at the top of Metadata-as-Source documents and // previous submissions are never viewed as metadata (i.e. we always have compilations) so there's no // need to consume compilation.ScriptCompilationInfo.PreviousScriptCompilation. var assemblyReference = compilation.GetMetadataReference(assemblySymbol); return assemblyReference?.Display ?? FeaturesResources.location_unknown; } public static INamedTypeSymbol GetTopLevelContainingNamedType(ISymbol symbol) { // Traverse up until we find a named type that is parented by the namespace var topLevelNamedType = symbol; while (topLevelNamedType.ContainingSymbol != symbol.ContainingNamespace || topLevelNamedType.Kind != SymbolKind.NamedType) { topLevelNamedType = topLevelNamedType.ContainingSymbol; } return (INamedTypeSymbol)topLevelNamedType; } public static async Task<Location> GetLocationInGeneratedSourceAsync(SymbolKey symbolId, Document generatedDocument, CancellationToken cancellationToken) { var resolution = symbolId.Resolve( await generatedDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false), ignoreAssemblyKey: true, cancellationToken: cancellationToken); var location = GetFirstSourceLocation(resolution); if (location == null) { // If we cannot find the location of the symbol. Just put the caret at the // beginning of the file. var tree = await generatedDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); location = Location.Create(tree, new TextSpan(0, 0)); } return location; } private static Location GetFirstSourceLocation(SymbolKeyResolution resolution) { foreach (var symbol in resolution) { foreach (var location in symbol.Locations) { if (location.IsInSource) { return location; } } } return null; } } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/EditorFeatures/CSharpTest/EditorConfigSettings/Updater/SettingsUpdaterTests.TestAnalyzerConfigOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.UnitTests { public partial class SettingsUpdaterTests { private class TestAnalyzerConfigOptions : AnalyzerConfigOptions { public static TestAnalyzerConfigOptions Instance = new(); private readonly Func<string, string?>? _lookup = null; public TestAnalyzerConfigOptions() { } public TestAnalyzerConfigOptions(Func<string, string?> lookup) { _lookup = lookup; } public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) { value = _lookup?.Invoke(key); return value != null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.UnitTests { public partial class SettingsUpdaterTests { private class TestAnalyzerConfigOptions : AnalyzerConfigOptions { public static TestAnalyzerConfigOptions Instance = new(); private readonly Func<string, string?>? _lookup = null; public TestAnalyzerConfigOptions() { } public TestAnalyzerConfigOptions(Func<string, string?> lookup) { _lookup = lookup; } public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) { value = _lookup?.Invoke(key); return value != null; } } } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Analyzers/CSharp/CodeFixes/UseExpressionBody/UseExpressionBodyCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseExpressionBody), Shared] internal partial class UseExpressionBodyCodeFixProvider : SyntaxEditorBasedCodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; private static readonly ImmutableArray<UseExpressionBodyHelper> _helpers = UseExpressionBodyHelper.Helpers; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UseExpressionBodyCodeFixProvider() => FixableDiagnosticIds = _helpers.SelectAsArray(h => h.DiagnosticId); protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.IsSuppressed || diagnostic.Properties.ContainsKey(UseExpressionBodyDiagnosticAnalyzer.FixesError); public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); var documentOptionSet = await context.Document.GetOptionsAsync(context.CancellationToken).ConfigureAwait(false); #if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer. var codeAction = new MyCodeAction(diagnostic.GetMessage(), c => FixAsync(context.Document, diagnostic, c)); #else var priority = diagnostic.Severity == DiagnosticSeverity.Hidden ? CodeActionPriority.Low : CodeActionPriority.Medium; var codeAction = new MyCodeAction(diagnostic.GetMessage(), priority, c => FixAsync(context.Document, diagnostic, c)); #endif context.RegisterCodeFix( codeAction, diagnostic); } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var accessorLists = new HashSet<AccessorListSyntax>(); foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); AddEdits(semanticModel, editor, diagnostic, accessorLists, cancellationToken); } // Ensure that if we changed any accessors that the accessor lists they're contained // in are formatted properly as well. Do this as a last pass so that we see all // individual changes made to the child accessors if we're doing a fix-all. foreach (var accessorList in accessorLists) { editor.ReplaceNode(accessorList, (current, _) => current.WithAdditionalAnnotations(Formatter.Annotation)); } } private static void AddEdits( SemanticModel semanticModel, SyntaxEditor editor, Diagnostic diagnostic, HashSet<AccessorListSyntax> accessorLists, CancellationToken cancellationToken) { var declarationLocation = diagnostic.AdditionalLocations[0]; var helper = _helpers.Single(h => h.DiagnosticId == diagnostic.Id); var declaration = declarationLocation.FindNode(cancellationToken); var useExpressionBody = diagnostic.Properties.ContainsKey(nameof(UseExpressionBody)); var updatedDeclaration = helper.Update(semanticModel, declaration, useExpressionBody) .WithAdditionalAnnotations(Formatter.Annotation); editor.ReplaceNode(declaration, updatedDeclaration); if (declaration.Parent is AccessorListSyntax accessorList) { accessorLists.Add(accessorList); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { #if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer. public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } #else internal override CodeActionPriority Priority { get; } public MyCodeAction(string title, CodeActionPriority priority, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { Priority = priority; } #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseExpressionBody), Shared] internal partial class UseExpressionBodyCodeFixProvider : SyntaxEditorBasedCodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; private static readonly ImmutableArray<UseExpressionBodyHelper> _helpers = UseExpressionBodyHelper.Helpers; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UseExpressionBodyCodeFixProvider() => FixableDiagnosticIds = _helpers.SelectAsArray(h => h.DiagnosticId); protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.IsSuppressed || diagnostic.Properties.ContainsKey(UseExpressionBodyDiagnosticAnalyzer.FixesError); public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); var documentOptionSet = await context.Document.GetOptionsAsync(context.CancellationToken).ConfigureAwait(false); #if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer. var codeAction = new MyCodeAction(diagnostic.GetMessage(), c => FixAsync(context.Document, diagnostic, c)); #else var priority = diagnostic.Severity == DiagnosticSeverity.Hidden ? CodeActionPriority.Low : CodeActionPriority.Medium; var codeAction = new MyCodeAction(diagnostic.GetMessage(), priority, c => FixAsync(context.Document, diagnostic, c)); #endif context.RegisterCodeFix( codeAction, diagnostic); } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var accessorLists = new HashSet<AccessorListSyntax>(); foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); AddEdits(semanticModel, editor, diagnostic, accessorLists, cancellationToken); } // Ensure that if we changed any accessors that the accessor lists they're contained // in are formatted properly as well. Do this as a last pass so that we see all // individual changes made to the child accessors if we're doing a fix-all. foreach (var accessorList in accessorLists) { editor.ReplaceNode(accessorList, (current, _) => current.WithAdditionalAnnotations(Formatter.Annotation)); } } private static void AddEdits( SemanticModel semanticModel, SyntaxEditor editor, Diagnostic diagnostic, HashSet<AccessorListSyntax> accessorLists, CancellationToken cancellationToken) { var declarationLocation = diagnostic.AdditionalLocations[0]; var helper = _helpers.Single(h => h.DiagnosticId == diagnostic.Id); var declaration = declarationLocation.FindNode(cancellationToken); var useExpressionBody = diagnostic.Properties.ContainsKey(nameof(UseExpressionBody)); var updatedDeclaration = helper.Update(semanticModel, declaration, useExpressionBody) .WithAdditionalAnnotations(Formatter.Annotation); editor.ReplaceNode(declaration, updatedDeclaration); if (declaration.Parent is AccessorListSyntax accessorList) { accessorLists.Add(accessorList); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { #if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer. public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } #else internal override CodeActionPriority Priority { get; } public MyCodeAction(string title, CodeActionPriority priority, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { Priority = priority; } #endif } } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Compilers/CSharp/Portable/BoundTree/Constructors.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class BoundFieldAccess { public BoundFieldAccess( SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, LookupResultKind.Viable, fieldSymbol.Type, hasErrors) { } public BoundFieldAccess( SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration: false, type: type, hasErrors: hasErrors) { } public BoundFieldAccess( SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, bool isDeclaration, TypeSymbol type, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration: isDeclaration, type: type, hasErrors: hasErrors) { } public BoundFieldAccess Update( BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol typeSymbol) { return this.Update(receiver, fieldSymbol, constantValueOpt, resultKind, this.IsByValue, this.IsDeclaration, typeSymbol); } private static bool NeedsByValueFieldAccess(BoundExpression? receiver, FieldSymbol fieldSymbol) { if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsValueType || receiver == null) // receiver may be null in error cases { return false; } switch (receiver.Kind) { case BoundKind.FieldAccess: return ((BoundFieldAccess)receiver).IsByValue; case BoundKind.Local: var localSymbol = ((BoundLocal)receiver).LocalSymbol; return !(localSymbol.IsWritableVariable || localSymbol.IsRef); default: return false; } } } internal partial class BoundCall { public BoundCall( SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, originalMethodsOpt: default, type, hasErrors) { } public BoundCall Update(BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol type) => Update(receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, this.OriginalMethodsOpt, type); public static BoundCall ErrorCall( SyntaxNode node, BoundExpression receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> namedArguments, ImmutableArray<RefKind> refKinds, bool isDelegateCall, bool invokedAsExtensionMethod, ImmutableArray<MethodSymbol> originalMethods, LookupResultKind resultKind, Binder binder) { if (!originalMethods.IsEmpty) resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); Debug.Assert(arguments.IsDefaultOrEmpty || (object)receiverOpt != (object)arguments[0]); return new BoundCall( syntax: node, receiverOpt: binder.BindToTypeForErrorRecovery(receiverOpt), method: method, arguments: arguments.SelectAsArray((e, binder) => binder.BindToTypeForErrorRecovery(e), binder), argumentNamesOpt: namedArguments, argumentRefKindsOpt: refKinds, isDelegateCall: isDelegateCall, expanded: false, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), resultKind: resultKind, originalMethodsOpt: originalMethods, type: method.ReturnType, hasErrors: true); } public BoundCall Update(ImmutableArray<BoundExpression> arguments) { return this.Update(ReceiverOpt, Method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, DefaultArguments, ResultKind, OriginalMethodsOpt, Type); } public BoundCall Update(BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments) { return this.Update(receiverOpt, method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, DefaultArguments, ResultKind, OriginalMethodsOpt, Type); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method) { return Synthesized(syntax, receiverOpt, method, ImmutableArray<BoundExpression>.Empty); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, BoundExpression arg0) { return Synthesized(syntax, receiverOpt, method, ImmutableArray.Create(arg0)); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, BoundExpression arg0, BoundExpression arg1) { return Synthesized(syntax, receiverOpt, method, ImmutableArray.Create(arg0, arg1)); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments) { return new BoundCall(syntax, receiverOpt, method, arguments, argumentNamesOpt: default(ImmutableArray<string>), argumentRefKindsOpt: method.ParameterRefKinds, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable, originalMethodsOpt: default, type: method.ReturnType, hasErrors: method.OriginalDefinition is ErrorMethodSymbol ) { WasCompilerGenerated = true }; } } internal sealed partial class BoundObjectCreationExpression { public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, params BoundExpression[] arguments) : this(syntax, constructor, ImmutableArray.Create<BoundExpression>(arguments), default(ImmutableArray<string>), default(ImmutableArray<RefKind>), false, default(ImmutableArray<int>), default(BitVector), null, null, constructor.ContainingType) { } public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, ImmutableArray<BoundExpression> arguments) : this(syntax, constructor, arguments, default(ImmutableArray<string>), default(ImmutableArray<RefKind>), false, default(ImmutableArray<int>), default(BitVector), null, null, constructor.ContainingType) { } } internal partial class BoundIndexerAccess { public static BoundIndexerAccess ErrorAccess( SyntaxNode node, BoundExpression receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> namedArguments, ImmutableArray<RefKind> refKinds, ImmutableArray<PropertySymbol> originalIndexers) { return new BoundIndexerAccess( node, receiverOpt, indexer, arguments, namedArguments, refKinds, expanded: false, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), originalIndexers, type: indexer.Type, hasErrors: true); } public BoundIndexerAccess( SyntaxNode syntax, BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool expanded, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, TypeSymbol type, bool hasErrors = false) : this(syntax, receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, originalIndexersOpt: default, type, hasErrors) { } public BoundIndexerAccess Update(BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool expanded, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, TypeSymbol type) => Update(receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, this.OriginalIndexersOpt, type); } internal sealed partial class BoundConversion { /// <remarks> /// This method is intended for passes other than the LocalRewriter. /// Use MakeConversion helper method in the LocalRewriter instead, /// it generates a synthesized conversion in its lowered form. /// </remarks> public static BoundConversion SynthesizedNonUserDefined(SyntaxNode syntax, BoundExpression operand, Conversion conversion, TypeSymbol type, ConstantValue? constantValueOpt = null) { return new BoundConversion( syntax, operand, conversion, isBaseConversion: false, @checked: false, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: constantValueOpt, originalUserDefinedConversionsOpt: default, type: type) { WasCompilerGenerated = true }; } /// <remarks> /// NOTE: This method is intended for passes other than the LocalRewriter. /// NOTE: Use MakeConversion helper method in the LocalRewriter instead, /// NOTE: it generates a synthesized conversion in its lowered form. /// </remarks> public static BoundConversion Synthesized( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, bool explicitCastInCode, ConversionGroup? conversionGroupOpt, ConstantValue? constantValueOpt, TypeSymbol type, bool hasErrors = false) { return new BoundConversion( syntax, operand, conversion, @checked, explicitCastInCode: explicitCastInCode, conversionGroupOpt, constantValueOpt, type, hasErrors || !conversion.IsValid) { WasCompilerGenerated = true }; } public BoundConversion( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, bool explicitCastInCode, ConversionGroup? conversionGroupOpt, ConstantValue? constantValueOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operand, conversion, isBaseConversion: false, @checked: @checked, explicitCastInCode: explicitCastInCode, constantValueOpt: constantValueOpt, conversionGroupOpt, conversion.OriginalUserDefinedConversions, type: type, hasErrors: hasErrors || !conversion.IsValid) { } public BoundConversion( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, TypeSymbol type, bool hasErrors = false) : this(syntax, operand, conversion, isBaseConversion, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, originalUserDefinedConversionsOpt: default, type, hasErrors) { } public BoundConversion Update(BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, TypeSymbol type) => Update(operand, conversion, isBaseConversion, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, this.OriginalUserDefinedConversionsOpt, type); } internal sealed partial class BoundBinaryOperator { public BoundBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression left, BoundExpression right, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operatorKind, UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, originalUserDefinedOperatorsOpt), resultKind, left, right, type, hasErrors) { } public BoundBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, originalUserDefinedOperatorsOpt: default), resultKind, left, right, type, hasErrors) { } public BoundBinaryOperator Update(BinaryOperatorKind operatorKind, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type) { var uncommonData = UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, OriginalUserDefinedOperatorsOpt); return Update(operatorKind, uncommonData, resultKind, left, right, type); } public BoundBinaryOperator Update(UncommonData uncommonData) { return Update(OperatorKind, uncommonData, ResultKind, Left, Right, Type); } } internal sealed partial class BoundUserDefinedConditionalLogicalOperator { public BoundUserDefinedConditionalLogicalOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression left, BoundExpression right, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operatorKind, logicalOperator, trueOperator, falseOperator, constrainedToTypeOpt, resultKind, originalUserDefinedOperatorsOpt, left, right, type, hasErrors) { Debug.Assert(operatorKind.IsUserDefined() && operatorKind.IsLogical()); } public BoundUserDefinedConditionalLogicalOperator Update(BinaryOperatorKind operatorKind, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type) => Update(operatorKind, logicalOperator, trueOperator, falseOperator, constrainedToTypeOpt, resultKind, this.OriginalUserDefinedOperatorsOpt, left, right, type); } internal sealed partial class BoundParameter { public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol, bool hasErrors = false) : this(syntax, parameterSymbol, parameterSymbol.Type, hasErrors) { } public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol) : this(syntax, parameterSymbol, parameterSymbol.Type) { } } internal sealed partial class BoundTypeExpression { public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, BoundTypeExpression? boundContainingTypeOpt, ImmutableArray<BoundExpression> boundDimensionsOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, boundContainingTypeOpt, boundDimensionsOpt, typeWithAnnotations, typeWithAnnotations.Type, hasErrors) { Debug.Assert((object)typeWithAnnotations.Type != null, "Field 'type' cannot be null"); } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, BoundTypeExpression? boundContainingTypeOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, boundContainingTypeOpt, ImmutableArray<BoundExpression>.Empty, typeWithAnnotations, hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, null, typeWithAnnotations, hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, TypeSymbol type, bool hasErrors = false) : this(syntax, aliasOpt, null, TypeWithAnnotations.Create(type), hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, ImmutableArray<BoundExpression> dimensionsOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, null, dimensionsOpt, typeWithAnnotations, hasErrors) { } } internal sealed partial class BoundNamespaceExpression { public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol, bool hasErrors = false) : this(syntax, namespaceSymbol, null, hasErrors) { } public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol) : this(syntax, namespaceSymbol, null) { } public BoundNamespaceExpression Update(NamespaceSymbol namespaceSymbol) { return Update(namespaceSymbol, this.AliasOpt); } } internal sealed partial class BoundAssignmentOperator { public BoundAssignmentOperator(SyntaxNode syntax, BoundExpression left, BoundExpression right, TypeSymbol type, bool isRef = false, bool hasErrors = false) : this(syntax, left, right, isRef, type, hasErrors) { } } internal sealed partial class BoundBadExpression { public BoundBadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol?> symbols, ImmutableArray<BoundExpression> childBoundNodes, TypeSymbol type) : this(syntax, resultKind, symbols, childBoundNodes, type, true) { Debug.Assert((object)type != null); } } internal partial class BoundStatementList { public static BoundStatementList Synthesized(SyntaxNode syntax, params BoundStatement[] statements) { return Synthesized(syntax, false, statements.AsImmutableOrNull()); } public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, params BoundStatement[] statements) { return Synthesized(syntax, hasErrors, statements.AsImmutableOrNull()); } public static BoundStatementList Synthesized(SyntaxNode syntax, ImmutableArray<BoundStatement> statements) { return Synthesized(syntax, false, statements); } public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, ImmutableArray<BoundStatement> statements) { return new BoundStatementList(syntax, statements, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundReturnStatement { public static BoundReturnStatement Synthesized(SyntaxNode syntax, RefKind refKind, BoundExpression expression, bool hasErrors = false) { return new BoundReturnStatement(syntax, refKind, expression, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundYieldBreakStatement { public static BoundYieldBreakStatement Synthesized(SyntaxNode syntax, bool hasErrors = false) { return new BoundYieldBreakStatement(syntax, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundGotoStatement { public BoundGotoStatement(SyntaxNode syntax, LabelSymbol label, bool hasErrors = false) : this(syntax, label, caseExpressionOpt: null, labelExpressionOpt: null, hasErrors: hasErrors) { } } internal partial class BoundBlock { public BoundBlock(SyntaxNode syntax, ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundStatement> statements, bool hasErrors = false) : this(syntax, locals, ImmutableArray<LocalFunctionSymbol>.Empty, statements, hasErrors) { } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, BoundStatement statement) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create(statement)) { WasCompilerGenerated = true }; } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, ImmutableArray<BoundStatement> statements) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements) { WasCompilerGenerated = true }; } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, params BoundStatement[] statements) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements.AsImmutableOrNull()) { WasCompilerGenerated = true }; } } internal sealed partial class BoundDefaultExpression { public BoundDefaultExpression(SyntaxNode syntax, TypeSymbol type, bool hasErrors = false) : this(syntax, targetType: null, type.GetDefaultValue(), type, hasErrors) { } public override ConstantValue? ConstantValue => ConstantValueOpt; } internal partial class BoundTryStatement { public BoundTryStatement(SyntaxNode syntax, BoundBlock tryBlock, ImmutableArray<BoundCatchBlock> catchBlocks, BoundBlock? finallyBlockOpt, LabelSymbol? finallyLabelOpt = null) : this(syntax, tryBlock, catchBlocks, finallyBlockOpt, finallyLabelOpt, preferFaultHandler: false, hasErrors: false) { } } internal partial class BoundAddressOfOperator { public BoundAddressOfOperator(SyntaxNode syntax, BoundExpression operand, TypeSymbol type, bool hasErrors = false) : this(syntax, operand, isManaged: false, type, hasErrors) { } } internal partial class BoundDagTemp { public BoundDagTemp(SyntaxNode syntax, TypeSymbol type, BoundDagEvaluation? source) : this(syntax, type, source, index: 0, hasErrors: false) { } public static BoundDagTemp ForOriginalInput(BoundExpression expr) => new BoundDagTemp(expr.Syntax, expr.Type!, source: null); } internal partial class BoundCompoundAssignmentOperator { public BoundCompoundAssignmentOperator(SyntaxNode syntax, BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, Conversion leftConversion, Conversion finalConversion, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, @operator, left, right, leftConversion, finalConversion, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundCompoundAssignmentOperator Update(BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, Conversion leftConversion, Conversion finalConversion, LookupResultKind resultKind, TypeSymbol type) => Update(@operator, left, right, leftConversion, finalConversion, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } internal partial class BoundUnaryOperator { public BoundUnaryOperator( SyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, operand, constantValueOpt, methodOpt, constrainedToTypeOpt, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundUnaryOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, TypeSymbol type) => Update(operatorKind, operand, constantValueOpt, methodOpt, constrainedToTypeOpt, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } internal partial class BoundIncrementOperator { public BoundIncrementOperator( CSharpSyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, Conversion operandConversion, Conversion resultConversion, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, operand, methodOpt, constrainedToTypeOpt, operandConversion, resultConversion, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundIncrementOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, Conversion operandConversion, Conversion resultConversion, LookupResultKind resultKind, TypeSymbol type) { return Update(operatorKind, operand, methodOpt, constrainedToTypeOpt, operandConversion, resultConversion, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class BoundFieldAccess { public BoundFieldAccess( SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, LookupResultKind.Viable, fieldSymbol.Type, hasErrors) { } public BoundFieldAccess( SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration: false, type: type, hasErrors: hasErrors) { } public BoundFieldAccess( SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, bool isDeclaration, TypeSymbol type, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration: isDeclaration, type: type, hasErrors: hasErrors) { } public BoundFieldAccess Update( BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol typeSymbol) { return this.Update(receiver, fieldSymbol, constantValueOpt, resultKind, this.IsByValue, this.IsDeclaration, typeSymbol); } private static bool NeedsByValueFieldAccess(BoundExpression? receiver, FieldSymbol fieldSymbol) { if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsValueType || receiver == null) // receiver may be null in error cases { return false; } switch (receiver.Kind) { case BoundKind.FieldAccess: return ((BoundFieldAccess)receiver).IsByValue; case BoundKind.Local: var localSymbol = ((BoundLocal)receiver).LocalSymbol; return !(localSymbol.IsWritableVariable || localSymbol.IsRef); default: return false; } } } internal partial class BoundCall { public BoundCall( SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, originalMethodsOpt: default, type, hasErrors) { } public BoundCall Update(BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol type) => Update(receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, this.OriginalMethodsOpt, type); public static BoundCall ErrorCall( SyntaxNode node, BoundExpression receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> namedArguments, ImmutableArray<RefKind> refKinds, bool isDelegateCall, bool invokedAsExtensionMethod, ImmutableArray<MethodSymbol> originalMethods, LookupResultKind resultKind, Binder binder) { if (!originalMethods.IsEmpty) resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); Debug.Assert(arguments.IsDefaultOrEmpty || (object)receiverOpt != (object)arguments[0]); return new BoundCall( syntax: node, receiverOpt: binder.BindToTypeForErrorRecovery(receiverOpt), method: method, arguments: arguments.SelectAsArray((e, binder) => binder.BindToTypeForErrorRecovery(e), binder), argumentNamesOpt: namedArguments, argumentRefKindsOpt: refKinds, isDelegateCall: isDelegateCall, expanded: false, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), resultKind: resultKind, originalMethodsOpt: originalMethods, type: method.ReturnType, hasErrors: true); } public BoundCall Update(ImmutableArray<BoundExpression> arguments) { return this.Update(ReceiverOpt, Method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, DefaultArguments, ResultKind, OriginalMethodsOpt, Type); } public BoundCall Update(BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments) { return this.Update(receiverOpt, method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, DefaultArguments, ResultKind, OriginalMethodsOpt, Type); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method) { return Synthesized(syntax, receiverOpt, method, ImmutableArray<BoundExpression>.Empty); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, BoundExpression arg0) { return Synthesized(syntax, receiverOpt, method, ImmutableArray.Create(arg0)); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, BoundExpression arg0, BoundExpression arg1) { return Synthesized(syntax, receiverOpt, method, ImmutableArray.Create(arg0, arg1)); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments) { return new BoundCall(syntax, receiverOpt, method, arguments, argumentNamesOpt: default(ImmutableArray<string>), argumentRefKindsOpt: method.ParameterRefKinds, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable, originalMethodsOpt: default, type: method.ReturnType, hasErrors: method.OriginalDefinition is ErrorMethodSymbol ) { WasCompilerGenerated = true }; } } internal sealed partial class BoundObjectCreationExpression { public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, params BoundExpression[] arguments) : this(syntax, constructor, ImmutableArray.Create<BoundExpression>(arguments), default(ImmutableArray<string>), default(ImmutableArray<RefKind>), false, default(ImmutableArray<int>), default(BitVector), null, null, constructor.ContainingType) { } public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, ImmutableArray<BoundExpression> arguments) : this(syntax, constructor, arguments, default(ImmutableArray<string>), default(ImmutableArray<RefKind>), false, default(ImmutableArray<int>), default(BitVector), null, null, constructor.ContainingType) { } } internal partial class BoundIndexerAccess { public static BoundIndexerAccess ErrorAccess( SyntaxNode node, BoundExpression receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> namedArguments, ImmutableArray<RefKind> refKinds, ImmutableArray<PropertySymbol> originalIndexers) { return new BoundIndexerAccess( node, receiverOpt, indexer, arguments, namedArguments, refKinds, expanded: false, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), originalIndexers, type: indexer.Type, hasErrors: true); } public BoundIndexerAccess( SyntaxNode syntax, BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool expanded, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, TypeSymbol type, bool hasErrors = false) : this(syntax, receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, originalIndexersOpt: default, type, hasErrors) { } public BoundIndexerAccess Update(BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool expanded, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, TypeSymbol type) => Update(receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, this.OriginalIndexersOpt, type); } internal sealed partial class BoundConversion { /// <remarks> /// This method is intended for passes other than the LocalRewriter. /// Use MakeConversion helper method in the LocalRewriter instead, /// it generates a synthesized conversion in its lowered form. /// </remarks> public static BoundConversion SynthesizedNonUserDefined(SyntaxNode syntax, BoundExpression operand, Conversion conversion, TypeSymbol type, ConstantValue? constantValueOpt = null) { return new BoundConversion( syntax, operand, conversion, isBaseConversion: false, @checked: false, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: constantValueOpt, originalUserDefinedConversionsOpt: default, type: type) { WasCompilerGenerated = true }; } /// <remarks> /// NOTE: This method is intended for passes other than the LocalRewriter. /// NOTE: Use MakeConversion helper method in the LocalRewriter instead, /// NOTE: it generates a synthesized conversion in its lowered form. /// </remarks> public static BoundConversion Synthesized( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, bool explicitCastInCode, ConversionGroup? conversionGroupOpt, ConstantValue? constantValueOpt, TypeSymbol type, bool hasErrors = false) { return new BoundConversion( syntax, operand, conversion, @checked, explicitCastInCode: explicitCastInCode, conversionGroupOpt, constantValueOpt, type, hasErrors || !conversion.IsValid) { WasCompilerGenerated = true }; } public BoundConversion( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, bool explicitCastInCode, ConversionGroup? conversionGroupOpt, ConstantValue? constantValueOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operand, conversion, isBaseConversion: false, @checked: @checked, explicitCastInCode: explicitCastInCode, constantValueOpt: constantValueOpt, conversionGroupOpt, conversion.OriginalUserDefinedConversions, type: type, hasErrors: hasErrors || !conversion.IsValid) { } public BoundConversion( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, TypeSymbol type, bool hasErrors = false) : this(syntax, operand, conversion, isBaseConversion, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, originalUserDefinedConversionsOpt: default, type, hasErrors) { } public BoundConversion Update(BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, TypeSymbol type) => Update(operand, conversion, isBaseConversion, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, this.OriginalUserDefinedConversionsOpt, type); } internal sealed partial class BoundBinaryOperator { public BoundBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression left, BoundExpression right, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operatorKind, UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, originalUserDefinedOperatorsOpt), resultKind, left, right, type, hasErrors) { } public BoundBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, originalUserDefinedOperatorsOpt: default), resultKind, left, right, type, hasErrors) { } public BoundBinaryOperator Update(BinaryOperatorKind operatorKind, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type) { var uncommonData = UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, OriginalUserDefinedOperatorsOpt); return Update(operatorKind, uncommonData, resultKind, left, right, type); } public BoundBinaryOperator Update(UncommonData uncommonData) { return Update(OperatorKind, uncommonData, ResultKind, Left, Right, Type); } } internal sealed partial class BoundUserDefinedConditionalLogicalOperator { public BoundUserDefinedConditionalLogicalOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression left, BoundExpression right, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operatorKind, logicalOperator, trueOperator, falseOperator, constrainedToTypeOpt, resultKind, originalUserDefinedOperatorsOpt, left, right, type, hasErrors) { Debug.Assert(operatorKind.IsUserDefined() && operatorKind.IsLogical()); } public BoundUserDefinedConditionalLogicalOperator Update(BinaryOperatorKind operatorKind, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type) => Update(operatorKind, logicalOperator, trueOperator, falseOperator, constrainedToTypeOpt, resultKind, this.OriginalUserDefinedOperatorsOpt, left, right, type); } internal sealed partial class BoundParameter { public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol, bool hasErrors = false) : this(syntax, parameterSymbol, parameterSymbol.Type, hasErrors) { } public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol) : this(syntax, parameterSymbol, parameterSymbol.Type) { } } internal sealed partial class BoundTypeExpression { public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, BoundTypeExpression? boundContainingTypeOpt, ImmutableArray<BoundExpression> boundDimensionsOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, boundContainingTypeOpt, boundDimensionsOpt, typeWithAnnotations, typeWithAnnotations.Type, hasErrors) { Debug.Assert((object)typeWithAnnotations.Type != null, "Field 'type' cannot be null"); } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, BoundTypeExpression? boundContainingTypeOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, boundContainingTypeOpt, ImmutableArray<BoundExpression>.Empty, typeWithAnnotations, hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, null, typeWithAnnotations, hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, TypeSymbol type, bool hasErrors = false) : this(syntax, aliasOpt, null, TypeWithAnnotations.Create(type), hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, ImmutableArray<BoundExpression> dimensionsOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, null, dimensionsOpt, typeWithAnnotations, hasErrors) { } } internal sealed partial class BoundNamespaceExpression { public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol, bool hasErrors = false) : this(syntax, namespaceSymbol, null, hasErrors) { } public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol) : this(syntax, namespaceSymbol, null) { } public BoundNamespaceExpression Update(NamespaceSymbol namespaceSymbol) { return Update(namespaceSymbol, this.AliasOpt); } } internal sealed partial class BoundAssignmentOperator { public BoundAssignmentOperator(SyntaxNode syntax, BoundExpression left, BoundExpression right, TypeSymbol type, bool isRef = false, bool hasErrors = false) : this(syntax, left, right, isRef, type, hasErrors) { } } internal sealed partial class BoundBadExpression { public BoundBadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol?> symbols, ImmutableArray<BoundExpression> childBoundNodes, TypeSymbol type) : this(syntax, resultKind, symbols, childBoundNodes, type, true) { Debug.Assert((object)type != null); } } internal partial class BoundStatementList { public static BoundStatementList Synthesized(SyntaxNode syntax, params BoundStatement[] statements) { return Synthesized(syntax, false, statements.AsImmutableOrNull()); } public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, params BoundStatement[] statements) { return Synthesized(syntax, hasErrors, statements.AsImmutableOrNull()); } public static BoundStatementList Synthesized(SyntaxNode syntax, ImmutableArray<BoundStatement> statements) { return Synthesized(syntax, false, statements); } public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, ImmutableArray<BoundStatement> statements) { return new BoundStatementList(syntax, statements, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundReturnStatement { public static BoundReturnStatement Synthesized(SyntaxNode syntax, RefKind refKind, BoundExpression expression, bool hasErrors = false) { return new BoundReturnStatement(syntax, refKind, expression, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundYieldBreakStatement { public static BoundYieldBreakStatement Synthesized(SyntaxNode syntax, bool hasErrors = false) { return new BoundYieldBreakStatement(syntax, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundGotoStatement { public BoundGotoStatement(SyntaxNode syntax, LabelSymbol label, bool hasErrors = false) : this(syntax, label, caseExpressionOpt: null, labelExpressionOpt: null, hasErrors: hasErrors) { } } internal partial class BoundBlock { public BoundBlock(SyntaxNode syntax, ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundStatement> statements, bool hasErrors = false) : this(syntax, locals, ImmutableArray<LocalFunctionSymbol>.Empty, statements, hasErrors) { } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, BoundStatement statement) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create(statement)) { WasCompilerGenerated = true }; } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, ImmutableArray<BoundStatement> statements) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements) { WasCompilerGenerated = true }; } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, params BoundStatement[] statements) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements.AsImmutableOrNull()) { WasCompilerGenerated = true }; } } internal sealed partial class BoundDefaultExpression { public BoundDefaultExpression(SyntaxNode syntax, TypeSymbol type, bool hasErrors = false) : this(syntax, targetType: null, type.GetDefaultValue(), type, hasErrors) { } public override ConstantValue? ConstantValue => ConstantValueOpt; } internal partial class BoundTryStatement { public BoundTryStatement(SyntaxNode syntax, BoundBlock tryBlock, ImmutableArray<BoundCatchBlock> catchBlocks, BoundBlock? finallyBlockOpt, LabelSymbol? finallyLabelOpt = null) : this(syntax, tryBlock, catchBlocks, finallyBlockOpt, finallyLabelOpt, preferFaultHandler: false, hasErrors: false) { } } internal partial class BoundAddressOfOperator { public BoundAddressOfOperator(SyntaxNode syntax, BoundExpression operand, TypeSymbol type, bool hasErrors = false) : this(syntax, operand, isManaged: false, type, hasErrors) { } } internal partial class BoundDagTemp { public BoundDagTemp(SyntaxNode syntax, TypeSymbol type, BoundDagEvaluation? source) : this(syntax, type, source, index: 0, hasErrors: false) { } public static BoundDagTemp ForOriginalInput(BoundExpression expr) => new BoundDagTemp(expr.Syntax, expr.Type!, source: null); } internal partial class BoundCompoundAssignmentOperator { public BoundCompoundAssignmentOperator(SyntaxNode syntax, BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, Conversion leftConversion, Conversion finalConversion, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, @operator, left, right, leftConversion, finalConversion, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundCompoundAssignmentOperator Update(BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, Conversion leftConversion, Conversion finalConversion, LookupResultKind resultKind, TypeSymbol type) => Update(@operator, left, right, leftConversion, finalConversion, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } internal partial class BoundUnaryOperator { public BoundUnaryOperator( SyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, operand, constantValueOpt, methodOpt, constrainedToTypeOpt, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundUnaryOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, TypeSymbol type) => Update(operatorKind, operand, constantValueOpt, methodOpt, constrainedToTypeOpt, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } internal partial class BoundIncrementOperator { public BoundIncrementOperator( CSharpSyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, Conversion operandConversion, Conversion resultConversion, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, operand, methodOpt, constrainedToTypeOpt, operandConversion, resultConversion, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundIncrementOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, Conversion operandConversion, Conversion resultConversion, LookupResultKind resultKind, TypeSymbol type) { return Update(operatorKind, operand, methodOpt, constrainedToTypeOpt, operandConversion, resultConversion, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/CancellableLazy.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; namespace Roslyn.Utilities { internal static class CancellableLazy { public static CancellableLazy<T> Create<T>(T value) => new(value); public static CancellableLazy<T> Create<T>(Func<CancellationToken, T> valueFactory) => new(valueFactory); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; namespace Roslyn.Utilities { internal static class CancellableLazy { public static CancellableLazy<T> Create<T>(T value) => new(value); public static CancellableLazy<T> Create<T>(Func<CancellationToken, T> valueFactory) => new(valueFactory); } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Compilers/CSharp/Portable/Symbols/Source/SourceDelegateMethodSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceDelegateMethodSymbol : SourceMemberMethodSymbol { private ImmutableArray<ParameterSymbol> _parameters; private readonly TypeWithAnnotations _returnType; protected SourceDelegateMethodSymbol( SourceMemberContainerTypeSymbol delegateType, TypeWithAnnotations returnType, DelegateDeclarationSyntax syntax, MethodKind methodKind, DeclarationModifiers declarationModifiers) : base(delegateType, syntax.GetReference(), location: syntax.Identifier.GetLocation(), isIterator: false) { _returnType = returnType; this.MakeFlags(methodKind, declarationModifiers, _returnType.IsVoidType(), isExtensionMethod: false, isNullableAnalysisEnabled: false); } protected void InitializeParameters(ImmutableArray<ParameterSymbol> parameters) { Debug.Assert(_parameters.IsDefault); _parameters = parameters; } internal static void AddDelegateMembers( SourceMemberContainerTypeSymbol delegateType, ArrayBuilder<Symbol> symbols, DelegateDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) { var compilation = delegateType.DeclaringCompilation; Binder binder = delegateType.GetBinder(syntax.ParameterList); RefKind refKind; TypeSyntax returnTypeSyntax = syntax.ReturnType.SkipRef(out refKind); var returnType = binder.BindType(returnTypeSyntax, diagnostics); // reuse types to avoid reporting duplicate errors if missing: var voidType = TypeWithAnnotations.Create(binder.GetSpecialType(SpecialType.System_Void, diagnostics, syntax)); // https://github.com/dotnet/roslyn/issues/30079: Should the 'object', IAsyncResult and AsyncCallback parameters be considered nullable or not nullable? var objectType = TypeWithAnnotations.Create(binder.GetSpecialType(SpecialType.System_Object, diagnostics, syntax)); var intPtrType = TypeWithAnnotations.Create(binder.GetSpecialType(SpecialType.System_IntPtr, diagnostics, syntax)); if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true)) { // The return type of a method, delegate, or function pointer cannot be '{0}' diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, returnTypeSyntax.Location, returnType.Type); } // A delegate has the following members: (see CLI spec 13.6) // (1) a method named Invoke with the specified signature var invoke = new InvokeMethod(delegateType, refKind, returnType, syntax, binder, diagnostics); invoke.CheckDelegateVarianceSafety(diagnostics); symbols.Add(invoke); // (2) a constructor with argument types (object, System.IntPtr) symbols.Add(new Constructor(delegateType, voidType, objectType, intPtrType, syntax)); if (binder.Compilation.GetSpecialType(SpecialType.System_IAsyncResult).TypeKind != TypeKind.Error && binder.Compilation.GetSpecialType(SpecialType.System_AsyncCallback).TypeKind != TypeKind.Error && // WinRT delegates don't have Begin/EndInvoke methods !delegateType.IsCompilationOutputWinMdObj()) { var iAsyncResultType = TypeWithAnnotations.Create(binder.GetSpecialType(SpecialType.System_IAsyncResult, diagnostics, syntax)); var asyncCallbackType = TypeWithAnnotations.Create(binder.GetSpecialType(SpecialType.System_AsyncCallback, diagnostics, syntax)); // (3) BeginInvoke symbols.Add(new BeginInvokeMethod(invoke, iAsyncResultType, objectType, asyncCallbackType, syntax)); // and (4) EndInvoke methods symbols.Add(new EndInvokeMethod(invoke, iAsyncResultType, syntax)); } if (delegateType.DeclaredAccessibility <= Accessibility.Private) { return; } var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, delegateType.ContainingAssembly); if (!delegateType.IsNoMoreVisibleThan(invoke.ReturnTypeWithAnnotations, ref useSiteInfo)) { // Inconsistent accessibility: return type '{1}' is less accessible than delegate '{0}' diagnostics.Add(ErrorCode.ERR_BadVisDelegateReturn, delegateType.Locations[0], delegateType, invoke.ReturnType); } foreach (var parameter in invoke.Parameters) { if (!parameter.TypeWithAnnotations.IsAtLeastAsVisibleAs(delegateType, ref useSiteInfo)) { // Inconsistent accessibility: parameter type '{1}' is less accessible than delegate '{0}' diagnostics.Add(ErrorCode.ERR_BadVisDelegateParam, delegateType.Locations[0], delegateType, parameter.Type); } } diagnostics.Add(delegateType.Locations[0], useSiteInfo); } protected override void MethodChecks(BindingDiagnosticBag diagnostics) { // TODO: move more functionality into here, making these symbols more lazy } public sealed override bool IsVararg { get { return false; } } public sealed override ImmutableArray<ParameterSymbol> Parameters { get { Debug.Assert(!_parameters.IsDefault, $"Expected {nameof(InitializeParameters)} prior to accessing this property."); return _parameters.NullToEmpty(); } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; public sealed override TypeWithAnnotations ReturnTypeWithAnnotations { get { return _returnType; } } public sealed override bool IsImplicitlyDeclared { get { return true; } } internal override bool IsExpressionBodied { get { return false; } } internal override bool GenerateDebugInfo { get { return false; } } protected sealed override IAttributeTargetSymbol AttributeOwner { get { return (SourceNamedTypeSymbol)ContainingSymbol; } } internal sealed override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return System.Reflection.MethodImplAttributes.Runtime; } } internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { // TODO: This implementation looks strange. It might make sense for the Invoke method, but // not for constructor and other methods. return OneOrMany.Create(((SourceNamedTypeSymbol)ContainingSymbol).GetAttributeDeclarations()); } internal sealed override System.AttributeTargets GetAttributeTarget() { return System.AttributeTargets.Delegate; } private sealed class Constructor : SourceDelegateMethodSymbol { internal Constructor( SourceMemberContainerTypeSymbol delegateType, TypeWithAnnotations voidType, TypeWithAnnotations objectType, TypeWithAnnotations intPtrType, DelegateDeclarationSyntax syntax) : base(delegateType, voidType, syntax, MethodKind.Constructor, DeclarationModifiers.Public) { InitializeParameters(ImmutableArray.Create<ParameterSymbol>( SynthesizedParameterSymbol.Create(this, objectType, 0, RefKind.None, "object"), SynthesizedParameterSymbol.Create(this, intPtrType, 1, RefKind.None, "method"))); } public override string Name { get { return WellKnownMemberNames.InstanceConstructorName; } } public override RefKind RefKind { get { return RefKind.None; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetReturnTypeAttributeDeclarations() { // Constructors don't have return type attributes return OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); } internal override LexicalSortKey GetLexicalSortKey() { // associate "Invoke and .ctor" with whole delegate declaration for the sorting purposes // other methods will be associated with delegate's identifier // we want this just to keep the order of synthesized methods the same as in Dev12 // Dev12 order is not strictly alphabetical - .ctor and Invoke go before other members. // there are no real reasons for emitting the members in one order or another, // so we will keep them the same. return new LexicalSortKey(this.syntaxReferenceOpt.GetLocation(), this.DeclaringCompilation); } } private sealed class InvokeMethod : SourceDelegateMethodSymbol { private readonly RefKind _refKind; private readonly ImmutableArray<CustomModifier> _refCustomModifiers; internal InvokeMethod( SourceMemberContainerTypeSymbol delegateType, RefKind refKind, TypeWithAnnotations returnType, DelegateDeclarationSyntax syntax, Binder binder, BindingDiagnosticBag diagnostics) : base(delegateType, returnType, syntax, MethodKind.DelegateInvoke, DeclarationModifiers.Virtual | DeclarationModifiers.Public) { this._refKind = refKind; SyntaxToken arglistToken; var parameters = ParameterHelpers.MakeParameters( binder, this, syntax.ParameterList, out arglistToken, allowRefOrOut: true, allowThis: false, addRefReadOnlyModifier: true, diagnostics: diagnostics); if (arglistToken.Kind() == SyntaxKind.ArgListKeyword) { // This is a parse-time error in the native compiler; it is a semantic analysis error in Roslyn. // error CS1669: __arglist is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, new SourceLocation(arglistToken)); } if (_refKind == RefKind.RefReadOnly) { var modifierType = binder.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_InAttribute, diagnostics, syntax.ReturnType); _refCustomModifiers = ImmutableArray.Create(CSharpCustomModifier.CreateRequired(modifierType)); } else { _refCustomModifiers = ImmutableArray<CustomModifier>.Empty; } InitializeParameters(parameters); } public override string Name { get { return WellKnownMemberNames.DelegateInvokeName; } } public override RefKind RefKind { get { return _refKind; } } internal override LexicalSortKey GetLexicalSortKey() { // associate "Invoke and .ctor" with whole delegate declaration for the sorting purposes // other methods will be associated with delegate's identifier // we want this just to keep the order of synthesized methods the same as in Dev12 // Dev12 order is not strictly alphabetical - .ctor and Invoke go before other members. // there are no real reasons for emitting the members in one order or another, // so we will keep them the same. return new LexicalSortKey(this.syntaxReferenceOpt.GetLocation(), this.DeclaringCompilation); } internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { var syntax = (DelegateDeclarationSyntax)SyntaxRef.GetSyntax(); var location = syntax.ReturnType.GetLocation(); var compilation = DeclaringCompilation; Debug.Assert(location != null); base.AfterAddingTypeMembersChecks(conversions, diagnostics); if (_refKind == RefKind.RefReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } ParameterHelpers.EnsureIsReadOnlyAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true); if (ReturnType.ContainsNativeInteger()) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true); } ParameterHelpers.EnsureNativeIntegerAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true); if (compilation.ShouldEmitNullableAttributes(this) && ReturnTypeWithAnnotations.NeedsNullableAttribute()) { compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true); } ParameterHelpers.EnsureNullableAttributeExists(compilation, this, Parameters, diagnostics, modifyCompilation: true); } public override ImmutableArray<CustomModifier> RefCustomModifiers => _refCustomModifiers; } private sealed class BeginInvokeMethod : SourceDelegateMethodSymbol { internal BeginInvokeMethod( InvokeMethod invoke, TypeWithAnnotations iAsyncResultType, TypeWithAnnotations objectType, TypeWithAnnotations asyncCallbackType, DelegateDeclarationSyntax syntax) : base((SourceNamedTypeSymbol)invoke.ContainingType, iAsyncResultType, syntax, MethodKind.Ordinary, DeclarationModifiers.Virtual | DeclarationModifiers.Public) { var parameters = ArrayBuilder<ParameterSymbol>.GetInstance(); foreach (SourceParameterSymbol p in invoke.Parameters) { var synthesizedParam = new SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(originalParam: p, newOwner: this, newOrdinal: p.Ordinal); parameters.Add(synthesizedParam); } int paramCount = invoke.ParameterCount; parameters.Add(SynthesizedParameterSymbol.Create(this, asyncCallbackType, paramCount, RefKind.None, GetUniqueParameterName(parameters, "callback"))); parameters.Add(SynthesizedParameterSymbol.Create(this, objectType, paramCount + 1, RefKind.None, GetUniqueParameterName(parameters, "object"))); InitializeParameters(parameters.ToImmutableAndFree()); } public override string Name { get { return WellKnownMemberNames.DelegateBeginInvokeName; } } public override RefKind RefKind { get { return RefKind.None; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetReturnTypeAttributeDeclarations() { // BeginInvoke method doesn't have return type attributes // because it doesn't inherit Delegate declaration's return type. // It has a special return type: SpecialType.System.IAsyncResult. return OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); } } private sealed class EndInvokeMethod : SourceDelegateMethodSymbol { private readonly InvokeMethod _invoke; internal EndInvokeMethod( InvokeMethod invoke, TypeWithAnnotations iAsyncResultType, DelegateDeclarationSyntax syntax) : base((SourceNamedTypeSymbol)invoke.ContainingType, invoke.ReturnTypeWithAnnotations, syntax, MethodKind.Ordinary, DeclarationModifiers.Virtual | DeclarationModifiers.Public) { _invoke = invoke; var parameters = ArrayBuilder<ParameterSymbol>.GetInstance(); int ordinal = 0; foreach (SourceParameterSymbol p in invoke.Parameters) { if (p.RefKind != RefKind.None) { var synthesizedParam = new SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(originalParam: p, newOwner: this, newOrdinal: ordinal++); parameters.Add(synthesizedParam); } } parameters.Add(SynthesizedParameterSymbol.Create(this, iAsyncResultType, ordinal++, RefKind.None, GetUniqueParameterName(parameters, "result"))); InitializeParameters(parameters.ToImmutableAndFree()); } protected override SourceMemberMethodSymbol BoundAttributesSource => _invoke; public override string Name => WellKnownMemberNames.DelegateEndInvokeName; public override RefKind RefKind => _invoke.RefKind; public override ImmutableArray<CustomModifier> RefCustomModifiers => _invoke.RefCustomModifiers; } private static string GetUniqueParameterName(ArrayBuilder<ParameterSymbol> currentParameters, string name) { while (!IsUnique(currentParameters, name)) { name = "__" + name; } return name; } private static bool IsUnique(ArrayBuilder<ParameterSymbol> currentParameters, string name) { foreach (var p in currentParameters) { if (string.CompareOrdinal(p.Name, name) == 0) { return false; } } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceDelegateMethodSymbol : SourceMemberMethodSymbol { private ImmutableArray<ParameterSymbol> _parameters; private readonly TypeWithAnnotations _returnType; protected SourceDelegateMethodSymbol( SourceMemberContainerTypeSymbol delegateType, TypeWithAnnotations returnType, DelegateDeclarationSyntax syntax, MethodKind methodKind, DeclarationModifiers declarationModifiers) : base(delegateType, syntax.GetReference(), location: syntax.Identifier.GetLocation(), isIterator: false) { _returnType = returnType; this.MakeFlags(methodKind, declarationModifiers, _returnType.IsVoidType(), isExtensionMethod: false, isNullableAnalysisEnabled: false); } protected void InitializeParameters(ImmutableArray<ParameterSymbol> parameters) { Debug.Assert(_parameters.IsDefault); _parameters = parameters; } internal static void AddDelegateMembers( SourceMemberContainerTypeSymbol delegateType, ArrayBuilder<Symbol> symbols, DelegateDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) { var compilation = delegateType.DeclaringCompilation; Binder binder = delegateType.GetBinder(syntax.ParameterList); RefKind refKind; TypeSyntax returnTypeSyntax = syntax.ReturnType.SkipRef(out refKind); var returnType = binder.BindType(returnTypeSyntax, diagnostics); // reuse types to avoid reporting duplicate errors if missing: var voidType = TypeWithAnnotations.Create(binder.GetSpecialType(SpecialType.System_Void, diagnostics, syntax)); // https://github.com/dotnet/roslyn/issues/30079: Should the 'object', IAsyncResult and AsyncCallback parameters be considered nullable or not nullable? var objectType = TypeWithAnnotations.Create(binder.GetSpecialType(SpecialType.System_Object, diagnostics, syntax)); var intPtrType = TypeWithAnnotations.Create(binder.GetSpecialType(SpecialType.System_IntPtr, diagnostics, syntax)); if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true)) { // The return type of a method, delegate, or function pointer cannot be '{0}' diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, returnTypeSyntax.Location, returnType.Type); } // A delegate has the following members: (see CLI spec 13.6) // (1) a method named Invoke with the specified signature var invoke = new InvokeMethod(delegateType, refKind, returnType, syntax, binder, diagnostics); invoke.CheckDelegateVarianceSafety(diagnostics); symbols.Add(invoke); // (2) a constructor with argument types (object, System.IntPtr) symbols.Add(new Constructor(delegateType, voidType, objectType, intPtrType, syntax)); if (binder.Compilation.GetSpecialType(SpecialType.System_IAsyncResult).TypeKind != TypeKind.Error && binder.Compilation.GetSpecialType(SpecialType.System_AsyncCallback).TypeKind != TypeKind.Error && // WinRT delegates don't have Begin/EndInvoke methods !delegateType.IsCompilationOutputWinMdObj()) { var iAsyncResultType = TypeWithAnnotations.Create(binder.GetSpecialType(SpecialType.System_IAsyncResult, diagnostics, syntax)); var asyncCallbackType = TypeWithAnnotations.Create(binder.GetSpecialType(SpecialType.System_AsyncCallback, diagnostics, syntax)); // (3) BeginInvoke symbols.Add(new BeginInvokeMethod(invoke, iAsyncResultType, objectType, asyncCallbackType, syntax)); // and (4) EndInvoke methods symbols.Add(new EndInvokeMethod(invoke, iAsyncResultType, syntax)); } if (delegateType.DeclaredAccessibility <= Accessibility.Private) { return; } var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, delegateType.ContainingAssembly); if (!delegateType.IsNoMoreVisibleThan(invoke.ReturnTypeWithAnnotations, ref useSiteInfo)) { // Inconsistent accessibility: return type '{1}' is less accessible than delegate '{0}' diagnostics.Add(ErrorCode.ERR_BadVisDelegateReturn, delegateType.Locations[0], delegateType, invoke.ReturnType); } foreach (var parameter in invoke.Parameters) { if (!parameter.TypeWithAnnotations.IsAtLeastAsVisibleAs(delegateType, ref useSiteInfo)) { // Inconsistent accessibility: parameter type '{1}' is less accessible than delegate '{0}' diagnostics.Add(ErrorCode.ERR_BadVisDelegateParam, delegateType.Locations[0], delegateType, parameter.Type); } } diagnostics.Add(delegateType.Locations[0], useSiteInfo); } protected override void MethodChecks(BindingDiagnosticBag diagnostics) { // TODO: move more functionality into here, making these symbols more lazy } public sealed override bool IsVararg { get { return false; } } public sealed override ImmutableArray<ParameterSymbol> Parameters { get { Debug.Assert(!_parameters.IsDefault, $"Expected {nameof(InitializeParameters)} prior to accessing this property."); return _parameters.NullToEmpty(); } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; public sealed override TypeWithAnnotations ReturnTypeWithAnnotations { get { return _returnType; } } public sealed override bool IsImplicitlyDeclared { get { return true; } } internal override bool IsExpressionBodied { get { return false; } } internal override bool GenerateDebugInfo { get { return false; } } protected sealed override IAttributeTargetSymbol AttributeOwner { get { return (SourceNamedTypeSymbol)ContainingSymbol; } } internal sealed override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return System.Reflection.MethodImplAttributes.Runtime; } } internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { // TODO: This implementation looks strange. It might make sense for the Invoke method, but // not for constructor and other methods. return OneOrMany.Create(((SourceNamedTypeSymbol)ContainingSymbol).GetAttributeDeclarations()); } internal sealed override System.AttributeTargets GetAttributeTarget() { return System.AttributeTargets.Delegate; } private sealed class Constructor : SourceDelegateMethodSymbol { internal Constructor( SourceMemberContainerTypeSymbol delegateType, TypeWithAnnotations voidType, TypeWithAnnotations objectType, TypeWithAnnotations intPtrType, DelegateDeclarationSyntax syntax) : base(delegateType, voidType, syntax, MethodKind.Constructor, DeclarationModifiers.Public) { InitializeParameters(ImmutableArray.Create<ParameterSymbol>( SynthesizedParameterSymbol.Create(this, objectType, 0, RefKind.None, "object"), SynthesizedParameterSymbol.Create(this, intPtrType, 1, RefKind.None, "method"))); } public override string Name { get { return WellKnownMemberNames.InstanceConstructorName; } } public override RefKind RefKind { get { return RefKind.None; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetReturnTypeAttributeDeclarations() { // Constructors don't have return type attributes return OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); } internal override LexicalSortKey GetLexicalSortKey() { // associate "Invoke and .ctor" with whole delegate declaration for the sorting purposes // other methods will be associated with delegate's identifier // we want this just to keep the order of synthesized methods the same as in Dev12 // Dev12 order is not strictly alphabetical - .ctor and Invoke go before other members. // there are no real reasons for emitting the members in one order or another, // so we will keep them the same. return new LexicalSortKey(this.syntaxReferenceOpt.GetLocation(), this.DeclaringCompilation); } } private sealed class InvokeMethod : SourceDelegateMethodSymbol { private readonly RefKind _refKind; private readonly ImmutableArray<CustomModifier> _refCustomModifiers; internal InvokeMethod( SourceMemberContainerTypeSymbol delegateType, RefKind refKind, TypeWithAnnotations returnType, DelegateDeclarationSyntax syntax, Binder binder, BindingDiagnosticBag diagnostics) : base(delegateType, returnType, syntax, MethodKind.DelegateInvoke, DeclarationModifiers.Virtual | DeclarationModifiers.Public) { this._refKind = refKind; SyntaxToken arglistToken; var parameters = ParameterHelpers.MakeParameters( binder, this, syntax.ParameterList, out arglistToken, allowRefOrOut: true, allowThis: false, addRefReadOnlyModifier: true, diagnostics: diagnostics); if (arglistToken.Kind() == SyntaxKind.ArgListKeyword) { // This is a parse-time error in the native compiler; it is a semantic analysis error in Roslyn. // error CS1669: __arglist is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, new SourceLocation(arglistToken)); } if (_refKind == RefKind.RefReadOnly) { var modifierType = binder.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_InAttribute, diagnostics, syntax.ReturnType); _refCustomModifiers = ImmutableArray.Create(CSharpCustomModifier.CreateRequired(modifierType)); } else { _refCustomModifiers = ImmutableArray<CustomModifier>.Empty; } InitializeParameters(parameters); } public override string Name { get { return WellKnownMemberNames.DelegateInvokeName; } } public override RefKind RefKind { get { return _refKind; } } internal override LexicalSortKey GetLexicalSortKey() { // associate "Invoke and .ctor" with whole delegate declaration for the sorting purposes // other methods will be associated with delegate's identifier // we want this just to keep the order of synthesized methods the same as in Dev12 // Dev12 order is not strictly alphabetical - .ctor and Invoke go before other members. // there are no real reasons for emitting the members in one order or another, // so we will keep them the same. return new LexicalSortKey(this.syntaxReferenceOpt.GetLocation(), this.DeclaringCompilation); } internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { var syntax = (DelegateDeclarationSyntax)SyntaxRef.GetSyntax(); var location = syntax.ReturnType.GetLocation(); var compilation = DeclaringCompilation; Debug.Assert(location != null); base.AfterAddingTypeMembersChecks(conversions, diagnostics); if (_refKind == RefKind.RefReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } ParameterHelpers.EnsureIsReadOnlyAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true); if (ReturnType.ContainsNativeInteger()) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true); } ParameterHelpers.EnsureNativeIntegerAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true); if (compilation.ShouldEmitNullableAttributes(this) && ReturnTypeWithAnnotations.NeedsNullableAttribute()) { compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true); } ParameterHelpers.EnsureNullableAttributeExists(compilation, this, Parameters, diagnostics, modifyCompilation: true); } public override ImmutableArray<CustomModifier> RefCustomModifiers => _refCustomModifiers; } private sealed class BeginInvokeMethod : SourceDelegateMethodSymbol { internal BeginInvokeMethod( InvokeMethod invoke, TypeWithAnnotations iAsyncResultType, TypeWithAnnotations objectType, TypeWithAnnotations asyncCallbackType, DelegateDeclarationSyntax syntax) : base((SourceNamedTypeSymbol)invoke.ContainingType, iAsyncResultType, syntax, MethodKind.Ordinary, DeclarationModifiers.Virtual | DeclarationModifiers.Public) { var parameters = ArrayBuilder<ParameterSymbol>.GetInstance(); foreach (SourceParameterSymbol p in invoke.Parameters) { var synthesizedParam = new SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(originalParam: p, newOwner: this, newOrdinal: p.Ordinal); parameters.Add(synthesizedParam); } int paramCount = invoke.ParameterCount; parameters.Add(SynthesizedParameterSymbol.Create(this, asyncCallbackType, paramCount, RefKind.None, GetUniqueParameterName(parameters, "callback"))); parameters.Add(SynthesizedParameterSymbol.Create(this, objectType, paramCount + 1, RefKind.None, GetUniqueParameterName(parameters, "object"))); InitializeParameters(parameters.ToImmutableAndFree()); } public override string Name { get { return WellKnownMemberNames.DelegateBeginInvokeName; } } public override RefKind RefKind { get { return RefKind.None; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetReturnTypeAttributeDeclarations() { // BeginInvoke method doesn't have return type attributes // because it doesn't inherit Delegate declaration's return type. // It has a special return type: SpecialType.System.IAsyncResult. return OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); } } private sealed class EndInvokeMethod : SourceDelegateMethodSymbol { private readonly InvokeMethod _invoke; internal EndInvokeMethod( InvokeMethod invoke, TypeWithAnnotations iAsyncResultType, DelegateDeclarationSyntax syntax) : base((SourceNamedTypeSymbol)invoke.ContainingType, invoke.ReturnTypeWithAnnotations, syntax, MethodKind.Ordinary, DeclarationModifiers.Virtual | DeclarationModifiers.Public) { _invoke = invoke; var parameters = ArrayBuilder<ParameterSymbol>.GetInstance(); int ordinal = 0; foreach (SourceParameterSymbol p in invoke.Parameters) { if (p.RefKind != RefKind.None) { var synthesizedParam = new SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(originalParam: p, newOwner: this, newOrdinal: ordinal++); parameters.Add(synthesizedParam); } } parameters.Add(SynthesizedParameterSymbol.Create(this, iAsyncResultType, ordinal++, RefKind.None, GetUniqueParameterName(parameters, "result"))); InitializeParameters(parameters.ToImmutableAndFree()); } protected override SourceMemberMethodSymbol BoundAttributesSource => _invoke; public override string Name => WellKnownMemberNames.DelegateEndInvokeName; public override RefKind RefKind => _invoke.RefKind; public override ImmutableArray<CustomModifier> RefCustomModifiers => _invoke.RefCustomModifiers; } private static string GetUniqueParameterName(ArrayBuilder<ParameterSymbol> currentParameters, string name) { while (!IsUnique(currentParameters, name)) { name = "__" + name; } return name; } private static bool IsUnique(ArrayBuilder<ParameterSymbol> currentParameters, string name) { foreach (var p in currentParameters) { if (string.CompareOrdinal(p.Name, name) == 0) { return false; } } return true; } } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/CodeStyle/Core/Analyzers/AnalyzerConfigOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis { internal sealed class CompilerAnalyzerConfigOptions : AnalyzerConfigOptions { public static CompilerAnalyzerConfigOptions Empty { get; } = new CompilerAnalyzerConfigOptions(); private CompilerAnalyzerConfigOptions() { } public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) { value = null; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis { internal sealed class CompilerAnalyzerConfigOptions : AnalyzerConfigOptions { public static CompilerAnalyzerConfigOptions Empty { get; } = new CompilerAnalyzerConfigOptions(); private CompilerAnalyzerConfigOptions() { } public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) { value = null; return false; } } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Features/Core/Portable/EditAndContinue/StateMachineKinds.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.EditAndContinue { [Flags] internal enum StateMachineKinds { None = 0, Async = 1, Iterator = 1 << 1, } }
// Licensed to the .NET Foundation under one or more 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.EditAndContinue { [Flags] internal enum StateMachineKinds { None = 0, Async = 1, Iterator = 1 << 1, } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/CSharpProjectShim.ICSCompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { internal partial class CSharpProjectShim : ICSCompiler { public ICSSourceModule CreateSourceModule(ICSSourceText text) => throw new NotImplementedException(); public ICSNameTable GetNameTable() => throw new NotImplementedException(); public void Shutdown() => throw new NotImplementedException(); public ICSCompilerConfig GetConfiguration() => this; public ICSInputSet AddInputSet() => throw new NotImplementedException(); public void RemoveInputSet(ICSInputSet inputSet) => throw new NotImplementedException(); public void Compile(ICSCompileProgress progress) => throw new NotImplementedException(); public void BuildForEnc(ICSCompileProgress progress, ICSEncProjectServices encService, object pe) => throw new NotImplementedException(); public object CreateParser() => throw new NotImplementedException(); public object CreateLanguageAnalysisEngine() => throw new NotImplementedException(); public void ReleaseReservedMemory() => throw new NotImplementedException(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { internal partial class CSharpProjectShim : ICSCompiler { public ICSSourceModule CreateSourceModule(ICSSourceText text) => throw new NotImplementedException(); public ICSNameTable GetNameTable() => throw new NotImplementedException(); public void Shutdown() => throw new NotImplementedException(); public ICSCompilerConfig GetConfiguration() => this; public ICSInputSet AddInputSet() => throw new NotImplementedException(); public void RemoveInputSet(ICSInputSet inputSet) => throw new NotImplementedException(); public void Compile(ICSCompileProgress progress) => throw new NotImplementedException(); public void BuildForEnc(ICSCompileProgress progress, ICSEncProjectServices encService, object pe) => throw new NotImplementedException(); public object CreateParser() => throw new NotImplementedException(); public object CreateLanguageAnalysisEngine() => throw new NotImplementedException(); public void ReleaseReservedMemory() => throw new NotImplementedException(); } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/EditorFeatures/CSharpTest/Wrapping/ArgumentWrappingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Wrapping; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping { public class ArgumentWrappingTests : AbstractWrappingTests { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpWrappingCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSyntaxError() { await TestMissingAsync( @"class C { void Bar() { Goobar([||]i, j } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSelection() { await TestMissingAsync( @"class C { void Bar() { Goobar([|i|], j); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingBeforeName() { await TestMissingAsync( @"class C { void Bar() { a.[||]b.Goobar(i, j); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSingleParameter() { await TestMissingAsync( @"class C { void Bar() { Goobar([||]i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithMultiLineParameter() { await TestMissingAsync( @"class C { void Bar() { Goobar([||]i, j + k); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithMultiLineParameter2() { await TestMissingAsync( @"class C { void Bar() { Goobar([||]i, @"" ""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader1() { await TestInRegularAndScript1Async( @"class C { void Bar() { [||]Goobar(i, j); } }", @"class C { void Bar() { Goobar(i, j); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader2() { await TestInRegularAndScript1Async( @"class C { void Bar() { a.[||]Goobar(i, j); } }", @"class C { void Bar() { a.Goobar(i, j); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader4() { await TestInRegularAndScript1Async( @"class C { void Bar() { a.Goobar(i, j[||]); } }", @"class C { void Bar() { a.Goobar(i, j); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestTwoParamWrappingCases() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.Goobar([||]i, j); } }", @"class C { void Bar() { a.Goobar(i, j); } }", @"class C { void Bar() { a.Goobar( i, j); } }", @"class C { void Bar() { a.Goobar(i, j); } }", @"class C { void Bar() { a.Goobar( i, j); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestThreeParamWrappingCases() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.Goobar([||]i, j, k); } }", @"class C { void Bar() { a.Goobar(i, j, k); } }", @"class C { void Bar() { a.Goobar( i, j, k); } }", @"class C { void Bar() { a.Goobar(i, j, k); } }", @"class C { void Bar() { a.Goobar( i, j, k); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_AllOptions_NoInitialMatches() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.Goobar( [||]i, j, k); } }", @"class C { void Bar() { a.Goobar(i, j, k); } }", @"class C { void Bar() { a.Goobar( i, j, k); } }", @"class C { void Bar() { a.Goobar(i, j, k); } }", @"class C { void Bar() { a.Goobar(i, j, k); } }", @"class C { void Bar() { a.Goobar( i, j, k); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_LongWrapping_ShortIds() { await TestAllWrappingCasesAsync( @"class C { void Goo() { this.Goobar([||] i, j, k, l, m, n, o, p, n); } }", GetIndentionColumn(30), @"class C { void Goo() { this.Goobar(i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar( i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar(i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar(i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar( i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar(i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar( i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar(i, j, k, l, m, n, o, p, n); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_LongWrapping_VariadicLengthIds() { await TestAllWrappingCasesAsync( @"class C { void Goo() { this.Goobar([||] i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", GetIndentionColumn(30), @"class C { void Goo() { this.Goobar(i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar( i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar(i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar(i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar( i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar(i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar( i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar(i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferLongWrappingOptionThatAlreadyAppeared() { await TestAllWrappingCasesAsync( @"class C { void Goo() { this.Goobar([||] iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", GetIndentionColumn(25), @"class C { void Goo() { this.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Goo() { this.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Goo() { this.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Goo() { this.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Goo() { this.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Goo() { this.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Goo() { this.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferAllLongWrappingOptionThatAlreadyAppeared() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.[||]Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", GetIndentionColumn(20), @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_LongWrapping_VariadicLengthIds2() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.[||]Goobar( i, jj, kkkk, lll, mm, n) { } }", GetIndentionColumn(30), @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar( i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar( i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar( i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption1() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.[||]Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", GetIndentionColumn(30), @"class C { void Bar() { a.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption2() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.Goobar([||] i, jj, kkkk, lll, mm, n); } }", GetIndentionColumn(30), @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n); } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n); } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n); } }", @"class C { void Bar() { a.Goobar( i, jj, kkkk, lll, mm, n); } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n); } }", @"class C { void Bar() { a.Goobar( i, jj, kkkk, lll, mm, n); } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInElementAccess1() { await TestInRegularAndScript1Async( @"class C { void Goo() { var v = this[[||]a, b, c]; } }", @"class C { void Goo() { var v = this[a, b, c]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInElementAccess2() { await TestInRegularAndScript1Async( @"class C { void Goo() { var v = [||]this[a, b, c]; } }", @"class C { void Goo() { var v = this[a, b, c]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInObjectCreation1() { await TestInRegularAndScript1Async( @"class C { void Goo() { var v = [||]new Bar(a, b, c); } }", @"class C { void Goo() { var v = new Bar(a, b, c); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInObjectCreation2() { await TestInRegularAndScript1Async( @"class C { void Goo() { var v = new Bar([||]a, b, c); } }", @"class C { void Goo() { var v = new Bar(a, b, c); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] [WorkItem(50104, "https://github.com/dotnet/roslyn/issues/50104")] public async Task TestInImplicitObjectCreation() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { Program p1 = new([||]1, 2); } public Program(object o1, object o2) { } } ", @"class Program { static void Main(string[] args) { Program p1 = new(1, 2); } public Program(object o1, object o2) { } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInConstructorInitializer1() { await TestInRegularAndScript1Async( @"class C { public C() : base([||]a, b, c) { } }", @"class C { public C() : base(a, b, c) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInConstructorInitializer2() { await TestInRegularAndScript1Async( @"class C { public C() : [||]base(a, b, c) { } }", @"class C { public C() : base(a, b, c) { } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Wrapping; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping { public class ArgumentWrappingTests : AbstractWrappingTests { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpWrappingCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSyntaxError() { await TestMissingAsync( @"class C { void Bar() { Goobar([||]i, j } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSelection() { await TestMissingAsync( @"class C { void Bar() { Goobar([|i|], j); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingBeforeName() { await TestMissingAsync( @"class C { void Bar() { a.[||]b.Goobar(i, j); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSingleParameter() { await TestMissingAsync( @"class C { void Bar() { Goobar([||]i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithMultiLineParameter() { await TestMissingAsync( @"class C { void Bar() { Goobar([||]i, j + k); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithMultiLineParameter2() { await TestMissingAsync( @"class C { void Bar() { Goobar([||]i, @"" ""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader1() { await TestInRegularAndScript1Async( @"class C { void Bar() { [||]Goobar(i, j); } }", @"class C { void Bar() { Goobar(i, j); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader2() { await TestInRegularAndScript1Async( @"class C { void Bar() { a.[||]Goobar(i, j); } }", @"class C { void Bar() { a.Goobar(i, j); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader4() { await TestInRegularAndScript1Async( @"class C { void Bar() { a.Goobar(i, j[||]); } }", @"class C { void Bar() { a.Goobar(i, j); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestTwoParamWrappingCases() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.Goobar([||]i, j); } }", @"class C { void Bar() { a.Goobar(i, j); } }", @"class C { void Bar() { a.Goobar( i, j); } }", @"class C { void Bar() { a.Goobar(i, j); } }", @"class C { void Bar() { a.Goobar( i, j); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestThreeParamWrappingCases() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.Goobar([||]i, j, k); } }", @"class C { void Bar() { a.Goobar(i, j, k); } }", @"class C { void Bar() { a.Goobar( i, j, k); } }", @"class C { void Bar() { a.Goobar(i, j, k); } }", @"class C { void Bar() { a.Goobar( i, j, k); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_AllOptions_NoInitialMatches() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.Goobar( [||]i, j, k); } }", @"class C { void Bar() { a.Goobar(i, j, k); } }", @"class C { void Bar() { a.Goobar( i, j, k); } }", @"class C { void Bar() { a.Goobar(i, j, k); } }", @"class C { void Bar() { a.Goobar(i, j, k); } }", @"class C { void Bar() { a.Goobar( i, j, k); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_LongWrapping_ShortIds() { await TestAllWrappingCasesAsync( @"class C { void Goo() { this.Goobar([||] i, j, k, l, m, n, o, p, n); } }", GetIndentionColumn(30), @"class C { void Goo() { this.Goobar(i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar( i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar(i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar(i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar( i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar(i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar( i, j, k, l, m, n, o, p, n); } }", @"class C { void Goo() { this.Goobar(i, j, k, l, m, n, o, p, n); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_LongWrapping_VariadicLengthIds() { await TestAllWrappingCasesAsync( @"class C { void Goo() { this.Goobar([||] i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", GetIndentionColumn(30), @"class C { void Goo() { this.Goobar(i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar( i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar(i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar(i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar( i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar(i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar( i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }", @"class C { void Goo() { this.Goobar(i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferLongWrappingOptionThatAlreadyAppeared() { await TestAllWrappingCasesAsync( @"class C { void Goo() { this.Goobar([||] iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", GetIndentionColumn(25), @"class C { void Goo() { this.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Goo() { this.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Goo() { this.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Goo() { this.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Goo() { this.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Goo() { this.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Goo() { this.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferAllLongWrappingOptionThatAlreadyAppeared() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.[||]Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", GetIndentionColumn(20), @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_LongWrapping_VariadicLengthIds2() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.[||]Goobar( i, jj, kkkk, lll, mm, n) { } }", GetIndentionColumn(30), @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar( i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar( i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar( i, jj, kkkk, lll, mm, n) { } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption1() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.[||]Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", GetIndentionColumn(30), @"class C { void Bar() { a.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar( iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }", @"class C { void Bar() { a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption2() { await TestAllWrappingCasesAsync( @"class C { void Bar() { a.Goobar([||] i, jj, kkkk, lll, mm, n); } }", GetIndentionColumn(30), @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n); } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n); } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n); } }", @"class C { void Bar() { a.Goobar( i, jj, kkkk, lll, mm, n); } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n); } }", @"class C { void Bar() { a.Goobar( i, jj, kkkk, lll, mm, n); } }", @"class C { void Bar() { a.Goobar(i, jj, kkkk, lll, mm, n); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInElementAccess1() { await TestInRegularAndScript1Async( @"class C { void Goo() { var v = this[[||]a, b, c]; } }", @"class C { void Goo() { var v = this[a, b, c]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInElementAccess2() { await TestInRegularAndScript1Async( @"class C { void Goo() { var v = [||]this[a, b, c]; } }", @"class C { void Goo() { var v = this[a, b, c]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInObjectCreation1() { await TestInRegularAndScript1Async( @"class C { void Goo() { var v = [||]new Bar(a, b, c); } }", @"class C { void Goo() { var v = new Bar(a, b, c); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInObjectCreation2() { await TestInRegularAndScript1Async( @"class C { void Goo() { var v = new Bar([||]a, b, c); } }", @"class C { void Goo() { var v = new Bar(a, b, c); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] [WorkItem(50104, "https://github.com/dotnet/roslyn/issues/50104")] public async Task TestInImplicitObjectCreation() { await TestInRegularAndScript1Async( @"class Program { static void Main(string[] args) { Program p1 = new([||]1, 2); } public Program(object o1, object o2) { } } ", @"class Program { static void Main(string[] args) { Program p1 = new(1, 2); } public Program(object o1, object o2) { } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInConstructorInitializer1() { await TestInRegularAndScript1Async( @"class C { public C() : base([||]a, b, c) { } }", @"class C { public C() : base(a, b, c) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInConstructorInitializer2() { await TestInRegularAndScript1Async( @"class C { public C() : [||]base(a, b, c) { } }", @"class C { public C() : base(a, b, c) { } }"); } } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { public static partial class SymbolFinder { /// <summary> /// Obsolete. Use <see cref="FindSymbolAtPositionAsync(SemanticModel, int, Workspace, CancellationToken)"/>. /// </summary> [Obsolete("Use FindSymbolAtPositionAsync instead.")] public static ISymbol FindSymbolAtPosition( SemanticModel semanticModel, int position, Workspace workspace, CancellationToken cancellationToken = default) { return FindSymbolAtPositionAsync(semanticModel, position, workspace, cancellationToken).WaitAndGetResult(cancellationToken); } /// <summary> /// Finds the symbol that is associated with a position in the text of a document. /// </summary> /// <param name="semanticModel">The semantic model associated with the document.</param> /// <param name="position">The character position within the document.</param> /// <param name="workspace">A workspace to provide context.</param> /// <param name="cancellationToken">A CancellationToken.</param> public static async Task<ISymbol> FindSymbolAtPositionAsync( SemanticModel semanticModel, int position, Workspace workspace, CancellationToken cancellationToken = default) { if (semanticModel is null) throw new ArgumentNullException(nameof(semanticModel)); if (workspace is null) throw new ArgumentNullException(nameof(workspace)); var semanticInfo = await GetSemanticInfoAtPositionAsync( semanticModel, position, workspace, cancellationToken: cancellationToken).ConfigureAwait(false); return semanticInfo.GetAnySymbol(includeType: false); } internal static async Task<TokenSemanticInfo> GetSemanticInfoAtPositionAsync( SemanticModel semanticModel, int position, Workspace workspace, CancellationToken cancellationToken) { var token = await GetTokenAtPositionAsync(semanticModel, position, workspace, cancellationToken).ConfigureAwait(false); if (token != default && token.Span.IntersectsWith(position)) { return semanticModel.GetSemanticInfo(token, workspace, cancellationToken); } return TokenSemanticInfo.Empty; } private static Task<SyntaxToken> GetTokenAtPositionAsync( SemanticModel semanticModel, int position, Workspace workspace, CancellationToken cancellationToken) { var syntaxTree = semanticModel.SyntaxTree; var syntaxFacts = workspace.Services.GetLanguageServices(semanticModel.Language).GetRequiredService<ISyntaxFactsService>(); return syntaxTree.GetTouchingTokenAsync(position, syntaxFacts.IsBindableToken, cancellationToken, findInsideTrivia: true); } public static async Task<ISymbol> FindSymbolAtPositionAsync( Document document, int position, CancellationToken cancellationToken = default) { if (document is null) throw new ArgumentNullException(nameof(document)); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); return await FindSymbolAtPositionAsync(semanticModel, position, document.Project.Solution.Workspace, cancellationToken).ConfigureAwait(false); } /// <summary> /// Finds the definition symbol declared in source code for a corresponding reference symbol. /// Returns null if no such symbol can be found in the specified solution. /// </summary> public static Task<ISymbol?> FindSourceDefinitionAsync( ISymbol? symbol, Solution solution, CancellationToken cancellationToken = default) { if (symbol != null) { symbol = symbol.GetOriginalUnreducedDefinition(); switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Local: case SymbolKind.NamedType: case SymbolKind.Parameter: case SymbolKind.Property: case SymbolKind.TypeParameter: case SymbolKind.Namespace: return FindSourceDefinitionWorkerAsync(symbol, solution, cancellationToken); } } return SpecializedTasks.Null<ISymbol>(); } private static async Task<ISymbol?> FindSourceDefinitionWorkerAsync( ISymbol symbol, Solution solution, CancellationToken cancellationToken) { // If it's already in source, then we might already be done if (InSource(symbol)) { // If our symbol doesn't have a containing assembly, there's nothing better we can do to map this // symbol somewhere else. The common case for this is a merged INamespaceSymbol that spans assemblies. if (symbol.ContainingAssembly == null) { return symbol; } // Just because it's a source symbol doesn't mean we have the final symbol we actually want. In retargeting cases, // the retargeted symbol is from "source" but isn't equal to the actual source definition in the other project. Thus, // we only want to return symbols from source here if it actually came from a project's compilation's assembly. If it isn't // then we have a retargeting scenario and want to take our usual path below as if it was a metadata reference foreach (var sourceProject in solution.Projects) { // If our symbol is actually a "regular" source symbol, then we know the compilation is holding the symbol alive // and thus TryGetCompilation is sufficient. For another example of this pattern, see Solution.GetProject(IAssemblySymbol) // which we happen to call below. if (sourceProject.TryGetCompilation(out var compilation)) { if (symbol.ContainingAssembly.Equals(compilation.Assembly)) { return symbol; } } } } else if (!symbol.Locations.Any(loc => loc.IsInMetadata)) { // We have a symbol that's neither in source nor metadata return null; } var project = solution.GetProject(symbol.ContainingAssembly, cancellationToken); if (project != null && project.SupportsCompilation) { var symbolId = symbol.GetSymbolKey(cancellationToken); var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var result = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken); if (result.Symbol != null && InSource(result.Symbol)) { return result.Symbol; } else { return result.CandidateSymbols.FirstOrDefault(InSource); } } return null; } private static bool InSource(ISymbol symbol) { return symbol.Locations.Any(loc => loc.IsInSource); } /// <summary> /// Finds symbols in the given compilation that are similar to the specified symbol. /// /// A found symbol may be the exact same symbol instance if the compilation is the origin of the specified symbol, /// or it may be a different symbol instance if the compilation is not the originating compilation. /// /// Multiple symbols may be returned if there are ambiguous matches. /// No symbols may be returned if the compilation does not define or have access to a similar symbol. /// </summary> /// <param name="symbol">The symbol to find corresponding matches for.</param> /// <param name="compilation">A compilation to find the corresponding symbol within. The compilation may or may not be the origin of the symbol.</param> /// <param name="cancellationToken">A CancellationToken.</param> /// <returns></returns> public static IEnumerable<TSymbol> FindSimilarSymbols<TSymbol>(TSymbol symbol, Compilation compilation, CancellationToken cancellationToken = default) where TSymbol : ISymbol { if (symbol is null) throw new ArgumentNullException(nameof(symbol)); if (compilation is null) throw new ArgumentNullException(nameof(compilation)); var key = symbol.GetSymbolKey(cancellationToken); // We may be talking about different compilations. So do not try to resolve locations. var result = new HashSet<TSymbol>(); var resolution = key.Resolve(compilation, cancellationToken: cancellationToken); foreach (var current in resolution.OfType<TSymbol>()) { result.Add(current); } return result; } /// <summary> /// If <paramref name="symbol"/> is declared in a linked file, then this function returns all the symbols that /// are defined by the same symbol's syntax in the all projects that the linked file is referenced from. /// <para/> /// In order to be returned the other symbols must have the same <see cref="ISymbol.Name"/> and <see /// cref="ISymbol.Kind"/> as <paramref name="symbol"/>. This matches general user intuition that these are all /// the 'same' symbol, and should be examined, regardless of the project context and <see cref="ISymbol"/> they /// originally started with. /// </summary> internal static async Task<ImmutableArray<ISymbol>> FindLinkedSymbolsAsync( ISymbol symbol, Solution solution, CancellationToken cancellationToken) { // Add the original symbol to the result set. var linkedSymbols = new HashSet<ISymbol> { symbol }; foreach (var location in symbol.DeclaringSyntaxReferences) { var originalDocument = solution.GetDocument(location.SyntaxTree); // GetDocument will return null for locations in #load'ed trees. TODO: Remove this check and add logic // to fetch the #load'ed tree's Document once https://github.com/dotnet/roslyn/issues/5260 is fixed. if (originalDocument == null) { Debug.Assert(solution.Workspace.Kind == WorkspaceKind.Interactive || solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles); continue; } foreach (var linkedDocumentId in originalDocument.GetLinkedDocumentIds()) { var linkedDocument = solution.GetRequiredDocument(linkedDocumentId); var linkedSyntaxRoot = await linkedDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var linkedNode = linkedSyntaxRoot.FindNode(location.Span, getInnermostNodeForTie: true); var semanticModel = await linkedDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var linkedSymbol = semanticModel.GetDeclaredSymbol(linkedNode, cancellationToken); if (linkedSymbol != null && linkedSymbol.Kind == symbol.Kind && linkedSymbol.Name == symbol.Name) { linkedSymbols.Add(linkedSymbol); } } } return linkedSymbols.ToImmutableArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { public static partial class SymbolFinder { /// <summary> /// Obsolete. Use <see cref="FindSymbolAtPositionAsync(SemanticModel, int, Workspace, CancellationToken)"/>. /// </summary> [Obsolete("Use FindSymbolAtPositionAsync instead.")] public static ISymbol FindSymbolAtPosition( SemanticModel semanticModel, int position, Workspace workspace, CancellationToken cancellationToken = default) { return FindSymbolAtPositionAsync(semanticModel, position, workspace, cancellationToken).WaitAndGetResult(cancellationToken); } /// <summary> /// Finds the symbol that is associated with a position in the text of a document. /// </summary> /// <param name="semanticModel">The semantic model associated with the document.</param> /// <param name="position">The character position within the document.</param> /// <param name="workspace">A workspace to provide context.</param> /// <param name="cancellationToken">A CancellationToken.</param> public static async Task<ISymbol> FindSymbolAtPositionAsync( SemanticModel semanticModel, int position, Workspace workspace, CancellationToken cancellationToken = default) { if (semanticModel is null) throw new ArgumentNullException(nameof(semanticModel)); if (workspace is null) throw new ArgumentNullException(nameof(workspace)); var semanticInfo = await GetSemanticInfoAtPositionAsync( semanticModel, position, workspace, cancellationToken: cancellationToken).ConfigureAwait(false); return semanticInfo.GetAnySymbol(includeType: false); } internal static async Task<TokenSemanticInfo> GetSemanticInfoAtPositionAsync( SemanticModel semanticModel, int position, Workspace workspace, CancellationToken cancellationToken) { var token = await GetTokenAtPositionAsync(semanticModel, position, workspace, cancellationToken).ConfigureAwait(false); if (token != default && token.Span.IntersectsWith(position)) { return semanticModel.GetSemanticInfo(token, workspace, cancellationToken); } return TokenSemanticInfo.Empty; } private static Task<SyntaxToken> GetTokenAtPositionAsync( SemanticModel semanticModel, int position, Workspace workspace, CancellationToken cancellationToken) { var syntaxTree = semanticModel.SyntaxTree; var syntaxFacts = workspace.Services.GetLanguageServices(semanticModel.Language).GetRequiredService<ISyntaxFactsService>(); return syntaxTree.GetTouchingTokenAsync(position, syntaxFacts.IsBindableToken, cancellationToken, findInsideTrivia: true); } public static async Task<ISymbol> FindSymbolAtPositionAsync( Document document, int position, CancellationToken cancellationToken = default) { if (document is null) throw new ArgumentNullException(nameof(document)); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); return await FindSymbolAtPositionAsync(semanticModel, position, document.Project.Solution.Workspace, cancellationToken).ConfigureAwait(false); } /// <summary> /// Finds the definition symbol declared in source code for a corresponding reference symbol. /// Returns null if no such symbol can be found in the specified solution. /// </summary> public static Task<ISymbol?> FindSourceDefinitionAsync( ISymbol? symbol, Solution solution, CancellationToken cancellationToken = default) { if (symbol != null) { symbol = symbol.GetOriginalUnreducedDefinition(); switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Local: case SymbolKind.NamedType: case SymbolKind.Parameter: case SymbolKind.Property: case SymbolKind.TypeParameter: case SymbolKind.Namespace: return FindSourceDefinitionWorkerAsync(symbol, solution, cancellationToken); } } return SpecializedTasks.Null<ISymbol>(); } private static async Task<ISymbol?> FindSourceDefinitionWorkerAsync( ISymbol symbol, Solution solution, CancellationToken cancellationToken) { // If it's already in source, then we might already be done if (InSource(symbol)) { // If our symbol doesn't have a containing assembly, there's nothing better we can do to map this // symbol somewhere else. The common case for this is a merged INamespaceSymbol that spans assemblies. if (symbol.ContainingAssembly == null) { return symbol; } // Just because it's a source symbol doesn't mean we have the final symbol we actually want. In retargeting cases, // the retargeted symbol is from "source" but isn't equal to the actual source definition in the other project. Thus, // we only want to return symbols from source here if it actually came from a project's compilation's assembly. If it isn't // then we have a retargeting scenario and want to take our usual path below as if it was a metadata reference foreach (var sourceProject in solution.Projects) { // If our symbol is actually a "regular" source symbol, then we know the compilation is holding the symbol alive // and thus TryGetCompilation is sufficient. For another example of this pattern, see Solution.GetProject(IAssemblySymbol) // which we happen to call below. if (sourceProject.TryGetCompilation(out var compilation)) { if (symbol.ContainingAssembly.Equals(compilation.Assembly)) { return symbol; } } } } else if (!symbol.Locations.Any(loc => loc.IsInMetadata)) { // We have a symbol that's neither in source nor metadata return null; } var project = solution.GetProject(symbol.ContainingAssembly, cancellationToken); if (project != null && project.SupportsCompilation) { var symbolId = symbol.GetSymbolKey(cancellationToken); var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var result = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken); if (result.Symbol != null && InSource(result.Symbol)) { return result.Symbol; } else { return result.CandidateSymbols.FirstOrDefault(InSource); } } return null; } private static bool InSource(ISymbol symbol) { return symbol.Locations.Any(loc => loc.IsInSource); } /// <summary> /// Finds symbols in the given compilation that are similar to the specified symbol. /// /// A found symbol may be the exact same symbol instance if the compilation is the origin of the specified symbol, /// or it may be a different symbol instance if the compilation is not the originating compilation. /// /// Multiple symbols may be returned if there are ambiguous matches. /// No symbols may be returned if the compilation does not define or have access to a similar symbol. /// </summary> /// <param name="symbol">The symbol to find corresponding matches for.</param> /// <param name="compilation">A compilation to find the corresponding symbol within. The compilation may or may not be the origin of the symbol.</param> /// <param name="cancellationToken">A CancellationToken.</param> /// <returns></returns> public static IEnumerable<TSymbol> FindSimilarSymbols<TSymbol>(TSymbol symbol, Compilation compilation, CancellationToken cancellationToken = default) where TSymbol : ISymbol { if (symbol is null) throw new ArgumentNullException(nameof(symbol)); if (compilation is null) throw new ArgumentNullException(nameof(compilation)); var key = symbol.GetSymbolKey(cancellationToken); // We may be talking about different compilations. So do not try to resolve locations. var result = new HashSet<TSymbol>(); var resolution = key.Resolve(compilation, cancellationToken: cancellationToken); foreach (var current in resolution.OfType<TSymbol>()) { result.Add(current); } return result; } /// <summary> /// If <paramref name="symbol"/> is declared in a linked file, then this function returns all the symbols that /// are defined by the same symbol's syntax in the all projects that the linked file is referenced from. /// <para/> /// In order to be returned the other symbols must have the same <see cref="ISymbol.Name"/> and <see /// cref="ISymbol.Kind"/> as <paramref name="symbol"/>. This matches general user intuition that these are all /// the 'same' symbol, and should be examined, regardless of the project context and <see cref="ISymbol"/> they /// originally started with. /// </summary> internal static async Task<ImmutableArray<ISymbol>> FindLinkedSymbolsAsync( ISymbol symbol, Solution solution, CancellationToken cancellationToken) { // Add the original symbol to the result set. var linkedSymbols = new HashSet<ISymbol> { symbol }; foreach (var location in symbol.DeclaringSyntaxReferences) { var originalDocument = solution.GetDocument(location.SyntaxTree); // GetDocument will return null for locations in #load'ed trees. TODO: Remove this check and add logic // to fetch the #load'ed tree's Document once https://github.com/dotnet/roslyn/issues/5260 is fixed. if (originalDocument == null) { Debug.Assert(solution.Workspace.Kind == WorkspaceKind.Interactive || solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles); continue; } foreach (var linkedDocumentId in originalDocument.GetLinkedDocumentIds()) { var linkedDocument = solution.GetRequiredDocument(linkedDocumentId); var linkedSyntaxRoot = await linkedDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var linkedNode = linkedSyntaxRoot.FindNode(location.Span, getInnermostNodeForTie: true); var semanticModel = await linkedDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var linkedSymbol = semanticModel.GetDeclaredSymbol(linkedNode, cancellationToken); if (linkedSymbol != null && linkedSymbol.Kind == symbol.Kind && linkedSymbol.Name == symbol.Name) { linkedSymbols.Add(linkedSymbol); } } } return linkedSymbols.ToImmutableArray(); } } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/EditorFeatures/CSharpTest/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests_DotnetNegativeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text.RegularExpressions; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions { // These tests came from tests found at: // https://github.com/dotnet/corefx/blob/main/src/System.Text.RegularExpressions/tests/ public partial class CSharpRegexParserTests { [Fact] public void NegativeTest0() { Test(@"@""cat([a-\d]*)dog""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "d")}"" Span=""[17..19)"" Text=""\d"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""cat([a-\d]*)dog"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""([a-\d]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest1() { Test(@"@""\k<1""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;1</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k&lt;1"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest2() { Test(@"@""\k<""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\k&lt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest3() { Test(@"@""\k""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\k"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest4() { Test(@"@""\1""", $@"<Tree> <CompilationUnit> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "1")}"" Span=""[11..12)"" Text=""1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\1"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest5() { Test(@"@""(?')""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken /> <SingleQuoteToken /> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""(?')"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest6() { Test(@"@""(?<)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""(?&lt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest7() { Test(@"@""(?)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest8() { Test(@"@""(?>""", $@"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </AtomicGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest9() { Test(@"@""(?<!""", $@"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken /> </NegativeLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""(?&lt;!"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest10() { Test(@"@""(?<=""", $@"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken /> </PositiveLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""(?&lt;="" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest11() { Test(@"@""(?!""", $@"<Tree> <CompilationUnit> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken /> </NegativeLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?!"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest12() { Test(@"@""(?=""", $@"<Tree> <CompilationUnit> <Sequence> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken /> </PositiveLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?="" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest13() { Test(@"@""(?imn )""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>imn</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> <Text> <TextToken> </TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[16..17)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?imn )"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest14() { Test(@"@""(?imn""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>imn</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""(?imn"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest15() { Test(@"@""(?:""", $@"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken /> </NonCapturingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?:"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest16() { Test(@"@""(?'cat'""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?'cat'"" /> <Capture Name=""1"" Span=""[10..17)"" Text=""(?'cat'"" /> <Capture Name=""cat"" Span=""[10..17)"" Text=""(?'cat'"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest17() { Test(@"@""(?'""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken /> <SingleQuoteToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..13)"" Text=""(?'"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?'"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest18() { Test(@"@""[^""", $@"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence /> <CloseBracketToken /> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""[^"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest19() { Test(@"@""[cat""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[cat"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest20() { Test(@"@""[^cat""", $@"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseBracketToken /> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[^cat"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest21() { Test(@"@""[a-""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken /> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""[a-"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest22() { Test(@"@""\p{""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\p{{"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest23() { Test(@"@""\p{cat""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{cat</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\p{{cat"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest24() { Test(@"@""\k<cat""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;cat</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k&lt;cat"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest25() { Test(@"@""\p{cat}""", $@"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>cat</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unknown_property_0, "cat")}"" Span=""[13..16)"" Text=""cat"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\p{{cat}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest26() { Test(@"@""\P{cat""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> </SimpleEscape> <Text> <TextToken>{{cat</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\P"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\P{{cat"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest27() { Test(@"@""\P{cat}""", $@"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>cat</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unknown_property_0, "cat")}"" Span=""[13..16)"" Text=""cat"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\P{{cat}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest28() { Test(@"@""(""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[11..11)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..11)"" Text=""("" /> <Capture Name=""1"" Span=""[10..11)"" Text=""("" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest29() { Test(@"@""(?""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""(?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest30() { Test(@"@""(?<""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..13)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?&lt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest31() { Test(@"@""(?<cat>""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?&lt;cat&gt;"" /> <Capture Name=""1"" Span=""[10..17)"" Text=""(?&lt;cat&gt;"" /> <Capture Name=""cat"" Span=""[10..17)"" Text=""(?&lt;cat&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest32() { Test(@"@""\P{""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> </SimpleEscape> <Text> <TextToken>{{</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\P"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\P{{"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest33() { Test(@"@""\k<>""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k&lt;&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest34() { Test(@"@""(?(""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?("" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest35() { Test(@"@""(?()|""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""(?()|"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest36() { Test(@"@""?(a|b)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""?(a|b)"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""(a|b)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest37() { Test(@"@""?((a)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""?((a)"" /> <Capture Name=""1"" Span=""[11..15)"" Text=""((a)"" /> <Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest38() { Test(@"@""?((a)a""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""?((a)a"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""((a)a"" /> <Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest39() { Test(@"@""?((a)a|""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence /> </Alternation> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""?((a)a|"" /> <Capture Name=""1"" Span=""[11..17)"" Text=""((a)a|"" /> <Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest40() { Test(@"@""?((a)a|b""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[18..18)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""?((a)a|b"" /> <Capture Name=""1"" Span=""[11..18)"" Text=""((a)a|b"" /> <Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest41() { Test(@"@""(?(?i))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>i</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?i))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest42() { Test(@"@""?(a)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""?(a)"" /> <Capture Name=""1"" Span=""[11..14)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest43() { Test(@"@""(?(?I))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>I</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?I))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest44() { Test(@"@""(?(?M))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>M</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?M))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest45() { Test(@"@""(?(?s))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>s</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?s))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest46() { Test(@"@""(?(?S))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>S</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?S))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest47() { Test(@"@""(?(?x))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?x))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest48() { Test(@"@""(?(?X))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>X</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?X))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest49() { Test(@"@""(?(?n))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?n))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest50() { Test(@"@""(?(?m))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>m</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?m))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest51() { Test(@"@""[a""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""[a"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest52() { Test(@"@""?(a:b)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a:b</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""?(a:b)"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""(a:b)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest53() { Test(@"@""(?(?""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[12..13)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[13..14)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""(?(?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest54() { Test(@"@""(?(cat""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(?(cat"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest55() { Test(@"@""(?(cat)|""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[18..18)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""(?(cat)|"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest56() { Test(@"@""foo(?<0>bar)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>foo</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>bar</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[16..17)"" Text=""0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""foo(?&lt;0&gt;bar)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest57() { Test(@"@""foo(?'0'bar)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>foo</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>bar</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[16..17)"" Text=""0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""foo(?'0'bar)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest58() { Test(@"@""foo(?<1bar)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>foo</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken /> <Sequence> <Text> <TextToken>bar</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""b"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""foo(?&lt;1bar)"" /> <Capture Name=""1"" Span=""[13..21)"" Text=""(?&lt;1bar)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest59() { Test(@"@""foo(?'1bar)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>foo</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""1"">1</NumberToken> <SingleQuoteToken /> <Sequence> <Text> <TextToken>bar</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""b"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""foo(?'1bar)"" /> <Capture Name=""1"" Span=""[13..21)"" Text=""(?'1bar)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest60() { Test(@"@""(?(""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?("" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest61() { Test(@"@""\p{klsak""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{klsak</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\p{{klsak"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest62() { Test(@"@""(?c:cat)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken>c:cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""(?c:cat)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest63() { Test(@"@""(??e:cat)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <Text> <TextToken>?</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <Text> <TextToken>e:cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""(??e:cat)"" /> <Capture Name=""1"" Span=""[10..19)"" Text=""(??e:cat)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest64() { Test(@"@""[a-f-[]]+""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>f</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>]</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> <Text> <TextToken>+</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.A_subtraction_must_be_the_last_element_in_a_character_class}"" Span=""[14..14)"" Text="""" /> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[19..19)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[a-f-[]]+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest65() { Test(@"@""[A-[]+""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>A</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>]+</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[A-[]+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest66() { Test(@"@""(?(?e))""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken>e</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[12..13)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[13..14)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?e))"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest67() { Test(@"@""(?(?a)""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[12..13)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[13..14)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(?(?a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest68() { Test(@"@""(?r:cat)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken>r:cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""(?r:cat)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest69() { Test(@"@""(?(?N))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>N</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?N))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest70() { Test(@"@""[]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>]</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""[]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest71() { Test(@"@""\x2""", $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>2</TextToken> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\x2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\x2"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest72() { Test(@"@""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia>(?#cat)</CommentTrivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia>(?#followed by 1 or more whitespace</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[31..66)"" Text=""(?#followed by 1 or more whitespace"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..66)"" Text=""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void NegativeTest73() { Test(@"@""cat(?(?afdcat)dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken>afdcat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[15..16)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[16..17)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..28)"" Text=""cat(?(?afdcat)dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest74() { Test(@"@""cat(?(?<cat>cat)dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[13..14)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..30)"" Text=""cat(?(?&lt;cat&gt;cat)dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest75() { Test(@"@""cat(?(?'cat'cat)dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[13..14)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..30)"" Text=""cat(?(?'cat'cat)dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest76() { Test(@"@""cat(?(?#COMMENT)cat)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken>#COMMENT</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_cannot_be_comments}"" Span=""[13..14)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[15..16)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[16..17)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..30)"" Text=""cat(?(?#COMMENT)cat)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest77() { Test(@"@""(?<cat>cat)\w+(?<dog-()*!@>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>!@&gt;dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[31..32)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..41)"" Text=""(?&lt;cat&gt;cat)\w+(?&lt;dog-()*!@&gt;dog)"" /> <Capture Name=""1"" Span=""[31..33)"" Text=""()"" /> <Capture Name=""2"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""3"" Span=""[24..41)"" Text=""(?&lt;dog-()*!@&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..41)"" Text=""(?&lt;dog-()*!@&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void NegativeTest78() { Test(@"@""(?<cat>cat)\w+(?<dog-catdog>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""catdog"">catdog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "catdog")}"" Span=""[31..37)"" Text=""catdog"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""(?&lt;cat&gt;cat)\w+(?&lt;dog-catdog&gt;dog)"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..42)"" Text=""(?&lt;dog-catdog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..42)"" Text=""(?&lt;dog-catdog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void NegativeTest79() { Test(@"@""(?<cat>cat)\w+(?<dog-1uosn>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken /> <Sequence> <Text> <TextToken>uosn&gt;dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[32..33)"" Text=""u"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..41)"" Text=""(?&lt;cat&gt;cat)\w+(?&lt;dog-1uosn&gt;dog)"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..41)"" Text=""(?&lt;dog-1uosn&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..41)"" Text=""(?&lt;dog-1uosn&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void NegativeTest80() { Test(@"@""(?<cat>cat)\w+(?<dog-16>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""16"">16</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "16")}"" Span=""[31..33)"" Text=""16"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..38)"" Text=""(?&lt;cat&gt;cat)\w+(?&lt;dog-16&gt;dog)"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..38)"" Text=""(?&lt;dog-16&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..38)"" Text=""(?&lt;dog-16&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void NegativeTest81() { Test(@"@""cat(?<->dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""cat(?&lt;-&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void NegativeTest82() { Test(@"@""cat(?<>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[16..17)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""cat(?&lt;&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest83() { Test(@"@""cat(?<dog<>)_*>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken /> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <Text> <TextToken>_</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>&gt;dog</TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text=""&lt;"" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[28..29)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""cat(?&lt;dog&lt;&gt;)_*&gt;dog)"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""(?&lt;dog&lt;&gt;)"" /> <Capture Name=""dog"" Span=""[13..22)"" Text=""(?&lt;dog&lt;&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest84() { Test(@"@""cat(?<dog >)_*>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken /> <Sequence> <Text> <TextToken> &gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <Text> <TextToken>_</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>&gt;dog</TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text="" "" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[28..29)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""cat(?&lt;dog &gt;)_*&gt;dog)"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""(?&lt;dog &gt;)"" /> <Capture Name=""dog"" Span=""[13..22)"" Text=""(?&lt;dog &gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest85() { Test(@"@""cat(?<dog!>)_*>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken /> <Sequence> <Text> <TextToken>!&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <Text> <TextToken>_</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>&gt;dog</TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text=""!"" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[28..29)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""cat(?&lt;dog!&gt;)_*&gt;dog)"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""(?&lt;dog!&gt;)"" /> <Capture Name=""dog"" Span=""[13..22)"" Text=""(?&lt;dog!&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest86() { Test(@"@""cat(?<dog)_*>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken /> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <Text> <TextToken>_</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>&gt;dog</TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text="")"" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[26..27)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""cat(?&lt;dog)_*&gt;dog)"" /> <Capture Name=""1"" Span=""[13..20)"" Text=""(?&lt;dog)"" /> <Capture Name=""dog"" Span=""[13..20)"" Text=""(?&lt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest87() { Test(@"@""cat(?<1dog>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken /> <Sequence> <Text> <TextToken>dog&gt;dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""d"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""cat(?&lt;1dog&gt;dog)"" /> <Capture Name=""1"" Span=""[13..25)"" Text=""(?&lt;1dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest88() { Test(@"@""cat(?<0>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[16..17)"" Text=""0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""cat(?&lt;0&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest89() { Test(@"@""([5-\D]*)dog""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>5</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "D")}"" Span=""[14..16)"" Text=""\D"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""([5-\D]*)dog"" /> <Capture Name=""1"" Span=""[10..19)"" Text=""([5-\D]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest90() { Test(@"@""cat([6-\s]*)dog""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>6</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "s")}"" Span=""[17..19)"" Text=""\s"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""cat([6-\s]*)dog"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""([6-\s]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest91() { Test(@"@""cat([c-\S]*)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>c</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "S")}"" Span=""[17..19)"" Text=""\S"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""cat([c-\S]*)"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""([c-\S]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest92() { Test(@"@""cat([7-\w]*)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>7</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "w")}"" Span=""[17..19)"" Text=""\w"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""cat([7-\w]*)"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""([7-\w]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest93() { Test(@"@""cat([a-\W]*)dog""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "W")}"" Span=""[17..19)"" Text=""\W"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""cat([a-\W]*)dog"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""([a-\W]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest94() { Test(@"@""([f-\p{Lu}]\w*)\s([\p{Lu}]\w*)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>f</TextToken> </Text> <MinusToken>-</MinusToken> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "p")}"" Span=""[14..16)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""([f-\p{{Lu}}]\w*)\s([\p{{Lu}}]\w*)"" /> <Capture Name=""1"" Span=""[10..25)"" Text=""([f-\p{{Lu}}]\w*)"" /> <Capture Name=""2"" Span=""[27..40)"" Text=""([\p{{Lu}}]\w*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest95() { Test(@"@""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken> </TextToken> </Text> <Text> <TextToken> <Trivia> <CommentTrivia>(?#cat)</CommentTrivia> </Trivia> </TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile> <Trivia> <CommentTrivia>(?#followed by 1 or more whitespace</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[31..66)"" Text=""(?#followed by 1 or more whitespace"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..66)"" Text=""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest96() { Test(@"@""([1-\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>1</TextToken> </Text> <MinusToken>-</MinusToken> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Ll</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Ll</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Ll</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Ll</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "P")}"" Span=""[14..16)"" Text=""\P"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..52)"" Text=""([1-\P{{Ll}}][\p{{Ll}}]*)\s([\P{{Ll}}][\p{{Ll}}]*)"" /> <Capture Name=""1"" Span=""[10..31)"" Text=""([1-\P{{Ll}}][\p{{Ll}}]*)"" /> <Capture Name=""2"" Span=""[33..52)"" Text=""([\P{{Ll}}][\p{{Ll}}]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest97() { Test(@"@""[\P]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\P"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[\P]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest98() { Test(@"@""([\pcat])""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_character_escape}"" Span=""[12..14)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""([\pcat])"" /> <Capture Name=""1"" Span=""[10..19)"" Text=""([\pcat])"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest99() { Test(@"@""([\Pcat])""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> </SimpleEscape> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_character_escape}"" Span=""[12..14)"" Text=""\P"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""([\Pcat])"" /> <Capture Name=""1"" Span=""[10..19)"" Text=""([\Pcat])"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest100() { Test(@"@""(\p{""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\p"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""(\p{{"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\p{{"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest101() { Test(@"@""(\p{Ll""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{Ll</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\p"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\p{{Ll"" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(\p{{Ll"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest102() { Test(@"@""(cat)([\o]*)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>o</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "o")}"" Span=""[18..19)"" Text=""o"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(cat)([\o]*)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..22)"" Text=""([\o]*)"" /> <Capture Name=""3"" Span=""[22..27)"" Text=""(dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest103() { Test(@"@""[\p]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[\p]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest104() { Test(@"@""(?<cat>cat)\s+(?<dog>dog)\kcat""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[35..37)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""(?&lt;cat&gt;cat)\s+(?&lt;dog&gt;dog)\kcat"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest105() { Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k<cat2>""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat2"">cat2</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "cat2")}"" Span=""[38..42)"" Text=""cat2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""(?&lt;cat&gt;cat)\s+(?&lt;dog&gt;dog)\k&lt;cat2&gt;"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest106() { Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k<8>cat""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""8"">8</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "8")}"" Span=""[38..39)"" Text=""8"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""(?&lt;cat&gt;cat)\s+(?&lt;dog&gt;dog)\k&lt;8&gt;cat"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest107() { Test(@"@""^[abcd]{1}?*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <LazyQuantifier> <ExactNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ExactNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[21..22)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""^[abcd]{{1}}?*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest108() { Test(@"@""^[abcd]*+$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>+</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "+")}"" Span=""[18..19)"" Text=""+"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""^[abcd]*+$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest109() { Test(@"@""^[abcd]+*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[18..19)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""^[abcd]+*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest110() { Test(@"@""^[abcd]?*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[18..19)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""^[abcd]?*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest111() { Test(@"@""^[abcd]*?+$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>+</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "+")}"" Span=""[19..20)"" Text=""+"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""^[abcd]*?+$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest112() { Test(@"@""^[abcd]+?*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[19..20)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""^[abcd]+?*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest113() { Test(@"@""^[abcd]{1,}?*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <LazyQuantifier> <OpenRangeNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}}</CloseBraceToken> </OpenRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[22..23)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]{{1,}}?*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest114() { Test(@"@""^[abcd]??*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <LazyQuantifier> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[19..20)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""^[abcd]??*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest115() { Test(@"@""^[abcd]+{0,5}$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>0,5}}</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[18..19)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]+{{0,5}}$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest116() { Test(@"@""^[abcd]?{0,5}$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>0,5}}</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[18..19)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]?{{0,5}}$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest117() { Test(@"@""\u""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken /> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\u"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\u"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest118() { Test(@"@""\ua""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>a</TextToken> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\ua"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\ua"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest119() { Test(@"@""\u0""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0</TextToken> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\u0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\u0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest120() { Test(@"@""\x""", $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken /> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\x"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\x"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest121() { Test(@"@""^[abcd]*{0,5}$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>0,5}}</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[18..19)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]*{{0,5}}$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest122() { Test(@"@""[""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence /> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[11..11)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..11)"" Text=""["" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest123() { Test(@"@""^[abcd]{0,16}?*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <LazyQuantifier> <ClosedRangeNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""16"">16</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ClosedRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[24..25)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""^[abcd]{{0,16}}?*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest124() { Test(@"@""^[abcd]{1,}*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OpenRangeNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}}</CloseBraceToken> </OpenRangeNumericQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[21..22)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""^[abcd]{{1,}}*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest125() { Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k<8>cat""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""8"">8</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "8")}"" Span=""[38..39)"" Text=""8"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""(?&lt;cat&gt;cat)\s+(?&lt;dog&gt;dog)\k&lt;8&gt;cat"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void NegativeTest126() { Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k8""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>8</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[35..37)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..38)"" Text=""(?&lt;cat&gt;cat)\s+(?&lt;dog&gt;dog)\k8"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest127() { Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k8""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>8</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[35..37)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..38)"" Text=""(?&lt;cat&gt;cat)\s+(?&lt;dog&gt;dog)\k8"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void NegativeTest128() { Test(@"@""(cat)(\7)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""7"">7</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "7")}"" Span=""[17..18)"" Text=""7"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""(cat)(\7)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..19)"" Text=""(\7)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest129() { Test(@"@""(cat)\s+(?<2147483648>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""-2147483648"">2147483648</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[21..31)"" Text=""2147483648"" /> </Diagnostics> <Captures> <Capture Name=""-2147483648"" Span=""[18..36)"" Text=""(?&lt;2147483648&gt;dog)"" /> <Capture Name=""0"" Span=""[10..36)"" Text=""(cat)\s+(?&lt;2147483648&gt;dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest130() { Test(@"@""(cat)\s+(?<21474836481097>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1097"">21474836481097</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[21..35)"" Text=""21474836481097"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""(cat)\s+(?&lt;21474836481097&gt;dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""1097"" Span=""[18..40)"" Text=""(?&lt;21474836481097&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest131() { Test(@"@""^[abcd]{1}*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ExactNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[20..21)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""^[abcd]{{1}}*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest132() { Test(@"@""(cat)(\c*)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""(cat)(\c*)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..20)"" Text=""(\c*)"" /> <Capture Name=""3"" Span=""[20..25)"" Text=""(dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest133() { Test(@"@""(cat)(\c *)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <ZeroOrMoreQuantifier> <Text> <TextToken> </TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(cat)(\c *)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..21)"" Text=""(\c *)"" /> <Capture Name=""3"" Span=""[21..26)"" Text=""(dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest134() { Test(@"@""(cat)(\c?*)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <Text> <TextToken>*</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text=""?"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[19..20)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(cat)(\c?*)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..21)"" Text=""(\c?*)"" /> <Capture Name=""3"" Span=""[21..26)"" Text=""(dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest135() { Test(@"@""(cat)(\c`*)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <ZeroOrMoreQuantifier> <Text> <TextToken>`</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text=""`"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(cat)(\c`*)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..21)"" Text=""(\c`*)"" /> <Capture Name=""3"" Span=""[21..26)"" Text=""(dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest136() { Test(@"@""(cat)(\c\|*)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>\</TextToken> </ControlEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>*</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[20..21)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(cat)(\c\|*)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..22)"" Text=""(\c\|*)"" /> <Capture Name=""3"" Span=""[22..27)"" Text=""(dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest137() { Test(@"@""(cat)(\c\[*)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>\</TextToken> </ControlEscape> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>*)(dog)</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[27..27)"" Text="""" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[27..27)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(cat)(\c\[*)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..27)"" Text=""(\c\[*)(dog)"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false); } [Fact] public void NegativeTest138() { Test(@"@""^[abcd]{0,16}*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ClosedRangeNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""16"">16</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ClosedRangeNumericQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[23..24)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""^[abcd]{{0,16}}*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest139() { Test(@"@""(cat)\c""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Missing_control_character}"" Span=""[16..17)"" Text=""c"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(cat)\c"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> </Captures> </Tree>", RegexOptions.None); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text.RegularExpressions; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions { // These tests came from tests found at: // https://github.com/dotnet/corefx/blob/main/src/System.Text.RegularExpressions/tests/ public partial class CSharpRegexParserTests { [Fact] public void NegativeTest0() { Test(@"@""cat([a-\d]*)dog""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "d")}"" Span=""[17..19)"" Text=""\d"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""cat([a-\d]*)dog"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""([a-\d]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest1() { Test(@"@""\k<1""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;1</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k&lt;1"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest2() { Test(@"@""\k<""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\k&lt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest3() { Test(@"@""\k""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\k"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest4() { Test(@"@""\1""", $@"<Tree> <CompilationUnit> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "1")}"" Span=""[11..12)"" Text=""1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\1"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest5() { Test(@"@""(?')""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken /> <SingleQuoteToken /> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""(?')"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest6() { Test(@"@""(?<)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""(?&lt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest7() { Test(@"@""(?)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest8() { Test(@"@""(?>""", $@"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </AtomicGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest9() { Test(@"@""(?<!""", $@"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken /> </NegativeLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""(?&lt;!"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest10() { Test(@"@""(?<=""", $@"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken /> </PositiveLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""(?&lt;="" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest11() { Test(@"@""(?!""", $@"<Tree> <CompilationUnit> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken /> </NegativeLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?!"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest12() { Test(@"@""(?=""", $@"<Tree> <CompilationUnit> <Sequence> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken /> </PositiveLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?="" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest13() { Test(@"@""(?imn )""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>imn</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> <Text> <TextToken> </TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[16..17)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?imn )"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest14() { Test(@"@""(?imn""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>imn</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""(?imn"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest15() { Test(@"@""(?:""", $@"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken /> </NonCapturingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?:"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest16() { Test(@"@""(?'cat'""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?'cat'"" /> <Capture Name=""1"" Span=""[10..17)"" Text=""(?'cat'"" /> <Capture Name=""cat"" Span=""[10..17)"" Text=""(?'cat'"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest17() { Test(@"@""(?'""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken /> <SingleQuoteToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..13)"" Text=""(?'"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?'"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest18() { Test(@"@""[^""", $@"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence /> <CloseBracketToken /> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""[^"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest19() { Test(@"@""[cat""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[cat"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest20() { Test(@"@""[^cat""", $@"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseBracketToken /> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[^cat"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest21() { Test(@"@""[a-""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken /> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""[a-"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest22() { Test(@"@""\p{""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\p{{"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest23() { Test(@"@""\p{cat""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{cat</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\p{{cat"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest24() { Test(@"@""\k<cat""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;cat</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k&lt;cat"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest25() { Test(@"@""\p{cat}""", $@"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>cat</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unknown_property_0, "cat")}"" Span=""[13..16)"" Text=""cat"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\p{{cat}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest26() { Test(@"@""\P{cat""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> </SimpleEscape> <Text> <TextToken>{{cat</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\P"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\P{{cat"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest27() { Test(@"@""\P{cat}""", $@"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>cat</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unknown_property_0, "cat")}"" Span=""[13..16)"" Text=""cat"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\P{{cat}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest28() { Test(@"@""(""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[11..11)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..11)"" Text=""("" /> <Capture Name=""1"" Span=""[10..11)"" Text=""("" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest29() { Test(@"@""(?""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""(?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest30() { Test(@"@""(?<""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..13)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?&lt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest31() { Test(@"@""(?<cat>""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?&lt;cat&gt;"" /> <Capture Name=""1"" Span=""[10..17)"" Text=""(?&lt;cat&gt;"" /> <Capture Name=""cat"" Span=""[10..17)"" Text=""(?&lt;cat&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest32() { Test(@"@""\P{""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> </SimpleEscape> <Text> <TextToken>{{</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\P"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\P{{"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest33() { Test(@"@""\k<>""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k&lt;&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest34() { Test(@"@""(?(""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?("" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest35() { Test(@"@""(?()|""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""(?()|"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest36() { Test(@"@""?(a|b)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""?(a|b)"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""(a|b)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest37() { Test(@"@""?((a)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""?((a)"" /> <Capture Name=""1"" Span=""[11..15)"" Text=""((a)"" /> <Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest38() { Test(@"@""?((a)a""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""?((a)a"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""((a)a"" /> <Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest39() { Test(@"@""?((a)a|""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence /> </Alternation> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""?((a)a|"" /> <Capture Name=""1"" Span=""[11..17)"" Text=""((a)a|"" /> <Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest40() { Test(@"@""?((a)a|b""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[18..18)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""?((a)a|b"" /> <Capture Name=""1"" Span=""[11..18)"" Text=""((a)a|b"" /> <Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest41() { Test(@"@""(?(?i))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>i</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?i))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest42() { Test(@"@""?(a)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""?(a)"" /> <Capture Name=""1"" Span=""[11..14)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest43() { Test(@"@""(?(?I))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>I</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?I))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest44() { Test(@"@""(?(?M))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>M</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?M))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest45() { Test(@"@""(?(?s))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>s</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?s))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest46() { Test(@"@""(?(?S))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>S</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?S))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest47() { Test(@"@""(?(?x))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?x))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest48() { Test(@"@""(?(?X))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>X</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?X))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest49() { Test(@"@""(?(?n))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?n))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest50() { Test(@"@""(?(?m))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>m</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?m))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest51() { Test(@"@""[a""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""[a"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest52() { Test(@"@""?(a:b)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a:b</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""?(a:b)"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""(a:b)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest53() { Test(@"@""(?(?""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[12..13)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[13..14)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""(?(?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest54() { Test(@"@""(?(cat""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(?(cat"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest55() { Test(@"@""(?(cat)|""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[18..18)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""(?(cat)|"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest56() { Test(@"@""foo(?<0>bar)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>foo</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>bar</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[16..17)"" Text=""0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""foo(?&lt;0&gt;bar)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest57() { Test(@"@""foo(?'0'bar)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>foo</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>bar</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[16..17)"" Text=""0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""foo(?'0'bar)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest58() { Test(@"@""foo(?<1bar)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>foo</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken /> <Sequence> <Text> <TextToken>bar</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""b"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""foo(?&lt;1bar)"" /> <Capture Name=""1"" Span=""[13..21)"" Text=""(?&lt;1bar)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest59() { Test(@"@""foo(?'1bar)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>foo</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""1"">1</NumberToken> <SingleQuoteToken /> <Sequence> <Text> <TextToken>bar</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""b"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""foo(?'1bar)"" /> <Capture Name=""1"" Span=""[13..21)"" Text=""(?'1bar)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest60() { Test(@"@""(?(""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""(?("" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest61() { Test(@"@""\p{klsak""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{klsak</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\p{{klsak"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest62() { Test(@"@""(?c:cat)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken>c:cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""(?c:cat)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest63() { Test(@"@""(??e:cat)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <Text> <TextToken>?</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <Text> <TextToken>e:cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""(??e:cat)"" /> <Capture Name=""1"" Span=""[10..19)"" Text=""(??e:cat)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest64() { Test(@"@""[a-f-[]]+""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>f</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>]</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> <Text> <TextToken>+</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.A_subtraction_must_be_the_last_element_in_a_character_class}"" Span=""[14..14)"" Text="""" /> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[19..19)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[a-f-[]]+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest65() { Test(@"@""[A-[]+""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>A</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>]+</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[A-[]+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest66() { Test(@"@""(?(?e))""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken>e</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[12..13)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[13..14)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?e))"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest67() { Test(@"@""(?(?a)""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[12..13)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[13..14)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(?(?a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest68() { Test(@"@""(?r:cat)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken>r:cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""(?r:cat)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest69() { Test(@"@""(?(?N))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>N</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?(?N))"" /> </Captures> </Tree>", RegexOptions.None, allowNullReference: true); } [Fact] public void NegativeTest70() { Test(@"@""[]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>]</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""[]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest71() { Test(@"@""\x2""", $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>2</TextToken> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\x2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\x2"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest72() { Test(@"@""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia>(?#cat)</CommentTrivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia>(?#followed by 1 or more whitespace</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[31..66)"" Text=""(?#followed by 1 or more whitespace"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..66)"" Text=""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void NegativeTest73() { Test(@"@""cat(?(?afdcat)dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken>afdcat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[15..16)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[16..17)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..28)"" Text=""cat(?(?afdcat)dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest74() { Test(@"@""cat(?(?<cat>cat)dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[13..14)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..30)"" Text=""cat(?(?&lt;cat&gt;cat)dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest75() { Test(@"@""cat(?(?'cat'cat)dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[13..14)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..30)"" Text=""cat(?(?'cat'cat)dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest76() { Test(@"@""cat(?(?#COMMENT)cat)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken>#COMMENT</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_cannot_be_comments}"" Span=""[13..14)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[15..16)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[16..17)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..30)"" Text=""cat(?(?#COMMENT)cat)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest77() { Test(@"@""(?<cat>cat)\w+(?<dog-()*!@>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>!@&gt;dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[31..32)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..41)"" Text=""(?&lt;cat&gt;cat)\w+(?&lt;dog-()*!@&gt;dog)"" /> <Capture Name=""1"" Span=""[31..33)"" Text=""()"" /> <Capture Name=""2"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""3"" Span=""[24..41)"" Text=""(?&lt;dog-()*!@&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..41)"" Text=""(?&lt;dog-()*!@&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void NegativeTest78() { Test(@"@""(?<cat>cat)\w+(?<dog-catdog>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""catdog"">catdog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "catdog")}"" Span=""[31..37)"" Text=""catdog"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""(?&lt;cat&gt;cat)\w+(?&lt;dog-catdog&gt;dog)"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..42)"" Text=""(?&lt;dog-catdog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..42)"" Text=""(?&lt;dog-catdog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void NegativeTest79() { Test(@"@""(?<cat>cat)\w+(?<dog-1uosn>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken /> <Sequence> <Text> <TextToken>uosn&gt;dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[32..33)"" Text=""u"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..41)"" Text=""(?&lt;cat&gt;cat)\w+(?&lt;dog-1uosn&gt;dog)"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..41)"" Text=""(?&lt;dog-1uosn&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..41)"" Text=""(?&lt;dog-1uosn&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void NegativeTest80() { Test(@"@""(?<cat>cat)\w+(?<dog-16>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""16"">16</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "16")}"" Span=""[31..33)"" Text=""16"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..38)"" Text=""(?&lt;cat&gt;cat)\w+(?&lt;dog-16&gt;dog)"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..38)"" Text=""(?&lt;dog-16&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..38)"" Text=""(?&lt;dog-16&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void NegativeTest81() { Test(@"@""cat(?<->dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""cat(?&lt;-&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void NegativeTest82() { Test(@"@""cat(?<>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[16..17)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""cat(?&lt;&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest83() { Test(@"@""cat(?<dog<>)_*>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken /> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <Text> <TextToken>_</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>&gt;dog</TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text=""&lt;"" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[28..29)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""cat(?&lt;dog&lt;&gt;)_*&gt;dog)"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""(?&lt;dog&lt;&gt;)"" /> <Capture Name=""dog"" Span=""[13..22)"" Text=""(?&lt;dog&lt;&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest84() { Test(@"@""cat(?<dog >)_*>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken /> <Sequence> <Text> <TextToken> &gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <Text> <TextToken>_</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>&gt;dog</TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text="" "" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[28..29)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""cat(?&lt;dog &gt;)_*&gt;dog)"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""(?&lt;dog &gt;)"" /> <Capture Name=""dog"" Span=""[13..22)"" Text=""(?&lt;dog &gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest85() { Test(@"@""cat(?<dog!>)_*>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken /> <Sequence> <Text> <TextToken>!&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <Text> <TextToken>_</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>&gt;dog</TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text=""!"" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[28..29)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""cat(?&lt;dog!&gt;)_*&gt;dog)"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""(?&lt;dog!&gt;)"" /> <Capture Name=""dog"" Span=""[13..22)"" Text=""(?&lt;dog!&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest86() { Test(@"@""cat(?<dog)_*>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken /> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <Text> <TextToken>_</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>&gt;dog</TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text="")"" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[26..27)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""cat(?&lt;dog)_*&gt;dog)"" /> <Capture Name=""1"" Span=""[13..20)"" Text=""(?&lt;dog)"" /> <Capture Name=""dog"" Span=""[13..20)"" Text=""(?&lt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest87() { Test(@"@""cat(?<1dog>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken /> <Sequence> <Text> <TextToken>dog&gt;dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""d"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""cat(?&lt;1dog&gt;dog)"" /> <Capture Name=""1"" Span=""[13..25)"" Text=""(?&lt;1dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest88() { Test(@"@""cat(?<0>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[16..17)"" Text=""0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""cat(?&lt;0&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest89() { Test(@"@""([5-\D]*)dog""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>5</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "D")}"" Span=""[14..16)"" Text=""\D"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""([5-\D]*)dog"" /> <Capture Name=""1"" Span=""[10..19)"" Text=""([5-\D]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest90() { Test(@"@""cat([6-\s]*)dog""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>6</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "s")}"" Span=""[17..19)"" Text=""\s"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""cat([6-\s]*)dog"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""([6-\s]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest91() { Test(@"@""cat([c-\S]*)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>c</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "S")}"" Span=""[17..19)"" Text=""\S"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""cat([c-\S]*)"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""([c-\S]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest92() { Test(@"@""cat([7-\w]*)""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>7</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "w")}"" Span=""[17..19)"" Text=""\w"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""cat([7-\w]*)"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""([7-\w]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest93() { Test(@"@""cat([a-\W]*)dog""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>cat</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "W")}"" Span=""[17..19)"" Text=""\W"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""cat([a-\W]*)dog"" /> <Capture Name=""1"" Span=""[13..22)"" Text=""([a-\W]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest94() { Test(@"@""([f-\p{Lu}]\w*)\s([\p{Lu}]\w*)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>f</TextToken> </Text> <MinusToken>-</MinusToken> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "p")}"" Span=""[14..16)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""([f-\p{{Lu}}]\w*)\s([\p{{Lu}}]\w*)"" /> <Capture Name=""1"" Span=""[10..25)"" Text=""([f-\p{{Lu}}]\w*)"" /> <Capture Name=""2"" Span=""[27..40)"" Text=""([\p{{Lu}}]\w*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest95() { Test(@"@""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken> </TextToken> </Text> <Text> <TextToken> <Trivia> <CommentTrivia>(?#cat)</CommentTrivia> </Trivia> </TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile> <Trivia> <CommentTrivia>(?#followed by 1 or more whitespace</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[31..66)"" Text=""(?#followed by 1 or more whitespace"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..66)"" Text=""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest96() { Test(@"@""([1-\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>1</TextToken> </Text> <MinusToken>-</MinusToken> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Ll</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Ll</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Ll</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Ll</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "P")}"" Span=""[14..16)"" Text=""\P"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..52)"" Text=""([1-\P{{Ll}}][\p{{Ll}}]*)\s([\P{{Ll}}][\p{{Ll}}]*)"" /> <Capture Name=""1"" Span=""[10..31)"" Text=""([1-\P{{Ll}}][\p{{Ll}}]*)"" /> <Capture Name=""2"" Span=""[33..52)"" Text=""([\P{{Ll}}][\p{{Ll}}]*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest97() { Test(@"@""[\P]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\P"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[\P]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest98() { Test(@"@""([\pcat])""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_character_escape}"" Span=""[12..14)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""([\pcat])"" /> <Capture Name=""1"" Span=""[10..19)"" Text=""([\pcat])"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest99() { Test(@"@""([\Pcat])""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> </SimpleEscape> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_character_escape}"" Span=""[12..14)"" Text=""\P"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""([\Pcat])"" /> <Capture Name=""1"" Span=""[10..19)"" Text=""([\Pcat])"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest100() { Test(@"@""(\p{""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\p"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""(\p{{"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\p{{"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest101() { Test(@"@""(\p{Ll""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{Ll</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\p"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\p{{Ll"" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(\p{{Ll"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest102() { Test(@"@""(cat)([\o]*)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>o</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "o")}"" Span=""[18..19)"" Text=""o"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(cat)([\o]*)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..22)"" Text=""([\o]*)"" /> <Capture Name=""3"" Span=""[22..27)"" Text=""(dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest103() { Test(@"@""[\p]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[\p]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest104() { Test(@"@""(?<cat>cat)\s+(?<dog>dog)\kcat""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[35..37)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""(?&lt;cat&gt;cat)\s+(?&lt;dog&gt;dog)\kcat"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest105() { Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k<cat2>""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat2"">cat2</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "cat2")}"" Span=""[38..42)"" Text=""cat2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""(?&lt;cat&gt;cat)\s+(?&lt;dog&gt;dog)\k&lt;cat2&gt;"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest106() { Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k<8>cat""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""8"">8</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "8")}"" Span=""[38..39)"" Text=""8"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""(?&lt;cat&gt;cat)\s+(?&lt;dog&gt;dog)\k&lt;8&gt;cat"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest107() { Test(@"@""^[abcd]{1}?*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <LazyQuantifier> <ExactNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ExactNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[21..22)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""^[abcd]{{1}}?*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest108() { Test(@"@""^[abcd]*+$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>+</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "+")}"" Span=""[18..19)"" Text=""+"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""^[abcd]*+$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest109() { Test(@"@""^[abcd]+*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[18..19)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""^[abcd]+*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest110() { Test(@"@""^[abcd]?*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[18..19)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""^[abcd]?*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest111() { Test(@"@""^[abcd]*?+$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>+</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "+")}"" Span=""[19..20)"" Text=""+"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""^[abcd]*?+$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest112() { Test(@"@""^[abcd]+?*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[19..20)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""^[abcd]+?*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest113() { Test(@"@""^[abcd]{1,}?*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <LazyQuantifier> <OpenRangeNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}}</CloseBraceToken> </OpenRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[22..23)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]{{1,}}?*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest114() { Test(@"@""^[abcd]??*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <LazyQuantifier> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[19..20)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""^[abcd]??*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest115() { Test(@"@""^[abcd]+{0,5}$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>0,5}}</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[18..19)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]+{{0,5}}$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest116() { Test(@"@""^[abcd]?{0,5}$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>0,5}}</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[18..19)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]?{{0,5}}$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest117() { Test(@"@""\u""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken /> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\u"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\u"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest118() { Test(@"@""\ua""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>a</TextToken> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\ua"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\ua"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest119() { Test(@"@""\u0""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0</TextToken> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\u0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\u0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest120() { Test(@"@""\x""", $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken /> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\x"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\x"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest121() { Test(@"@""^[abcd]*{0,5}$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>0,5}}</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[18..19)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]*{{0,5}}$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest122() { Test(@"@""[""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence /> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[11..11)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..11)"" Text=""["" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest123() { Test(@"@""^[abcd]{0,16}?*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <LazyQuantifier> <ClosedRangeNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""16"">16</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ClosedRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[24..25)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""^[abcd]{{0,16}}?*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest124() { Test(@"@""^[abcd]{1,}*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OpenRangeNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}}</CloseBraceToken> </OpenRangeNumericQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[21..22)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""^[abcd]{{1,}}*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest125() { Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k<8>cat""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""8"">8</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "8")}"" Span=""[38..39)"" Text=""8"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""(?&lt;cat&gt;cat)\s+(?&lt;dog&gt;dog)\k&lt;8&gt;cat"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void NegativeTest126() { Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k8""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>8</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[35..37)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..38)"" Text=""(?&lt;cat&gt;cat)\s+(?&lt;dog&gt;dog)\k8"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest127() { Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k8""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""cat"">cat</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""dog"">dog</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>8</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[35..37)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..38)"" Text=""(?&lt;cat&gt;cat)\s+(?&lt;dog&gt;dog)\k8"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""2"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> <Capture Name=""cat"" Span=""[10..21)"" Text=""(?&lt;cat&gt;cat)"" /> <Capture Name=""dog"" Span=""[24..35)"" Text=""(?&lt;dog&gt;dog)"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void NegativeTest128() { Test(@"@""(cat)(\7)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""7"">7</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "7")}"" Span=""[17..18)"" Text=""7"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""(cat)(\7)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..19)"" Text=""(\7)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest129() { Test(@"@""(cat)\s+(?<2147483648>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""-2147483648"">2147483648</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[21..31)"" Text=""2147483648"" /> </Diagnostics> <Captures> <Capture Name=""-2147483648"" Span=""[18..36)"" Text=""(?&lt;2147483648&gt;dog)"" /> <Capture Name=""0"" Span=""[10..36)"" Text=""(cat)\s+(?&lt;2147483648&gt;dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest130() { Test(@"@""(cat)\s+(?<21474836481097>dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1097"">21474836481097</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[21..35)"" Text=""21474836481097"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""(cat)\s+(?&lt;21474836481097&gt;dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""1097"" Span=""[18..40)"" Text=""(?&lt;21474836481097&gt;dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest131() { Test(@"@""^[abcd]{1}*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ExactNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[20..21)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""^[abcd]{{1}}*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest132() { Test(@"@""(cat)(\c*)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""(cat)(\c*)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..20)"" Text=""(\c*)"" /> <Capture Name=""3"" Span=""[20..25)"" Text=""(dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest133() { Test(@"@""(cat)(\c *)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <ZeroOrMoreQuantifier> <Text> <TextToken> </TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(cat)(\c *)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..21)"" Text=""(\c *)"" /> <Capture Name=""3"" Span=""[21..26)"" Text=""(dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest134() { Test(@"@""(cat)(\c?*)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <Text> <TextToken>*</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text=""?"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[19..20)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(cat)(\c?*)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..21)"" Text=""(\c?*)"" /> <Capture Name=""3"" Span=""[21..26)"" Text=""(dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest135() { Test(@"@""(cat)(\c`*)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <ZeroOrMoreQuantifier> <Text> <TextToken>`</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text=""`"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(cat)(\c`*)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..21)"" Text=""(\c`*)"" /> <Capture Name=""3"" Span=""[21..26)"" Text=""(dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest136() { Test(@"@""(cat)(\c\|*)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>\</TextToken> </ControlEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>*</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>dog</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[20..21)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(cat)(\c\|*)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..22)"" Text=""(\c\|*)"" /> <Capture Name=""3"" Span=""[22..27)"" Text=""(dog)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest137() { Test(@"@""(cat)(\c\[*)(dog)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>\</TextToken> </ControlEscape> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>*)(dog)</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[27..27)"" Text="""" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[27..27)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(cat)(\c\[*)(dog)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> <Capture Name=""2"" Span=""[15..27)"" Text=""(\c\[*)(dog)"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false); } [Fact] public void NegativeTest138() { Test(@"@""^[abcd]{0,16}*$""", $@"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ClosedRangeNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>abcd</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""16"">16</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ClosedRangeNumericQuantifier> <Text> <TextToken>*</TextToken> </Text> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[23..24)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""^[abcd]{{0,16}}*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void NegativeTest139() { Test(@"@""(cat)\c""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>cat</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Missing_control_character}"" Span=""[16..17)"" Text=""c"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(cat)\c"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" /> </Captures> </Tree>", RegexOptions.None); } } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./Compilers.sln
Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.29519.87 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.UnitTests", "src\Compilers\Core\CodeAnalysisTest\Microsoft.CodeAnalysis.UnitTests.csproj", "{A4C99B85-765C-4C65-9C2A-BB609AAB09E6}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis", "src\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj", "{1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VBCSCompiler", "src\Compilers\Server\VBCSCompiler\VBCSCompiler.csproj", "{9508F118-F62E-4C16-A6F4-7C3B56E166AD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VBCSCompiler.UnitTests", "src\Compilers\Server\VBCSCompilerTests\VBCSCompiler.UnitTests.csproj", "{F5CE416E-B906-41D2-80B9-0078E887A3F6}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{A41D1B99-F489-4C43-BBDF-96D61B19A6B9}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CSharp", "CSharp", "{32A48625-F0AD-419D-828B-A50BDABA38EA}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "csc", "src\Compilers\CSharp\csc\csc.csproj", "{4B45CA0C-03A0-400F-B454-3D4BCB16AF38}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp", "src\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj", "{B501A547-C911-4A05-AC6E-274A50DFF30E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests", "src\Compilers\CSharp\Test\CommandLine\Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests.csproj", "{50D26304-0961-4A51-ABF6-6CAD1A56D203}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Emit.UnitTests", "src\Compilers\CSharp\Test\Emit\Microsoft.CodeAnalysis.CSharp.Emit.UnitTests.csproj", "{4462B57A-7245-4146-B504-D46FDE762948}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests", "src\Compilers\CSharp\Test\IOperation\Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests.csproj", "{1AF3672A-C5F1-4604-B6AB-D98C4DE9C3B1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests", "src\Compilers\CSharp\Test\Semantic\Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.csproj", "{B2C33A93-DB30-4099-903E-77D75C4C3F45}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests", "src\Compilers\CSharp\Test\Symbol\Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests.csproj", "{28026D16-EB0C-40B0-BDA7-11CAA2B97CCC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Syntax.UnitTests", "src\Compilers\CSharp\Test\Syntax\Microsoft.CodeAnalysis.CSharp.Syntax.UnitTests.csproj", "{50D26304-0961-4A51-ABF6-6CAD1A56D202}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "VisualBasic", "VisualBasic", "{C65C6143-BED3-46E6-869E-9F0BE6E84C37}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Compiler.Test.Resources", "src\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj", "{7FE6B002-89D8-4298-9B1B-0B5C247DD1FD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Test.Utilities", "src\Compilers\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj", "{4371944A-D3BA-4B5B-8285-82E5FFC6D1F9}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Test.Utilities", "src\Compilers\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj", "{4371944A-D3BA-4B5B-8285-82E5FFC6D1F8}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic", "src\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj", "{2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests", "src\Compilers\VisualBasic\Test\CommandLine\Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests.vbproj", "{E3B32027-3362-41DF-9172-4D3B623F42A5}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests", "src\Compilers\VisualBasic\Test\Emit\Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests.vbproj", "{190CE348-596E-435A-9E5B-12A689F9FC29}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Roslyn.Compilers.VisualBasic.IOperation.UnitTests", "src\Compilers\VisualBasic\Test\IOperation\Roslyn.Compilers.VisualBasic.IOperation.UnitTests.vbproj", "{9C9DABA4-0E72-4469-ADF1-4991F3CA572A}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests", "src\Compilers\VisualBasic\Test\Semantic\Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests.vbproj", "{BF180BD2-4FB7-4252-A7EC-A00E0C7A028A}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests", "src\Compilers\VisualBasic\Test\Symbol\Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests.vbproj", "{BDA5D613-596D-4B61-837C-63554151C8F5}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests", "src\Compilers\VisualBasic\Test\Syntax\Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests.vbproj", "{91F6F646-4F6E-449A-9AB4-2986348F329D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Roslyn.Test.PdbUtilities", "src\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj", "{AFDE6BEA-5038-4A4A-A88E-DBD2E4088EED}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CompilersBoundTreeGenerator", "src\Tools\Source\CompilerGeneratorTools\Source\BoundTreeGenerator\CompilersBoundTreeGenerator.csproj", "{02459936-CD2C-4F61-B671-5C518F2A3DDC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharpErrorFactsGenerator", "src\Tools\Source\CompilerGeneratorTools\Source\CSharpErrorFactsGenerator\CSharpErrorFactsGenerator.csproj", "{288089C5-8721-458E-BE3E-78990DAB5E2E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharpSyntaxGenerator", "src\Tools\Source\CompilerGeneratorTools\Source\CSharpSyntaxGenerator\CSharpSyntaxGenerator.csproj", "{288089C5-8721-458E-BE3E-78990DAB5E2D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CompilersIOperationGenerator", "src\Tools\Source\CompilerGeneratorTools\Source\IOperationGenerator\CompilersIOperationGenerator.csproj", "{D0A79850-B32A-45E5-9FD5-D43CB345867A}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "VisualBasicSyntaxGenerator", "src\Tools\Source\CompilerGeneratorTools\Source\VisualBasicSyntaxGenerator\VisualBasicSyntaxGenerator.vbproj", "{6AA96934-D6B7-4CC8-990D-DB6B9DD56E34}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "VisualBasicErrorFactsGenerator", "src\Tools\Source\CompilerGeneratorTools\Source\VisualBasicErrorFactsGenerator\VisualBasicErrorFactsGenerator.vbproj", "{909B656F-6095-4AC2-A5AB-C3F032315C45}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "AnalyzerDriver", "src\Compilers\Core\AnalyzerDriver\AnalyzerDriver.shproj", "{D0BC9BE7-24F6-40CA-8DC6-FCB93BD44B34}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.WinRT.UnitTests", "src\Compilers\CSharp\Test\WinRT\Microsoft.CodeAnalysis.CSharp.WinRT.UnitTests.csproj", "{FCFA8808-A1B6-48CC-A1EA-0B8CA8AEDA8E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "vbc", "src\Compilers\VisualBasic\vbc\vbc.csproj", "{E58EE9D7-1239-4961-A0C1-F9EC3952C4C1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Build.Tasks.CodeAnalysis.UnitTests", "src\Compilers\Core\MSBuildTaskTests\Microsoft.Build.Tasks.CodeAnalysis.UnitTests.csproj", "{1DFEA9C5-973C-4179-9B1B-0F32288E1EF2}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Server", "Server", "{E35DA3D1-16C0-4318-9187-6B664F12A870}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "CommandLine", "src\Compilers\Core\CommandLine\CommandLine.shproj", "{AD6F474E-E6D4-4217-91F3-B7AF1BE31CCC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RunTests", "src\Tools\Source\RunTests\RunTests.csproj", "{1A3941F1-1E1F-4EF7-8064-7729C4C2E2AA}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Test.Utilities", "src\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj", "{CCBD3438-3E84-40A9-83AD-533F23BCFCA5}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Dependencies", "Dependencies", "{3CDEA9FB-CD44-4AB4-98A8-5537AAA2169B}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Microsoft.CodeAnalysis.PooledObjects", "src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.shproj", "{C1930979-C824-496B-A630-70F5369A636F}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Microsoft.CodeAnalysis.Debugging", "src\Dependencies\CodeAnalysis.Debugging\Microsoft.CodeAnalysis.Debugging.shproj", "{D73ADF7D-2C1C-42AE-B2AB-EDC9497E4B71}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Build.Tasks.CodeAnalysis", "src\Compilers\Core\MSBuildTask\Microsoft.Build.Tasks.CodeAnalysis.csproj", "{7AD4FE65-9A30-41A6-8004-AA8F89BCB7F3}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Scripting.UnitTests", "src\Scripting\CoreTest\Microsoft.CodeAnalysis.Scripting.UnitTests.csproj", "{2DAE4406-7A89-4B5F-95C3-BC5472CE47CE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests", "src\Scripting\CSharpTest\Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.csproj", "{2DAE4406-7A89-4B5F-95C3-BC5422CE47CE}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests", "src\Scripting\VisualBasicTest\Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests.vbproj", "{ABC7262E-1053-49F3-B846-E3091BB92E8C}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Scripting", "Scripting", "{3FF38FD4-DF16-44B0-924F-0D5AE155495B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Scripting", "src\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj", "{12A68549-4E8C-42D6-8703-A09335F97997}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Scripting", "src\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj", "{066F0DBD-C46C-4C20-AFEC-99829A172625}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Scripting", "src\Scripting\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj", "{3E7DEA65-317B-4F43-A25D-62F18D96CFD7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Scripting.TestUtilities", "src\Scripting\CoreTestUtilities\Microsoft.CodeAnalysis.Scripting.TestUtilities.csproj", "{21A01C2D-2501-4619-8144-48977DD22D9C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "csi", "src\Interactive\csi\csi.csproj", "{14118347-ED06-4608-9C45-18228273C712}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Workspace", "Workspace", "{D9591377-7868-4D64-9314-83E0C92A871B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Workspaces", "src\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj", "{5F8D2414-064A-4B3A-9B42-8E2A04246BE5}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Workspaces", "src\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj", "{21B239D0-D144-430F-A394-C066D58EE267}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Workspaces", "src\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj", "{57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "CSharpAnalyzerDriver", "src\Compilers\CSharp\CSharpAnalyzerDriver\CSharpAnalyzerDriver.shproj", "{54E08BF5-F819-404F-A18D-0AB9EA81EA04}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "BasicAnalyzerDriver", "src\Compilers\VisualBasic\BasicAnalyzerDriver\BasicAnalyzerDriver.shproj", "{E8F0BAA5-7327-43D1-9A51-644E81AE55F1}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Packages", "Packages", "{274B96B7-F815-47E3-9CA4-4024A57A478F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.NETCore.Compilers.Package", "src\NuGet\Microsoft.NETCore.Compilers\Microsoft.NETCore.Compilers.Package.csproj", "{15FEBD1B-55CE-4EBD-85E3-04898260A25B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Net.Compilers.Package", "src\NuGet\Microsoft.Net.Compilers\Microsoft.Net.Compilers.Package.csproj", "{27B1EAE2-2E06-48EF-8A67-06D6FB3DC275}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Compilers.Package", "src\NuGet\Microsoft.CodeAnalysis.Compilers.Package.csproj", "{E0756C89-603F-4B48-8E64-1D53E62654C8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Scripting.Package", "src\NuGet\Microsoft.CodeAnalysis.Scripting.Package.csproj", "{7F8057D9-F70F-4EA7-BD64-AB2D0DD8057B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Package", "src\NuGet\Microsoft.CodeAnalysis.Package.csproj", "{2483917E-7024-4D10-99C6-2BEF338FF53B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BuildBoss", "src\Tools\BuildBoss\BuildBoss.csproj", "{8A02AFAF-F622-4E3E-9E1A-8CFDACC7C7E1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Net.Compilers.Toolset.Package", "src\NuGet\Microsoft.Net.Compilers.Toolset\Microsoft.Net.Compilers.Toolset.Package.csproj", "{6D407402-CC4A-4125-9B00-C70562A636A5}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "vbi", "src\Interactive\vbi\vbi.vbproj", "{706CFC25-B6E0-4DAA-BCC4-F6FAAFEEDF87}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BuildValidator", "src\Tools\BuildValidator\BuildValidator.csproj", "{E9211052-7700-4A2F-B1AE-34FD5CCAB8AF}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PrepareTests", "src\Tools\PrepareTests\PrepareTests.csproj", "{9B25E472-DF94-4E24-9F5D-E487CE5A91FB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeStyleConfigFileGenerator", "src\CodeStyle\Tools\CodeStyleConfigFileGenerator.csproj", "{432F4461-E198-44AA-8022-9E8C06A17C93}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Microsoft.CodeAnalysis.Collections", "src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.shproj", "{E919DD77-34F8-4F57-8058-4D3FF4C2B241}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Rebuild", "src\Compilers\Core\Rebuild\Microsoft.CodeAnalysis.Rebuild.csproj", "{321F9FED-AACC-42CB-93E5-541D79E099E8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Rebuild.UnitTests", "src\Compilers\Core\RebuildTest\Microsoft.CodeAnalysis.Rebuild.UnitTests.csproj", "{FDBFBB64-5980-41C2-9E3E-FB8E2F700A5C}" EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution src\Compilers\Core\AnalyzerDriver\AnalyzerDriver.projitems*{1ee8cad3-55f9-4d91-96b2-084641da9a6c}*SharedItemsImports = 5 src\Dependencies\CodeAnalysis.Debugging\Microsoft.CodeAnalysis.Debugging.projitems*{1ee8cad3-55f9-4d91-96b2-084641da9a6c}*SharedItemsImports = 5 src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{1ee8cad3-55f9-4d91-96b2-084641da9a6c}*SharedItemsImports = 5 src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{1ee8cad3-55f9-4d91-96b2-084641da9a6c}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\CSharp\CSharpCompilerExtensions.projitems*{21b239d0-d144-430f-a394-c066d58ee267}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Workspace\CSharp\CSharpWorkspaceExtensions.projitems*{21b239d0-d144-430f-a394-c066d58ee267}*SharedItemsImports = 5 src\Compilers\VisualBasic\BasicAnalyzerDriver\BasicAnalyzerDriver.projitems*{2523d0e6-df32-4a3e-8ae0-a19bffae2ef6}*SharedItemsImports = 5 src\Compilers\Core\CommandLine\CommandLine.projitems*{4b45ca0c-03a0-400f-b454-3d4bcb16af38}*SharedItemsImports = 5 src\Compilers\CSharp\CSharpAnalyzerDriver\CSharpAnalyzerDriver.projitems*{54e08bf5-f819-404f-a18d-0ab9ea81ea04}*SharedItemsImports = 13 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\VisualBasic\VisualBasicCompilerExtensions.projitems*{57ca988d-f010-4bf2-9a2e-07d6dcd2ff2c}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Workspace\VisualBasic\VisualBasicWorkspaceExtensions.projitems*{57ca988d-f010-4bf2-9a2e-07d6dcd2ff2c}*SharedItemsImports = 5 src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{5f8d2414-064a-4b3a-9b42-8e2a04246be5}*SharedItemsImports = 5 src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{5f8d2414-064a-4b3a-9b42-8e2a04246be5}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{5f8d2414-064a-4b3a-9b42-8e2a04246be5}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Workspace\Core\WorkspaceExtensions.projitems*{5f8d2414-064a-4b3a-9b42-8e2a04246be5}*SharedItemsImports = 5 src\Compilers\Core\CommandLine\CommandLine.projitems*{7ad4fe65-9a30-41a6-8004-aa8f89bcb7f3}*SharedItemsImports = 5 src\Compilers\Core\CommandLine\CommandLine.projitems*{9508f118-f62e-4c16-a6f4-7c3b56e166ad}*SharedItemsImports = 5 src\Compilers\Core\CommandLine\CommandLine.projitems*{ad6f474e-e6d4-4217-91f3-b7af1be31ccc}*SharedItemsImports = 13 src\Compilers\CSharp\CSharpAnalyzerDriver\CSharpAnalyzerDriver.projitems*{b501a547-c911-4a05-ac6e-274a50dff30e}*SharedItemsImports = 5 src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{c1930979-c824-496b-a630-70f5369a636f}*SharedItemsImports = 13 src\Compilers\Core\AnalyzerDriver\AnalyzerDriver.projitems*{d0bc9be7-24f6-40ca-8dc6-fcb93bd44b34}*SharedItemsImports = 13 src\Dependencies\CodeAnalysis.Debugging\Microsoft.CodeAnalysis.Debugging.projitems*{d73adf7d-2c1c-42ae-b2ab-edc9497e4b71}*SharedItemsImports = 13 src\Compilers\Core\CommandLine\CommandLine.projitems*{e58ee9d7-1239-4961-a0c1-f9ec3952c4c1}*SharedItemsImports = 5 src\Compilers\VisualBasic\BasicAnalyzerDriver\BasicAnalyzerDriver.projitems*{e8f0baa5-7327-43d1-9a51-644e81ae55f1}*SharedItemsImports = 13 src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{e919dd77-34f8-4f57-8058-4d3ff4c2b241}*SharedItemsImports = 13 EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {A4C99B85-765C-4C65-9C2A-BB609AAB09E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A4C99B85-765C-4C65-9C2A-BB609AAB09E6}.Debug|Any CPU.Build.0 = Debug|Any CPU {A4C99B85-765C-4C65-9C2A-BB609AAB09E6}.Release|Any CPU.ActiveCfg = Release|Any CPU {A4C99B85-765C-4C65-9C2A-BB609AAB09E6}.Release|Any CPU.Build.0 = Release|Any CPU {1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}.Debug|Any CPU.Build.0 = Debug|Any CPU {1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}.Release|Any CPU.ActiveCfg = Release|Any CPU {1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}.Release|Any CPU.Build.0 = Release|Any CPU {9508F118-F62E-4C16-A6F4-7C3B56E166AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9508F118-F62E-4C16-A6F4-7C3B56E166AD}.Debug|Any CPU.Build.0 = Debug|Any CPU {9508F118-F62E-4C16-A6F4-7C3B56E166AD}.Release|Any CPU.ActiveCfg = Release|Any CPU {9508F118-F62E-4C16-A6F4-7C3B56E166AD}.Release|Any CPU.Build.0 = Release|Any CPU {F5CE416E-B906-41D2-80B9-0078E887A3F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F5CE416E-B906-41D2-80B9-0078E887A3F6}.Debug|Any CPU.Build.0 = Debug|Any CPU {F5CE416E-B906-41D2-80B9-0078E887A3F6}.Release|Any CPU.ActiveCfg = Release|Any CPU {F5CE416E-B906-41D2-80B9-0078E887A3F6}.Release|Any CPU.Build.0 = Release|Any CPU {4B45CA0C-03A0-400F-B454-3D4BCB16AF38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B45CA0C-03A0-400F-B454-3D4BCB16AF38}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B45CA0C-03A0-400F-B454-3D4BCB16AF38}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B45CA0C-03A0-400F-B454-3D4BCB16AF38}.Release|Any CPU.Build.0 = Release|Any CPU {B501A547-C911-4A05-AC6E-274A50DFF30E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B501A547-C911-4A05-AC6E-274A50DFF30E}.Debug|Any CPU.Build.0 = Debug|Any CPU {B501A547-C911-4A05-AC6E-274A50DFF30E}.Release|Any CPU.ActiveCfg = Release|Any CPU {B501A547-C911-4A05-AC6E-274A50DFF30E}.Release|Any CPU.Build.0 = Release|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D203}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D203}.Debug|Any CPU.Build.0 = Debug|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D203}.Release|Any CPU.ActiveCfg = Release|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D203}.Release|Any CPU.Build.0 = Release|Any CPU {4462B57A-7245-4146-B504-D46FDE762948}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4462B57A-7245-4146-B504-D46FDE762948}.Debug|Any CPU.Build.0 = Debug|Any CPU {4462B57A-7245-4146-B504-D46FDE762948}.Release|Any CPU.ActiveCfg = Release|Any CPU {4462B57A-7245-4146-B504-D46FDE762948}.Release|Any CPU.Build.0 = Release|Any CPU {1AF3672A-C5F1-4604-B6AB-D98C4DE9C3B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1AF3672A-C5F1-4604-B6AB-D98C4DE9C3B1}.Debug|Any CPU.Build.0 = Debug|Any CPU {1AF3672A-C5F1-4604-B6AB-D98C4DE9C3B1}.Release|Any CPU.ActiveCfg = Release|Any CPU {1AF3672A-C5F1-4604-B6AB-D98C4DE9C3B1}.Release|Any CPU.Build.0 = Release|Any CPU {B2C33A93-DB30-4099-903E-77D75C4C3F45}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B2C33A93-DB30-4099-903E-77D75C4C3F45}.Debug|Any CPU.Build.0 = Debug|Any CPU {B2C33A93-DB30-4099-903E-77D75C4C3F45}.Release|Any CPU.ActiveCfg = Release|Any CPU {B2C33A93-DB30-4099-903E-77D75C4C3F45}.Release|Any CPU.Build.0 = Release|Any CPU {28026D16-EB0C-40B0-BDA7-11CAA2B97CCC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {28026D16-EB0C-40B0-BDA7-11CAA2B97CCC}.Debug|Any CPU.Build.0 = Debug|Any CPU {28026D16-EB0C-40B0-BDA7-11CAA2B97CCC}.Release|Any CPU.ActiveCfg = Release|Any CPU {28026D16-EB0C-40B0-BDA7-11CAA2B97CCC}.Release|Any CPU.Build.0 = Release|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D202}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D202}.Debug|Any CPU.Build.0 = Debug|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D202}.Release|Any CPU.ActiveCfg = Release|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D202}.Release|Any CPU.Build.0 = Release|Any CPU {7FE6B002-89D8-4298-9B1B-0B5C247DD1FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7FE6B002-89D8-4298-9B1B-0B5C247DD1FD}.Debug|Any CPU.Build.0 = Debug|Any CPU {7FE6B002-89D8-4298-9B1B-0B5C247DD1FD}.Release|Any CPU.ActiveCfg = Release|Any CPU {7FE6B002-89D8-4298-9B1B-0B5C247DD1FD}.Release|Any CPU.Build.0 = Release|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F9}.Release|Any CPU.Build.0 = Release|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F8}.Debug|Any CPU.Build.0 = Debug|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F8}.Release|Any CPU.ActiveCfg = Release|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F8}.Release|Any CPU.Build.0 = Release|Any CPU {2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6}.Debug|Any CPU.Build.0 = Debug|Any CPU {2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6}.Release|Any CPU.ActiveCfg = Release|Any CPU {2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6}.Release|Any CPU.Build.0 = Release|Any CPU {E3B32027-3362-41DF-9172-4D3B623F42A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E3B32027-3362-41DF-9172-4D3B623F42A5}.Debug|Any CPU.Build.0 = Debug|Any CPU {E3B32027-3362-41DF-9172-4D3B623F42A5}.Release|Any CPU.ActiveCfg = Release|Any CPU {E3B32027-3362-41DF-9172-4D3B623F42A5}.Release|Any CPU.Build.0 = Release|Any CPU {190CE348-596E-435A-9E5B-12A689F9FC29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {190CE348-596E-435A-9E5B-12A689F9FC29}.Debug|Any CPU.Build.0 = Debug|Any CPU {190CE348-596E-435A-9E5B-12A689F9FC29}.Release|Any CPU.ActiveCfg = Release|Any CPU {190CE348-596E-435A-9E5B-12A689F9FC29}.Release|Any CPU.Build.0 = Release|Any CPU {9C9DABA4-0E72-4469-ADF1-4991F3CA572A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9C9DABA4-0E72-4469-ADF1-4991F3CA572A}.Debug|Any CPU.Build.0 = Debug|Any CPU {9C9DABA4-0E72-4469-ADF1-4991F3CA572A}.Release|Any CPU.ActiveCfg = Release|Any CPU {9C9DABA4-0E72-4469-ADF1-4991F3CA572A}.Release|Any CPU.Build.0 = Release|Any CPU {BF180BD2-4FB7-4252-A7EC-A00E0C7A028A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BF180BD2-4FB7-4252-A7EC-A00E0C7A028A}.Debug|Any CPU.Build.0 = Debug|Any CPU {BF180BD2-4FB7-4252-A7EC-A00E0C7A028A}.Release|Any CPU.ActiveCfg = Release|Any CPU {BF180BD2-4FB7-4252-A7EC-A00E0C7A028A}.Release|Any CPU.Build.0 = Release|Any CPU {BDA5D613-596D-4B61-837C-63554151C8F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BDA5D613-596D-4B61-837C-63554151C8F5}.Debug|Any CPU.Build.0 = Debug|Any CPU {BDA5D613-596D-4B61-837C-63554151C8F5}.Release|Any CPU.ActiveCfg = Release|Any CPU {BDA5D613-596D-4B61-837C-63554151C8F5}.Release|Any CPU.Build.0 = Release|Any CPU {91F6F646-4F6E-449A-9AB4-2986348F329D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {91F6F646-4F6E-449A-9AB4-2986348F329D}.Debug|Any CPU.Build.0 = Debug|Any CPU {91F6F646-4F6E-449A-9AB4-2986348F329D}.Release|Any CPU.ActiveCfg = Release|Any CPU {91F6F646-4F6E-449A-9AB4-2986348F329D}.Release|Any CPU.Build.0 = Release|Any CPU {AFDE6BEA-5038-4A4A-A88E-DBD2E4088EED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AFDE6BEA-5038-4A4A-A88E-DBD2E4088EED}.Debug|Any CPU.Build.0 = Debug|Any CPU {AFDE6BEA-5038-4A4A-A88E-DBD2E4088EED}.Release|Any CPU.ActiveCfg = Release|Any CPU {AFDE6BEA-5038-4A4A-A88E-DBD2E4088EED}.Release|Any CPU.Build.0 = Release|Any CPU {02459936-CD2C-4F61-B671-5C518F2A3DDC}.Debug|Any CPU.ActiveCfg = Debug|x64 {02459936-CD2C-4F61-B671-5C518F2A3DDC}.Debug|Any CPU.Build.0 = Debug|x64 {02459936-CD2C-4F61-B671-5C518F2A3DDC}.Release|Any CPU.ActiveCfg = Release|x64 {02459936-CD2C-4F61-B671-5C518F2A3DDC}.Release|Any CPU.Build.0 = Release|x64 {288089C5-8721-458E-BE3E-78990DAB5E2E}.Debug|Any CPU.ActiveCfg = Debug|x64 {288089C5-8721-458E-BE3E-78990DAB5E2E}.Debug|Any CPU.Build.0 = Debug|x64 {288089C5-8721-458E-BE3E-78990DAB5E2E}.Release|Any CPU.ActiveCfg = Release|x64 {288089C5-8721-458E-BE3E-78990DAB5E2E}.Release|Any CPU.Build.0 = Release|x64 {288089C5-8721-458E-BE3E-78990DAB5E2D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {288089C5-8721-458E-BE3E-78990DAB5E2D}.Debug|Any CPU.Build.0 = Debug|Any CPU {288089C5-8721-458E-BE3E-78990DAB5E2D}.Release|Any CPU.ActiveCfg = Release|Any CPU {288089C5-8721-458E-BE3E-78990DAB5E2D}.Release|Any CPU.Build.0 = Release|Any CPU {D0A79850-B32A-45E5-9FD5-D43CB345867A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D0A79850-B32A-45E5-9FD5-D43CB345867A}.Debug|Any CPU.Build.0 = Debug|Any CPU {D0A79850-B32A-45E5-9FD5-D43CB345867A}.Release|Any CPU.ActiveCfg = Release|Any CPU {D0A79850-B32A-45E5-9FD5-D43CB345867A}.Release|Any CPU.Build.0 = Release|Any CPU {6AA96934-D6B7-4CC8-990D-DB6B9DD56E34}.Debug|Any CPU.ActiveCfg = Debug|x64 {6AA96934-D6B7-4CC8-990D-DB6B9DD56E34}.Debug|Any CPU.Build.0 = Debug|x64 {6AA96934-D6B7-4CC8-990D-DB6B9DD56E34}.Release|Any CPU.ActiveCfg = Release|x64 {6AA96934-D6B7-4CC8-990D-DB6B9DD56E34}.Release|Any CPU.Build.0 = Release|x64 {909B656F-6095-4AC2-A5AB-C3F032315C45}.Debug|Any CPU.ActiveCfg = Debug|x64 {909B656F-6095-4AC2-A5AB-C3F032315C45}.Debug|Any CPU.Build.0 = Debug|x64 {909B656F-6095-4AC2-A5AB-C3F032315C45}.Release|Any CPU.ActiveCfg = Release|x64 {909B656F-6095-4AC2-A5AB-C3F032315C45}.Release|Any CPU.Build.0 = Release|x64 {FCFA8808-A1B6-48CC-A1EA-0B8CA8AEDA8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FCFA8808-A1B6-48CC-A1EA-0B8CA8AEDA8E}.Debug|Any CPU.Build.0 = Debug|Any CPU {FCFA8808-A1B6-48CC-A1EA-0B8CA8AEDA8E}.Release|Any CPU.ActiveCfg = Release|Any CPU {FCFA8808-A1B6-48CC-A1EA-0B8CA8AEDA8E}.Release|Any CPU.Build.0 = Release|Any CPU {E58EE9D7-1239-4961-A0C1-F9EC3952C4C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E58EE9D7-1239-4961-A0C1-F9EC3952C4C1}.Debug|Any CPU.Build.0 = Debug|Any CPU {E58EE9D7-1239-4961-A0C1-F9EC3952C4C1}.Release|Any CPU.ActiveCfg = Release|Any CPU {E58EE9D7-1239-4961-A0C1-F9EC3952C4C1}.Release|Any CPU.Build.0 = Release|Any CPU {1DFEA9C5-973C-4179-9B1B-0F32288E1EF2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1DFEA9C5-973C-4179-9B1B-0F32288E1EF2}.Debug|Any CPU.Build.0 = Debug|Any CPU {1DFEA9C5-973C-4179-9B1B-0F32288E1EF2}.Release|Any CPU.ActiveCfg = Release|Any CPU {1DFEA9C5-973C-4179-9B1B-0F32288E1EF2}.Release|Any CPU.Build.0 = Release|Any CPU {1A3941F1-1E1F-4EF7-8064-7729C4C2E2AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1A3941F1-1E1F-4EF7-8064-7729C4C2E2AA}.Debug|Any CPU.Build.0 = Debug|Any CPU {1A3941F1-1E1F-4EF7-8064-7729C4C2E2AA}.Release|Any CPU.ActiveCfg = Release|Any CPU {1A3941F1-1E1F-4EF7-8064-7729C4C2E2AA}.Release|Any CPU.Build.0 = Release|Any CPU {CCBD3438-3E84-40A9-83AD-533F23BCFCA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CCBD3438-3E84-40A9-83AD-533F23BCFCA5}.Debug|Any CPU.Build.0 = Debug|Any CPU {CCBD3438-3E84-40A9-83AD-533F23BCFCA5}.Release|Any CPU.ActiveCfg = Release|Any CPU {CCBD3438-3E84-40A9-83AD-533F23BCFCA5}.Release|Any CPU.Build.0 = Release|Any CPU {7AD4FE65-9A30-41A6-8004-AA8F89BCB7F3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7AD4FE65-9A30-41A6-8004-AA8F89BCB7F3}.Debug|Any CPU.Build.0 = Debug|Any CPU {7AD4FE65-9A30-41A6-8004-AA8F89BCB7F3}.Release|Any CPU.ActiveCfg = Release|Any CPU {7AD4FE65-9A30-41A6-8004-AA8F89BCB7F3}.Release|Any CPU.Build.0 = Release|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5472CE47CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5472CE47CE}.Debug|Any CPU.Build.0 = Debug|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5472CE47CE}.Release|Any CPU.ActiveCfg = Release|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5472CE47CE}.Release|Any CPU.Build.0 = Release|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5422CE47CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5422CE47CE}.Debug|Any CPU.Build.0 = Debug|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5422CE47CE}.Release|Any CPU.ActiveCfg = Release|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5422CE47CE}.Release|Any CPU.Build.0 = Release|Any CPU {ABC7262E-1053-49F3-B846-E3091BB92E8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ABC7262E-1053-49F3-B846-E3091BB92E8C}.Debug|Any CPU.Build.0 = Debug|Any CPU {ABC7262E-1053-49F3-B846-E3091BB92E8C}.Release|Any CPU.ActiveCfg = Release|Any CPU {ABC7262E-1053-49F3-B846-E3091BB92E8C}.Release|Any CPU.Build.0 = Release|Any CPU {12A68549-4E8C-42D6-8703-A09335F97997}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {12A68549-4E8C-42D6-8703-A09335F97997}.Debug|Any CPU.Build.0 = Debug|Any CPU {12A68549-4E8C-42D6-8703-A09335F97997}.Release|Any CPU.ActiveCfg = Release|Any CPU {12A68549-4E8C-42D6-8703-A09335F97997}.Release|Any CPU.Build.0 = Release|Any CPU {066F0DBD-C46C-4C20-AFEC-99829A172625}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {066F0DBD-C46C-4C20-AFEC-99829A172625}.Debug|Any CPU.Build.0 = Debug|Any CPU {066F0DBD-C46C-4C20-AFEC-99829A172625}.Release|Any CPU.ActiveCfg = Release|Any CPU {066F0DBD-C46C-4C20-AFEC-99829A172625}.Release|Any CPU.Build.0 = Release|Any CPU {3E7DEA65-317B-4F43-A25D-62F18D96CFD7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3E7DEA65-317B-4F43-A25D-62F18D96CFD7}.Debug|Any CPU.Build.0 = Debug|Any CPU {3E7DEA65-317B-4F43-A25D-62F18D96CFD7}.Release|Any CPU.ActiveCfg = Release|Any CPU {3E7DEA65-317B-4F43-A25D-62F18D96CFD7}.Release|Any CPU.Build.0 = Release|Any CPU {21A01C2D-2501-4619-8144-48977DD22D9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {21A01C2D-2501-4619-8144-48977DD22D9C}.Debug|Any CPU.Build.0 = Debug|Any CPU {21A01C2D-2501-4619-8144-48977DD22D9C}.Release|Any CPU.ActiveCfg = Release|Any CPU {21A01C2D-2501-4619-8144-48977DD22D9C}.Release|Any CPU.Build.0 = Release|Any CPU {14118347-ED06-4608-9C45-18228273C712}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {14118347-ED06-4608-9C45-18228273C712}.Debug|Any CPU.Build.0 = Debug|Any CPU {14118347-ED06-4608-9C45-18228273C712}.Release|Any CPU.ActiveCfg = Release|Any CPU {14118347-ED06-4608-9C45-18228273C712}.Release|Any CPU.Build.0 = Release|Any CPU {5F8D2414-064A-4B3A-9B42-8E2A04246BE5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5F8D2414-064A-4B3A-9B42-8E2A04246BE5}.Debug|Any CPU.Build.0 = Debug|Any CPU {5F8D2414-064A-4B3A-9B42-8E2A04246BE5}.Release|Any CPU.ActiveCfg = Release|Any CPU {5F8D2414-064A-4B3A-9B42-8E2A04246BE5}.Release|Any CPU.Build.0 = Release|Any CPU {21B239D0-D144-430F-A394-C066D58EE267}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {21B239D0-D144-430F-A394-C066D58EE267}.Debug|Any CPU.Build.0 = Debug|Any CPU {21B239D0-D144-430F-A394-C066D58EE267}.Release|Any CPU.ActiveCfg = Release|Any CPU {21B239D0-D144-430F-A394-C066D58EE267}.Release|Any CPU.Build.0 = Release|Any CPU {57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C}.Debug|Any CPU.Build.0 = Debug|Any CPU {57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C}.Release|Any CPU.ActiveCfg = Release|Any CPU {57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C}.Release|Any CPU.Build.0 = Release|Any CPU {15FEBD1B-55CE-4EBD-85E3-04898260A25B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {15FEBD1B-55CE-4EBD-85E3-04898260A25B}.Debug|Any CPU.Build.0 = Debug|Any CPU {15FEBD1B-55CE-4EBD-85E3-04898260A25B}.Release|Any CPU.ActiveCfg = Release|Any CPU {15FEBD1B-55CE-4EBD-85E3-04898260A25B}.Release|Any CPU.Build.0 = Release|Any CPU {27B1EAE2-2E06-48EF-8A67-06D6FB3DC275}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {27B1EAE2-2E06-48EF-8A67-06D6FB3DC275}.Debug|Any CPU.Build.0 = Debug|Any CPU {27B1EAE2-2E06-48EF-8A67-06D6FB3DC275}.Release|Any CPU.ActiveCfg = Release|Any CPU {27B1EAE2-2E06-48EF-8A67-06D6FB3DC275}.Release|Any CPU.Build.0 = Release|Any CPU {E0756C89-603F-4B48-8E64-1D53E62654C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E0756C89-603F-4B48-8E64-1D53E62654C8}.Debug|Any CPU.Build.0 = Debug|Any CPU {E0756C89-603F-4B48-8E64-1D53E62654C8}.Release|Any CPU.ActiveCfg = Release|Any CPU {E0756C89-603F-4B48-8E64-1D53E62654C8}.Release|Any CPU.Build.0 = Release|Any CPU {7F8057D9-F70F-4EA7-BD64-AB2D0DD8057B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7F8057D9-F70F-4EA7-BD64-AB2D0DD8057B}.Debug|Any CPU.Build.0 = Debug|Any CPU {7F8057D9-F70F-4EA7-BD64-AB2D0DD8057B}.Release|Any CPU.ActiveCfg = Release|Any CPU {7F8057D9-F70F-4EA7-BD64-AB2D0DD8057B}.Release|Any CPU.Build.0 = Release|Any CPU {2483917E-7024-4D10-99C6-2BEF338FF53B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2483917E-7024-4D10-99C6-2BEF338FF53B}.Debug|Any CPU.Build.0 = Debug|Any CPU {2483917E-7024-4D10-99C6-2BEF338FF53B}.Release|Any CPU.ActiveCfg = Release|Any CPU {2483917E-7024-4D10-99C6-2BEF338FF53B}.Release|Any CPU.Build.0 = Release|Any CPU {8A02AFAF-F622-4E3E-9E1A-8CFDACC7C7E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8A02AFAF-F622-4E3E-9E1A-8CFDACC7C7E1}.Debug|Any CPU.Build.0 = Debug|Any CPU {8A02AFAF-F622-4E3E-9E1A-8CFDACC7C7E1}.Release|Any CPU.ActiveCfg = Release|Any CPU {8A02AFAF-F622-4E3E-9E1A-8CFDACC7C7E1}.Release|Any CPU.Build.0 = Release|Any CPU {6D407402-CC4A-4125-9B00-C70562A636A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6D407402-CC4A-4125-9B00-C70562A636A5}.Debug|Any CPU.Build.0 = Debug|Any CPU {6D407402-CC4A-4125-9B00-C70562A636A5}.Release|Any CPU.ActiveCfg = Release|Any CPU {6D407402-CC4A-4125-9B00-C70562A636A5}.Release|Any CPU.Build.0 = Release|Any CPU {706CFC25-B6E0-4DAA-BCC4-F6FAAFEEDF87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {706CFC25-B6E0-4DAA-BCC4-F6FAAFEEDF87}.Debug|Any CPU.Build.0 = Debug|Any CPU {706CFC25-B6E0-4DAA-BCC4-F6FAAFEEDF87}.Release|Any CPU.ActiveCfg = Release|Any CPU {706CFC25-B6E0-4DAA-BCC4-F6FAAFEEDF87}.Release|Any CPU.Build.0 = Release|Any CPU {E9211052-7700-4A2F-B1AE-34FD5CCAB8AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E9211052-7700-4A2F-B1AE-34FD5CCAB8AF}.Debug|Any CPU.Build.0 = Debug|Any CPU {E9211052-7700-4A2F-B1AE-34FD5CCAB8AF}.Release|Any CPU.ActiveCfg = Release|Any CPU {E9211052-7700-4A2F-B1AE-34FD5CCAB8AF}.Release|Any CPU.Build.0 = Release|Any CPU {9B25E472-DF94-4E24-9F5D-E487CE5A91FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9B25E472-DF94-4E24-9F5D-E487CE5A91FB}.Debug|Any CPU.Build.0 = Debug|Any CPU {9B25E472-DF94-4E24-9F5D-E487CE5A91FB}.Release|Any CPU.ActiveCfg = Release|Any CPU {9B25E472-DF94-4E24-9F5D-E487CE5A91FB}.Release|Any CPU.Build.0 = Release|Any CPU {432F4461-E198-44AA-8022-9E8C06A17C93}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {432F4461-E198-44AA-8022-9E8C06A17C93}.Debug|Any CPU.Build.0 = Debug|Any CPU {432F4461-E198-44AA-8022-9E8C06A17C93}.Release|Any CPU.ActiveCfg = Release|Any CPU {432F4461-E198-44AA-8022-9E8C06A17C93}.Release|Any CPU.Build.0 = Release|Any CPU {321F9FED-AACC-42CB-93E5-541D79E099E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {321F9FED-AACC-42CB-93E5-541D79E099E8}.Debug|Any CPU.Build.0 = Debug|Any CPU {321F9FED-AACC-42CB-93E5-541D79E099E8}.Release|Any CPU.ActiveCfg = Release|Any CPU {321F9FED-AACC-42CB-93E5-541D79E099E8}.Release|Any CPU.Build.0 = Release|Any CPU {FDBFBB64-5980-41C2-9E3E-FB8E2F700A5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FDBFBB64-5980-41C2-9E3E-FB8E2F700A5C}.Debug|Any CPU.Build.0 = Debug|Any CPU {FDBFBB64-5980-41C2-9E3E-FB8E2F700A5C}.Release|Any CPU.ActiveCfg = Release|Any CPU {FDBFBB64-5980-41C2-9E3E-FB8E2F700A5C}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {A4C99B85-765C-4C65-9C2A-BB609AAB09E6} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {1EE8CAD3-55F9-4D91-96B2-084641DA9A6C} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {9508F118-F62E-4C16-A6F4-7C3B56E166AD} = {E35DA3D1-16C0-4318-9187-6B664F12A870} {F5CE416E-B906-41D2-80B9-0078E887A3F6} = {E35DA3D1-16C0-4318-9187-6B664F12A870} {4B45CA0C-03A0-400F-B454-3D4BCB16AF38} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {B501A547-C911-4A05-AC6E-274A50DFF30E} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {50D26304-0961-4A51-ABF6-6CAD1A56D203} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {4462B57A-7245-4146-B504-D46FDE762948} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {1AF3672A-C5F1-4604-B6AB-D98C4DE9C3B1} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {B2C33A93-DB30-4099-903E-77D75C4C3F45} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {28026D16-EB0C-40B0-BDA7-11CAA2B97CCC} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {50D26304-0961-4A51-ABF6-6CAD1A56D202} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {7FE6B002-89D8-4298-9B1B-0B5C247DD1FD} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {4371944A-D3BA-4B5B-8285-82E5FFC6D1F9} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {4371944A-D3BA-4B5B-8285-82E5FFC6D1F8} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {E3B32027-3362-41DF-9172-4D3B623F42A5} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {190CE348-596E-435A-9E5B-12A689F9FC29} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {9C9DABA4-0E72-4469-ADF1-4991F3CA572A} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {BF180BD2-4FB7-4252-A7EC-A00E0C7A028A} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {BDA5D613-596D-4B61-837C-63554151C8F5} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {91F6F646-4F6E-449A-9AB4-2986348F329D} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {AFDE6BEA-5038-4A4A-A88E-DBD2E4088EED} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {02459936-CD2C-4F61-B671-5C518F2A3DDC} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {288089C5-8721-458E-BE3E-78990DAB5E2E} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {288089C5-8721-458E-BE3E-78990DAB5E2D} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {D0A79850-B32A-45E5-9FD5-D43CB345867A} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {6AA96934-D6B7-4CC8-990D-DB6B9DD56E34} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {909B656F-6095-4AC2-A5AB-C3F032315C45} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {D0BC9BE7-24F6-40CA-8DC6-FCB93BD44B34} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {FCFA8808-A1B6-48CC-A1EA-0B8CA8AEDA8E} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {E58EE9D7-1239-4961-A0C1-F9EC3952C4C1} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {1DFEA9C5-973C-4179-9B1B-0F32288E1EF2} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {AD6F474E-E6D4-4217-91F3-B7AF1BE31CCC} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {1A3941F1-1E1F-4EF7-8064-7729C4C2E2AA} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {CCBD3438-3E84-40A9-83AD-533F23BCFCA5} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {C1930979-C824-496B-A630-70F5369A636F} = {3CDEA9FB-CD44-4AB4-98A8-5537AAA2169B} {D73ADF7D-2C1C-42AE-B2AB-EDC9497E4B71} = {3CDEA9FB-CD44-4AB4-98A8-5537AAA2169B} {7AD4FE65-9A30-41A6-8004-AA8F89BCB7F3} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {2DAE4406-7A89-4B5F-95C3-BC5472CE47CE} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {2DAE4406-7A89-4B5F-95C3-BC5422CE47CE} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {ABC7262E-1053-49F3-B846-E3091BB92E8C} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {12A68549-4E8C-42D6-8703-A09335F97997} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {066F0DBD-C46C-4C20-AFEC-99829A172625} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {3E7DEA65-317B-4F43-A25D-62F18D96CFD7} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {21A01C2D-2501-4619-8144-48977DD22D9C} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {14118347-ED06-4608-9C45-18228273C712} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {5F8D2414-064A-4B3A-9B42-8E2A04246BE5} = {D9591377-7868-4D64-9314-83E0C92A871B} {21B239D0-D144-430F-A394-C066D58EE267} = {D9591377-7868-4D64-9314-83E0C92A871B} {57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C} = {D9591377-7868-4D64-9314-83E0C92A871B} {54E08BF5-F819-404F-A18D-0AB9EA81EA04} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {E8F0BAA5-7327-43D1-9A51-644E81AE55F1} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {15FEBD1B-55CE-4EBD-85E3-04898260A25B} = {274B96B7-F815-47E3-9CA4-4024A57A478F} {27B1EAE2-2E06-48EF-8A67-06D6FB3DC275} = {274B96B7-F815-47E3-9CA4-4024A57A478F} {E0756C89-603F-4B48-8E64-1D53E62654C8} = {274B96B7-F815-47E3-9CA4-4024A57A478F} {7F8057D9-F70F-4EA7-BD64-AB2D0DD8057B} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {2483917E-7024-4D10-99C6-2BEF338FF53B} = {274B96B7-F815-47E3-9CA4-4024A57A478F} {8A02AFAF-F622-4E3E-9E1A-8CFDACC7C7E1} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {6D407402-CC4A-4125-9B00-C70562A636A5} = {274B96B7-F815-47E3-9CA4-4024A57A478F} {706CFC25-B6E0-4DAA-BCC4-F6FAAFEEDF87} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {E9211052-7700-4A2F-B1AE-34FD5CCAB8AF} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {9B25E472-DF94-4E24-9F5D-E487CE5A91FB} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {E919DD77-34F8-4F57-8058-4D3FF4C2B241} = {3CDEA9FB-CD44-4AB4-98A8-5537AAA2169B} {321F9FED-AACC-42CB-93E5-541D79E099E8} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {FDBFBB64-5980-41C2-9E3E-FB8E2F700A5C} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {6F599E08-A9EA-4FAA-897F-5D824B0210E6} EndGlobalSection EndGlobal
Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.29519.87 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.UnitTests", "src\Compilers\Core\CodeAnalysisTest\Microsoft.CodeAnalysis.UnitTests.csproj", "{A4C99B85-765C-4C65-9C2A-BB609AAB09E6}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis", "src\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj", "{1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VBCSCompiler", "src\Compilers\Server\VBCSCompiler\VBCSCompiler.csproj", "{9508F118-F62E-4C16-A6F4-7C3B56E166AD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VBCSCompiler.UnitTests", "src\Compilers\Server\VBCSCompilerTests\VBCSCompiler.UnitTests.csproj", "{F5CE416E-B906-41D2-80B9-0078E887A3F6}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{A41D1B99-F489-4C43-BBDF-96D61B19A6B9}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CSharp", "CSharp", "{32A48625-F0AD-419D-828B-A50BDABA38EA}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "csc", "src\Compilers\CSharp\csc\csc.csproj", "{4B45CA0C-03A0-400F-B454-3D4BCB16AF38}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp", "src\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj", "{B501A547-C911-4A05-AC6E-274A50DFF30E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests", "src\Compilers\CSharp\Test\CommandLine\Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests.csproj", "{50D26304-0961-4A51-ABF6-6CAD1A56D203}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Emit.UnitTests", "src\Compilers\CSharp\Test\Emit\Microsoft.CodeAnalysis.CSharp.Emit.UnitTests.csproj", "{4462B57A-7245-4146-B504-D46FDE762948}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests", "src\Compilers\CSharp\Test\IOperation\Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests.csproj", "{1AF3672A-C5F1-4604-B6AB-D98C4DE9C3B1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests", "src\Compilers\CSharp\Test\Semantic\Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.csproj", "{B2C33A93-DB30-4099-903E-77D75C4C3F45}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests", "src\Compilers\CSharp\Test\Symbol\Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests.csproj", "{28026D16-EB0C-40B0-BDA7-11CAA2B97CCC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Syntax.UnitTests", "src\Compilers\CSharp\Test\Syntax\Microsoft.CodeAnalysis.CSharp.Syntax.UnitTests.csproj", "{50D26304-0961-4A51-ABF6-6CAD1A56D202}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "VisualBasic", "VisualBasic", "{C65C6143-BED3-46E6-869E-9F0BE6E84C37}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Compiler.Test.Resources", "src\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj", "{7FE6B002-89D8-4298-9B1B-0B5C247DD1FD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Test.Utilities", "src\Compilers\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj", "{4371944A-D3BA-4B5B-8285-82E5FFC6D1F9}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Test.Utilities", "src\Compilers\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj", "{4371944A-D3BA-4B5B-8285-82E5FFC6D1F8}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic", "src\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj", "{2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests", "src\Compilers\VisualBasic\Test\CommandLine\Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests.vbproj", "{E3B32027-3362-41DF-9172-4D3B623F42A5}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests", "src\Compilers\VisualBasic\Test\Emit\Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests.vbproj", "{190CE348-596E-435A-9E5B-12A689F9FC29}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Roslyn.Compilers.VisualBasic.IOperation.UnitTests", "src\Compilers\VisualBasic\Test\IOperation\Roslyn.Compilers.VisualBasic.IOperation.UnitTests.vbproj", "{9C9DABA4-0E72-4469-ADF1-4991F3CA572A}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests", "src\Compilers\VisualBasic\Test\Semantic\Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests.vbproj", "{BF180BD2-4FB7-4252-A7EC-A00E0C7A028A}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests", "src\Compilers\VisualBasic\Test\Symbol\Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests.vbproj", "{BDA5D613-596D-4B61-837C-63554151C8F5}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests", "src\Compilers\VisualBasic\Test\Syntax\Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests.vbproj", "{91F6F646-4F6E-449A-9AB4-2986348F329D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Roslyn.Test.PdbUtilities", "src\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj", "{AFDE6BEA-5038-4A4A-A88E-DBD2E4088EED}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CompilersBoundTreeGenerator", "src\Tools\Source\CompilerGeneratorTools\Source\BoundTreeGenerator\CompilersBoundTreeGenerator.csproj", "{02459936-CD2C-4F61-B671-5C518F2A3DDC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharpErrorFactsGenerator", "src\Tools\Source\CompilerGeneratorTools\Source\CSharpErrorFactsGenerator\CSharpErrorFactsGenerator.csproj", "{288089C5-8721-458E-BE3E-78990DAB5E2E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharpSyntaxGenerator", "src\Tools\Source\CompilerGeneratorTools\Source\CSharpSyntaxGenerator\CSharpSyntaxGenerator.csproj", "{288089C5-8721-458E-BE3E-78990DAB5E2D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CompilersIOperationGenerator", "src\Tools\Source\CompilerGeneratorTools\Source\IOperationGenerator\CompilersIOperationGenerator.csproj", "{D0A79850-B32A-45E5-9FD5-D43CB345867A}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "VisualBasicSyntaxGenerator", "src\Tools\Source\CompilerGeneratorTools\Source\VisualBasicSyntaxGenerator\VisualBasicSyntaxGenerator.vbproj", "{6AA96934-D6B7-4CC8-990D-DB6B9DD56E34}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "VisualBasicErrorFactsGenerator", "src\Tools\Source\CompilerGeneratorTools\Source\VisualBasicErrorFactsGenerator\VisualBasicErrorFactsGenerator.vbproj", "{909B656F-6095-4AC2-A5AB-C3F032315C45}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "AnalyzerDriver", "src\Compilers\Core\AnalyzerDriver\AnalyzerDriver.shproj", "{D0BC9BE7-24F6-40CA-8DC6-FCB93BD44B34}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.WinRT.UnitTests", "src\Compilers\CSharp\Test\WinRT\Microsoft.CodeAnalysis.CSharp.WinRT.UnitTests.csproj", "{FCFA8808-A1B6-48CC-A1EA-0B8CA8AEDA8E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "vbc", "src\Compilers\VisualBasic\vbc\vbc.csproj", "{E58EE9D7-1239-4961-A0C1-F9EC3952C4C1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Build.Tasks.CodeAnalysis.UnitTests", "src\Compilers\Core\MSBuildTaskTests\Microsoft.Build.Tasks.CodeAnalysis.UnitTests.csproj", "{1DFEA9C5-973C-4179-9B1B-0F32288E1EF2}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Server", "Server", "{E35DA3D1-16C0-4318-9187-6B664F12A870}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "CommandLine", "src\Compilers\Core\CommandLine\CommandLine.shproj", "{AD6F474E-E6D4-4217-91F3-B7AF1BE31CCC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RunTests", "src\Tools\Source\RunTests\RunTests.csproj", "{1A3941F1-1E1F-4EF7-8064-7729C4C2E2AA}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Test.Utilities", "src\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj", "{CCBD3438-3E84-40A9-83AD-533F23BCFCA5}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Dependencies", "Dependencies", "{3CDEA9FB-CD44-4AB4-98A8-5537AAA2169B}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Microsoft.CodeAnalysis.PooledObjects", "src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.shproj", "{C1930979-C824-496B-A630-70F5369A636F}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Microsoft.CodeAnalysis.Debugging", "src\Dependencies\CodeAnalysis.Debugging\Microsoft.CodeAnalysis.Debugging.shproj", "{D73ADF7D-2C1C-42AE-B2AB-EDC9497E4B71}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Build.Tasks.CodeAnalysis", "src\Compilers\Core\MSBuildTask\Microsoft.Build.Tasks.CodeAnalysis.csproj", "{7AD4FE65-9A30-41A6-8004-AA8F89BCB7F3}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Scripting.UnitTests", "src\Scripting\CoreTest\Microsoft.CodeAnalysis.Scripting.UnitTests.csproj", "{2DAE4406-7A89-4B5F-95C3-BC5472CE47CE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests", "src\Scripting\CSharpTest\Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.csproj", "{2DAE4406-7A89-4B5F-95C3-BC5422CE47CE}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests", "src\Scripting\VisualBasicTest\Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests.vbproj", "{ABC7262E-1053-49F3-B846-E3091BB92E8C}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Scripting", "Scripting", "{3FF38FD4-DF16-44B0-924F-0D5AE155495B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Scripting", "src\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj", "{12A68549-4E8C-42D6-8703-A09335F97997}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Scripting", "src\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj", "{066F0DBD-C46C-4C20-AFEC-99829A172625}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Scripting", "src\Scripting\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj", "{3E7DEA65-317B-4F43-A25D-62F18D96CFD7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Scripting.TestUtilities", "src\Scripting\CoreTestUtilities\Microsoft.CodeAnalysis.Scripting.TestUtilities.csproj", "{21A01C2D-2501-4619-8144-48977DD22D9C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "csi", "src\Interactive\csi\csi.csproj", "{14118347-ED06-4608-9C45-18228273C712}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Workspace", "Workspace", "{D9591377-7868-4D64-9314-83E0C92A871B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Workspaces", "src\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj", "{5F8D2414-064A-4B3A-9B42-8E2A04246BE5}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CSharp.Workspaces", "src\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj", "{21B239D0-D144-430F-A394-C066D58EE267}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Microsoft.CodeAnalysis.VisualBasic.Workspaces", "src\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj", "{57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "CSharpAnalyzerDriver", "src\Compilers\CSharp\CSharpAnalyzerDriver\CSharpAnalyzerDriver.shproj", "{54E08BF5-F819-404F-A18D-0AB9EA81EA04}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "BasicAnalyzerDriver", "src\Compilers\VisualBasic\BasicAnalyzerDriver\BasicAnalyzerDriver.shproj", "{E8F0BAA5-7327-43D1-9A51-644E81AE55F1}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Packages", "Packages", "{274B96B7-F815-47E3-9CA4-4024A57A478F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.NETCore.Compilers.Package", "src\NuGet\Microsoft.NETCore.Compilers\Microsoft.NETCore.Compilers.Package.csproj", "{15FEBD1B-55CE-4EBD-85E3-04898260A25B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Net.Compilers.Package", "src\NuGet\Microsoft.Net.Compilers\Microsoft.Net.Compilers.Package.csproj", "{27B1EAE2-2E06-48EF-8A67-06D6FB3DC275}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Compilers.Package", "src\NuGet\Microsoft.CodeAnalysis.Compilers.Package.csproj", "{E0756C89-603F-4B48-8E64-1D53E62654C8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Scripting.Package", "src\NuGet\Microsoft.CodeAnalysis.Scripting.Package.csproj", "{7F8057D9-F70F-4EA7-BD64-AB2D0DD8057B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Package", "src\NuGet\Microsoft.CodeAnalysis.Package.csproj", "{2483917E-7024-4D10-99C6-2BEF338FF53B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BuildBoss", "src\Tools\BuildBoss\BuildBoss.csproj", "{8A02AFAF-F622-4E3E-9E1A-8CFDACC7C7E1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Net.Compilers.Toolset.Package", "src\NuGet\Microsoft.Net.Compilers.Toolset\Microsoft.Net.Compilers.Toolset.Package.csproj", "{6D407402-CC4A-4125-9B00-C70562A636A5}" EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "vbi", "src\Interactive\vbi\vbi.vbproj", "{706CFC25-B6E0-4DAA-BCC4-F6FAAFEEDF87}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BuildValidator", "src\Tools\BuildValidator\BuildValidator.csproj", "{E9211052-7700-4A2F-B1AE-34FD5CCAB8AF}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PrepareTests", "src\Tools\PrepareTests\PrepareTests.csproj", "{9B25E472-DF94-4E24-9F5D-E487CE5A91FB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeStyleConfigFileGenerator", "src\CodeStyle\Tools\CodeStyleConfigFileGenerator.csproj", "{432F4461-E198-44AA-8022-9E8C06A17C93}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Microsoft.CodeAnalysis.Collections", "src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.shproj", "{E919DD77-34F8-4F57-8058-4D3FF4C2B241}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Rebuild", "src\Compilers\Core\Rebuild\Microsoft.CodeAnalysis.Rebuild.csproj", "{321F9FED-AACC-42CB-93E5-541D79E099E8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Rebuild.UnitTests", "src\Compilers\Core\RebuildTest\Microsoft.CodeAnalysis.Rebuild.UnitTests.csproj", "{FDBFBB64-5980-41C2-9E3E-FB8E2F700A5C}" EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution src\Compilers\Core\AnalyzerDriver\AnalyzerDriver.projitems*{1ee8cad3-55f9-4d91-96b2-084641da9a6c}*SharedItemsImports = 5 src\Dependencies\CodeAnalysis.Debugging\Microsoft.CodeAnalysis.Debugging.projitems*{1ee8cad3-55f9-4d91-96b2-084641da9a6c}*SharedItemsImports = 5 src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{1ee8cad3-55f9-4d91-96b2-084641da9a6c}*SharedItemsImports = 5 src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{1ee8cad3-55f9-4d91-96b2-084641da9a6c}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\CSharp\CSharpCompilerExtensions.projitems*{21b239d0-d144-430f-a394-c066d58ee267}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Workspace\CSharp\CSharpWorkspaceExtensions.projitems*{21b239d0-d144-430f-a394-c066d58ee267}*SharedItemsImports = 5 src\Compilers\VisualBasic\BasicAnalyzerDriver\BasicAnalyzerDriver.projitems*{2523d0e6-df32-4a3e-8ae0-a19bffae2ef6}*SharedItemsImports = 5 src\Compilers\Core\CommandLine\CommandLine.projitems*{4b45ca0c-03a0-400f-b454-3d4bcb16af38}*SharedItemsImports = 5 src\Compilers\CSharp\CSharpAnalyzerDriver\CSharpAnalyzerDriver.projitems*{54e08bf5-f819-404f-a18d-0ab9ea81ea04}*SharedItemsImports = 13 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\VisualBasic\VisualBasicCompilerExtensions.projitems*{57ca988d-f010-4bf2-9a2e-07d6dcd2ff2c}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Workspace\VisualBasic\VisualBasicWorkspaceExtensions.projitems*{57ca988d-f010-4bf2-9a2e-07d6dcd2ff2c}*SharedItemsImports = 5 src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{5f8d2414-064a-4b3a-9b42-8e2a04246be5}*SharedItemsImports = 5 src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{5f8d2414-064a-4b3a-9b42-8e2a04246be5}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\CompilerExtensions.projitems*{5f8d2414-064a-4b3a-9b42-8e2a04246be5}*SharedItemsImports = 5 src\Workspaces\SharedUtilitiesAndExtensions\Workspace\Core\WorkspaceExtensions.projitems*{5f8d2414-064a-4b3a-9b42-8e2a04246be5}*SharedItemsImports = 5 src\Compilers\Core\CommandLine\CommandLine.projitems*{7ad4fe65-9a30-41a6-8004-aa8f89bcb7f3}*SharedItemsImports = 5 src\Compilers\Core\CommandLine\CommandLine.projitems*{9508f118-f62e-4c16-a6f4-7c3b56e166ad}*SharedItemsImports = 5 src\Compilers\Core\CommandLine\CommandLine.projitems*{ad6f474e-e6d4-4217-91f3-b7af1be31ccc}*SharedItemsImports = 13 src\Compilers\CSharp\CSharpAnalyzerDriver\CSharpAnalyzerDriver.projitems*{b501a547-c911-4a05-ac6e-274a50dff30e}*SharedItemsImports = 5 src\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{c1930979-c824-496b-a630-70f5369a636f}*SharedItemsImports = 13 src\Compilers\Core\AnalyzerDriver\AnalyzerDriver.projitems*{d0bc9be7-24f6-40ca-8dc6-fcb93bd44b34}*SharedItemsImports = 13 src\Dependencies\CodeAnalysis.Debugging\Microsoft.CodeAnalysis.Debugging.projitems*{d73adf7d-2c1c-42ae-b2ab-edc9497e4b71}*SharedItemsImports = 13 src\Compilers\Core\CommandLine\CommandLine.projitems*{e58ee9d7-1239-4961-a0c1-f9ec3952c4c1}*SharedItemsImports = 5 src\Compilers\VisualBasic\BasicAnalyzerDriver\BasicAnalyzerDriver.projitems*{e8f0baa5-7327-43d1-9a51-644e81ae55f1}*SharedItemsImports = 13 src\Dependencies\Collections\Microsoft.CodeAnalysis.Collections.projitems*{e919dd77-34f8-4f57-8058-4d3ff4c2b241}*SharedItemsImports = 13 EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {A4C99B85-765C-4C65-9C2A-BB609AAB09E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A4C99B85-765C-4C65-9C2A-BB609AAB09E6}.Debug|Any CPU.Build.0 = Debug|Any CPU {A4C99B85-765C-4C65-9C2A-BB609AAB09E6}.Release|Any CPU.ActiveCfg = Release|Any CPU {A4C99B85-765C-4C65-9C2A-BB609AAB09E6}.Release|Any CPU.Build.0 = Release|Any CPU {1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}.Debug|Any CPU.Build.0 = Debug|Any CPU {1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}.Release|Any CPU.ActiveCfg = Release|Any CPU {1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}.Release|Any CPU.Build.0 = Release|Any CPU {9508F118-F62E-4C16-A6F4-7C3B56E166AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9508F118-F62E-4C16-A6F4-7C3B56E166AD}.Debug|Any CPU.Build.0 = Debug|Any CPU {9508F118-F62E-4C16-A6F4-7C3B56E166AD}.Release|Any CPU.ActiveCfg = Release|Any CPU {9508F118-F62E-4C16-A6F4-7C3B56E166AD}.Release|Any CPU.Build.0 = Release|Any CPU {F5CE416E-B906-41D2-80B9-0078E887A3F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F5CE416E-B906-41D2-80B9-0078E887A3F6}.Debug|Any CPU.Build.0 = Debug|Any CPU {F5CE416E-B906-41D2-80B9-0078E887A3F6}.Release|Any CPU.ActiveCfg = Release|Any CPU {F5CE416E-B906-41D2-80B9-0078E887A3F6}.Release|Any CPU.Build.0 = Release|Any CPU {4B45CA0C-03A0-400F-B454-3D4BCB16AF38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B45CA0C-03A0-400F-B454-3D4BCB16AF38}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B45CA0C-03A0-400F-B454-3D4BCB16AF38}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B45CA0C-03A0-400F-B454-3D4BCB16AF38}.Release|Any CPU.Build.0 = Release|Any CPU {B501A547-C911-4A05-AC6E-274A50DFF30E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B501A547-C911-4A05-AC6E-274A50DFF30E}.Debug|Any CPU.Build.0 = Debug|Any CPU {B501A547-C911-4A05-AC6E-274A50DFF30E}.Release|Any CPU.ActiveCfg = Release|Any CPU {B501A547-C911-4A05-AC6E-274A50DFF30E}.Release|Any CPU.Build.0 = Release|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D203}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D203}.Debug|Any CPU.Build.0 = Debug|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D203}.Release|Any CPU.ActiveCfg = Release|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D203}.Release|Any CPU.Build.0 = Release|Any CPU {4462B57A-7245-4146-B504-D46FDE762948}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4462B57A-7245-4146-B504-D46FDE762948}.Debug|Any CPU.Build.0 = Debug|Any CPU {4462B57A-7245-4146-B504-D46FDE762948}.Release|Any CPU.ActiveCfg = Release|Any CPU {4462B57A-7245-4146-B504-D46FDE762948}.Release|Any CPU.Build.0 = Release|Any CPU {1AF3672A-C5F1-4604-B6AB-D98C4DE9C3B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1AF3672A-C5F1-4604-B6AB-D98C4DE9C3B1}.Debug|Any CPU.Build.0 = Debug|Any CPU {1AF3672A-C5F1-4604-B6AB-D98C4DE9C3B1}.Release|Any CPU.ActiveCfg = Release|Any CPU {1AF3672A-C5F1-4604-B6AB-D98C4DE9C3B1}.Release|Any CPU.Build.0 = Release|Any CPU {B2C33A93-DB30-4099-903E-77D75C4C3F45}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B2C33A93-DB30-4099-903E-77D75C4C3F45}.Debug|Any CPU.Build.0 = Debug|Any CPU {B2C33A93-DB30-4099-903E-77D75C4C3F45}.Release|Any CPU.ActiveCfg = Release|Any CPU {B2C33A93-DB30-4099-903E-77D75C4C3F45}.Release|Any CPU.Build.0 = Release|Any CPU {28026D16-EB0C-40B0-BDA7-11CAA2B97CCC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {28026D16-EB0C-40B0-BDA7-11CAA2B97CCC}.Debug|Any CPU.Build.0 = Debug|Any CPU {28026D16-EB0C-40B0-BDA7-11CAA2B97CCC}.Release|Any CPU.ActiveCfg = Release|Any CPU {28026D16-EB0C-40B0-BDA7-11CAA2B97CCC}.Release|Any CPU.Build.0 = Release|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D202}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D202}.Debug|Any CPU.Build.0 = Debug|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D202}.Release|Any CPU.ActiveCfg = Release|Any CPU {50D26304-0961-4A51-ABF6-6CAD1A56D202}.Release|Any CPU.Build.0 = Release|Any CPU {7FE6B002-89D8-4298-9B1B-0B5C247DD1FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7FE6B002-89D8-4298-9B1B-0B5C247DD1FD}.Debug|Any CPU.Build.0 = Debug|Any CPU {7FE6B002-89D8-4298-9B1B-0B5C247DD1FD}.Release|Any CPU.ActiveCfg = Release|Any CPU {7FE6B002-89D8-4298-9B1B-0B5C247DD1FD}.Release|Any CPU.Build.0 = Release|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F9}.Release|Any CPU.Build.0 = Release|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F8}.Debug|Any CPU.Build.0 = Debug|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F8}.Release|Any CPU.ActiveCfg = Release|Any CPU {4371944A-D3BA-4B5B-8285-82E5FFC6D1F8}.Release|Any CPU.Build.0 = Release|Any CPU {2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6}.Debug|Any CPU.Build.0 = Debug|Any CPU {2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6}.Release|Any CPU.ActiveCfg = Release|Any CPU {2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6}.Release|Any CPU.Build.0 = Release|Any CPU {E3B32027-3362-41DF-9172-4D3B623F42A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E3B32027-3362-41DF-9172-4D3B623F42A5}.Debug|Any CPU.Build.0 = Debug|Any CPU {E3B32027-3362-41DF-9172-4D3B623F42A5}.Release|Any CPU.ActiveCfg = Release|Any CPU {E3B32027-3362-41DF-9172-4D3B623F42A5}.Release|Any CPU.Build.0 = Release|Any CPU {190CE348-596E-435A-9E5B-12A689F9FC29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {190CE348-596E-435A-9E5B-12A689F9FC29}.Debug|Any CPU.Build.0 = Debug|Any CPU {190CE348-596E-435A-9E5B-12A689F9FC29}.Release|Any CPU.ActiveCfg = Release|Any CPU {190CE348-596E-435A-9E5B-12A689F9FC29}.Release|Any CPU.Build.0 = Release|Any CPU {9C9DABA4-0E72-4469-ADF1-4991F3CA572A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9C9DABA4-0E72-4469-ADF1-4991F3CA572A}.Debug|Any CPU.Build.0 = Debug|Any CPU {9C9DABA4-0E72-4469-ADF1-4991F3CA572A}.Release|Any CPU.ActiveCfg = Release|Any CPU {9C9DABA4-0E72-4469-ADF1-4991F3CA572A}.Release|Any CPU.Build.0 = Release|Any CPU {BF180BD2-4FB7-4252-A7EC-A00E0C7A028A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BF180BD2-4FB7-4252-A7EC-A00E0C7A028A}.Debug|Any CPU.Build.0 = Debug|Any CPU {BF180BD2-4FB7-4252-A7EC-A00E0C7A028A}.Release|Any CPU.ActiveCfg = Release|Any CPU {BF180BD2-4FB7-4252-A7EC-A00E0C7A028A}.Release|Any CPU.Build.0 = Release|Any CPU {BDA5D613-596D-4B61-837C-63554151C8F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BDA5D613-596D-4B61-837C-63554151C8F5}.Debug|Any CPU.Build.0 = Debug|Any CPU {BDA5D613-596D-4B61-837C-63554151C8F5}.Release|Any CPU.ActiveCfg = Release|Any CPU {BDA5D613-596D-4B61-837C-63554151C8F5}.Release|Any CPU.Build.0 = Release|Any CPU {91F6F646-4F6E-449A-9AB4-2986348F329D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {91F6F646-4F6E-449A-9AB4-2986348F329D}.Debug|Any CPU.Build.0 = Debug|Any CPU {91F6F646-4F6E-449A-9AB4-2986348F329D}.Release|Any CPU.ActiveCfg = Release|Any CPU {91F6F646-4F6E-449A-9AB4-2986348F329D}.Release|Any CPU.Build.0 = Release|Any CPU {AFDE6BEA-5038-4A4A-A88E-DBD2E4088EED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AFDE6BEA-5038-4A4A-A88E-DBD2E4088EED}.Debug|Any CPU.Build.0 = Debug|Any CPU {AFDE6BEA-5038-4A4A-A88E-DBD2E4088EED}.Release|Any CPU.ActiveCfg = Release|Any CPU {AFDE6BEA-5038-4A4A-A88E-DBD2E4088EED}.Release|Any CPU.Build.0 = Release|Any CPU {02459936-CD2C-4F61-B671-5C518F2A3DDC}.Debug|Any CPU.ActiveCfg = Debug|x64 {02459936-CD2C-4F61-B671-5C518F2A3DDC}.Debug|Any CPU.Build.0 = Debug|x64 {02459936-CD2C-4F61-B671-5C518F2A3DDC}.Release|Any CPU.ActiveCfg = Release|x64 {02459936-CD2C-4F61-B671-5C518F2A3DDC}.Release|Any CPU.Build.0 = Release|x64 {288089C5-8721-458E-BE3E-78990DAB5E2E}.Debug|Any CPU.ActiveCfg = Debug|x64 {288089C5-8721-458E-BE3E-78990DAB5E2E}.Debug|Any CPU.Build.0 = Debug|x64 {288089C5-8721-458E-BE3E-78990DAB5E2E}.Release|Any CPU.ActiveCfg = Release|x64 {288089C5-8721-458E-BE3E-78990DAB5E2E}.Release|Any CPU.Build.0 = Release|x64 {288089C5-8721-458E-BE3E-78990DAB5E2D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {288089C5-8721-458E-BE3E-78990DAB5E2D}.Debug|Any CPU.Build.0 = Debug|Any CPU {288089C5-8721-458E-BE3E-78990DAB5E2D}.Release|Any CPU.ActiveCfg = Release|Any CPU {288089C5-8721-458E-BE3E-78990DAB5E2D}.Release|Any CPU.Build.0 = Release|Any CPU {D0A79850-B32A-45E5-9FD5-D43CB345867A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D0A79850-B32A-45E5-9FD5-D43CB345867A}.Debug|Any CPU.Build.0 = Debug|Any CPU {D0A79850-B32A-45E5-9FD5-D43CB345867A}.Release|Any CPU.ActiveCfg = Release|Any CPU {D0A79850-B32A-45E5-9FD5-D43CB345867A}.Release|Any CPU.Build.0 = Release|Any CPU {6AA96934-D6B7-4CC8-990D-DB6B9DD56E34}.Debug|Any CPU.ActiveCfg = Debug|x64 {6AA96934-D6B7-4CC8-990D-DB6B9DD56E34}.Debug|Any CPU.Build.0 = Debug|x64 {6AA96934-D6B7-4CC8-990D-DB6B9DD56E34}.Release|Any CPU.ActiveCfg = Release|x64 {6AA96934-D6B7-4CC8-990D-DB6B9DD56E34}.Release|Any CPU.Build.0 = Release|x64 {909B656F-6095-4AC2-A5AB-C3F032315C45}.Debug|Any CPU.ActiveCfg = Debug|x64 {909B656F-6095-4AC2-A5AB-C3F032315C45}.Debug|Any CPU.Build.0 = Debug|x64 {909B656F-6095-4AC2-A5AB-C3F032315C45}.Release|Any CPU.ActiveCfg = Release|x64 {909B656F-6095-4AC2-A5AB-C3F032315C45}.Release|Any CPU.Build.0 = Release|x64 {FCFA8808-A1B6-48CC-A1EA-0B8CA8AEDA8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FCFA8808-A1B6-48CC-A1EA-0B8CA8AEDA8E}.Debug|Any CPU.Build.0 = Debug|Any CPU {FCFA8808-A1B6-48CC-A1EA-0B8CA8AEDA8E}.Release|Any CPU.ActiveCfg = Release|Any CPU {FCFA8808-A1B6-48CC-A1EA-0B8CA8AEDA8E}.Release|Any CPU.Build.0 = Release|Any CPU {E58EE9D7-1239-4961-A0C1-F9EC3952C4C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E58EE9D7-1239-4961-A0C1-F9EC3952C4C1}.Debug|Any CPU.Build.0 = Debug|Any CPU {E58EE9D7-1239-4961-A0C1-F9EC3952C4C1}.Release|Any CPU.ActiveCfg = Release|Any CPU {E58EE9D7-1239-4961-A0C1-F9EC3952C4C1}.Release|Any CPU.Build.0 = Release|Any CPU {1DFEA9C5-973C-4179-9B1B-0F32288E1EF2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1DFEA9C5-973C-4179-9B1B-0F32288E1EF2}.Debug|Any CPU.Build.0 = Debug|Any CPU {1DFEA9C5-973C-4179-9B1B-0F32288E1EF2}.Release|Any CPU.ActiveCfg = Release|Any CPU {1DFEA9C5-973C-4179-9B1B-0F32288E1EF2}.Release|Any CPU.Build.0 = Release|Any CPU {1A3941F1-1E1F-4EF7-8064-7729C4C2E2AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1A3941F1-1E1F-4EF7-8064-7729C4C2E2AA}.Debug|Any CPU.Build.0 = Debug|Any CPU {1A3941F1-1E1F-4EF7-8064-7729C4C2E2AA}.Release|Any CPU.ActiveCfg = Release|Any CPU {1A3941F1-1E1F-4EF7-8064-7729C4C2E2AA}.Release|Any CPU.Build.0 = Release|Any CPU {CCBD3438-3E84-40A9-83AD-533F23BCFCA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CCBD3438-3E84-40A9-83AD-533F23BCFCA5}.Debug|Any CPU.Build.0 = Debug|Any CPU {CCBD3438-3E84-40A9-83AD-533F23BCFCA5}.Release|Any CPU.ActiveCfg = Release|Any CPU {CCBD3438-3E84-40A9-83AD-533F23BCFCA5}.Release|Any CPU.Build.0 = Release|Any CPU {7AD4FE65-9A30-41A6-8004-AA8F89BCB7F3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7AD4FE65-9A30-41A6-8004-AA8F89BCB7F3}.Debug|Any CPU.Build.0 = Debug|Any CPU {7AD4FE65-9A30-41A6-8004-AA8F89BCB7F3}.Release|Any CPU.ActiveCfg = Release|Any CPU {7AD4FE65-9A30-41A6-8004-AA8F89BCB7F3}.Release|Any CPU.Build.0 = Release|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5472CE47CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5472CE47CE}.Debug|Any CPU.Build.0 = Debug|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5472CE47CE}.Release|Any CPU.ActiveCfg = Release|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5472CE47CE}.Release|Any CPU.Build.0 = Release|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5422CE47CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5422CE47CE}.Debug|Any CPU.Build.0 = Debug|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5422CE47CE}.Release|Any CPU.ActiveCfg = Release|Any CPU {2DAE4406-7A89-4B5F-95C3-BC5422CE47CE}.Release|Any CPU.Build.0 = Release|Any CPU {ABC7262E-1053-49F3-B846-E3091BB92E8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ABC7262E-1053-49F3-B846-E3091BB92E8C}.Debug|Any CPU.Build.0 = Debug|Any CPU {ABC7262E-1053-49F3-B846-E3091BB92E8C}.Release|Any CPU.ActiveCfg = Release|Any CPU {ABC7262E-1053-49F3-B846-E3091BB92E8C}.Release|Any CPU.Build.0 = Release|Any CPU {12A68549-4E8C-42D6-8703-A09335F97997}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {12A68549-4E8C-42D6-8703-A09335F97997}.Debug|Any CPU.Build.0 = Debug|Any CPU {12A68549-4E8C-42D6-8703-A09335F97997}.Release|Any CPU.ActiveCfg = Release|Any CPU {12A68549-4E8C-42D6-8703-A09335F97997}.Release|Any CPU.Build.0 = Release|Any CPU {066F0DBD-C46C-4C20-AFEC-99829A172625}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {066F0DBD-C46C-4C20-AFEC-99829A172625}.Debug|Any CPU.Build.0 = Debug|Any CPU {066F0DBD-C46C-4C20-AFEC-99829A172625}.Release|Any CPU.ActiveCfg = Release|Any CPU {066F0DBD-C46C-4C20-AFEC-99829A172625}.Release|Any CPU.Build.0 = Release|Any CPU {3E7DEA65-317B-4F43-A25D-62F18D96CFD7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3E7DEA65-317B-4F43-A25D-62F18D96CFD7}.Debug|Any CPU.Build.0 = Debug|Any CPU {3E7DEA65-317B-4F43-A25D-62F18D96CFD7}.Release|Any CPU.ActiveCfg = Release|Any CPU {3E7DEA65-317B-4F43-A25D-62F18D96CFD7}.Release|Any CPU.Build.0 = Release|Any CPU {21A01C2D-2501-4619-8144-48977DD22D9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {21A01C2D-2501-4619-8144-48977DD22D9C}.Debug|Any CPU.Build.0 = Debug|Any CPU {21A01C2D-2501-4619-8144-48977DD22D9C}.Release|Any CPU.ActiveCfg = Release|Any CPU {21A01C2D-2501-4619-8144-48977DD22D9C}.Release|Any CPU.Build.0 = Release|Any CPU {14118347-ED06-4608-9C45-18228273C712}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {14118347-ED06-4608-9C45-18228273C712}.Debug|Any CPU.Build.0 = Debug|Any CPU {14118347-ED06-4608-9C45-18228273C712}.Release|Any CPU.ActiveCfg = Release|Any CPU {14118347-ED06-4608-9C45-18228273C712}.Release|Any CPU.Build.0 = Release|Any CPU {5F8D2414-064A-4B3A-9B42-8E2A04246BE5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5F8D2414-064A-4B3A-9B42-8E2A04246BE5}.Debug|Any CPU.Build.0 = Debug|Any CPU {5F8D2414-064A-4B3A-9B42-8E2A04246BE5}.Release|Any CPU.ActiveCfg = Release|Any CPU {5F8D2414-064A-4B3A-9B42-8E2A04246BE5}.Release|Any CPU.Build.0 = Release|Any CPU {21B239D0-D144-430F-A394-C066D58EE267}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {21B239D0-D144-430F-A394-C066D58EE267}.Debug|Any CPU.Build.0 = Debug|Any CPU {21B239D0-D144-430F-A394-C066D58EE267}.Release|Any CPU.ActiveCfg = Release|Any CPU {21B239D0-D144-430F-A394-C066D58EE267}.Release|Any CPU.Build.0 = Release|Any CPU {57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C}.Debug|Any CPU.Build.0 = Debug|Any CPU {57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C}.Release|Any CPU.ActiveCfg = Release|Any CPU {57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C}.Release|Any CPU.Build.0 = Release|Any CPU {15FEBD1B-55CE-4EBD-85E3-04898260A25B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {15FEBD1B-55CE-4EBD-85E3-04898260A25B}.Debug|Any CPU.Build.0 = Debug|Any CPU {15FEBD1B-55CE-4EBD-85E3-04898260A25B}.Release|Any CPU.ActiveCfg = Release|Any CPU {15FEBD1B-55CE-4EBD-85E3-04898260A25B}.Release|Any CPU.Build.0 = Release|Any CPU {27B1EAE2-2E06-48EF-8A67-06D6FB3DC275}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {27B1EAE2-2E06-48EF-8A67-06D6FB3DC275}.Debug|Any CPU.Build.0 = Debug|Any CPU {27B1EAE2-2E06-48EF-8A67-06D6FB3DC275}.Release|Any CPU.ActiveCfg = Release|Any CPU {27B1EAE2-2E06-48EF-8A67-06D6FB3DC275}.Release|Any CPU.Build.0 = Release|Any CPU {E0756C89-603F-4B48-8E64-1D53E62654C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E0756C89-603F-4B48-8E64-1D53E62654C8}.Debug|Any CPU.Build.0 = Debug|Any CPU {E0756C89-603F-4B48-8E64-1D53E62654C8}.Release|Any CPU.ActiveCfg = Release|Any CPU {E0756C89-603F-4B48-8E64-1D53E62654C8}.Release|Any CPU.Build.0 = Release|Any CPU {7F8057D9-F70F-4EA7-BD64-AB2D0DD8057B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7F8057D9-F70F-4EA7-BD64-AB2D0DD8057B}.Debug|Any CPU.Build.0 = Debug|Any CPU {7F8057D9-F70F-4EA7-BD64-AB2D0DD8057B}.Release|Any CPU.ActiveCfg = Release|Any CPU {7F8057D9-F70F-4EA7-BD64-AB2D0DD8057B}.Release|Any CPU.Build.0 = Release|Any CPU {2483917E-7024-4D10-99C6-2BEF338FF53B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2483917E-7024-4D10-99C6-2BEF338FF53B}.Debug|Any CPU.Build.0 = Debug|Any CPU {2483917E-7024-4D10-99C6-2BEF338FF53B}.Release|Any CPU.ActiveCfg = Release|Any CPU {2483917E-7024-4D10-99C6-2BEF338FF53B}.Release|Any CPU.Build.0 = Release|Any CPU {8A02AFAF-F622-4E3E-9E1A-8CFDACC7C7E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8A02AFAF-F622-4E3E-9E1A-8CFDACC7C7E1}.Debug|Any CPU.Build.0 = Debug|Any CPU {8A02AFAF-F622-4E3E-9E1A-8CFDACC7C7E1}.Release|Any CPU.ActiveCfg = Release|Any CPU {8A02AFAF-F622-4E3E-9E1A-8CFDACC7C7E1}.Release|Any CPU.Build.0 = Release|Any CPU {6D407402-CC4A-4125-9B00-C70562A636A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6D407402-CC4A-4125-9B00-C70562A636A5}.Debug|Any CPU.Build.0 = Debug|Any CPU {6D407402-CC4A-4125-9B00-C70562A636A5}.Release|Any CPU.ActiveCfg = Release|Any CPU {6D407402-CC4A-4125-9B00-C70562A636A5}.Release|Any CPU.Build.0 = Release|Any CPU {706CFC25-B6E0-4DAA-BCC4-F6FAAFEEDF87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {706CFC25-B6E0-4DAA-BCC4-F6FAAFEEDF87}.Debug|Any CPU.Build.0 = Debug|Any CPU {706CFC25-B6E0-4DAA-BCC4-F6FAAFEEDF87}.Release|Any CPU.ActiveCfg = Release|Any CPU {706CFC25-B6E0-4DAA-BCC4-F6FAAFEEDF87}.Release|Any CPU.Build.0 = Release|Any CPU {E9211052-7700-4A2F-B1AE-34FD5CCAB8AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E9211052-7700-4A2F-B1AE-34FD5CCAB8AF}.Debug|Any CPU.Build.0 = Debug|Any CPU {E9211052-7700-4A2F-B1AE-34FD5CCAB8AF}.Release|Any CPU.ActiveCfg = Release|Any CPU {E9211052-7700-4A2F-B1AE-34FD5CCAB8AF}.Release|Any CPU.Build.0 = Release|Any CPU {9B25E472-DF94-4E24-9F5D-E487CE5A91FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9B25E472-DF94-4E24-9F5D-E487CE5A91FB}.Debug|Any CPU.Build.0 = Debug|Any CPU {9B25E472-DF94-4E24-9F5D-E487CE5A91FB}.Release|Any CPU.ActiveCfg = Release|Any CPU {9B25E472-DF94-4E24-9F5D-E487CE5A91FB}.Release|Any CPU.Build.0 = Release|Any CPU {432F4461-E198-44AA-8022-9E8C06A17C93}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {432F4461-E198-44AA-8022-9E8C06A17C93}.Debug|Any CPU.Build.0 = Debug|Any CPU {432F4461-E198-44AA-8022-9E8C06A17C93}.Release|Any CPU.ActiveCfg = Release|Any CPU {432F4461-E198-44AA-8022-9E8C06A17C93}.Release|Any CPU.Build.0 = Release|Any CPU {321F9FED-AACC-42CB-93E5-541D79E099E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {321F9FED-AACC-42CB-93E5-541D79E099E8}.Debug|Any CPU.Build.0 = Debug|Any CPU {321F9FED-AACC-42CB-93E5-541D79E099E8}.Release|Any CPU.ActiveCfg = Release|Any CPU {321F9FED-AACC-42CB-93E5-541D79E099E8}.Release|Any CPU.Build.0 = Release|Any CPU {FDBFBB64-5980-41C2-9E3E-FB8E2F700A5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FDBFBB64-5980-41C2-9E3E-FB8E2F700A5C}.Debug|Any CPU.Build.0 = Debug|Any CPU {FDBFBB64-5980-41C2-9E3E-FB8E2F700A5C}.Release|Any CPU.ActiveCfg = Release|Any CPU {FDBFBB64-5980-41C2-9E3E-FB8E2F700A5C}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {A4C99B85-765C-4C65-9C2A-BB609AAB09E6} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {1EE8CAD3-55F9-4D91-96B2-084641DA9A6C} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {9508F118-F62E-4C16-A6F4-7C3B56E166AD} = {E35DA3D1-16C0-4318-9187-6B664F12A870} {F5CE416E-B906-41D2-80B9-0078E887A3F6} = {E35DA3D1-16C0-4318-9187-6B664F12A870} {4B45CA0C-03A0-400F-B454-3D4BCB16AF38} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {B501A547-C911-4A05-AC6E-274A50DFF30E} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {50D26304-0961-4A51-ABF6-6CAD1A56D203} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {4462B57A-7245-4146-B504-D46FDE762948} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {1AF3672A-C5F1-4604-B6AB-D98C4DE9C3B1} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {B2C33A93-DB30-4099-903E-77D75C4C3F45} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {28026D16-EB0C-40B0-BDA7-11CAA2B97CCC} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {50D26304-0961-4A51-ABF6-6CAD1A56D202} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {7FE6B002-89D8-4298-9B1B-0B5C247DD1FD} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {4371944A-D3BA-4B5B-8285-82E5FFC6D1F9} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {4371944A-D3BA-4B5B-8285-82E5FFC6D1F8} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {E3B32027-3362-41DF-9172-4D3B623F42A5} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {190CE348-596E-435A-9E5B-12A689F9FC29} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {9C9DABA4-0E72-4469-ADF1-4991F3CA572A} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {BF180BD2-4FB7-4252-A7EC-A00E0C7A028A} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {BDA5D613-596D-4B61-837C-63554151C8F5} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {91F6F646-4F6E-449A-9AB4-2986348F329D} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {AFDE6BEA-5038-4A4A-A88E-DBD2E4088EED} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {02459936-CD2C-4F61-B671-5C518F2A3DDC} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {288089C5-8721-458E-BE3E-78990DAB5E2E} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {288089C5-8721-458E-BE3E-78990DAB5E2D} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {D0A79850-B32A-45E5-9FD5-D43CB345867A} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {6AA96934-D6B7-4CC8-990D-DB6B9DD56E34} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {909B656F-6095-4AC2-A5AB-C3F032315C45} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {D0BC9BE7-24F6-40CA-8DC6-FCB93BD44B34} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {FCFA8808-A1B6-48CC-A1EA-0B8CA8AEDA8E} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {E58EE9D7-1239-4961-A0C1-F9EC3952C4C1} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {1DFEA9C5-973C-4179-9B1B-0F32288E1EF2} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {AD6F474E-E6D4-4217-91F3-B7AF1BE31CCC} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {1A3941F1-1E1F-4EF7-8064-7729C4C2E2AA} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {CCBD3438-3E84-40A9-83AD-533F23BCFCA5} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {C1930979-C824-496B-A630-70F5369A636F} = {3CDEA9FB-CD44-4AB4-98A8-5537AAA2169B} {D73ADF7D-2C1C-42AE-B2AB-EDC9497E4B71} = {3CDEA9FB-CD44-4AB4-98A8-5537AAA2169B} {7AD4FE65-9A30-41A6-8004-AA8F89BCB7F3} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {2DAE4406-7A89-4B5F-95C3-BC5472CE47CE} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {2DAE4406-7A89-4B5F-95C3-BC5422CE47CE} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {ABC7262E-1053-49F3-B846-E3091BB92E8C} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {12A68549-4E8C-42D6-8703-A09335F97997} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {066F0DBD-C46C-4C20-AFEC-99829A172625} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {3E7DEA65-317B-4F43-A25D-62F18D96CFD7} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {21A01C2D-2501-4619-8144-48977DD22D9C} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {14118347-ED06-4608-9C45-18228273C712} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {5F8D2414-064A-4B3A-9B42-8E2A04246BE5} = {D9591377-7868-4D64-9314-83E0C92A871B} {21B239D0-D144-430F-A394-C066D58EE267} = {D9591377-7868-4D64-9314-83E0C92A871B} {57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C} = {D9591377-7868-4D64-9314-83E0C92A871B} {54E08BF5-F819-404F-A18D-0AB9EA81EA04} = {32A48625-F0AD-419D-828B-A50BDABA38EA} {E8F0BAA5-7327-43D1-9A51-644E81AE55F1} = {C65C6143-BED3-46E6-869E-9F0BE6E84C37} {15FEBD1B-55CE-4EBD-85E3-04898260A25B} = {274B96B7-F815-47E3-9CA4-4024A57A478F} {27B1EAE2-2E06-48EF-8A67-06D6FB3DC275} = {274B96B7-F815-47E3-9CA4-4024A57A478F} {E0756C89-603F-4B48-8E64-1D53E62654C8} = {274B96B7-F815-47E3-9CA4-4024A57A478F} {7F8057D9-F70F-4EA7-BD64-AB2D0DD8057B} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {2483917E-7024-4D10-99C6-2BEF338FF53B} = {274B96B7-F815-47E3-9CA4-4024A57A478F} {8A02AFAF-F622-4E3E-9E1A-8CFDACC7C7E1} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {6D407402-CC4A-4125-9B00-C70562A636A5} = {274B96B7-F815-47E3-9CA4-4024A57A478F} {706CFC25-B6E0-4DAA-BCC4-F6FAAFEEDF87} = {3FF38FD4-DF16-44B0-924F-0D5AE155495B} {E9211052-7700-4A2F-B1AE-34FD5CCAB8AF} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {9B25E472-DF94-4E24-9F5D-E487CE5A91FB} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {E919DD77-34F8-4F57-8058-4D3FF4C2B241} = {3CDEA9FB-CD44-4AB4-98A8-5537AAA2169B} {321F9FED-AACC-42CB-93E5-541D79E099E8} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} {FDBFBB64-5980-41C2-9E3E-FB8E2F700A5C} = {A41D1B99-F489-4C43-BBDF-96D61B19A6B9} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {6F599E08-A9EA-4FAA-897F-5D824B0210E6} EndGlobalSection EndGlobal
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Workspaces/Core/Portable/SymbolSearch/SymbolSearchCallbackDispatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.SymbolSearch { [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteSymbolSearchUpdateService)), Shared] internal sealed class SymbolSearchCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteSymbolSearchUpdateService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SymbolSearchCallbackDispatcher() { } private ISymbolSearchLogService GetLogService(RemoteServiceCallbackId callbackId) => (ISymbolSearchLogService)GetCallback(callbackId); public ValueTask LogExceptionAsync(RemoteServiceCallbackId callbackId, string exception, string text, CancellationToken cancellationToken) => GetLogService(callbackId).LogExceptionAsync(exception, text, cancellationToken); public ValueTask LogInfoAsync(RemoteServiceCallbackId callbackId, string text, CancellationToken cancellationToken) => GetLogService(callbackId).LogInfoAsync(text, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.SymbolSearch { [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteSymbolSearchUpdateService)), Shared] internal sealed class SymbolSearchCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteSymbolSearchUpdateService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SymbolSearchCallbackDispatcher() { } private ISymbolSearchLogService GetLogService(RemoteServiceCallbackId callbackId) => (ISymbolSearchLogService)GetCallback(callbackId); public ValueTask LogExceptionAsync(RemoteServiceCallbackId callbackId, string exception, string text, CancellationToken cancellationToken) => GetLogService(callbackId).LogExceptionAsync(exception, text, cancellationToken); public ValueTask LogInfoAsync(RemoteServiceCallbackId callbackId, string text, CancellationToken cancellationToken) => GetLogService(callbackId).LogInfoAsync(text, cancellationToken); } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Compilers/Server/VBCSCompilerTests/BuildProtocolTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class BuildProtocolTest : TestBase { private void VerifyShutdownRequest(BuildRequest request) { Assert.Equal(1, request.Arguments.Count); var argument = request.Arguments[0]; Assert.Equal(BuildProtocolConstants.ArgumentId.Shutdown, argument.ArgumentId); Assert.Equal(0, argument.ArgumentIndex); Assert.Equal("", argument.Value); } [Fact] public async Task ReadWriteCompleted() { var response = new CompletedBuildResponse(42, utf8output: false, output: "a string"); var memoryStream = new MemoryStream(); await response.WriteAsync(memoryStream, default(CancellationToken)); Assert.True(memoryStream.Position > 0); memoryStream.Position = 0; var read = (CompletedBuildResponse)(await BuildResponse.ReadAsync(memoryStream, default(CancellationToken))); Assert.Equal(42, read.ReturnCode); Assert.False(read.Utf8Output); Assert.Equal("a string", read.Output); } [Fact] public async Task ReadWriteRequest() { var request = new BuildRequest( RequestLanguage.VisualBasicCompile, "HashValue", ImmutableArray.Create( new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CurrentDirectory, argumentIndex: 0, value: "directory"), new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CommandLineArgument, argumentIndex: 1, value: "file"))); var memoryStream = new MemoryStream(); await request.WriteAsync(memoryStream, default(CancellationToken)); Assert.True(memoryStream.Position > 0); memoryStream.Position = 0; var read = await BuildRequest.ReadAsync(memoryStream, default(CancellationToken)); Assert.Equal(RequestLanguage.VisualBasicCompile, read.Language); Assert.Equal("HashValue", read.CompilerHash); Assert.Equal(2, read.Arguments.Count); Assert.Equal(BuildProtocolConstants.ArgumentId.CurrentDirectory, read.Arguments[0].ArgumentId); Assert.Equal(0, read.Arguments[0].ArgumentIndex); Assert.Equal("directory", read.Arguments[0].Value); Assert.Equal(BuildProtocolConstants.ArgumentId.CommandLineArgument, read.Arguments[1].ArgumentId); Assert.Equal(1, read.Arguments[1].ArgumentIndex); Assert.Equal("file", read.Arguments[1].Value); } [Fact] public void ShutdownMessage() { var request = BuildRequest.CreateShutdown(); VerifyShutdownRequest(request); Assert.Equal(1, request.Arguments.Count); var argument = request.Arguments[0]; Assert.Equal(BuildProtocolConstants.ArgumentId.Shutdown, argument.ArgumentId); Assert.Equal(0, argument.ArgumentIndex); Assert.Equal("", argument.Value); } [Fact] public async Task ShutdownRequestWriteRead() { var memoryStream = new MemoryStream(); var request = BuildRequest.CreateShutdown(); await request.WriteAsync(memoryStream, CancellationToken.None); memoryStream.Position = 0; var read = await BuildRequest.ReadAsync(memoryStream, CancellationToken.None); VerifyShutdownRequest(read); } [Fact] public async Task ShutdownResponseWriteRead() { var response = new ShutdownBuildResponse(42); Assert.Equal(BuildResponse.ResponseType.Shutdown, response.Type); var memoryStream = new MemoryStream(); await response.WriteAsync(memoryStream, CancellationToken.None); memoryStream.Position = 0; var read = await BuildResponse.ReadAsync(memoryStream, CancellationToken.None); Assert.Equal(BuildResponse.ResponseType.Shutdown, read.Type); var typed = (ShutdownBuildResponse)read; Assert.Equal(42, typed.ServerProcessId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class BuildProtocolTest : TestBase { private void VerifyShutdownRequest(BuildRequest request) { Assert.Equal(1, request.Arguments.Count); var argument = request.Arguments[0]; Assert.Equal(BuildProtocolConstants.ArgumentId.Shutdown, argument.ArgumentId); Assert.Equal(0, argument.ArgumentIndex); Assert.Equal("", argument.Value); } [Fact] public async Task ReadWriteCompleted() { var response = new CompletedBuildResponse(42, utf8output: false, output: "a string"); var memoryStream = new MemoryStream(); await response.WriteAsync(memoryStream, default(CancellationToken)); Assert.True(memoryStream.Position > 0); memoryStream.Position = 0; var read = (CompletedBuildResponse)(await BuildResponse.ReadAsync(memoryStream, default(CancellationToken))); Assert.Equal(42, read.ReturnCode); Assert.False(read.Utf8Output); Assert.Equal("a string", read.Output); } [Fact] public async Task ReadWriteRequest() { var request = new BuildRequest( RequestLanguage.VisualBasicCompile, "HashValue", ImmutableArray.Create( new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CurrentDirectory, argumentIndex: 0, value: "directory"), new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CommandLineArgument, argumentIndex: 1, value: "file"))); var memoryStream = new MemoryStream(); await request.WriteAsync(memoryStream, default(CancellationToken)); Assert.True(memoryStream.Position > 0); memoryStream.Position = 0; var read = await BuildRequest.ReadAsync(memoryStream, default(CancellationToken)); Assert.Equal(RequestLanguage.VisualBasicCompile, read.Language); Assert.Equal("HashValue", read.CompilerHash); Assert.Equal(2, read.Arguments.Count); Assert.Equal(BuildProtocolConstants.ArgumentId.CurrentDirectory, read.Arguments[0].ArgumentId); Assert.Equal(0, read.Arguments[0].ArgumentIndex); Assert.Equal("directory", read.Arguments[0].Value); Assert.Equal(BuildProtocolConstants.ArgumentId.CommandLineArgument, read.Arguments[1].ArgumentId); Assert.Equal(1, read.Arguments[1].ArgumentIndex); Assert.Equal("file", read.Arguments[1].Value); } [Fact] public void ShutdownMessage() { var request = BuildRequest.CreateShutdown(); VerifyShutdownRequest(request); Assert.Equal(1, request.Arguments.Count); var argument = request.Arguments[0]; Assert.Equal(BuildProtocolConstants.ArgumentId.Shutdown, argument.ArgumentId); Assert.Equal(0, argument.ArgumentIndex); Assert.Equal("", argument.Value); } [Fact] public async Task ShutdownRequestWriteRead() { var memoryStream = new MemoryStream(); var request = BuildRequest.CreateShutdown(); await request.WriteAsync(memoryStream, CancellationToken.None); memoryStream.Position = 0; var read = await BuildRequest.ReadAsync(memoryStream, CancellationToken.None); VerifyShutdownRequest(read); } [Fact] public async Task ShutdownResponseWriteRead() { var response = new ShutdownBuildResponse(42); Assert.Equal(BuildResponse.ResponseType.Shutdown, response.Type); var memoryStream = new MemoryStream(); await response.WriteAsync(memoryStream, CancellationToken.None); memoryStream.Position = 0; var read = await BuildResponse.ReadAsync(memoryStream, CancellationToken.None); Assert.Equal(BuildResponse.ResponseType.Shutdown, read.Type); var typed = (ShutdownBuildResponse)read; Assert.Equal(42, typed.ServerProcessId); } } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Compilers/CSharp/Portable/Syntax/TypeSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp.Syntax { public abstract partial class TypeSyntax { public bool IsVar => ((InternalSyntax.TypeSyntax)this.Green).IsVar; public bool IsUnmanaged => ((InternalSyntax.TypeSyntax)this.Green).IsUnmanaged; public bool IsNotNull => ((InternalSyntax.TypeSyntax)this.Green).IsNotNull; public bool IsNint => ((InternalSyntax.TypeSyntax)this.Green).IsNint; public bool IsNuint => ((InternalSyntax.TypeSyntax)this.Green).IsNuint; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp.Syntax { public abstract partial class TypeSyntax { public bool IsVar => ((InternalSyntax.TypeSyntax)this.Green).IsVar; public bool IsUnmanaged => ((InternalSyntax.TypeSyntax)this.Green).IsUnmanaged; public bool IsNotNull => ((InternalSyntax.TypeSyntax)this.Green).IsNotNull; public bool IsNint => ((InternalSyntax.TypeSyntax)this.Green).IsNint; public bool IsNuint => ((InternalSyntax.TypeSyntax)this.Green).IsNuint; } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Workspaces/MSBuildTest/Resources/Dlls/EmptyLibrary.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL{T" 0~& @ `+&O@` %  H.text  `.rsrc@ @@.reloc `@B_&HP HBSJB v4.0.30319l|#~,#Strings#US#GUID( #Blob 3Z! IA &`5{x  )19AIQYaiqy. #.,.K.#T.+f.3f.;l.CT.K{.Sf.[f.c.k.s <Module>mscorlibGuidAttributeDebuggableAttributeComVisibleAttributeAssemblyTitleAttributeAssemblyTrademarkAttributeTargetFrameworkAttributeAssemblyFileVersionAttributeAssemblyConfigurationAttributeAssemblyDescriptionAttributeCompilationRelaxationsAttributeAssemblyProductAttributeAssemblyCopyrightAttributeAssemblyCompanyAttributeRuntimeCompatibilityAttributeSystem.Runtime.VersioningEmptyLibrary.dllSystem.Reflection.ctorSystem.DiagnosticsSystem.Runtime.InteropServicesSystem.Runtime.CompilerServicesDebuggingModesEmptyLibrary.DV\     z\V4TWrapNonExceptionThrows EmptyLibrary Microsoft Copyright © Microsoft 2015)$a32ef9de-5e97-46fe-9c49-e70fbccfbb11 1.0.0.0I.NETFramework,Version=v4.5TFrameworkDisplayName.NET Framework 4.5{Tw%RSDS>yNwr2c:\users\mattwar\documents\visual studio next\Projects\EmptyLibrary\obj\Debug\EmptyLibrary.pdbS&m& _&_CorDllMainmscoree.dll% 0HX@``4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0Comments4 CompanyNameMicrosoftB FileDescriptionEmptyLibrary0FileVersion1.0.0.0BInternalNameEmptyLibrary.dllZLegalCopyrightCopyright Microsoft 2015*LegalTrademarksJOriginalFilenameEmptyLibrary.dll: ProductNameEmptyLibrary4ProductVersion1.0.0.08Assembly Version1.0.0.0 6
MZ@ !L!This program cannot be run in DOS mode. $PEL{T" 0~& @ `+&O@` %  H.text  `.rsrc@ @@.reloc `@B_&HP HBSJB v4.0.30319l|#~,#Strings#US#GUID( #Blob 3Z! IA &`5{x  )19AIQYaiqy. #.,.K.#T.+f.3f.;l.CT.K{.Sf.[f.c.k.s <Module>mscorlibGuidAttributeDebuggableAttributeComVisibleAttributeAssemblyTitleAttributeAssemblyTrademarkAttributeTargetFrameworkAttributeAssemblyFileVersionAttributeAssemblyConfigurationAttributeAssemblyDescriptionAttributeCompilationRelaxationsAttributeAssemblyProductAttributeAssemblyCopyrightAttributeAssemblyCompanyAttributeRuntimeCompatibilityAttributeSystem.Runtime.VersioningEmptyLibrary.dllSystem.Reflection.ctorSystem.DiagnosticsSystem.Runtime.InteropServicesSystem.Runtime.CompilerServicesDebuggingModesEmptyLibrary.DV\     z\V4TWrapNonExceptionThrows EmptyLibrary Microsoft Copyright © Microsoft 2015)$a32ef9de-5e97-46fe-9c49-e70fbccfbb11 1.0.0.0I.NETFramework,Version=v4.5TFrameworkDisplayName.NET Framework 4.5{Tw%RSDS>yNwr2c:\users\mattwar\documents\visual studio next\Projects\EmptyLibrary\obj\Debug\EmptyLibrary.pdbS&m& _&_CorDllMainmscoree.dll% 0HX@``4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0Comments4 CompanyNameMicrosoftB FileDescriptionEmptyLibrary0FileVersion1.0.0.0BInternalNameEmptyLibrary.dllZLegalCopyrightCopyright Microsoft 2015*LegalTrademarksJOriginalFilenameEmptyLibrary.dll: ProductNameEmptyLibrary4ProductVersion1.0.0.08Assembly Version1.0.0.0 6
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfFixAllTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.ConvertTypeOfToNameOf; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertTypeOfToNameOf { using VerifyCS = CSharpCodeFixVerifier<CSharpConvertTypeOfToNameOfDiagnosticAnalyzer, CSharpConvertTypeOfToNameOfCodeFixProvider>; public partial class ConvertTypeOfToNameOfTests { [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task FixAllDocumentBasic() { var input = @"class Test { static void Main() { var typeName1 = [|typeof(Test).Name|]; var typeName2 = [|typeof(Test).Name|]; var typeName3 = [|typeof(Test).Name|]; } } "; var expected = @"class Test { static void Main() { var typeName1 = nameof(Test); var typeName2 = nameof(Test); var typeName3 = nameof(Test); } } "; await VerifyCS.VerifyCodeFixAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task FixAllDocumentVariedSingleLine() { var input = @"class Test { static void Main() { var typeName1 = [|typeof(Test).Name|]; var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(System.String).Name|]; } } "; var expected = @"class Test { static void Main() { var typeName1 = nameof(Test); var typeName2 = nameof(System.Int32); var typeName3 = nameof(System.String); } } "; await VerifyCS.VerifyCodeFixAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task FixAllDocumentVariedWithUsing() { var input = @"using System; class Test { static void Main() { var typeName1 = [|typeof(Test).Name|]; var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(String).Name|]; var typeName4 = [|typeof(System.Double).Name|]; } } "; var expected = @"using System; class Test { static void Main() { var typeName1 = nameof(Test); var typeName2 = nameof(Int32); var typeName3 = nameof(String); var typeName4 = nameof(Double); } } "; await VerifyCS.VerifyCodeFixAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task FixAllProject() { await new VerifyCS.Test { TestState = { Sources = { @" class Test1 { static void Main() { var typeName1 = [|typeof(Test1).Name|]; var typeName2 = [|typeof(Test1).Name|]; var typeName3 = [|typeof(Test1).Name|]; } } ", @" using System; class Test2 { static void Main() { var typeName1 = [|typeof(Test1).Name|]; var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(System.String).Name|]; var typeName4 = [|typeof(Double).Name|]; } } " } }, FixedState = { Sources = { @" class Test1 { static void Main() { var typeName1 = nameof(Test1); var typeName2 = nameof(Test1); var typeName3 = nameof(Test1); } } ", @" using System; class Test2 { static void Main() { var typeName1 = nameof(Test1); var typeName2 = nameof(Int32); var typeName3 = nameof(String); var typeName4 = nameof(Double); } } ", } } }.RunAsync(); } [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task FixAllSolution() { await new VerifyCS.Test { TestState = { Sources = { @" class Test1 { static void Main() { var typeName1 = [|typeof(Test1).Name|]; var typeName2 = [|typeof(Test1).Name|]; var typeName3 = [|typeof(Test1).Name|]; } } ", @" using System; class Test2 { static void Main() { var typeName1 = [|typeof(Test1).Name|]; var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(System.String).Name|]; var typeName4 = [|typeof(Double).Name|]; } } " }, AdditionalProjects = { ["DependencyProject"] = { Sources = { @" class Test3 { static void Main() { var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(System.String).Name|]; } } " } } } }, FixedState = { Sources = { @" class Test1 { static void Main() { var typeName1 = nameof(Test1); var typeName2 = nameof(Test1); var typeName3 = nameof(Test1); } } ", @" using System; class Test2 { static void Main() { var typeName1 = nameof(Test1); var typeName2 = nameof(Int32); var typeName3 = nameof(String); var typeName4 = nameof(Double); } } " }, AdditionalProjects = { ["DependencyProject"] = { Sources = { @" class Test3 { static void Main() { var typeName2 = nameof(System.Int32); var typeName3 = nameof(System.String); } } " } } } } }.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.ConvertTypeOfToNameOf; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertTypeOfToNameOf { using VerifyCS = CSharpCodeFixVerifier<CSharpConvertTypeOfToNameOfDiagnosticAnalyzer, CSharpConvertTypeOfToNameOfCodeFixProvider>; public partial class ConvertTypeOfToNameOfTests { [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task FixAllDocumentBasic() { var input = @"class Test { static void Main() { var typeName1 = [|typeof(Test).Name|]; var typeName2 = [|typeof(Test).Name|]; var typeName3 = [|typeof(Test).Name|]; } } "; var expected = @"class Test { static void Main() { var typeName1 = nameof(Test); var typeName2 = nameof(Test); var typeName3 = nameof(Test); } } "; await VerifyCS.VerifyCodeFixAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task FixAllDocumentVariedSingleLine() { var input = @"class Test { static void Main() { var typeName1 = [|typeof(Test).Name|]; var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(System.String).Name|]; } } "; var expected = @"class Test { static void Main() { var typeName1 = nameof(Test); var typeName2 = nameof(System.Int32); var typeName3 = nameof(System.String); } } "; await VerifyCS.VerifyCodeFixAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task FixAllDocumentVariedWithUsing() { var input = @"using System; class Test { static void Main() { var typeName1 = [|typeof(Test).Name|]; var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(String).Name|]; var typeName4 = [|typeof(System.Double).Name|]; } } "; var expected = @"using System; class Test { static void Main() { var typeName1 = nameof(Test); var typeName2 = nameof(Int32); var typeName3 = nameof(String); var typeName4 = nameof(Double); } } "; await VerifyCS.VerifyCodeFixAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task FixAllProject() { await new VerifyCS.Test { TestState = { Sources = { @" class Test1 { static void Main() { var typeName1 = [|typeof(Test1).Name|]; var typeName2 = [|typeof(Test1).Name|]; var typeName3 = [|typeof(Test1).Name|]; } } ", @" using System; class Test2 { static void Main() { var typeName1 = [|typeof(Test1).Name|]; var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(System.String).Name|]; var typeName4 = [|typeof(Double).Name|]; } } " } }, FixedState = { Sources = { @" class Test1 { static void Main() { var typeName1 = nameof(Test1); var typeName2 = nameof(Test1); var typeName3 = nameof(Test1); } } ", @" using System; class Test2 { static void Main() { var typeName1 = nameof(Test1); var typeName2 = nameof(Int32); var typeName3 = nameof(String); var typeName4 = nameof(Double); } } ", } } }.RunAsync(); } [Fact] [Trait(Traits.Feature, Traits.Features.ConvertTypeOfToNameOf)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task FixAllSolution() { await new VerifyCS.Test { TestState = { Sources = { @" class Test1 { static void Main() { var typeName1 = [|typeof(Test1).Name|]; var typeName2 = [|typeof(Test1).Name|]; var typeName3 = [|typeof(Test1).Name|]; } } ", @" using System; class Test2 { static void Main() { var typeName1 = [|typeof(Test1).Name|]; var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(System.String).Name|]; var typeName4 = [|typeof(Double).Name|]; } } " }, AdditionalProjects = { ["DependencyProject"] = { Sources = { @" class Test3 { static void Main() { var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(System.String).Name|]; } } " } } } }, FixedState = { Sources = { @" class Test1 { static void Main() { var typeName1 = nameof(Test1); var typeName2 = nameof(Test1); var typeName3 = nameof(Test1); } } ", @" using System; class Test2 { static void Main() { var typeName1 = nameof(Test1); var typeName2 = nameof(Int32); var typeName3 = nameof(String); var typeName4 = nameof(Double); } } " }, AdditionalProjects = { ["DependencyProject"] = { Sources = { @" class Test3 { static void Main() { var typeName2 = nameof(System.Int32); var typeName3 = nameof(System.String); } } " } } } } }.RunAsync(); } } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Features/Core/Portable/IntroduceUsingStatement/AbstractIntroduceUsingStatementCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.IntroduceUsingStatement { internal abstract class AbstractIntroduceUsingStatementCodeRefactoringProvider<TStatementSyntax, TLocalDeclarationSyntax> : CodeRefactoringProvider where TStatementSyntax : SyntaxNode where TLocalDeclarationSyntax : TStatementSyntax { protected abstract string CodeActionTitle { get; } protected abstract bool CanRefactorToContainBlockStatements(SyntaxNode parent); protected abstract SyntaxList<TStatementSyntax> GetStatements(SyntaxNode parentOfStatementsToSurround); protected abstract SyntaxNode WithStatements(SyntaxNode parentOfStatementsToSurround, SyntaxList<TStatementSyntax> statements); protected abstract TStatementSyntax CreateUsingStatement(TLocalDeclarationSyntax declarationStatement, SyntaxTriviaList sameLineTrivia, SyntaxList<TStatementSyntax> statementsToSurround); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var declarationSyntax = await FindDisposableLocalDeclarationAsync(document, span, cancellationToken).ConfigureAwait(false); if (declarationSyntax != null) { context.RegisterRefactoring( new MyCodeAction( CodeActionTitle, cancellationToken => IntroduceUsingStatementAsync(document, declarationSyntax, cancellationToken)), declarationSyntax.Span); } } private async Task<TLocalDeclarationSyntax?> FindDisposableLocalDeclarationAsync(Document document, TextSpan selection, CancellationToken cancellationToken) { var declarationSyntax = await document.TryGetRelevantNodeAsync<TLocalDeclarationSyntax>(selection, cancellationToken).ConfigureAwait(false); if (declarationSyntax is null || !CanRefactorToContainBlockStatements(declarationSyntax.GetRequiredParent())) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var disposableType = semanticModel.Compilation.GetSpecialType(SpecialType.System_IDisposable); if (disposableType is null) { return null; } var operation = semanticModel.GetOperation(declarationSyntax, cancellationToken) as IVariableDeclarationGroupOperation; if (operation?.Declarations.Length != 1) { return null; } var localDeclaration = operation.Declarations[0]; if (localDeclaration.Declarators.Length != 1) { return null; } var declarator = localDeclaration.Declarators[0]; var localType = declarator.Symbol?.Type; if (localType is null) { return null; } var initializer = (localDeclaration.Initializer ?? declarator.Initializer)?.Value; // Initializer kind is invalid when incomplete declaration syntax ends in an equals token. if (initializer is null || initializer.Kind == OperationKind.Invalid) { return null; } if (!IsLegalUsingStatementType(semanticModel.Compilation, disposableType, localType)) { return null; } return declarationSyntax; } /// <summary> /// Up to date with C# 7.3. Pattern-based disposal is likely to be added to C# 8.0, /// in which case accessible instance and extension methods will need to be detected. /// </summary> private static bool IsLegalUsingStatementType(Compilation compilation, ITypeSymbol disposableType, ITypeSymbol type) { if (disposableType == null) { return false; } // CS1674: type used in a using statement must be implicitly convertible to 'System.IDisposable' return compilation.ClassifyCommonConversion(type, disposableType).IsImplicit; } private async Task<Document> IntroduceUsingStatementAsync( Document document, TLocalDeclarationSyntax declarationStatement, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); var statementsToSurround = GetStatementsToSurround(declarationStatement, semanticModel, syntaxFactsService, cancellationToken); // Separate the newline from the trivia that is going on the using declaration line. var (sameLine, endOfLine) = SplitTrailingTrivia(declarationStatement, syntaxFactsService); var usingStatement = CreateUsingStatement( declarationStatement, sameLine, statementsToSurround) .WithLeadingTrivia(declarationStatement.GetLeadingTrivia()) .WithTrailingTrivia(endOfLine); if (statementsToSurround.Any()) { var parentStatements = GetStatements(declarationStatement.GetRequiredParent()); var declarationStatementIndex = parentStatements.IndexOf(declarationStatement); var newParent = WithStatements( declarationStatement.GetRequiredParent(), new SyntaxList<TStatementSyntax>(parentStatements .Take(declarationStatementIndex) .Concat(usingStatement) .Concat(parentStatements.Skip(declarationStatementIndex + 1 + statementsToSurround.Count)))); return document.WithSyntaxRoot(root.ReplaceNode( declarationStatement.GetRequiredParent(), newParent.WithAdditionalAnnotations(Formatter.Annotation))); } else { // Either the parent is not blocklike, meaning WithStatements can’t be used as in the other branch, // or there’s just no need to replace more than the statement itself because no following statements // will be surrounded. return document.WithSyntaxRoot(root.ReplaceNode( declarationStatement, usingStatement.WithAdditionalAnnotations(Formatter.Annotation))); } } private SyntaxList<TStatementSyntax> GetStatementsToSurround( TLocalDeclarationSyntax declarationStatement, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService, CancellationToken cancellationToken) { // Find the minimal number of statements to move into the using block // in order to not break existing references to the local. var lastUsageStatement = FindSiblingStatementContainingLastUsage( declarationStatement, semanticModel, syntaxFactsService, cancellationToken); if (lastUsageStatement == declarationStatement) { return default; } var parentStatements = GetStatements(declarationStatement.GetRequiredParent()); var declarationStatementIndex = parentStatements.IndexOf(declarationStatement); var lastUsageStatementIndex = parentStatements.IndexOf(lastUsageStatement, declarationStatementIndex + 1); return new SyntaxList<TStatementSyntax>(parentStatements .Take(lastUsageStatementIndex + 1) .Skip(declarationStatementIndex + 1)); } private static (SyntaxTriviaList sameLine, SyntaxTriviaList endOfLine) SplitTrailingTrivia(SyntaxNode node, ISyntaxFactsService syntaxFactsService) { var trailingTrivia = node.GetTrailingTrivia(); var lastIndex = trailingTrivia.Count - 1; return lastIndex != -1 && syntaxFactsService.IsEndOfLineTrivia(trailingTrivia[lastIndex]) ? (sameLine: trailingTrivia.RemoveAt(lastIndex), endOfLine: new SyntaxTriviaList(trailingTrivia[lastIndex])) : (sameLine: trailingTrivia, endOfLine: SyntaxTriviaList.Empty); } private static TStatementSyntax FindSiblingStatementContainingLastUsage( TStatementSyntax declarationSyntax, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService, CancellationToken cancellationToken) { // We are going to step through the statements starting with the trigger variable's declaration. // We will track when new locals are declared and when they are used. To determine the last // statement that we should surround, we will walk through the locals in the order they are declared. // If the local's declaration index falls within the last variable usage index, we will extend // the last variable usage index to include the local's last usage. // Take all the statements starting with the trigger variable's declaration. var statementsFromDeclarationToEnd = declarationSyntax.GetRequiredParent().ChildNodesAndTokens() .Select(nodeOrToken => nodeOrToken.AsNode()) .OfType<TStatementSyntax>() .SkipWhile(node => node != declarationSyntax) .ToImmutableArray(); // List of local variables that will be in the order they are declared. using var _0 = ArrayBuilder<ISymbol>.GetInstance(out var localVariables); // Map a symbol to an index into the statementsFromDeclarationToEnd array. using var _1 = PooledDictionary<ISymbol, int>.GetInstance(out var variableDeclarationIndex); using var _2 = PooledDictionary<ISymbol, int>.GetInstance(out var lastVariableUsageIndex); // Loop through the statements from the trigger declaration to the end of the containing body. // By starting with the trigger declaration it will add the trigger variable to the list of // local variables. for (var statementIndex = 0; statementIndex < statementsFromDeclarationToEnd.Length; statementIndex++) { var currentStatement = statementsFromDeclarationToEnd[statementIndex]; // Determine which local variables were referenced in this statement. using var _ = PooledHashSet<ISymbol>.GetInstance(out var referencedVariables); AddReferencedLocalVariables(referencedVariables, currentStatement, localVariables, semanticModel, syntaxFactsService, cancellationToken); // Update the last usage index for each of the referenced variables. foreach (var referencedVariable in referencedVariables) { lastVariableUsageIndex[referencedVariable] = statementIndex; } // Determine if new variables were declared in this statement. var declaredVariables = semanticModel.GetAllDeclaredSymbols(currentStatement, cancellationToken); foreach (var declaredVariable in declaredVariables) { // Initialize the declaration and usage index for the new variable and add it // to the list of local variables. variableDeclarationIndex[declaredVariable] = statementIndex; lastVariableUsageIndex[declaredVariable] = statementIndex; localVariables.Add(declaredVariable); } } // Initially we will consider the trigger declaration statement the end of the using // statement. This index will grow as we examine the last usage index of the local // variables declared within the using statements scope. var endOfUsingStatementIndex = 0; // Walk through the local variables in the order that they were declared, starting // with the trigger variable. foreach (var localSymbol in localVariables) { var declarationIndex = variableDeclarationIndex[localSymbol]; if (declarationIndex > endOfUsingStatementIndex) { // If the variable was declared after the last statement to include in // the using statement, we have gone far enough and other variables will // also be declared outside the using statement. break; } // If this variable was used later in the method than what we were considering // the scope of the using statement, then increase the scope to include its last // usage. endOfUsingStatementIndex = Math.Max(endOfUsingStatementIndex, lastVariableUsageIndex[localSymbol]); } return statementsFromDeclarationToEnd[endOfUsingStatementIndex]; } /// <summary> /// Adds local variables that are being referenced within a statement to a set of symbols. /// </summary> private static void AddReferencedLocalVariables( HashSet<ISymbol> referencedVariables, SyntaxNode node, IReadOnlyList<ISymbol> localVariables, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService, CancellationToken cancellationToken) { // If this node matches one of our local variables, then we can say it has been referenced. if (syntaxFactsService.IsIdentifierName(node)) { var identifierName = syntaxFactsService.GetIdentifierOfSimpleName(node).ValueText; var variable = localVariables.FirstOrDefault(localVariable => syntaxFactsService.StringComparer.Equals(localVariable.Name, identifierName) && localVariable.Equals(semanticModel.GetSymbolInfo(node, cancellationToken).Symbol)); if (variable is object) { referencedVariables.Add(variable); } } // Walk through child nodes looking for references foreach (var nodeOrToken in node.ChildNodesAndTokens()) { // If we have already referenced all the local variables we are // concerned with, then we can return early. if (referencedVariables.Count == localVariables.Count) { return; } var childNode = nodeOrToken.AsNode(); if (childNode is null) { continue; } AddReferencedLocalVariables(referencedVariables, childNode, localVariables, semanticModel, syntaxFactsService, cancellationToken); } } private sealed class MyCodeAction : DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.IntroduceUsingStatement { internal abstract class AbstractIntroduceUsingStatementCodeRefactoringProvider<TStatementSyntax, TLocalDeclarationSyntax> : CodeRefactoringProvider where TStatementSyntax : SyntaxNode where TLocalDeclarationSyntax : TStatementSyntax { protected abstract string CodeActionTitle { get; } protected abstract bool CanRefactorToContainBlockStatements(SyntaxNode parent); protected abstract SyntaxList<TStatementSyntax> GetStatements(SyntaxNode parentOfStatementsToSurround); protected abstract SyntaxNode WithStatements(SyntaxNode parentOfStatementsToSurround, SyntaxList<TStatementSyntax> statements); protected abstract TStatementSyntax CreateUsingStatement(TLocalDeclarationSyntax declarationStatement, SyntaxTriviaList sameLineTrivia, SyntaxList<TStatementSyntax> statementsToSurround); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var declarationSyntax = await FindDisposableLocalDeclarationAsync(document, span, cancellationToken).ConfigureAwait(false); if (declarationSyntax != null) { context.RegisterRefactoring( new MyCodeAction( CodeActionTitle, cancellationToken => IntroduceUsingStatementAsync(document, declarationSyntax, cancellationToken)), declarationSyntax.Span); } } private async Task<TLocalDeclarationSyntax?> FindDisposableLocalDeclarationAsync(Document document, TextSpan selection, CancellationToken cancellationToken) { var declarationSyntax = await document.TryGetRelevantNodeAsync<TLocalDeclarationSyntax>(selection, cancellationToken).ConfigureAwait(false); if (declarationSyntax is null || !CanRefactorToContainBlockStatements(declarationSyntax.GetRequiredParent())) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var disposableType = semanticModel.Compilation.GetSpecialType(SpecialType.System_IDisposable); if (disposableType is null) { return null; } var operation = semanticModel.GetOperation(declarationSyntax, cancellationToken) as IVariableDeclarationGroupOperation; if (operation?.Declarations.Length != 1) { return null; } var localDeclaration = operation.Declarations[0]; if (localDeclaration.Declarators.Length != 1) { return null; } var declarator = localDeclaration.Declarators[0]; var localType = declarator.Symbol?.Type; if (localType is null) { return null; } var initializer = (localDeclaration.Initializer ?? declarator.Initializer)?.Value; // Initializer kind is invalid when incomplete declaration syntax ends in an equals token. if (initializer is null || initializer.Kind == OperationKind.Invalid) { return null; } if (!IsLegalUsingStatementType(semanticModel.Compilation, disposableType, localType)) { return null; } return declarationSyntax; } /// <summary> /// Up to date with C# 7.3. Pattern-based disposal is likely to be added to C# 8.0, /// in which case accessible instance and extension methods will need to be detected. /// </summary> private static bool IsLegalUsingStatementType(Compilation compilation, ITypeSymbol disposableType, ITypeSymbol type) { if (disposableType == null) { return false; } // CS1674: type used in a using statement must be implicitly convertible to 'System.IDisposable' return compilation.ClassifyCommonConversion(type, disposableType).IsImplicit; } private async Task<Document> IntroduceUsingStatementAsync( Document document, TLocalDeclarationSyntax declarationStatement, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); var statementsToSurround = GetStatementsToSurround(declarationStatement, semanticModel, syntaxFactsService, cancellationToken); // Separate the newline from the trivia that is going on the using declaration line. var (sameLine, endOfLine) = SplitTrailingTrivia(declarationStatement, syntaxFactsService); var usingStatement = CreateUsingStatement( declarationStatement, sameLine, statementsToSurround) .WithLeadingTrivia(declarationStatement.GetLeadingTrivia()) .WithTrailingTrivia(endOfLine); if (statementsToSurround.Any()) { var parentStatements = GetStatements(declarationStatement.GetRequiredParent()); var declarationStatementIndex = parentStatements.IndexOf(declarationStatement); var newParent = WithStatements( declarationStatement.GetRequiredParent(), new SyntaxList<TStatementSyntax>(parentStatements .Take(declarationStatementIndex) .Concat(usingStatement) .Concat(parentStatements.Skip(declarationStatementIndex + 1 + statementsToSurround.Count)))); return document.WithSyntaxRoot(root.ReplaceNode( declarationStatement.GetRequiredParent(), newParent.WithAdditionalAnnotations(Formatter.Annotation))); } else { // Either the parent is not blocklike, meaning WithStatements can’t be used as in the other branch, // or there’s just no need to replace more than the statement itself because no following statements // will be surrounded. return document.WithSyntaxRoot(root.ReplaceNode( declarationStatement, usingStatement.WithAdditionalAnnotations(Formatter.Annotation))); } } private SyntaxList<TStatementSyntax> GetStatementsToSurround( TLocalDeclarationSyntax declarationStatement, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService, CancellationToken cancellationToken) { // Find the minimal number of statements to move into the using block // in order to not break existing references to the local. var lastUsageStatement = FindSiblingStatementContainingLastUsage( declarationStatement, semanticModel, syntaxFactsService, cancellationToken); if (lastUsageStatement == declarationStatement) { return default; } var parentStatements = GetStatements(declarationStatement.GetRequiredParent()); var declarationStatementIndex = parentStatements.IndexOf(declarationStatement); var lastUsageStatementIndex = parentStatements.IndexOf(lastUsageStatement, declarationStatementIndex + 1); return new SyntaxList<TStatementSyntax>(parentStatements .Take(lastUsageStatementIndex + 1) .Skip(declarationStatementIndex + 1)); } private static (SyntaxTriviaList sameLine, SyntaxTriviaList endOfLine) SplitTrailingTrivia(SyntaxNode node, ISyntaxFactsService syntaxFactsService) { var trailingTrivia = node.GetTrailingTrivia(); var lastIndex = trailingTrivia.Count - 1; return lastIndex != -1 && syntaxFactsService.IsEndOfLineTrivia(trailingTrivia[lastIndex]) ? (sameLine: trailingTrivia.RemoveAt(lastIndex), endOfLine: new SyntaxTriviaList(trailingTrivia[lastIndex])) : (sameLine: trailingTrivia, endOfLine: SyntaxTriviaList.Empty); } private static TStatementSyntax FindSiblingStatementContainingLastUsage( TStatementSyntax declarationSyntax, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService, CancellationToken cancellationToken) { // We are going to step through the statements starting with the trigger variable's declaration. // We will track when new locals are declared and when they are used. To determine the last // statement that we should surround, we will walk through the locals in the order they are declared. // If the local's declaration index falls within the last variable usage index, we will extend // the last variable usage index to include the local's last usage. // Take all the statements starting with the trigger variable's declaration. var statementsFromDeclarationToEnd = declarationSyntax.GetRequiredParent().ChildNodesAndTokens() .Select(nodeOrToken => nodeOrToken.AsNode()) .OfType<TStatementSyntax>() .SkipWhile(node => node != declarationSyntax) .ToImmutableArray(); // List of local variables that will be in the order they are declared. using var _0 = ArrayBuilder<ISymbol>.GetInstance(out var localVariables); // Map a symbol to an index into the statementsFromDeclarationToEnd array. using var _1 = PooledDictionary<ISymbol, int>.GetInstance(out var variableDeclarationIndex); using var _2 = PooledDictionary<ISymbol, int>.GetInstance(out var lastVariableUsageIndex); // Loop through the statements from the trigger declaration to the end of the containing body. // By starting with the trigger declaration it will add the trigger variable to the list of // local variables. for (var statementIndex = 0; statementIndex < statementsFromDeclarationToEnd.Length; statementIndex++) { var currentStatement = statementsFromDeclarationToEnd[statementIndex]; // Determine which local variables were referenced in this statement. using var _ = PooledHashSet<ISymbol>.GetInstance(out var referencedVariables); AddReferencedLocalVariables(referencedVariables, currentStatement, localVariables, semanticModel, syntaxFactsService, cancellationToken); // Update the last usage index for each of the referenced variables. foreach (var referencedVariable in referencedVariables) { lastVariableUsageIndex[referencedVariable] = statementIndex; } // Determine if new variables were declared in this statement. var declaredVariables = semanticModel.GetAllDeclaredSymbols(currentStatement, cancellationToken); foreach (var declaredVariable in declaredVariables) { // Initialize the declaration and usage index for the new variable and add it // to the list of local variables. variableDeclarationIndex[declaredVariable] = statementIndex; lastVariableUsageIndex[declaredVariable] = statementIndex; localVariables.Add(declaredVariable); } } // Initially we will consider the trigger declaration statement the end of the using // statement. This index will grow as we examine the last usage index of the local // variables declared within the using statements scope. var endOfUsingStatementIndex = 0; // Walk through the local variables in the order that they were declared, starting // with the trigger variable. foreach (var localSymbol in localVariables) { var declarationIndex = variableDeclarationIndex[localSymbol]; if (declarationIndex > endOfUsingStatementIndex) { // If the variable was declared after the last statement to include in // the using statement, we have gone far enough and other variables will // also be declared outside the using statement. break; } // If this variable was used later in the method than what we were considering // the scope of the using statement, then increase the scope to include its last // usage. endOfUsingStatementIndex = Math.Max(endOfUsingStatementIndex, lastVariableUsageIndex[localSymbol]); } return statementsFromDeclarationToEnd[endOfUsingStatementIndex]; } /// <summary> /// Adds local variables that are being referenced within a statement to a set of symbols. /// </summary> private static void AddReferencedLocalVariables( HashSet<ISymbol> referencedVariables, SyntaxNode node, IReadOnlyList<ISymbol> localVariables, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService, CancellationToken cancellationToken) { // If this node matches one of our local variables, then we can say it has been referenced. if (syntaxFactsService.IsIdentifierName(node)) { var identifierName = syntaxFactsService.GetIdentifierOfSimpleName(node).ValueText; var variable = localVariables.FirstOrDefault(localVariable => syntaxFactsService.StringComparer.Equals(localVariable.Name, identifierName) && localVariable.Equals(semanticModel.GetSymbolInfo(node, cancellationToken).Symbol)); if (variable is object) { referencedVariables.Add(variable); } } // Walk through child nodes looking for references foreach (var nodeOrToken in node.ChildNodesAndTokens()) { // If we have already referenced all the local variables we are // concerned with, then we can return early. if (referencedVariables.Count == localVariables.Count) { return; } var childNode = nodeOrToken.AsNode(); if (childNode is null) { continue; } AddReferencedLocalVariables(referencedVariables, childNode, localVariables, semanticModel, syntaxFactsService, cancellationToken); } } private sealed class MyCodeAction : DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/Compilers/VisualBasic/Portable/Emit/NamespaceSymbolAdapter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.Cci Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols #If DEBUG Then Partial Friend NotInheritable Class NamespaceSymbolAdapter Inherits SymbolAdapter #Else Partial Friend MustInherit Class NamespaceSymbol #End If Implements Cci.INamespace Private ReadOnly Property INamedEntity_Name As String Implements INamedEntity.Name Get Return AdaptedNamespaceSymbol.MetadataName End Get End Property Private ReadOnly Property INamespaceSymbol_ContainingNamespace As Cci.INamespace Implements Cci.INamespace.ContainingNamespace Get Return AdaptedNamespaceSymbol.ContainingNamespace?.GetCciAdapter() End Get End Property Private Function INamespaceSymbol_GetInternalSymbol() As CodeAnalysis.Symbols.INamespaceSymbolInternal Implements Cci.INamespace.GetInternalSymbol Return AdaptedNamespaceSymbol End Function End Class Partial Friend Class NamespaceSymbol #If DEBUG Then Private _lazyAdapter As NamespaceSymbolAdapter Protected Overrides Function GetCciAdapterImpl() As SymbolAdapter Return GetCciAdapter() End Function Friend Shadows Function GetCciAdapter() As NamespaceSymbolAdapter If _lazyAdapter Is Nothing Then Return InterlockedOperations.Initialize(_lazyAdapter, New NamespaceSymbolAdapter(Me)) End If Return _lazyAdapter End Function #Else Friend ReadOnly Property AdaptedNamespaceSymbol As NamespaceSymbol Get Return Me End Get End Property Friend Shadows Function GetCciAdapter() As NamespaceSymbol Return Me End Function #End If End Class #If DEBUG Then Partial Friend Class NamespaceSymbolAdapter Friend ReadOnly Property AdaptedNamespaceSymbol As NamespaceSymbol Friend Sub New(underlyingNamespaceSymbol As NamespaceSymbol) AdaptedNamespaceSymbol = underlyingNamespaceSymbol End Sub Friend Overrides ReadOnly Property AdaptedSymbol As Symbol Get Return AdaptedNamespaceSymbol End Get End Property End Class #End If End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.Cci Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols #If DEBUG Then Partial Friend NotInheritable Class NamespaceSymbolAdapter Inherits SymbolAdapter #Else Partial Friend MustInherit Class NamespaceSymbol #End If Implements Cci.INamespace Private ReadOnly Property INamedEntity_Name As String Implements INamedEntity.Name Get Return AdaptedNamespaceSymbol.MetadataName End Get End Property Private ReadOnly Property INamespaceSymbol_ContainingNamespace As Cci.INamespace Implements Cci.INamespace.ContainingNamespace Get Return AdaptedNamespaceSymbol.ContainingNamespace?.GetCciAdapter() End Get End Property Private Function INamespaceSymbol_GetInternalSymbol() As CodeAnalysis.Symbols.INamespaceSymbolInternal Implements Cci.INamespace.GetInternalSymbol Return AdaptedNamespaceSymbol End Function End Class Partial Friend Class NamespaceSymbol #If DEBUG Then Private _lazyAdapter As NamespaceSymbolAdapter Protected Overrides Function GetCciAdapterImpl() As SymbolAdapter Return GetCciAdapter() End Function Friend Shadows Function GetCciAdapter() As NamespaceSymbolAdapter If _lazyAdapter Is Nothing Then Return InterlockedOperations.Initialize(_lazyAdapter, New NamespaceSymbolAdapter(Me)) End If Return _lazyAdapter End Function #Else Friend ReadOnly Property AdaptedNamespaceSymbol As NamespaceSymbol Get Return Me End Get End Property Friend Shadows Function GetCciAdapter() As NamespaceSymbol Return Me End Function #End If End Class #If DEBUG Then Partial Friend Class NamespaceSymbolAdapter Friend ReadOnly Property AdaptedNamespaceSymbol As NamespaceSymbol Friend Sub New(underlyingNamespaceSymbol As NamespaceSymbol) AdaptedNamespaceSymbol = underlyingNamespaceSymbol End Sub Friend Overrides ReadOnly Property AdaptedSymbol As Symbol Get Return AdaptedNamespaceSymbol End Get End Property End Class #End If End Namespace
-1
dotnet/roslyn
55,922
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.
Fixes #52639.
AlekseyTs
2021-08-26T16:50:08Z
2021-08-27T18:29:57Z
26c94b18f1bddadc789f5511b4dc3c9c3f3208c7
9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19
Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639.
./src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldTestState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.EncapsulateField; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EncapsulateField { internal class EncapsulateFieldTestState : IDisposable { private readonly TestHostDocument _testDocument; public TestWorkspace Workspace { get; } public Document TargetDocument { get; } public string NotificationMessage { get; private set; } public EncapsulateFieldTestState(TestWorkspace workspace) { Workspace = workspace; _testDocument = Workspace.Documents.Single(d => d.CursorPosition.HasValue || d.SelectedSpans.Any()); TargetDocument = Workspace.CurrentSolution.GetDocument(_testDocument.Id); var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback; var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => NotificationMessage = message); notificationService.NotificationCallback = callback; } public static EncapsulateFieldTestState Create(string markup) { var workspace = TestWorkspace.CreateCSharp(markup, composition: EditorTestCompositions.EditorFeatures); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement) .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement))); return new EncapsulateFieldTestState(workspace); } public void Encapsulate() { var args = new EncapsulateFieldCommandArgs(_testDocument.GetTextView(), _testDocument.GetTextBuffer()); var commandHandler = Workspace.ExportProvider.GetCommandHandler<EncapsulateFieldCommandHandler>(PredefinedCommandHandlerNames.EncapsulateField, ContentTypeNames.CSharpContentType); commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create()); } public void Dispose() { if (Workspace != null) { Workspace.Dispose(); } } public void AssertEncapsulateAs(string expected) { Encapsulate(); Assert.Equal(expected, _testDocument.GetTextBuffer().CurrentSnapshot.GetText().ToString()); } public void AssertError() { Encapsulate(); Assert.NotNull(NotificationMessage); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.EncapsulateField; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EncapsulateField { internal class EncapsulateFieldTestState : IDisposable { private readonly TestHostDocument _testDocument; public TestWorkspace Workspace { get; } public Document TargetDocument { get; } public string NotificationMessage { get; private set; } public EncapsulateFieldTestState(TestWorkspace workspace) { Workspace = workspace; _testDocument = Workspace.Documents.Single(d => d.CursorPosition.HasValue || d.SelectedSpans.Any()); TargetDocument = Workspace.CurrentSolution.GetDocument(_testDocument.Id); var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback; var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => NotificationMessage = message); notificationService.NotificationCallback = callback; } public static EncapsulateFieldTestState Create(string markup) { var workspace = TestWorkspace.CreateCSharp(markup, composition: EditorTestCompositions.EditorFeatures); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement) .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement))); return new EncapsulateFieldTestState(workspace); } public void Encapsulate() { var args = new EncapsulateFieldCommandArgs(_testDocument.GetTextView(), _testDocument.GetTextBuffer()); var commandHandler = Workspace.ExportProvider.GetCommandHandler<EncapsulateFieldCommandHandler>(PredefinedCommandHandlerNames.EncapsulateField, ContentTypeNames.CSharpContentType); commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create()); } public void Dispose() { if (Workspace != null) { Workspace.Dispose(); } } public void AssertEncapsulateAs(string expected) { Encapsulate(); Assert.Equal(expected, _testDocument.GetTextBuffer().CurrentSnapshot.GetText().ToString()); } public void AssertError() { Encapsulate(); Assert.NotNull(NotificationMessage); } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Workspaces/Core/Portable/Workspace/Solution/BranchId.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// solution branch Id /// </summary> internal class BranchId { private static int s_nextId; #pragma warning disable IDE0052 // Remove unread private members private readonly int _id; #pragma warning restore IDE0052 // Remove unread private members private BranchId(int id) => _id = id; internal static BranchId GetNextId() => new(Interlocked.Increment(ref s_nextId)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// solution branch Id /// </summary> [DebuggerDisplay("{_id}")] internal class BranchId { private static int s_nextId; #pragma warning disable IDE0052 // Remove unread private members private readonly int _id; #pragma warning restore IDE0052 // Remove unread private members private BranchId(int id) => _id = id; internal static BranchId GetNextId() => new(Interlocked.Increment(ref s_nextId)); } }
1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Workspaces/Core/Portable/Workspace/Solution/Document.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a source code document that is part of a project. /// It provides access to the source text, parsed syntax tree and the corresponding semantic model. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public class Document : TextDocument { /// <summary> /// A cached reference to the <see cref="SemanticModel"/>. /// </summary> private WeakReference<SemanticModel>? _model; /// <summary> /// A cached task that can be returned once the tree has already been created. This is only set if <see cref="SupportsSyntaxTree"/> returns true, /// so the inner value can be non-null. /// </summary> private Task<SyntaxTree>? _syntaxTreeResultTask; internal Document(Project project, DocumentState state) : base(project, state, TextDocumentKind.Document) { } internal DocumentState DocumentState => (DocumentState)State; /// <summary> /// The kind of source code this document contains. /// </summary> public SourceCodeKind SourceCodeKind => DocumentState.SourceCodeKind; /// <summary> /// True if the info of the document change (name, folders, file path; not the content) /// </summary> internal override bool HasInfoChanged(TextDocument otherTextDocument) { var otherDocument = otherTextDocument as Document ?? throw new ArgumentException($"{nameof(otherTextDocument)} isn't a regular document.", nameof(otherTextDocument)); return base.HasInfoChanged(otherDocument) || DocumentState.SourceCodeKind != otherDocument.SourceCodeKind; } [Obsolete("Use TextDocument.HasTextChanged")] internal bool HasTextChanged(Document otherDocument) => HasTextChanged(otherDocument, ignoreUnchangeableDocument: false); /// <summary> /// Get the current syntax tree for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxTreeAsync"/> to fetch the tree, which will parse the tree /// if it's not already parsed. /// </summary> public bool TryGetSyntaxTree([NotNullWhen(returnValue: true)] out SyntaxTree? syntaxTree) { // if we already have cache, use it if (_syntaxTreeResultTask != null) { syntaxTree = _syntaxTreeResultTask.Result; return true; } if (!DocumentState.TryGetSyntaxTree(out syntaxTree)) { return false; } // cache the result if it is not already cached if (_syntaxTreeResultTask == null) { var result = Task.FromResult(syntaxTree); Interlocked.CompareExchange(ref _syntaxTreeResultTask, result, null); } return true; } /// <summary> /// Get the current syntax tree version for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxVersionAsync"/> to fetch the version, which will load the tree /// if it's not already available. /// </summary> public bool TryGetSyntaxVersion(out VersionStamp version) { version = default; if (!this.TryGetTextVersion(out var textVersion)) { return false; } var projectVersion = this.Project.Version; version = textVersion.GetNewerVersion(projectVersion); return true; } /// <summary> /// Gets the version of the document's top level signature if it is already loaded and available. /// </summary> internal bool TryGetTopLevelChangeTextVersion(out VersionStamp version) => DocumentState.TryGetTopLevelChangeTextVersion(out version); /// <summary> /// Gets the version of the syntax tree. This is generally the newer of the text version and the project's version. /// </summary> public async Task<VersionStamp> GetSyntaxVersionAsync(CancellationToken cancellationToken = default) { var textVersion = await this.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = this.Project.Version; return textVersion.GetNewerVersion(projectVersion); } /// <summary> /// <see langword="true"/> if this Document supports providing data through the /// <see cref="GetSyntaxTreeAsync"/> and <see cref="GetSyntaxRootAsync"/> methods. /// /// If <see langword="false"/> then these methods will return <see langword="null"/> instead. /// </summary> public bool SupportsSyntaxTree => DocumentState.SupportsSyntaxTree; /// <summary> /// <see langword="true"/> if this Document supports providing data through the /// <see cref="GetSemanticModelAsync"/> method. /// /// If <see langword="false"/> then that method will return <see langword="null"/> instead. /// </summary> public bool SupportsSemanticModel { get { return this.SupportsSyntaxTree && this.Project.SupportsCompilation; } } /// <summary> /// Gets the <see cref="SyntaxTree" /> for this document asynchronously. /// </summary> /// <returns> /// The returned syntax tree can be <see langword="null"/> if the <see cref="SupportsSyntaxTree"/> returns <see /// langword="false"/>. This function may cause computation to occur the first time it is called, but will return /// a cached result every subsequent time. <see cref="SyntaxTree"/>'s can hold onto their roots lazily. So calls /// to <see cref="SyntaxTree.GetRoot"/> or <see cref="SyntaxTree.GetRootAsync"/> may end up causing computation /// to occur at that point. /// </returns> public Task<SyntaxTree?> GetSyntaxTreeAsync(CancellationToken cancellationToken = default) { // If the language doesn't support getting syntax trees for a document, then bail out immediately. if (!this.SupportsSyntaxTree) { return SpecializedTasks.Null<SyntaxTree>(); } // if we have a cached result task use it if (_syntaxTreeResultTask != null) { // _syntaxTreeResultTask is a Task<SyntaxTree> so the ! operator here isn't suppressing a possible null ref, but rather allowing the // conversion from Task<SyntaxTree> to Task<SyntaxTree?> since Task itself isn't properly variant. return _syntaxTreeResultTask!; } // check to see if we already have the tree before actually going async if (TryGetSyntaxTree(out var tree)) { // stash a completed result task for this value for the next request (to reduce extraneous allocations of tasks) // don't use the actual async task because it depends on a specific cancellation token // its okay to cache the task and hold onto the SyntaxTree, because the DocumentState already keeps the SyntaxTree alive. Interlocked.CompareExchange(ref _syntaxTreeResultTask, Task.FromResult(tree), null); // _syntaxTreeResultTask is a Task<SyntaxTree> so the ! operator here isn't suppressing a possible null ref, but rather allowing the // conversion from Task<SyntaxTree> to Task<SyntaxTree?> since Task itself isn't properly variant. return _syntaxTreeResultTask!; } // do it async for real. // GetSyntaxTreeAsync returns a Task<SyntaxTree> so the ! operator here isn't suppressing a possible null ref, but rather allowing the // conversion from Task<SyntaxTree> to Task<SyntaxTree?> since Task itself isn't properly variant. return DocumentState.GetSyntaxTreeAsync(cancellationToken).AsTask()!; } internal SyntaxTree? GetSyntaxTreeSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } return DocumentState.GetSyntaxTree(cancellationToken); } /// <summary> /// Gets the root node of the current syntax tree if the syntax tree has already been parsed and the tree is still cached. /// In almost all cases, you should call <see cref="GetSyntaxRootAsync"/> to fetch the root node, which will parse /// the document if necessary. /// </summary> public bool TryGetSyntaxRoot([NotNullWhen(returnValue: true)] out SyntaxNode? root) { root = null; return this.TryGetSyntaxTree(out var tree) && tree.TryGetRoot(out root) && root != null; } /// <summary> /// Gets the root node of the syntax tree asynchronously. /// </summary> /// <returns> /// The returned <see cref="SyntaxNode"/> will be <see langword="null"/> if <see /// cref="SupportsSyntaxTree"/> returns <see langword="false"/>. This function will return /// the same value if called multiple times. /// </returns> public async Task<SyntaxNode?> GetSyntaxRootAsync(CancellationToken cancellationToken = default) { if (!this.SupportsSyntaxTree) { return null; } var tree = (await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false))!; return await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); } /// <summary> /// Only for features that absolutely must run synchronously (probably because they're /// on the UI thread). Right now, the only feature this is for is Outlining as VS will /// block on that feature from the UI thread when a document is opened. /// </summary> internal SyntaxNode? GetSyntaxRootSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } var tree = this.GetSyntaxTreeSynchronously(cancellationToken)!; return tree.GetRoot(cancellationToken); } /// <summary> /// Gets the current semantic model for this document if the model is already computed and still cached. /// In almost all cases, you should call <see cref="GetSemanticModelAsync"/>, which will compute the semantic model /// if necessary. /// </summary> public bool TryGetSemanticModel([NotNullWhen(returnValue: true)] out SemanticModel? semanticModel) { semanticModel = null; return _model != null && _model.TryGetTarget(out semanticModel); } /// <summary> /// Gets the semantic model for this document asynchronously. /// </summary> /// <returns> /// The returned <see cref="SemanticModel"/> may be <see langword="null"/> if <see /// cref="SupportsSemanticModel"/> returns <see langword="false"/>. This function will /// return the same value if called multiple times. /// </returns> public async Task<SemanticModel?> GetSemanticModelAsync(CancellationToken cancellationToken = default) { try { if (!this.SupportsSemanticModel) { return null; } if (this.TryGetSemanticModel(out var semanticModel)) { return semanticModel; } var syntaxTree = await this.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var compilation = (await this.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false))!; var result = compilation.GetSemanticModel(syntaxTree); Contract.ThrowIfNull(result); // first try set the cache if it has not been set var original = Interlocked.CompareExchange(ref _model, new WeakReference<SemanticModel>(result), null); // okay, it is first time. if (original == null) { return result; } // It looks like someone has set it. Try to reuse same semantic model, or assign the new model if that // fails. The lock is required since there is no compare-and-set primitive for WeakReference<T>. lock (original) { if (original.TryGetTarget(out semanticModel)) { return semanticModel; } original.SetTarget(result); return result; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new instance of this document updated to have the source code kind specified. /// </summary> public Document WithSourceCodeKind(SourceCodeKind kind) => this.Project.Solution.WithDocumentSourceCodeKind(this.Id, kind).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the text specified. /// </summary> public Document WithText(SourceText text) => this.Project.Solution.WithDocumentText(this.Id, text, PreservationMode.PreserveIdentity).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have a syntax tree rooted by the specified syntax node. /// </summary> public Document WithSyntaxRoot(SyntaxNode root) => this.Project.Solution.WithDocumentSyntaxRoot(this.Id, root, PreservationMode.PreserveIdentity).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the specified name. /// </summary> public Document WithName(string name) => this.Project.Solution.WithDocumentName(this.Id, name).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the specified folders. /// </summary> public Document WithFolders(IEnumerable<string> folders) => this.Project.Solution.WithDocumentFolders(this.Id, folders).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the specified file path. /// </summary> /// <param name="filePath"></param> // TODO (https://github.com/dotnet/roslyn/issues/37125): Solution.WithDocumentFilePath will throw if // filePath is null, but it's odd because we *do* support null file paths. Why can't you switch a // document back to null? public Document WithFilePath(string filePath) => this.Project.Solution.WithDocumentFilePath(this.Id, filePath).GetDocument(this.Id)!; /// <summary> /// Get the text changes between this document and a prior version of the same document. /// The changes, when applied to the text of the old document, will produce the text of the current document. /// </summary> public async Task<IEnumerable<TextChange>> GetTextChangesAsync(Document oldDocument, CancellationToken cancellationToken = default) { try { using (Logger.LogBlock(FunctionId.Workspace_Document_GetTextChanges, this.Name, cancellationToken)) { if (oldDocument == this) { // no changes return SpecializedCollections.EmptyEnumerable<TextChange>(); } if (this.Id != oldDocument.Id) { throw new ArgumentException(WorkspacesResources.The_specified_document_is_not_a_version_of_this_document); } // first try to see if text already knows its changes if (this.TryGetText(out var text) && oldDocument.TryGetText(out var oldText)) { if (text == oldText) { return SpecializedCollections.EmptyEnumerable<TextChange>(); } var container = text.Container; if (container != null) { var textChanges = text.GetTextChanges(oldText).ToList(); // if changes are significant (not the whole document being replaced) then use these changes if (textChanges.Count > 1 || (textChanges.Count == 1 && textChanges[0].Span != new TextSpan(0, oldText.Length))) { return textChanges; } } } // get changes by diffing the trees if (this.SupportsSyntaxTree) { var tree = (await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false))!; var oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); RoslynDebug.Assert(oldTree is object); return tree.GetChanges(oldTree); } text = await this.GetTextAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); return text.GetTextChanges(oldText).ToList(); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Gets the list of <see cref="DocumentId"/>s that are linked to this /// <see cref="Document" />. <see cref="Document"/>s are considered to be linked if they /// share the same <see cref="TextDocument.FilePath" />. This <see cref="DocumentId"/> is excluded from the /// result. /// </summary> public ImmutableArray<DocumentId> GetLinkedDocumentIds() { var documentIdsWithPath = this.Project.Solution.GetDocumentIdsWithFilePath(this.FilePath); var filteredDocumentIds = this.Project.Solution.FilterDocumentIdsByLanguage(documentIdsWithPath, this.Project.Language); return filteredDocumentIds.Remove(this.Id); } /// <summary> /// Creates a branched version of this document that has its semantic model frozen in whatever state it is available at the time, /// assuming a background process is constructing the semantics asynchronously. Repeated calls to this method may return /// documents with increasingly more complete semantics. /// /// Use this method to gain access to potentially incomplete semantics quickly. /// </summary> internal virtual Document WithFrozenPartialSemantics(CancellationToken cancellationToken) { var solution = this.Project.Solution; var workspace = solution.Workspace; // only produce doc with frozen semantics if this document is part of the workspace's // primary branch and there is actual background compilation going on, since w/o // background compilation the semantics won't be moving toward completeness. Also, // ensure that the project that this document is part of actually supports compilations, // as partial semantics don't make sense otherwise. if (solution.BranchId == workspace.PrimaryBranchId && workspace.PartialSemanticsEnabled && this.Project.SupportsCompilation) { var newSolution = this.Project.Solution.WithFrozenPartialCompilationIncludingSpecificDocument(this.Id, cancellationToken); return newSolution.GetDocument(this.Id)!; } else { return this; } } private string GetDebuggerDisplay() => this.Name; private AsyncLazy<DocumentOptionSet>? _cachedOptions; /// <summary> /// Returns the options that should be applied to this document. This consists of global options from <see cref="Solution.Options"/>, /// merged with any settings the user has specified at the document levels. /// </summary> /// <remarks> /// This method is async because this may require reading other files. In files that are already open, this is expected to be cheap and complete synchronously. /// </remarks> public Task<DocumentOptionSet> GetOptionsAsync(CancellationToken cancellationToken = default) => GetOptionsAsync(Project.Solution.Options, cancellationToken); [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", AllowCaptures = false)] internal Task<DocumentOptionSet> GetOptionsAsync(OptionSet solutionOptions, CancellationToken cancellationToken) { // TODO: we have this workaround since Solution.Options is not actually snapshot but just return Workspace.Options which violate snapshot model. // this doesn't validate whether same optionset is given to invalidate the cache or not. this is not new since existing implementation // also didn't check whether Workspace.Option is same as before or not. all weird-ness come from the root cause of Solution.Options violating // snapshot model. once that is fixed, we can remove this workaround - https://github.com/dotnet/roslyn/issues/19284 if (_cachedOptions == null) { InitializeCachedOptions(solutionOptions); } Contract.ThrowIfNull(_cachedOptions); return _cachedOptions.GetValueAsync(cancellationToken); } private void InitializeCachedOptions(OptionSet solutionOptions) { var newAsyncLazy = new AsyncLazy<DocumentOptionSet>(async c => { var optionsService = Project.Solution.Workspace.Services.GetRequiredService<IOptionService>(); var documentOptionSet = await optionsService.GetUpdatedOptionSetForDocumentAsync(this, solutionOptions, c).ConfigureAwait(false); return new DocumentOptionSet(documentOptionSet, Project.Language); }, cacheResult: true); Interlocked.CompareExchange(ref _cachedOptions, newAsyncLazy, comparand: null); } internal Task<ImmutableDictionary<string, string>> GetAnalyzerOptionsAsync(CancellationToken cancellationToken) { var projectFilePath = Project.FilePath; // We need to work out path to this document. Documents may not have a "real" file path if they're something created // as a part of a code action, but haven't been written to disk yet. string? effectiveFilePath = null; if (FilePath != null) { effectiveFilePath = FilePath; } else if (Name != null && projectFilePath != null) { var projectPath = PathUtilities.GetDirectoryName(projectFilePath); if (!RoslynString.IsNullOrEmpty(projectPath) && PathUtilities.GetDirectoryName(projectFilePath) is string directory) { effectiveFilePath = PathUtilities.CombinePathsUnchecked(directory, Name); } } if (effectiveFilePath != null) { return Project.State.GetAnalyzerOptionsForPathAsync(effectiveFilePath, cancellationToken); } else { // Really no idea where this is going, so bail // TODO: use AnalyzerConfigOptions.EmptyDictionary, since we don't have a public dictionary return Task.FromResult(ImmutableDictionary.Create<string, string>(AnalyzerConfigOptions.KeyComparer)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a source code document that is part of a project. /// It provides access to the source text, parsed syntax tree and the corresponding semantic model. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public class Document : TextDocument { /// <summary> /// A cached reference to the <see cref="SemanticModel"/>. /// </summary> private WeakReference<SemanticModel>? _model; /// <summary> /// A cached task that can be returned once the tree has already been created. This is only set if <see cref="SupportsSyntaxTree"/> returns true, /// so the inner value can be non-null. /// </summary> private Task<SyntaxTree>? _syntaxTreeResultTask; internal Document(Project project, DocumentState state) : base(project, state, TextDocumentKind.Document) { } internal DocumentState DocumentState => (DocumentState)State; /// <summary> /// The kind of source code this document contains. /// </summary> public SourceCodeKind SourceCodeKind => DocumentState.SourceCodeKind; /// <summary> /// True if the info of the document change (name, folders, file path; not the content) /// </summary> internal override bool HasInfoChanged(TextDocument otherTextDocument) { var otherDocument = otherTextDocument as Document ?? throw new ArgumentException($"{nameof(otherTextDocument)} isn't a regular document.", nameof(otherTextDocument)); return base.HasInfoChanged(otherDocument) || DocumentState.SourceCodeKind != otherDocument.SourceCodeKind; } [Obsolete("Use TextDocument.HasTextChanged")] internal bool HasTextChanged(Document otherDocument) => HasTextChanged(otherDocument, ignoreUnchangeableDocument: false); /// <summary> /// Get the current syntax tree for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxTreeAsync"/> to fetch the tree, which will parse the tree /// if it's not already parsed. /// </summary> public bool TryGetSyntaxTree([NotNullWhen(returnValue: true)] out SyntaxTree? syntaxTree) { // if we already have cache, use it if (_syntaxTreeResultTask != null) { syntaxTree = _syntaxTreeResultTask.Result; return true; } if (!DocumentState.TryGetSyntaxTree(out syntaxTree)) { return false; } // cache the result if it is not already cached if (_syntaxTreeResultTask == null) { var result = Task.FromResult(syntaxTree); Interlocked.CompareExchange(ref _syntaxTreeResultTask, result, null); } return true; } /// <summary> /// Get the current syntax tree version for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxVersionAsync"/> to fetch the version, which will load the tree /// if it's not already available. /// </summary> public bool TryGetSyntaxVersion(out VersionStamp version) { version = default; if (!this.TryGetTextVersion(out var textVersion)) { return false; } var projectVersion = this.Project.Version; version = textVersion.GetNewerVersion(projectVersion); return true; } /// <summary> /// Gets the version of the document's top level signature if it is already loaded and available. /// </summary> internal bool TryGetTopLevelChangeTextVersion(out VersionStamp version) => DocumentState.TryGetTopLevelChangeTextVersion(out version); /// <summary> /// Gets the version of the syntax tree. This is generally the newer of the text version and the project's version. /// </summary> public async Task<VersionStamp> GetSyntaxVersionAsync(CancellationToken cancellationToken = default) { var textVersion = await this.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = this.Project.Version; return textVersion.GetNewerVersion(projectVersion); } /// <summary> /// <see langword="true"/> if this Document supports providing data through the /// <see cref="GetSyntaxTreeAsync"/> and <see cref="GetSyntaxRootAsync"/> methods. /// /// If <see langword="false"/> then these methods will return <see langword="null"/> instead. /// </summary> public bool SupportsSyntaxTree => DocumentState.SupportsSyntaxTree; /// <summary> /// <see langword="true"/> if this Document supports providing data through the /// <see cref="GetSemanticModelAsync"/> method. /// /// If <see langword="false"/> then that method will return <see langword="null"/> instead. /// </summary> public bool SupportsSemanticModel { get { return this.SupportsSyntaxTree && this.Project.SupportsCompilation; } } /// <summary> /// Gets the <see cref="SyntaxTree" /> for this document asynchronously. /// </summary> /// <returns> /// The returned syntax tree can be <see langword="null"/> if the <see cref="SupportsSyntaxTree"/> returns <see /// langword="false"/>. This function may cause computation to occur the first time it is called, but will return /// a cached result every subsequent time. <see cref="SyntaxTree"/>'s can hold onto their roots lazily. So calls /// to <see cref="SyntaxTree.GetRoot"/> or <see cref="SyntaxTree.GetRootAsync"/> may end up causing computation /// to occur at that point. /// </returns> public Task<SyntaxTree?> GetSyntaxTreeAsync(CancellationToken cancellationToken = default) { // If the language doesn't support getting syntax trees for a document, then bail out immediately. if (!this.SupportsSyntaxTree) { return SpecializedTasks.Null<SyntaxTree>(); } // if we have a cached result task use it if (_syntaxTreeResultTask != null) { // _syntaxTreeResultTask is a Task<SyntaxTree> so the ! operator here isn't suppressing a possible null ref, but rather allowing the // conversion from Task<SyntaxTree> to Task<SyntaxTree?> since Task itself isn't properly variant. return _syntaxTreeResultTask!; } // check to see if we already have the tree before actually going async if (TryGetSyntaxTree(out var tree)) { // stash a completed result task for this value for the next request (to reduce extraneous allocations of tasks) // don't use the actual async task because it depends on a specific cancellation token // its okay to cache the task and hold onto the SyntaxTree, because the DocumentState already keeps the SyntaxTree alive. Interlocked.CompareExchange(ref _syntaxTreeResultTask, Task.FromResult(tree), null); // _syntaxTreeResultTask is a Task<SyntaxTree> so the ! operator here isn't suppressing a possible null ref, but rather allowing the // conversion from Task<SyntaxTree> to Task<SyntaxTree?> since Task itself isn't properly variant. return _syntaxTreeResultTask!; } // do it async for real. // GetSyntaxTreeAsync returns a Task<SyntaxTree> so the ! operator here isn't suppressing a possible null ref, but rather allowing the // conversion from Task<SyntaxTree> to Task<SyntaxTree?> since Task itself isn't properly variant. return DocumentState.GetSyntaxTreeAsync(cancellationToken).AsTask()!; } internal SyntaxTree? GetSyntaxTreeSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } return DocumentState.GetSyntaxTree(cancellationToken); } /// <summary> /// Gets the root node of the current syntax tree if the syntax tree has already been parsed and the tree is still cached. /// In almost all cases, you should call <see cref="GetSyntaxRootAsync"/> to fetch the root node, which will parse /// the document if necessary. /// </summary> public bool TryGetSyntaxRoot([NotNullWhen(returnValue: true)] out SyntaxNode? root) { root = null; return this.TryGetSyntaxTree(out var tree) && tree.TryGetRoot(out root) && root != null; } /// <summary> /// Gets the root node of the syntax tree asynchronously. /// </summary> /// <returns> /// The returned <see cref="SyntaxNode"/> will be <see langword="null"/> if <see /// cref="SupportsSyntaxTree"/> returns <see langword="false"/>. This function will return /// the same value if called multiple times. /// </returns> public async Task<SyntaxNode?> GetSyntaxRootAsync(CancellationToken cancellationToken = default) { if (!this.SupportsSyntaxTree) { return null; } var tree = (await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false))!; return await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); } /// <summary> /// Only for features that absolutely must run synchronously (probably because they're /// on the UI thread). Right now, the only feature this is for is Outlining as VS will /// block on that feature from the UI thread when a document is opened. /// </summary> internal SyntaxNode? GetSyntaxRootSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } var tree = this.GetSyntaxTreeSynchronously(cancellationToken)!; return tree.GetRoot(cancellationToken); } /// <summary> /// Gets the current semantic model for this document if the model is already computed and still cached. /// In almost all cases, you should call <see cref="GetSemanticModelAsync"/>, which will compute the semantic model /// if necessary. /// </summary> public bool TryGetSemanticModel([NotNullWhen(returnValue: true)] out SemanticModel? semanticModel) { semanticModel = null; return _model != null && _model.TryGetTarget(out semanticModel); } /// <summary> /// Gets the semantic model for this document asynchronously. /// </summary> /// <returns> /// The returned <see cref="SemanticModel"/> may be <see langword="null"/> if <see /// cref="SupportsSemanticModel"/> returns <see langword="false"/>. This function will /// return the same value if called multiple times. /// </returns> public async Task<SemanticModel?> GetSemanticModelAsync(CancellationToken cancellationToken = default) { try { if (!this.SupportsSemanticModel) { return null; } if (this.TryGetSemanticModel(out var semanticModel)) { return semanticModel; } var syntaxTree = await this.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var compilation = (await this.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false))!; var result = compilation.GetSemanticModel(syntaxTree); Contract.ThrowIfNull(result); // first try set the cache if it has not been set var original = Interlocked.CompareExchange(ref _model, new WeakReference<SemanticModel>(result), null); // okay, it is first time. if (original == null) { return result; } // It looks like someone has set it. Try to reuse same semantic model, or assign the new model if that // fails. The lock is required since there is no compare-and-set primitive for WeakReference<T>. lock (original) { if (original.TryGetTarget(out semanticModel)) { return semanticModel; } original.SetTarget(result); return result; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new instance of this document updated to have the source code kind specified. /// </summary> public Document WithSourceCodeKind(SourceCodeKind kind) => this.Project.Solution.WithDocumentSourceCodeKind(this.Id, kind).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the text specified. /// </summary> public Document WithText(SourceText text) => this.Project.Solution.WithDocumentText(this.Id, text, PreservationMode.PreserveIdentity).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have a syntax tree rooted by the specified syntax node. /// </summary> public Document WithSyntaxRoot(SyntaxNode root) => this.Project.Solution.WithDocumentSyntaxRoot(this.Id, root, PreservationMode.PreserveIdentity).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the specified name. /// </summary> public Document WithName(string name) => this.Project.Solution.WithDocumentName(this.Id, name).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the specified folders. /// </summary> public Document WithFolders(IEnumerable<string> folders) => this.Project.Solution.WithDocumentFolders(this.Id, folders).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the specified file path. /// </summary> /// <param name="filePath"></param> // TODO (https://github.com/dotnet/roslyn/issues/37125): Solution.WithDocumentFilePath will throw if // filePath is null, but it's odd because we *do* support null file paths. Why can't you switch a // document back to null? public Document WithFilePath(string filePath) => this.Project.Solution.WithDocumentFilePath(this.Id, filePath).GetDocument(this.Id)!; /// <summary> /// Get the text changes between this document and a prior version of the same document. /// The changes, when applied to the text of the old document, will produce the text of the current document. /// </summary> public async Task<IEnumerable<TextChange>> GetTextChangesAsync(Document oldDocument, CancellationToken cancellationToken = default) { try { using (Logger.LogBlock(FunctionId.Workspace_Document_GetTextChanges, this.Name, cancellationToken)) { if (oldDocument == this) { // no changes return SpecializedCollections.EmptyEnumerable<TextChange>(); } if (this.Id != oldDocument.Id) { throw new ArgumentException(WorkspacesResources.The_specified_document_is_not_a_version_of_this_document); } // first try to see if text already knows its changes if (this.TryGetText(out var text) && oldDocument.TryGetText(out var oldText)) { if (text == oldText) { return SpecializedCollections.EmptyEnumerable<TextChange>(); } var container = text.Container; if (container != null) { var textChanges = text.GetTextChanges(oldText).ToList(); // if changes are significant (not the whole document being replaced) then use these changes if (textChanges.Count > 1 || (textChanges.Count == 1 && textChanges[0].Span != new TextSpan(0, oldText.Length))) { return textChanges; } } } // get changes by diffing the trees if (this.SupportsSyntaxTree) { var tree = (await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false))!; var oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); RoslynDebug.Assert(oldTree is object); return tree.GetChanges(oldTree); } text = await this.GetTextAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); return text.GetTextChanges(oldText).ToList(); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Gets the list of <see cref="DocumentId"/>s that are linked to this /// <see cref="Document" />. <see cref="Document"/>s are considered to be linked if they /// share the same <see cref="TextDocument.FilePath" />. This <see cref="DocumentId"/> is excluded from the /// result. /// </summary> public ImmutableArray<DocumentId> GetLinkedDocumentIds() { var documentIdsWithPath = this.Project.Solution.GetDocumentIdsWithFilePath(this.FilePath); var filteredDocumentIds = this.Project.Solution.FilterDocumentIdsByLanguage(documentIdsWithPath, this.Project.Language); return filteredDocumentIds.Remove(this.Id); } /// <summary> /// Creates a branched version of this document that has its semantic model frozen in whatever state it is available at the time, /// assuming a background process is constructing the semantics asynchronously. Repeated calls to this method may return /// documents with increasingly more complete semantics. /// /// Use this method to gain access to potentially incomplete semantics quickly. /// </summary> internal virtual Document WithFrozenPartialSemantics(CancellationToken cancellationToken) { var solution = this.Project.Solution; var workspace = solution.Workspace; // only produce doc with frozen semantics if this workspace has support for that, as without // background compilation the semantics won't be moving toward completeness. Also, // ensure that the project that this document is part of actually supports compilations, // as partial semantics don't make sense otherwise. if (workspace.PartialSemanticsEnabled && this.Project.SupportsCompilation) { var newSolution = this.Project.Solution.WithFrozenPartialCompilationIncludingSpecificDocument(this.Id, cancellationToken); return newSolution.GetDocument(this.Id)!; } else { return this; } } private string GetDebuggerDisplay() => this.Name; private AsyncLazy<DocumentOptionSet>? _cachedOptions; /// <summary> /// Returns the options that should be applied to this document. This consists of global options from <see cref="Solution.Options"/>, /// merged with any settings the user has specified at the document levels. /// </summary> /// <remarks> /// This method is async because this may require reading other files. In files that are already open, this is expected to be cheap and complete synchronously. /// </remarks> public Task<DocumentOptionSet> GetOptionsAsync(CancellationToken cancellationToken = default) => GetOptionsAsync(Project.Solution.Options, cancellationToken); [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", AllowCaptures = false)] internal Task<DocumentOptionSet> GetOptionsAsync(OptionSet solutionOptions, CancellationToken cancellationToken) { // TODO: we have this workaround since Solution.Options is not actually snapshot but just return Workspace.Options which violate snapshot model. // this doesn't validate whether same optionset is given to invalidate the cache or not. this is not new since existing implementation // also didn't check whether Workspace.Option is same as before or not. all weird-ness come from the root cause of Solution.Options violating // snapshot model. once that is fixed, we can remove this workaround - https://github.com/dotnet/roslyn/issues/19284 if (_cachedOptions == null) { InitializeCachedOptions(solutionOptions); } Contract.ThrowIfNull(_cachedOptions); return _cachedOptions.GetValueAsync(cancellationToken); } private void InitializeCachedOptions(OptionSet solutionOptions) { var newAsyncLazy = new AsyncLazy<DocumentOptionSet>(async c => { var optionsService = Project.Solution.Workspace.Services.GetRequiredService<IOptionService>(); var documentOptionSet = await optionsService.GetUpdatedOptionSetForDocumentAsync(this, solutionOptions, c).ConfigureAwait(false); return new DocumentOptionSet(documentOptionSet, Project.Language); }, cacheResult: true); Interlocked.CompareExchange(ref _cachedOptions, newAsyncLazy, comparand: null); } internal Task<ImmutableDictionary<string, string>> GetAnalyzerOptionsAsync(CancellationToken cancellationToken) { var projectFilePath = Project.FilePath; // We need to work out path to this document. Documents may not have a "real" file path if they're something created // as a part of a code action, but haven't been written to disk yet. string? effectiveFilePath = null; if (FilePath != null) { effectiveFilePath = FilePath; } else if (Name != null && projectFilePath != null) { var projectPath = PathUtilities.GetDirectoryName(projectFilePath); if (!RoslynString.IsNullOrEmpty(projectPath) && PathUtilities.GetDirectoryName(projectFilePath) is string directory) { effectiveFilePath = PathUtilities.CombinePathsUnchecked(directory, Name); } } if (effectiveFilePath != null) { return Project.State.GetAnalyzerOptionsForPathAsync(effectiveFilePath, cancellationToken); } else { // Really no idea where this is going, so bail // TODO: use AnalyzerConfigOptions.EmptyDictionary, since we don't have a public dictionary return Task.FromResult(ImmutableDictionary.Create<string, string>(AnalyzerConfigOptions.KeyComparer)); } } } }
1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Workspaces/CoreTest/SolutionTests/SolutionTestHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests.Persistence; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { internal static class SolutionTestHelpers { public static Workspace CreateWorkspace(Type[]? additionalParts = null) => new AdhocWorkspace(FeaturesTestCompositions.Features.AddParts(additionalParts).GetHostServices()); public static Workspace CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() { var workspace = CreateWorkspace(new[] { typeof(TestProjectCacheService), typeof(TestTemporaryStorageService) }); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0))); return workspace; } public static Project AddEmptyProject(Solution solution, string languageName = LanguageNames.CSharp) { var id = ProjectId.CreateNewId(); return solution.AddProject( ProjectInfo.Create( id, VersionStamp.Default, name: "TestProject", assemblyName: "TestProject", language: languageName)).GetRequiredProject(id); } #nullable disable public static void TestProperty<T, TValue>(T instance, Func<T, TValue, T> factory, Func<T, TValue> getter, TValue validNonDefaultValue, bool defaultThrows = false) where T : class { Assert.NotEqual<TValue>(default, validNonDefaultValue); var instanceWithValue = factory(instance, validNonDefaultValue); Assert.Equal(validNonDefaultValue, getter(instanceWithValue)); // the factory returns the unchanged instance if the value is unchanged: var instanceWithValue2 = factory(instanceWithValue, validNonDefaultValue); Assert.Same(instanceWithValue2, instanceWithValue); if (defaultThrows) { Assert.Throws<ArgumentNullException>(() => factory(instance, default)); } else { Assert.NotNull(factory(instance, default)); } } public static void TestListProperty<T, TValue>(T instance, Func<T, IEnumerable<TValue>, T> factory, Func<T, IEnumerable<TValue>> getter, TValue item, bool allowDuplicates) where T : class { var boxedItems = (IEnumerable<TValue>)ImmutableArray.Create(item); TestProperty(instance, factory, getter, boxedItems, defaultThrows: false); var instanceWithNoItem = factory(instance, null); Assert.Empty(getter(instanceWithNoItem)); var instanceWithItem = factory(instanceWithNoItem, boxedItems); // the factory preserves the identity of a boxed immutable array: Assert.Same(boxedItems, getter(instanceWithItem)); Assert.Same(instanceWithNoItem, factory(instanceWithNoItem, null)); Assert.Same(instanceWithNoItem, factory(instanceWithNoItem, Array.Empty<TValue>())); Assert.Same(instanceWithNoItem, factory(instanceWithNoItem, ImmutableArray<TValue>.Empty)); // the factory makes an immutable copy if given a mutable list: var mutableItems = new[] { item }; var instanceWithMutableItems = factory(instanceWithNoItem, mutableItems); var items = getter(instanceWithMutableItems); Assert.NotSame(mutableItems, items); // null item: Assert.Throws<ArgumentNullException>(() => factory(instanceWithNoItem, new TValue[] { item, default })); // duplicate item: if (allowDuplicates) { var boxedDupItems = (IEnumerable<TValue>)ImmutableArray.Create(item, item); Assert.Same(boxedDupItems, getter(factory(instanceWithNoItem, boxedDupItems))); } else { Assert.Throws<ArgumentException>(() => factory(instanceWithNoItem, new TValue[] { item, item })); } } #nullable enable } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests.Persistence; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { internal static class SolutionTestHelpers { public static Workspace CreateWorkspace(Type[]? additionalParts = null) => new AdhocWorkspace(FeaturesTestCompositions.Features.AddParts(additionalParts).GetHostServices()); public static Workspace CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() { var workspace = CreateWorkspace(new[] { typeof(TestProjectCacheService), typeof(TestTemporaryStorageService) }); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0))); return workspace; } public static Workspace CreateWorkspaceWithPartalSemantics(Type[]? additionalParts = null) => new WorkspaceWithPartialSemantics(FeaturesTestCompositions.Features.AddParts(additionalParts).GetHostServices()); private class WorkspaceWithPartialSemantics : Workspace { public WorkspaceWithPartialSemantics(HostServices hostServices) : base(hostServices, workspaceKind: nameof(WorkspaceWithPartialSemantics)) { } protected internal override bool PartialSemanticsEnabled => true; } public static Project AddEmptyProject(Solution solution, string languageName = LanguageNames.CSharp) { var id = ProjectId.CreateNewId(); return solution.AddProject( ProjectInfo.Create( id, VersionStamp.Default, name: "TestProject", assemblyName: "TestProject", language: languageName)).GetRequiredProject(id); } #nullable disable public static void TestProperty<T, TValue>(T instance, Func<T, TValue, T> factory, Func<T, TValue> getter, TValue validNonDefaultValue, bool defaultThrows = false) where T : class { Assert.NotEqual<TValue>(default, validNonDefaultValue); var instanceWithValue = factory(instance, validNonDefaultValue); Assert.Equal(validNonDefaultValue, getter(instanceWithValue)); // the factory returns the unchanged instance if the value is unchanged: var instanceWithValue2 = factory(instanceWithValue, validNonDefaultValue); Assert.Same(instanceWithValue2, instanceWithValue); if (defaultThrows) { Assert.Throws<ArgumentNullException>(() => factory(instance, default)); } else { Assert.NotNull(factory(instance, default)); } } public static void TestListProperty<T, TValue>(T instance, Func<T, IEnumerable<TValue>, T> factory, Func<T, IEnumerable<TValue>> getter, TValue item, bool allowDuplicates) where T : class { var boxedItems = (IEnumerable<TValue>)ImmutableArray.Create(item); TestProperty(instance, factory, getter, boxedItems, defaultThrows: false); var instanceWithNoItem = factory(instance, null); Assert.Empty(getter(instanceWithNoItem)); var instanceWithItem = factory(instanceWithNoItem, boxedItems); // the factory preserves the identity of a boxed immutable array: Assert.Same(boxedItems, getter(instanceWithItem)); Assert.Same(instanceWithNoItem, factory(instanceWithNoItem, null)); Assert.Same(instanceWithNoItem, factory(instanceWithNoItem, Array.Empty<TValue>())); Assert.Same(instanceWithNoItem, factory(instanceWithNoItem, ImmutableArray<TValue>.Empty)); // the factory makes an immutable copy if given a mutable list: var mutableItems = new[] { item }; var instanceWithMutableItems = factory(instanceWithNoItem, mutableItems); var items = getter(instanceWithMutableItems); Assert.NotSame(mutableItems, items); // null item: Assert.Throws<ArgumentNullException>(() => factory(instanceWithNoItem, new TValue[] { item, default })); // duplicate item: if (allowDuplicates) { var boxedDupItems = (IEnumerable<TValue>)ImmutableArray.Create(item, item); Assert.Same(boxedDupItems, getter(factory(instanceWithNoItem, boxedDupItems))); } else { Assert.Throws<ArgumentException>(() => factory(instanceWithNoItem, new TValue[] { item, item })); } } } }
1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Persistence; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.VisualStudio.Threading; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using CS = Microsoft.CodeAnalysis.CSharp; using static Microsoft.CodeAnalysis.UnitTests.SolutionTestHelpers; namespace Microsoft.CodeAnalysis.UnitTests { [UseExportProvider] [Trait(Traits.Feature, Traits.Features.Workspace)] public class SolutionTests : TestBase { #nullable enable private static readonly MetadataReference s_mscorlib = TestMetadata.Net451.mscorlib; private static readonly DocumentId s_unrelatedDocumentId = DocumentId.CreateNewId(ProjectId.CreateNewId()); private static Workspace CreateWorkspaceWithProjectAndDocuments() { var projectId = ProjectId.CreateNewId(); var workspace = CreateWorkspace(); Assert.True(workspace.TryApplyChanges(workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp) .AddDocument(DocumentId.CreateNewId(projectId), "goo.cs", "public class Goo { }") .AddAdditionalDocument(DocumentId.CreateNewId(projectId), "add.txt", "text") .AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From("config"), filePath: "/a/b"))); return workspace; } private static IEnumerable<T> EmptyEnumerable<T>() { yield break; } // Returns an enumerable that can only be enumerated once. private static IEnumerable<T> OnceEnumerable<T>(params T[] items) => OnceEnumerableImpl(new StrongBox<int>(), items); private static IEnumerable<T> OnceEnumerableImpl<T>(StrongBox<int> counter, T[] items) { Assert.Equal(0, counter.Value); counter.Value++; foreach (var item in items) { yield return item; } } [Fact] public void RemoveDocument_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveDocument(null!)); Assert.Throws<InvalidOperationException>(() => solution.RemoveDocument(s_unrelatedDocumentId)); } [Fact] public void RemoveDocuments_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveDocuments(default)); Assert.Throws<InvalidOperationException>(() => solution.RemoveDocuments(ImmutableArray.Create(s_unrelatedDocumentId))); Assert.Throws<ArgumentNullException>(() => solution.RemoveDocuments(ImmutableArray.Create((DocumentId)null!))); } [Fact] public void RemoveAdditionalDocument_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocument(null!)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAdditionalDocument(s_unrelatedDocumentId)); } [Fact] public void RemoveAdditionalDocuments_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocuments(default)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAdditionalDocuments(ImmutableArray.Create(s_unrelatedDocumentId))); Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocuments(ImmutableArray.Create((DocumentId)null!))); } [Fact] public void RemoveAnalyzerConfigDocument_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocument(null!)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerConfigDocument(s_unrelatedDocumentId)); } [Fact] public void RemoveAnalyzerConfigDocuments_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocuments(default)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerConfigDocuments(ImmutableArray.Create(s_unrelatedDocumentId))); Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocuments(ImmutableArray.Create((DocumentId)null!))); } [Fact] public void WithDocumentName() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var name = "new name"; var newSolution1 = solution.WithDocumentName(documentId, name); Assert.Equal(name, newSolution1.GetDocument(documentId)!.Name); var newSolution2 = newSolution1.WithDocumentName(documentId, name); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentName(documentId, name: null!)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentName(null!, name)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentName(s_unrelatedDocumentId, name)); } [Fact] public void WithDocumentFolders() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var folders = new[] { "folder1", "folder2" }; var newSolution1 = solution.WithDocumentFolders(documentId, folders); Assert.Equal(folders, newSolution1.GetDocument(documentId)!.Folders); var newSolution2 = newSolution1.WithDocumentFolders(documentId, folders); Assert.Same(newSolution2, newSolution1); // empty: var newSolution3 = solution.WithDocumentFolders(documentId, new string[0]); Assert.Equal(new string[0], newSolution3.GetDocument(documentId)!.Folders); var newSolution4 = solution.WithDocumentFolders(documentId, ImmutableArray<string>.Empty); Assert.Same(newSolution3, newSolution4); var newSolution5 = solution.WithDocumentFolders(documentId, null); Assert.Same(newSolution3, newSolution5); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFolders(documentId, folders: new string[] { null! })); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFolders(null!, folders)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentFolders(s_unrelatedDocumentId, folders)); } [Fact] [WorkItem(34837, "https://github.com/dotnet/roslyn/issues/34837")] [WorkItem(37125, "https://github.com/dotnet/roslyn/issues/37125")] public void WithDocumentFilePath() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var path = "new path"; var newSolution1 = solution.WithDocumentFilePath(documentId, path); Assert.Equal(path, newSolution1.GetDocument(documentId)!.FilePath); AssertEx.Equal(new[] { documentId }, newSolution1.GetDocumentIdsWithFilePath(path)); var newSolution2 = newSolution1.WithDocumentFilePath(documentId, path); Assert.Same(newSolution1, newSolution2); // empty path (TODO https://github.com/dotnet/roslyn/issues/37125): var newSolution3 = solution.WithDocumentFilePath(documentId, ""); Assert.Equal("", newSolution3.GetDocument(documentId)!.FilePath); Assert.Empty(newSolution3.GetDocumentIdsWithFilePath("")); // TODO: https://github.com/dotnet/roslyn/issues/37125 Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFilePath(documentId, filePath: null!)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFilePath(null!, path)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentFilePath(s_unrelatedDocumentId, path)); } [Fact] public void WithSourceCodeKind() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); Assert.Same(solution, solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Regular)); var newSolution1 = solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Script); Assert.Equal(SourceCodeKind.Script, newSolution1.GetDocument(documentId)!.SourceCodeKind); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentSourceCodeKind(documentId, (SourceCodeKind)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentSourceCodeKind(null!, SourceCodeKind.Script)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentSourceCodeKind(s_unrelatedDocumentId, SourceCodeKind.Script)); } [Fact, Obsolete] public void WithSourceCodeKind_Obsolete() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var newSolution = solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Interactive); Assert.Equal(SourceCodeKind.Script, newSolution.GetDocument(documentId)!.SourceCodeKind); } [Fact] public void WithDocumentSyntaxRoot() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var root = CS.SyntaxFactory.ParseSyntaxTree("class NewClass {}").GetRoot(); var newSolution1 = solution.WithDocumentSyntaxRoot(documentId, root, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetSyntaxRoot(out var actualRoot)); Assert.Equal(root.ToString(), actualRoot!.ToString()); // the actual root has a new parent SyntaxTree: Assert.NotSame(root, actualRoot); var newSolution2 = newSolution1.WithDocumentSyntaxRoot(documentId, actualRoot); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentSyntaxRoot(documentId, root, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentSyntaxRoot(null!, root)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentSyntaxRoot(s_unrelatedDocumentId, root)); } [Fact] [WorkItem(37125, "https://github.com/dotnet/roslyn/issues/41940")] public async Task WithDocumentSyntaxRoot_AnalyzerConfigWithoutFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(DocumentId.CreateNewId(projectId), "goo.cs", "public class Goo { }") .AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From("config")); var project = solution.GetProject(projectId)!; var compilation = (await project.GetCompilationAsync())!; var tree = compilation.SyntaxTrees.Single(); var provider = compilation.Options.SyntaxTreeOptionsProvider!; Assert.Throws<ArgumentException>(() => provider.TryGetDiagnosticValue(tree, "CA1234", CancellationToken.None, out _)); } [Fact] public void WithDocumentText_SourceText() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(documentId, text, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity)); } [Fact] public void WithDocumentText_TextAndVersion() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default); var newSolution1 = solution.WithDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText)); Assert.True(newSolution1.GetDocument(documentId)!.TryGetTextVersion(out var actualVersion)); Assert.Same(textAndVersion.Text, actualText); Assert.Equal(textAndVersion.Version, actualVersion); var newSolution2 = newSolution1.WithDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(documentId, textAndVersion, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity)); } [Fact] public void WithDocumentText_MultipleDocuments() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithDocumentText(new[] { documentId }, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithDocumentText(new[] { documentId }, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); // documents not in solution are skipped: https://github.com/dotnet/roslyn/issues/42029 Assert.Same(solution, solution.WithDocumentText(new DocumentId[] { null! }, text)); Assert.Same(solution, solution.WithDocumentText(new DocumentId[] { s_unrelatedDocumentId }, text)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId[])null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(new[] { documentId }, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(new[] { documentId }, text, (PreservationMode)(-1))); } [Fact] public void WithAdditionalDocumentText_SourceText() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AdditionalDocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithAdditionalDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithAdditionalDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentText(documentId, text, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity)); } [Fact] public void WithAdditionalDocumentText_TextAndVersion() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AdditionalDocumentIds.Single(); var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default); var newSolution1 = solution.WithAdditionalDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText)); Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetTextVersion(out var actualVersion)); Assert.Same(textAndVersion.Text, actualText); Assert.Equal(textAndVersion.Version, actualVersion); var newSolution2 = newSolution1.WithAdditionalDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentText(documentId, textAndVersion, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity)); } [Fact] public void WithAnalyzerConfigDocumentText_SourceText() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithAnalyzerConfigDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithAnalyzerConfigDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentText(documentId, text, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity)); } [Fact] public void WithAnalyzerConfigDocumentText_TextAndVersion() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single(); var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default); var newSolution1 = solution.WithAnalyzerConfigDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText)); Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetTextVersion(out var actualVersion)); Assert.Same(textAndVersion.Text, actualText); Assert.Equal(textAndVersion.Version, actualVersion); var newSolution2 = newSolution1.WithAnalyzerConfigDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentText(documentId, textAndVersion, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity)); } [Fact] public void WithDocumentTextLoader() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var loader = new TestTextLoader("new text"); var newSolution1 = solution.WithDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.Equal("new text", newSolution1.GetDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString()); // Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028 var newSolution2 = solution.WithDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.NotSame(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentTextLoader(documentId, loader, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity)); } [Fact] public void WithAdditionalDocumentTextLoader() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AdditionalDocumentIds.Single(); var loader = new TestTextLoader("new text"); var newSolution1 = solution.WithAdditionalDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.Equal("new text", newSolution1.GetAdditionalDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString()); // Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028 var newSolution2 = solution.WithAdditionalDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.NotSame(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentTextLoader(documentId, loader, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity)); } [Fact] public void WithAnalyzerConfigDocumentTextLoader() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single(); var loader = new TestTextLoader("new text"); var newSolution1 = solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.Equal("new text", newSolution1.GetAnalyzerConfigDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString()); // Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028 var newSolution2 = solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.NotSame(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity)); } [Fact] public void WithProjectAssemblyName() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var assemblyName = "\0<>a/b/*.dll"; var newSolution = solution.WithProjectAssemblyName(projectId, assemblyName); Assert.Equal(assemblyName, newSolution.GetProject(projectId)!.AssemblyName); Assert.Same(newSolution, newSolution.WithProjectAssemblyName(projectId, assemblyName)); Assert.Throws<ArgumentNullException>("assemblyName", () => solution.WithProjectAssemblyName(projectId, null!)); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectAssemblyName(null!, "x.dll")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectAssemblyName(ProjectId.CreateNewId(), "x.dll")); } [Fact] public void WithProjectOutputFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.dll"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectOutputFilePath(projectId, value), s => s.GetProject(projectId)!.OutputFilePath, (string?)path, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectOutputFilePath(null!, "x.dll")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectOutputFilePath(ProjectId.CreateNewId(), "x.dll")); } [Fact] public void WithProjectOutputRefFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.dll"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectOutputRefFilePath(projectId, value), s => s.GetProject(projectId)!.OutputRefFilePath, (string?)path, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectOutputRefFilePath(null!, "x.dll")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectOutputRefFilePath(ProjectId.CreateNewId(), "x.dll")); } [Fact] public void WithProjectCompilationOutputInfo() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.dll"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectCompilationOutputInfo(projectId, value), s => s.GetProject(projectId)!.CompilationOutputInfo, new CompilationOutputInfo(path), defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectCompilationOutputInfo(null!, new CompilationOutputInfo("x.dll"))); Assert.Throws<InvalidOperationException>(() => solution.WithProjectCompilationOutputInfo(ProjectId.CreateNewId(), new CompilationOutputInfo("x.dll"))); } [Fact] public void WithProjectDefaultNamespace() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var defaultNamespace = "\0<>a/b/*"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectDefaultNamespace(projectId, value), s => s.GetProject(projectId)!.DefaultNamespace, (string?)defaultNamespace, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectDefaultNamespace(null!, "x")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectDefaultNamespace(ProjectId.CreateNewId(), "x")); } [Fact] public void WithProjectName() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var projectName = "\0<>a/b/*"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectName(projectId, value), s => s.GetProject(projectId)!.Name, projectName, defaultThrows: true); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectName(null!, "x")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectName(ProjectId.CreateNewId(), "x")); } [Fact] public void WithProjectFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.csproj"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectFilePath(projectId, value), s => s.GetProject(projectId)!.FilePath, (string?)path, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectFilePath(null!, "x")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectFilePath(ProjectId.CreateNewId(), "x")); } [Fact] public void WithProjectCompilationOptionsExceptionHandling() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); var options = new CSharpCompilationOptions(OutputKind.NetModule); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectCompilationOptions(null!, options)); Assert.Throws<InvalidOperationException>(() => solution.WithProjectCompilationOptions(ProjectId.CreateNewId(), options)); } [Theory] [CombinatorialData] public void WithProjectCompilationOptionsReplacesSyntaxTreeOptionProvider([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName) { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", languageName); // We always have a non-null SyntaxTreeOptionsProvider for C# and VB projects var originalSyntaxTreeOptionsProvider = solution.Projects.Single().CompilationOptions!.SyntaxTreeOptionsProvider; Assert.NotNull(originalSyntaxTreeOptionsProvider); var defaultOptions = solution.Projects.Single().LanguageServices.GetRequiredService<ICompilationFactoryService>().GetDefaultCompilationOptions(); Assert.Null(defaultOptions.SyntaxTreeOptionsProvider); solution = solution.WithProjectCompilationOptions(projectId, defaultOptions); // The CompilationOptions we replaced with didn't have a SyntaxTreeOptionsProvider, but we would have placed it // back. The SyntaxTreeOptionsProvider should behave the same as the prior one and thus should be equal. var newSyntaxTreeOptionsProvider = solution.Projects.Single().CompilationOptions!.SyntaxTreeOptionsProvider; Assert.NotNull(newSyntaxTreeOptionsProvider); Assert.Equal(originalSyntaxTreeOptionsProvider, newSyntaxTreeOptionsProvider); } [Fact] public void WithProjectParseOptions() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); var options = new CSharpParseOptions(CS.LanguageVersion.CSharp1); SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectParseOptions(projectId, value), s => s.GetProject(projectId)!.ParseOptions!, (ParseOptions)options, defaultThrows: true); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectParseOptions(null!, options)); Assert.Throws<InvalidOperationException>(() => solution.WithProjectParseOptions(ProjectId.CreateNewId(), options)); } [Fact] public void WithProjectReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var projectId2 = ProjectId.CreateNewId(); solution = solution.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp); var projectRef = new ProjectReference(projectId2); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithProjectReferences(projectId, value), opt => opt.GetProject(projectId)!.AllProjectReferences, projectRef, allowDuplicates: false); var projectRefs = (IEnumerable<ProjectReference>)ImmutableArray.Create( new ProjectReference(projectId2), new ProjectReference(projectId2, ImmutableArray.Create("alias")), new ProjectReference(projectId2, embedInteropTypes: true)); var solution2 = solution.WithProjectReferences(projectId, projectRefs); Assert.Same(projectRefs, solution2.GetProject(projectId)!.AllProjectReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectReferences(null!, new[] { projectRef })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(ProjectId.CreateNewId(), new[] { projectRef })); // cycles: Assert.Throws<InvalidOperationException>(() => solution2.WithProjectReferences(projectId2, new[] { new ProjectReference(projectId) })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(projectId, new[] { new ProjectReference(projectId) })); } [Fact] [WorkItem(42406, "https://github.com/dotnet/roslyn/issues/42406")] public void WithProjectReferences_ProjectNotInSolution() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var externalProjectRef = new ProjectReference(ProjectId.CreateNewId()); var projectRefs = (IEnumerable<ProjectReference>)ImmutableArray.Create(externalProjectRef); var newSolution1 = solution.WithProjectReferences(projectId, projectRefs); Assert.Same(projectRefs, newSolution1.GetProject(projectId)!.AllProjectReferences); // project reference is not included: Assert.Empty(newSolution1.GetProject(projectId)!.ProjectReferences); } [Fact] public void AddProjectReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var projectId2 = ProjectId.CreateNewId(); var projectId3 = ProjectId.CreateNewId(); solution = solution .AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp) .AddProject(projectId3, "proj3", "proj3.dll", LanguageNames.CSharp); var projectRef2 = new ProjectReference(projectId2); var projectRef3 = new ProjectReference(projectId3); var externalProjectRef = new ProjectReference(ProjectId.CreateNewId()); solution = solution.AddProjectReference(projectId3, projectRef2); var solution2 = solution.AddProjectReferences(projectId, EmptyEnumerable<ProjectReference>()); Assert.Same(solution, solution2); var e = OnceEnumerable(projectRef2, externalProjectRef); var solution3 = solution.AddProjectReferences(projectId, e); AssertEx.Equal(new[] { projectRef2 }, solution3.GetProject(projectId)!.ProjectReferences); AssertEx.Equal(new[] { projectRef2, externalProjectRef }, solution3.GetProject(projectId)!.AllProjectReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.AddProjectReferences(null!, new[] { projectRef2 })); Assert.Throws<ArgumentNullException>("projectReferences", () => solution.AddProjectReferences(projectId, null!)); Assert.Throws<ArgumentNullException>("projectReferences[0]", () => solution.AddProjectReferences(projectId, new ProjectReference[] { null! })); Assert.Throws<ArgumentException>("projectReferences[1]", () => solution.AddProjectReferences(projectId, new[] { projectRef2, projectRef2 })); Assert.Throws<ArgumentException>("projectReferences[1]", () => solution.AddProjectReferences(projectId, new[] { new ProjectReference(projectId2), new ProjectReference(projectId2) })); // dup: Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(projectId3, new[] { projectRef2 })); // cycles: Assert.Throws<InvalidOperationException>(() => solution3.AddProjectReferences(projectId2, new[] { projectRef3 })); Assert.Throws<InvalidOperationException>(() => solution3.AddProjectReferences(projectId, new[] { new ProjectReference(projectId) })); } [Fact] public void RemoveProjectReference() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var projectId2 = ProjectId.CreateNewId(); solution = solution.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp); var projectRef2 = new ProjectReference(projectId2); var externalProjectRef = new ProjectReference(ProjectId.CreateNewId()); solution = solution.WithProjectReferences(projectId, new[] { projectRef2, externalProjectRef }); // remove reference to a project that's not part of the solution: var solution2 = solution.RemoveProjectReference(projectId, externalProjectRef); AssertEx.Equal(new[] { projectRef2 }, solution2.GetProject(projectId)!.AllProjectReferences); // remove reference to a project that's part of the solution: var solution3 = solution.RemoveProjectReference(projectId, projectRef2); AssertEx.Equal(new[] { externalProjectRef }, solution3.GetProject(projectId)!.AllProjectReferences); var solution4 = solution3.RemoveProjectReference(projectId, externalProjectRef); Assert.Empty(solution4.GetProject(projectId)!.AllProjectReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveProjectReference(null!, projectRef2)); Assert.Throws<ArgumentNullException>("projectReference", () => solution.RemoveProjectReference(projectId, null!)); // removing a reference that's not in the list: Assert.Throws<ArgumentException>("projectReference", () => solution.RemoveProjectReference(projectId, new ProjectReference(ProjectId.CreateNewId()))); // project not in solution: Assert.Throws<InvalidOperationException>(() => solution.RemoveProjectReference(ProjectId.CreateNewId(), projectRef2)); } [Fact] public void ProjectReferences_Submissions() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId0 = ProjectId.CreateNewId(); var submissionId1 = ProjectId.CreateNewId(); var submissionId2 = ProjectId.CreateNewId(); var submissionId3 = ProjectId.CreateNewId(); solution = solution .AddProject(projectId0, "non-submission", "non-submission.dll", LanguageNames.CSharp) .AddProject(ProjectInfo.Create(submissionId1, VersionStamp.Default, name: "submission1", assemblyName: "submission1.dll", LanguageNames.CSharp, isSubmission: true)) .AddProject(ProjectInfo.Create(submissionId2, VersionStamp.Default, name: "submission2", assemblyName: "submission2.dll", LanguageNames.CSharp, isSubmission: true)) .AddProject(ProjectInfo.Create(submissionId3, VersionStamp.Default, name: "submission3", assemblyName: "submission3.dll", LanguageNames.CSharp, isSubmission: true)) .AddProjectReference(submissionId2, new ProjectReference(submissionId1)) .WithProjectReferences(submissionId2, new[] { new ProjectReference(submissionId1) }); // submission may be referenced from multiple submissions (forming a tree): _ = solution.AddProjectReferences(submissionId3, new[] { new ProjectReference(submissionId1) }); _ = solution.WithProjectReferences(submissionId3, new[] { new ProjectReference(submissionId1) }); // submission may reference a non-submission project: _ = solution.AddProjectReferences(submissionId3, new[] { new ProjectReference(projectId0) }); _ = solution.WithProjectReferences(submissionId3, new[] { new ProjectReference(projectId0) }); // submission can't reference multiple submissions: Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(submissionId2, new[] { new ProjectReference(submissionId3) })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(submissionId1, new[] { new ProjectReference(submissionId2), new ProjectReference(submissionId3) })); // non-submission project can't reference a submission: Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(projectId0, new[] { new ProjectReference(submissionId1) })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(projectId0, new[] { new ProjectReference(submissionId1) })); } [Fact] public void WithProjectMetadataReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var metadataRef = (MetadataReference)new TestMetadataReference(); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithProjectMetadataReferences(projectId, value), opt => opt.GetProject(projectId)!.MetadataReferences, metadataRef, allowDuplicates: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectMetadataReferences(null!, new[] { metadataRef })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectMetadataReferences(ProjectId.CreateNewId(), new[] { metadataRef })); } [Fact] public void AddMetadataReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var solution2 = solution.AddMetadataReferences(projectId, EmptyEnumerable<MetadataReference>()); Assert.Same(solution, solution2); var metadataRef1 = new TestMetadataReference(); var metadataRef2 = new TestMetadataReference(); var solution3 = solution.AddMetadataReferences(projectId, OnceEnumerable(metadataRef1, metadataRef2)); AssertEx.Equal(new[] { metadataRef1, metadataRef2 }, solution3.GetProject(projectId)!.MetadataReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.AddMetadataReferences(null!, new[] { metadataRef1 })); Assert.Throws<ArgumentNullException>("metadataReferences", () => solution.AddMetadataReferences(projectId, null!)); Assert.Throws<ArgumentNullException>("metadataReferences[0]", () => solution.AddMetadataReferences(projectId, new MetadataReference[] { null! })); Assert.Throws<ArgumentException>("metadataReferences[1]", () => solution.AddMetadataReferences(projectId, new[] { metadataRef1, metadataRef1 })); // dup: Assert.Throws<InvalidOperationException>(() => solution3.AddMetadataReferences(projectId, new[] { metadataRef1 })); } [Fact] public void RemoveMetadataReference() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var metadataRef1 = new TestMetadataReference(); var metadataRef2 = new TestMetadataReference(); solution = solution.WithProjectMetadataReferences(projectId, new[] { metadataRef1, metadataRef2 }); var solution2 = solution.RemoveMetadataReference(projectId, metadataRef1); AssertEx.Equal(new[] { metadataRef2 }, solution2.GetProject(projectId)!.MetadataReferences); var solution3 = solution2.RemoveMetadataReference(projectId, metadataRef2); Assert.Empty(solution3.GetProject(projectId)!.MetadataReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveMetadataReference(null!, metadataRef1)); Assert.Throws<ArgumentNullException>("metadataReference", () => solution.RemoveMetadataReference(projectId, null!)); // removing a reference that's not in the list: Assert.Throws<InvalidOperationException>(() => solution.RemoveMetadataReference(projectId, new TestMetadataReference())); // project not in solution: Assert.Throws<InvalidOperationException>(() => solution.RemoveMetadataReference(ProjectId.CreateNewId(), metadataRef1)); } [Fact] public void WithProjectAnalyzerReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var analyzerRef = (AnalyzerReference)new TestAnalyzerReference(); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithProjectAnalyzerReferences(projectId, value), opt => opt.GetProject(projectId)!.AnalyzerReferences, analyzerRef, allowDuplicates: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectAnalyzerReferences(null!, new[] { analyzerRef })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectAnalyzerReferences(ProjectId.CreateNewId(), new[] { analyzerRef })); } [Fact] public void AddAnalyzerReferences_Project() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var solution2 = solution.AddAnalyzerReferences(projectId, EmptyEnumerable<AnalyzerReference>()); Assert.Same(solution, solution2); var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); var solution3 = solution.AddAnalyzerReferences(projectId, OnceEnumerable(analyzerRef1, analyzerRef2)); AssertEx.Equal(new[] { analyzerRef1, analyzerRef2 }, solution3.GetProject(projectId)!.AnalyzerReferences); var solution4 = solution3.AddAnalyzerReferences(projectId, new AnalyzerReference[0]); Assert.Same(solution, solution2); Assert.Throws<ArgumentNullException>("projectId", () => solution.AddAnalyzerReferences(null!, new[] { analyzerRef1 })); Assert.Throws<ArgumentNullException>("analyzerReferences", () => solution.AddAnalyzerReferences(projectId, null!)); Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => solution.AddAnalyzerReferences(projectId, new AnalyzerReference[] { null! })); Assert.Throws<ArgumentException>("analyzerReferences[1]", () => solution.AddAnalyzerReferences(projectId, new[] { analyzerRef1, analyzerRef1 })); // dup: Assert.Throws<InvalidOperationException>(() => solution3.AddAnalyzerReferences(projectId, new[] { analyzerRef1 })); } [Fact] public void RemoveAnalyzerReference_Project() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); solution = solution.WithProjectAnalyzerReferences(projectId, new[] { analyzerRef1, analyzerRef2 }); var solution2 = solution.RemoveAnalyzerReference(projectId, analyzerRef1); AssertEx.Equal(new[] { analyzerRef2 }, solution2.GetProject(projectId)!.AnalyzerReferences); var solution3 = solution2.RemoveAnalyzerReference(projectId, analyzerRef2); Assert.Empty(solution3.GetProject(projectId)!.AnalyzerReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveAnalyzerReference(null!, analyzerRef1)); Assert.Throws<ArgumentNullException>("analyzerReference", () => solution.RemoveAnalyzerReference(projectId, null!)); // removing a reference that's not in the list: Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(projectId, new TestAnalyzerReference())); // project not in solution: Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(ProjectId.CreateNewId(), analyzerRef1)); } [Fact] public void WithAnalyzerReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var analyzerRef = (AnalyzerReference)new TestAnalyzerReference(); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithAnalyzerReferences(value), opt => opt.AnalyzerReferences, analyzerRef, allowDuplicates: false); } [Fact] public void AddAnalyzerReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var solution2 = solution.AddAnalyzerReferences(EmptyEnumerable<AnalyzerReference>()); Assert.Same(solution, solution2); var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); var solution3 = solution.AddAnalyzerReferences(OnceEnumerable(analyzerRef1, analyzerRef2)); AssertEx.Equal(new[] { analyzerRef1, analyzerRef2 }, solution3.AnalyzerReferences); var solution4 = solution3.AddAnalyzerReferences(new AnalyzerReference[0]); Assert.Same(solution, solution2); Assert.Throws<ArgumentNullException>("analyzerReferences", () => solution.AddAnalyzerReferences(null!)); Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => solution.AddAnalyzerReferences(new AnalyzerReference[] { null! })); Assert.Throws<ArgumentException>("analyzerReferences[1]", () => solution.AddAnalyzerReferences(new[] { analyzerRef1, analyzerRef1 })); // dup: Assert.Throws<InvalidOperationException>(() => solution3.AddAnalyzerReferences(new[] { analyzerRef1 })); } [Fact] public void RemoveAnalyzerReference() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); solution = solution.WithAnalyzerReferences(new[] { analyzerRef1, analyzerRef2 }); var solution2 = solution.RemoveAnalyzerReference(analyzerRef1); AssertEx.Equal(new[] { analyzerRef2 }, solution2.AnalyzerReferences); var solution3 = solution2.RemoveAnalyzerReference(analyzerRef2); Assert.Empty(solution3.AnalyzerReferences); Assert.Throws<ArgumentNullException>("analyzerReference", () => solution.RemoveAnalyzerReference(null!)); // removing a reference that's not in the list: Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(new TestAnalyzerReference())); } #nullable disable [Fact] public void TestAddProject() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); solution = solution.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp); Assert.True(solution.ProjectIds.Any(), "Solution was expected to have projects"); Assert.NotNull(pid); var project = solution.GetProject(pid); Assert.False(project.HasDocuments); } [Fact] public void TestUpdateAssemblyName() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); solution = solution.WithProjectAssemblyName(project1, "bar"); var project = solution.GetProject(project1); Assert.Equal("bar", project.AssemblyName); } [Fact] [WorkItem(543964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543964")] public void MultipleProjectsWithSameDisplayName() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); var project2 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "name", "assemblyName", LanguageNames.CSharp); solution = solution.AddProject(project2, "name", "assemblyName", LanguageNames.CSharp); Assert.Equal(2, solution.GetProjectsByName("name").Count()); } [Fact] public async Task TestAddFirstDocumentAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", "public class Goo { }"); // verify project & document Assert.NotNull(pid); var project = solution.GetProject(pid); Assert.NotNull(project); Assert.True(solution.ContainsProject(pid), "Solution was expected to have project " + pid); Assert.True(project.HasDocuments, "Project was expected to have documents"); Assert.Equal(project, solution.GetProject(pid)); Assert.NotNull(did); var document = solution.GetDocument(did); Assert.True(project.ContainsDocument(did), "Project was expected to have document " + did); Assert.Equal(document, project.GetDocument(did)); Assert.Equal(document, solution.GetDocument(did)); var semantics = await document.GetSemanticModelAsync(); Assert.NotNull(semantics); await ValidateSolutionAndCompilationsAsync(solution); var pid2 = solution.Projects.Single().Id; var did2 = DocumentId.CreateNewId(pid2); solution = solution.AddDocument(did2, "bar.cs", "public class Bar { }"); // verify project & document var project2 = solution.GetProject(pid2); Assert.NotNull(project2); Assert.NotNull(did2); var document2 = solution.GetDocument(did2); Assert.True(project2.ContainsDocument(did2), "Project was expected to have document " + did2); Assert.Equal(document2, project2.GetDocument(did2)); Assert.Equal(document2, solution.GetDocument(did2)); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task AddTwoDocumentsForSingleProject() { var projectId = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); var project = Assert.Single(solution.Projects); var document1 = project.GetDocument(documentInfo1.Id); var document2 = project.GetDocument(documentInfo2.Id); Assert.NotSame(document1, document2); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task AddTwoDocumentsForTwoProjects() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); var project1 = solution.GetProject(projectId1); var project2 = solution.GetProject(projectId2); var document1 = project1.GetDocument(documentInfo1.Id); var document2 = project2.GetDocument(documentInfo2.Id); Assert.NotSame(document1, document2); Assert.NotSame(document1.Project, document2.Project); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public void AddTwoDocumentsWithMissingProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs"); // We're only adding the first project, but not the second one using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp); Assert.ThrowsAny<InvalidOperationException>(() => solution.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2))); } [Fact] public void RemoveZeroDocuments() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Same(solution, solution.RemoveDocuments(ImmutableArray<DocumentId>.Empty)); } [Fact] public async Task RemoveTwoDocuments() { var projectId = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "project1", "project1.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); solution = solution.RemoveDocuments(ImmutableArray.Create(documentInfo1.Id, documentInfo2.Id)); var finalProject = solution.Projects.Single(); Assert.Empty(finalProject.Documents); Assert.Empty((await finalProject.GetCompilationAsync()).SyntaxTrees); } [Fact] public void RemoveTwoDocumentsFromDifferentProjects() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); Assert.All(solution.Projects, p => Assert.Single(p.Documents)); solution = solution.RemoveDocuments(ImmutableArray.Create(documentInfo1.Id, documentInfo2.Id)); Assert.All(solution.Projects, p => Assert.Empty(p.Documents)); } [Fact] public void RemoveDocumentFromUnrelatedProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddDocument(documentInfo1); // This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveDocument // API due to https://github.com/dotnet/roslyn/issues/41211. Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveDocuments(ImmutableArray.Create(documentInfo1.Id))); } [Fact] public void RemoveAdditionalDocumentFromUnrelatedProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.txt"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddAdditionalDocument(documentInfo1); // This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveAdditionalDocument // API due to https://github.com/dotnet/roslyn/issues/41211. Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveAdditionalDocuments(ImmutableArray.Create(documentInfo1.Id))); } [Fact] public void RemoveAnalyzerConfigDocumentFromUnrelatedProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), ".editorconfig"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddAnalyzerConfigDocuments(ImmutableArray.Create(documentInfo1)); // This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveAdditionalDocument // API due to https://github.com/dotnet/roslyn/issues/41211. Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveAnalyzerConfigDocuments(ImmutableArray.Create(documentInfo1.Id))); } [Fact] public async Task TestOneCSharpProjectAsync() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject("goo", "goo.dll", LanguageNames.CSharp) .AddMetadataReference(s_mscorlib) .AddDocument("goo.cs", "public class Goo { }") .Project.Solution; await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task TestTwoCSharpProjectsAsync() { using var workspace = CreateWorkspace(); var pm1 = ProjectId.CreateNewId(); var pm2 = ProjectId.CreateNewId(); var doc1 = DocumentId.CreateNewId(pm1); var doc2 = DocumentId.CreateNewId(pm2); var solution = workspace.CurrentSolution .AddProject(pm1, "goo", "goo.dll", LanguageNames.CSharp) .AddProject(pm2, "bar", "bar.dll", LanguageNames.CSharp) .AddProjectReference(pm2, new ProjectReference(pm1)) .AddDocument(doc1, "goo.cs", "public class Goo { }") .AddDocument(doc2, "bar.cs", "public class Bar : Goo { }"); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task TestCrossLanguageProjectsAsync() { var pm1 = ProjectId.CreateNewId(); var pm2 = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(pm1, "goo", "goo.dll", LanguageNames.CSharp) .AddMetadataReference(pm1, s_mscorlib) .AddProject(pm2, "bar", "bar.dll", LanguageNames.VisualBasic) .AddMetadataReference(pm2, s_mscorlib) .AddProjectReference(pm2, new ProjectReference(pm1)) .AddDocument(DocumentId.CreateNewId(pm1), "goo.cs", "public class X { }") .AddDocument(DocumentId.CreateNewId(pm2), "bar.vb", "Public Class Y\r\nInherits X\r\nEnd Class"); await ValidateSolutionAndCompilationsAsync(solution); } private static async Task ValidateSolutionAndCompilationsAsync(Solution solution) { foreach (var project in solution.Projects) { Assert.True(solution.ContainsProject(project.Id), "Solution was expected to have project " + project.Id); Assert.Equal(project, solution.GetProject(project.Id)); // these won't always be unique in real-world but should be for these tests Assert.Equal(project, solution.GetProjectsByName(project.Name).FirstOrDefault()); var compilation = await project.GetCompilationAsync(); Assert.NotNull(compilation); // check that the options are the same Assert.Equal(project.CompilationOptions, compilation.Options); // check that all known metadata references are present in the compilation foreach (var meta in project.MetadataReferences) { Assert.True(compilation.References.Contains(meta), "Compilation references were expected to contain " + meta); } // check that all project-to-project reference metadata is present in the compilation foreach (var referenced in project.ProjectReferences) { if (solution.ContainsProject(referenced.ProjectId)) { var referencedMetadata = await solution.State.GetMetadataReferenceAsync(referenced, solution.GetProjectState(project.Id), CancellationToken.None); Assert.NotNull(referencedMetadata); if (referencedMetadata is CompilationReference compilationReference) { compilation.References.Single(r => { var cr = r as CompilationReference; return cr != null && cr.Compilation == compilationReference.Compilation; }); } } } // check that the syntax trees are the same var docs = project.Documents.ToList(); var trees = compilation.SyntaxTrees.ToList(); Assert.Equal(docs.Count, trees.Count); foreach (var doc in docs) { Assert.True(trees.Contains(await doc.GetSyntaxTreeAsync()), "trees list was expected to contain the syntax tree of doc"); } } } #if false [Fact(Skip = "641963")] public void TestDeepProjectReferenceTree() { int projectCount = 5; var solution = CreateSolutionWithProjectDependencyChain(projectCount); ProjectId[] projectIds = solution.ProjectIds.ToArray(); Compilation compilation; for (int i = 0; i < projectCount; i++) { Assert.False(solution.GetProject(projectIds[i]).TryGetCompilation(out compilation)); } var top = solution.GetCompilationAsync(projectIds.Last(), CancellationToken.None).Result; var partialSolution = solution.GetPartialSolution(); for (int i = 0; i < projectCount; i++) { // While holding a compilation, we also hold its references, plus one further level // of references alive. However, the references are only partial Declaration // compilations var isPartialAvailable = i >= projectCount - 3; var isFinalAvailable = i == projectCount - 1; var projectId = projectIds[i]; Assert.Equal(isFinalAvailable, solution.GetProject(projectId).TryGetCompilation(out compilation)); Assert.Equal(isPartialAvailable, partialSolution.ProjectIds.Contains(projectId) && partialSolution.GetProject(projectId).TryGetCompilation(out compilation)); } } #endif [WorkItem(636431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636431")] [Fact] public async Task TestProjectDependencyLoadingAsync() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var solution = workspace.CurrentSolution; var projectIds = Enumerable.Range(0, 5).Select(i => ProjectId.CreateNewId()).ToArray(); for (var i = 0; i < projectIds.Length; i++) { solution = solution.AddProject(projectIds[i], i.ToString(), i.ToString(), LanguageNames.CSharp); if (i >= 1) { solution = solution.AddProjectReference(projectIds[i], new ProjectReference(projectIds[i - 1])); } } await solution.GetProject(projectIds[0]).GetCompilationAsync(CancellationToken.None); await solution.GetProject(projectIds[2]).GetCompilationAsync(CancellationToken.None); } [Fact] public async Task TestAddMetadataReferencesAsync() { var mefReference = TestMetadata.Net451.SystemCore; using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); solution = solution.AddMetadataReference(project1, s_mscorlib); solution = solution.AddMetadataReference(project1, mefReference); var assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(mefReference); var namespacesAndTypes = assemblyReference.GlobalNamespace.GetAllNamespacesAndTypes(CancellationToken.None); var foundSymbol = from symbol in namespacesAndTypes where symbol.Name.Equals("Enumerable") select symbol; Assert.Equal(1, foundSymbol.Count()); solution = solution.RemoveMetadataReference(project1, mefReference); assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(mefReference); Assert.Null(assemblyReference); await ValidateSolutionAndCompilationsAsync(solution); } private class MockDiagnosticAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext analysisContext) { } } [Fact] public void TestProjectDiagnosticAnalyzers() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); Assert.Empty(solution.Projects.Single().AnalyzerReferences); DiagnosticAnalyzer analyzer = new MockDiagnosticAnalyzer(); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer)); // Test AddAnalyzer var newSolution = solution.AddAnalyzerReference(project1, analyzerReference); var actualAnalyzerReferences = newSolution.Projects.Single().AnalyzerReferences; Assert.Equal(1, actualAnalyzerReferences.Count); Assert.Equal(analyzerReference, actualAnalyzerReferences[0]); var actualAnalyzers = actualAnalyzerReferences[0].GetAnalyzersForAllLanguages(); Assert.Equal(1, actualAnalyzers.Length); Assert.Equal(analyzer, actualAnalyzers[0]); // Test ProjectChanges var changes = newSolution.GetChanges(solution).GetProjectChanges().Single(); var addedAnalyzerReference = changes.GetAddedAnalyzerReferences().Single(); Assert.Equal(analyzerReference, addedAnalyzerReference); var removedAnalyzerReferences = changes.GetRemovedAnalyzerReferences(); Assert.Empty(removedAnalyzerReferences); solution = newSolution; // Test RemoveAnalyzer solution = solution.RemoveAnalyzerReference(project1, analyzerReference); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Empty(actualAnalyzerReferences); // Test AddAnalyzers analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer)); DiagnosticAnalyzer secondAnalyzer = new MockDiagnosticAnalyzer(); var secondAnalyzerReference = new AnalyzerImageReference(ImmutableArray.Create(secondAnalyzer)); var analyzerReferences = new[] { analyzerReference, secondAnalyzerReference }; solution = solution.AddAnalyzerReferences(project1, analyzerReferences); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Equal(2, actualAnalyzerReferences.Count); Assert.Equal(analyzerReference, actualAnalyzerReferences[0]); Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]); solution = solution.RemoveAnalyzerReference(project1, analyzerReference); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Equal(1, actualAnalyzerReferences.Count); Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[0]); // Test WithAnalyzers solution = solution.WithProjectAnalyzerReferences(project1, analyzerReferences); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Equal(2, actualAnalyzerReferences.Count); Assert.Equal(analyzerReference, actualAnalyzerReferences[0]); Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]); } [Fact] public void TestProjectParseOptions() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); solution = solution.AddMetadataReference(project1, s_mscorlib); // Parse Options var oldParseOptions = solution.GetProject(project1).ParseOptions; var newParseOptions = new CSharpParseOptions(preprocessorSymbols: new[] { "AFTER" }); solution = solution.WithProjectParseOptions(project1, newParseOptions); var newUpdatedParseOptions = solution.GetProject(project1).ParseOptions; Assert.NotEqual(oldParseOptions, newUpdatedParseOptions); Assert.Same(newParseOptions, newUpdatedParseOptions); } [Fact] public async Task TestRemoveProjectAsync() { using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp); Assert.True(sol.ProjectIds.Any(), "Solution was expected to have projects"); Assert.NotNull(pid); var project = sol.GetProject(pid); Assert.False(project.HasDocuments); var sol2 = sol.RemoveProject(pid); Assert.False(sol2.ProjectIds.Any()); await ValidateSolutionAndCompilationsAsync(sol); } [Fact] public async Task TestRemoveProjectWithReferencesAsync() { using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); var pid2 = ProjectId.CreateNewId(); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp) .AddProjectReference(pid2, new ProjectReference(pid)); Assert.Equal(2, sol.Projects.Count()); // remove the project that is being referenced // this should leave a dangling reference var sol2 = sol.RemoveProject(pid); Assert.False(sol2.ContainsProject(pid)); Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2); Assert.Equal(1, sol2.Projects.Count()); Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 project pid2 was expected to contain project reference " + pid); await ValidateSolutionAndCompilationsAsync(sol2); } [Fact] public async Task TestRemoveProjectWithReferencesAndAddItBackAsync() { using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); var pid2 = ProjectId.CreateNewId(); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp) .AddProjectReference(pid2, new ProjectReference(pid)); Assert.Equal(2, sol.Projects.Count()); // remove the project that is being referenced var sol2 = sol.RemoveProject(pid); Assert.False(sol2.ContainsProject(pid)); Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2); Assert.Equal(1, sol2.Projects.Count()); Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 pid2 was expected to contain " + pid); var sol3 = sol2.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp); Assert.True(sol3.ContainsProject(pid), "sol3 was expected to contain " + pid); Assert.True(sol3.ContainsProject(pid2), "sol3 was expected to contain " + pid2); Assert.Equal(2, sol3.Projects.Count()); await ValidateSolutionAndCompilationsAsync(sol3); } [Fact] public async Task TestGetSyntaxRootAsync() { var text = "public class Goo { }"; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var document = sol.GetDocument(did); Assert.False(document.TryGetSyntaxRoot(out _)); var root = await document.GetSyntaxRootAsync(); Assert.NotNull(root); Assert.Equal(text, root.ToString()); Assert.True(document.TryGetSyntaxRoot(out root)); Assert.NotNull(root); } [Fact] public async Task TestUpdateDocumentAsync() { var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); using var workspace = CreateWorkspace(); var solution1 = workspace.CurrentSolution .AddProject(projectId, "ProjectName", "AssemblyName", LanguageNames.CSharp) .AddDocument(documentId, "DocumentName", SourceText.From("class Class{}")); var document = solution1.GetDocument(documentId); var newRoot = await Formatter.FormatAsync(document).Result.GetSyntaxRootAsync(); var solution2 = solution1.WithDocumentSyntaxRoot(documentId, newRoot); Assert.NotEqual(solution1, solution2); var newText = solution2.GetDocument(documentId).GetTextAsync().Result.ToString(); Assert.Equal("class Class { }", newText); } [Fact] public void TestUpdateSyntaxTreeWithAnnotations() { var text = "public class Goo { }"; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var document = sol.GetDocument(did); var tree = document.GetSyntaxTreeAsync().Result; var root = tree.GetRoot(); var annotation = new SyntaxAnnotation(); var annotatedRoot = root.WithAdditionalAnnotations(annotation); var sol2 = sol.WithDocumentSyntaxRoot(did, annotatedRoot); var doc2 = sol2.GetDocument(did); var tree2 = doc2.GetSyntaxTreeAsync().Result; var root2 = tree2.GetRoot(); // text should not be available yet (it should be defer created from the node) // and getting the document or root should not cause it to be created. Assert.False(tree2.TryGetText(out _)); var text2 = tree2.GetText(); Assert.NotNull(text2); Assert.NotSame(tree, tree2); Assert.NotSame(annotatedRoot, root2); Assert.True(annotatedRoot.IsEquivalentTo(root2)); Assert.True(root2.HasAnnotation(annotation)); } [Fact] public void TestUpdatingFilePathUpdatesSyntaxTree() { var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); const string OldFilePath = @"Z:\OldFilePath.cs"; const string NewFilePath = @"Z:\NewFilePath.cs"; using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(documentId, "OldFilePath.cs", "public class Goo { }", filePath: OldFilePath); // scope so later asserts don't accidentally use oldDocument { var oldDocument = solution.GetDocument(documentId); Assert.Equal(OldFilePath, oldDocument.FilePath); Assert.Equal(OldFilePath, oldDocument.GetSyntaxTreeAsync().Result.FilePath); } solution = solution.WithDocumentFilePath(documentId, NewFilePath); { var newDocument = solution.GetDocument(documentId); Assert.Equal(NewFilePath, newDocument.FilePath); Assert.Equal(NewFilePath, newDocument.GetSyntaxTreeAsync().Result.FilePath); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestSyntaxRootNotKeptAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", "public class Goo { }"); var observedRoot = GetObservedSyntaxTreeRoot(sol, did); observedRoot.AssertReleased(); // re-get the tree (should recover from storage, not reparse) _ = sol.GetDocument(did).GetSyntaxRootAsync().Result; } [MethodImpl(MethodImplOptions.NoInlining)] [Fact] [WorkItem(542736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542736")] public void TestDocumentChangedOnDiskIsNotObserved() { var text1 = "public class A {}"; var text2 = "public class B {}"; var file = Temp.CreateFile().WriteAllText(text1, Encoding.UTF8); // create a solution that evicts from the cache immediately. using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8)); var observedText = GetObservedText(sol, did, text1); // change text on disk & verify it is changed file.WriteAllText(text2); var textOnDisk = file.ReadAllText(); Assert.Equal(text2, textOnDisk); // stop observing it and let GC reclaim it observedText.AssertReleased(); // if we ask for the same text again we should get the original content var observedText2 = sol.GetDocument(did).GetTextAsync().Result; Assert.Equal(text1, observedText2.ToString()); } [Fact] public void TestGetTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docText = doc.GetTextAsync().Result; Assert.NotNull(docText); Assert.Equal(text, docText.ToString()); } [Fact] public void TestGetLoadedTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8)); var doc = sol.GetDocument(did); var docText = doc.GetTextAsync().Result; Assert.NotNull(docText); Assert.Equal(text, docText.ToString()); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19427")] public void TestGetRecoveredTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the text and then wait for the references to be GC'd var observed = GetObservedText(sol, did, text); observed.AssertReleased(); // get it async and force it to recover from temporary storage var doc = sol.GetDocument(did); var docText = doc.GetTextAsync().Result; Assert.NotNull(docText); Assert.Equal(text, docText.ToString()); } [Fact] public void TestGetSyntaxTreeAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docTree = doc.GetSyntaxTreeAsync().Result; Assert.NotNull(docTree); Assert.Equal(text, docTree.GetRoot().ToString()); } [Fact] public void TestGetSyntaxTreeFromLoadedTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8)); var doc = sol.GetDocument(did); var docTree = doc.GetSyntaxTreeAsync().Result; Assert.NotNull(docTree); Assert.Equal(text, docTree.GetRoot().ToString()); } [Fact] public void TestGetSyntaxTreeFromAddedTree() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var tree = CSharp.SyntaxFactory.ParseSyntaxTree("public class C {}").GetRoot(CancellationToken.None); tree = tree.WithAdditionalAnnotations(new SyntaxAnnotation("test")); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", tree); var doc = sol.GetDocument(did); var docTree = doc.GetSyntaxRootAsync().Result; Assert.NotNull(docTree); Assert.True(tree.IsEquivalentTo(docTree)); Assert.NotNull(docTree.GetAnnotatedNodes("test").Single()); } [Fact] public async Task TestGetSyntaxRootAsync2Async() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docRoot = await doc.GetSyntaxRootAsync(); Assert.NotNull(docRoot); Assert.Equal(text, docRoot.ToString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14954")] public void TestGetRecoveredSyntaxRootAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the syntax tree root and wait for the references to be GC'd var observed = GetObservedSyntaxTreeRoot(sol, did); observed.AssertReleased(); // get it async and force it to be recovered from storage var doc = sol.GetDocument(did); var docRoot = doc.GetSyntaxRootAsync().Result; Assert.NotNull(docRoot); Assert.Equal(text, docRoot.ToString()); } [Fact] public void TestGetCompilationAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var proj = sol.GetProject(pid); var compilation = proj.GetCompilationAsync().Result; Assert.NotNull(compilation); Assert.Equal(1, compilation.SyntaxTrees.Count()); } [Fact] public void TestGetSemanticModelAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docModel = doc.GetSemanticModelAsync().Result; Assert.NotNull(docModel); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetTextDoesNotKeepTextAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the text and then wait for the references to be GC'd var observed = GetObservedText(sol, did, text); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SourceText> GetObservedText(Solution solution, DocumentId documentId, string expectedText = null) { var observedText = solution.GetDocument(documentId).GetTextAsync().Result; if (expectedText != null) { Assert.Equal(expectedText, observedText.ToString()); } return new ObjectReference<SourceText>(observedText); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetTextAsyncDoesNotKeepTextAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the text and then wait for the references to be GC'd var observed = GetObservedTextAsync(sol, did, text); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SourceText> GetObservedTextAsync(Solution solution, DocumentId documentId, string expectedText = null) { var observedText = solution.GetDocument(documentId).GetTextAsync().Result; if (expectedText != null) { Assert.Equal(expectedText, observedText.ToString()); } return new ObjectReference<SourceText>(observedText); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetSyntaxRootDoesNotKeepRootAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedSyntaxTreeRoot(sol, did); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SyntaxNode> GetObservedSyntaxTreeRoot(Solution solution, DocumentId documentId) { var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result; return new ObjectReference<SyntaxNode>(observedTree); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetSyntaxRootAsyncDoesNotKeepRootAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedSyntaxTreeRootAsync(sol, did); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SyntaxNode> GetObservedSyntaxTreeRootAsync(Solution solution, DocumentId documentId) { var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result; return new ObjectReference<SyntaxNode>(observedTree); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13506")] [WorkItem(13506, "https://github.com/dotnet/roslyn/issues/13506")] public void TestRecoverableSyntaxTreeCSharp() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = @"public class C { public void Method1() {} public void Method2() {} public void Method3() {} public void Method4() {} public void Method5() {} public void Method6() {} }"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); TestRecoverableSyntaxTree(sol, did); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestRecoverableSyntaxTreeVisualBasic() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = @"Public Class C Sub Method1() End Sub Sub Method2() End Sub Sub Method3() End Sub Sub Method4() End Sub Sub Method5() End Sub Sub Method6() End Sub End Class"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.VisualBasic) .AddDocument(did, "goo.vb", text); TestRecoverableSyntaxTree(sol, did); } private static void TestRecoverableSyntaxTree(Solution sol, DocumentId did) { // get it async and wait for it to get GC'd var observed = GetObservedSyntaxTreeRootAsync(sol, did); observed.AssertReleased(); var doc = sol.GetDocument(did); // access the tree & root again (recover it) var tree = doc.GetSyntaxTreeAsync().Result; // this should cause reparsing var root = tree.GetRoot(); // prove that the new root is correctly associated with the tree Assert.Equal(tree, root.SyntaxTree); // reset the syntax root, to make it 'refactored' by adding an attribute var newRoot = doc.GetSyntaxRootAsync().Result.WithAdditionalAnnotations(SyntaxAnnotation.ElasticAnnotation); var doc2 = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot, PreservationMode.PreserveValue).GetDocument(doc.Id); // get it async and wait for it to get GC'd var observed2 = GetObservedSyntaxTreeRootAsync(doc2.Project.Solution, did); observed2.AssertReleased(); // access the tree & root again (recover it) var tree2 = doc2.GetSyntaxTreeAsync().Result; // this should cause deserialization var root2 = tree2.GetRoot(); // prove that the new root is correctly associated with the tree Assert.Equal(tree2, root2.SyntaxTree); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetCompilationAsyncDoesNotKeepCompilationAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedCompilationAsync(sol, pid); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<Compilation> GetObservedCompilationAsync(Solution solution, ProjectId projectId) { var observed = solution.GetProject(projectId).GetCompilationAsync().Result; return new ObjectReference<Compilation>(observed); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetCompilationDoesNotKeepCompilationAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedCompilation(sol, pid); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<Compilation> GetObservedCompilation(Solution solution, ProjectId projectId) { var observed = solution.GetProject(projectId).GetCompilationAsync().Result; return new ObjectReference<Compilation>(observed); } [Fact] public void TestWorkspaceLanguageServiceOverride() { var hostServices = FeaturesTestCompositions.Features.AddParts(new[] { typeof(TestLanguageServiceA), typeof(TestLanguageServiceB), }).GetHostServices(); var ws = new AdhocWorkspace(hostServices, ServiceLayer.Host); var service = ws.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>(); Assert.NotNull(service as TestLanguageServiceA); var ws2 = new AdhocWorkspace(hostServices, "Quasimodo"); var service2 = ws2.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>(); Assert.NotNull(service2 as TestLanguageServiceB); } #if false [Fact] public void TestSolutionInfo() { var oldSolutionId = SolutionId.CreateNewId("oldId"); var oldVersion = VersionStamp.Create(); var solutionInfo = SolutionInfo.Create(oldSolutionId, oldVersion, null, null); var newSolutionId = SolutionId.CreateNewId("newId"); solutionInfo = solutionInfo.WithId(newSolutionId); Assert.NotEqual(oldSolutionId, solutionInfo.Id); Assert.Equal(newSolutionId, solutionInfo.Id); var newVersion = oldVersion.GetNewerVersion(); solutionInfo = solutionInfo.WithVersion(newVersion); Assert.NotEqual(oldVersion, solutionInfo.Version); Assert.Equal(newVersion, solutionInfo.Version); Assert.Null(solutionInfo.FilePath); var newFilePath = @"C:\test\fake.sln"; solutionInfo = solutionInfo.WithFilePath(newFilePath); Assert.Equal(newFilePath, solutionInfo.FilePath); Assert.Equal(0, solutionInfo.Projects.Count()); } #endif private interface ITestLanguageService : ILanguageService { } [ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, ServiceLayer.Default), Shared, PartNotDiscoverable] private class TestLanguageServiceA : ITestLanguageService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestLanguageServiceA() { } } [ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, "Quasimodo"), Shared, PartNotDiscoverable] private class TestLanguageServiceB : ITestLanguageService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestLanguageServiceB() { } } [Fact] [WorkItem(666263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666263")] public async Task TestDocumentFileAccessFailureMissingFile() { var workspace = new AdhocWorkspace(); var solution = workspace.CurrentSolution; WorkspaceDiagnostic diagnosticFromEvent = null; solution.Workspace.WorkspaceFailed += (sender, args) => { diagnosticFromEvent = args.Diagnostic; }; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); solution = solution.AddProject(pid, "goo", "goo", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(@"C:\doesnotexist.cs", Encoding.UTF8)) .WithDocumentFilePath(did, "document path"); var doc = solution.GetDocument(did); var text = await doc.GetTextAsync().ConfigureAwait(false); var diagnostic = await doc.State.GetLoadDiagnosticAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(@"C:\doesnotexist.cs: (0,0)-(0,0)", diagnostic.Location.GetLineSpan().ToString()); Assert.Equal(WorkspaceDiagnosticKind.Failure, diagnosticFromEvent.Kind); Assert.Equal("", text.ToString()); // Verify invariant: The compilation is guaranteed to have a syntax tree for each document of the project (even if the contnet fails to load). var compilation = await solution.State.GetCompilationAsync(doc.Project.State, CancellationToken.None).ConfigureAwait(false); var syntaxTree = compilation.SyntaxTrees.Single(); Assert.Equal("", syntaxTree.ToString()); } [Fact] public void TestGetProjectForAssemblySymbol() { var pid1 = ProjectId.CreateNewId("p1"); var pid2 = ProjectId.CreateNewId("p2"); var pid3 = ProjectId.CreateNewId("p3"); var did1 = DocumentId.CreateNewId(pid1); var did2 = DocumentId.CreateNewId(pid2); var did3 = DocumentId.CreateNewId(pid3); var text1 = @" Public Class A End Class"; var text2 = @" Public Class B End Class "; var text3 = @" public class C : B { } "; var text4 = @" public class C : A { } "; var solution = new AdhocWorkspace().CurrentSolution .AddProject(pid1, "GooA", "Goo.dll", LanguageNames.VisualBasic) .AddDocument(did1, "A.vb", text1) .AddMetadataReference(pid1, s_mscorlib) .AddProject(pid2, "GooB", "Goo2.dll", LanguageNames.VisualBasic) .AddDocument(did2, "B.vb", text2) .AddMetadataReference(pid2, s_mscorlib) .AddProject(pid3, "Bar", "Bar.dll", LanguageNames.CSharp) .AddDocument(did3, "C.cs", text3) .AddMetadataReference(pid3, s_mscorlib) .AddProjectReference(pid3, new ProjectReference(pid1)) .AddProjectReference(pid3, new ProjectReference(pid2)); var project3 = solution.GetProject(pid3); var comp3 = project3.GetCompilationAsync().Result; var classC = comp3.GetTypeByMetadataName("C"); var projectForBaseType = solution.GetProject(classC.BaseType.ContainingAssembly); Assert.Equal(pid2, projectForBaseType.Id); // switch base type to A then try again var solution2 = solution.WithDocumentText(did3, SourceText.From(text4)); project3 = solution2.GetProject(pid3); comp3 = project3.GetCompilationAsync().Result; classC = comp3.GetTypeByMetadataName("C"); projectForBaseType = solution2.GetProject(classC.BaseType.ContainingAssembly); Assert.Equal(pid1, projectForBaseType.Id); } [WorkItem(1088127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088127")] [Fact] public void TestEncodingRetainedAfterTreeChanged() { var ws = new AdhocWorkspace(); var proj = ws.AddProject("proj", LanguageNames.CSharp); var doc = ws.AddDocument(proj.Id, "a.cs", SourceText.From("public class c { }", Encoding.UTF32)); Assert.Equal(Encoding.UTF32, doc.GetTextAsync().Result.Encoding); // updating root doesn't change original encoding var root = doc.GetSyntaxRootAsync().Result; var newRoot = root.WithLeadingTrivia(root.GetLeadingTrivia().Add(CS.SyntaxFactory.Whitespace(" "))); var newDoc = doc.WithSyntaxRoot(newRoot); Assert.Equal(Encoding.UTF32, newDoc.GetTextAsync().Result.Encoding); } [Fact] public void TestProjectWithNoBrokenReferencesHasNoIncompleteReferences() { var workspace = new AdhocWorkspace(); var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp); var project2 = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(project1.Id) })); // Nothing should have incomplete references, and everything should build Assert.True(project1.HasSuccessfullyLoadedAsync().Result); Assert.True(project2.HasSuccessfullyLoadedAsync().Result); Assert.Single(project2.GetCompilationAsync().Result.ExternalReferences); } [Fact] public void TestProjectWithBrokenCrossLanguageReferenceHasIncompleteReferences() { var workspace = new AdhocWorkspace(); var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp); workspace.AddDocument(project1.Id, "Broken.cs", SourceText.From("class ")); var project2 = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(project1.Id) })); Assert.True(project1.HasSuccessfullyLoadedAsync().Result); Assert.False(project2.HasSuccessfullyLoadedAsync().Result); Assert.Empty(project2.GetCompilationAsync().Result.ExternalReferences); } [Fact] public void TestFrozenPartialProjectAlwaysIsIncomplete() { var workspace = new AdhocWorkspace(); var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp); var project2 = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(project1.Id) })); var document = workspace.AddDocument(project2.Id, "Test.cs", SourceText.From("")); // Nothing should have incomplete references, and everything should build var frozenSolution = document.WithFrozenPartialSemantics(CancellationToken.None).Project.Solution; Assert.True(frozenSolution.GetProject(project1.Id).HasSuccessfullyLoadedAsync().Result); Assert.True(frozenSolution.GetProject(project2.Id).HasSuccessfullyLoadedAsync().Result); } [Fact] public void TestProjectCompletenessWithMultipleProjects() { GetMultipleProjects(out var csBrokenProject, out var vbNormalProject, out var dependsOnBrokenProject, out var dependsOnVbNormalProject, out var transitivelyDependsOnBrokenProjects, out var transitivelyDependsOnNormalProjects); // check flag for a broken project itself Assert.False(csBrokenProject.HasSuccessfullyLoadedAsync().Result); // check flag for a normal project itself Assert.True(vbNormalProject.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that directly reference a broken project Assert.True(dependsOnBrokenProject.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that directly reference only normal project Assert.True(dependsOnVbNormalProject.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that indirectly reference a borken project // normal project -> normal project -> broken project Assert.True(transitivelyDependsOnBrokenProjects.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that indirectly reference only normal project // normal project -> normal project -> normal project Assert.True(transitivelyDependsOnNormalProjects.HasSuccessfullyLoadedAsync().Result); } [Fact] public async Task TestMassiveFileSize() { // set max file length to 1 bytes var maxLength = 1; var workspace = new AdhocWorkspace(); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(FileTextLoaderOptions.FileLengthThreshold, maxLength))); using var root = new TempRoot(); var file = root.CreateFile(prefix: "massiveFile", extension: ".cs").WriteAllText("hello"); var loader = new FileTextLoader(file.Path, Encoding.UTF8); var textLength = FileUtilities.GetFileLength(file.Path); var expected = string.Format(WorkspacesResources.File_0_size_of_1_exceeds_maximum_allowed_size_of_2, file.Path, textLength, maxLength); var exceptionThrown = false; try { // test async one var unused = await loader.LoadTextAndVersionAsync(workspace, DocumentId.CreateNewId(ProjectId.CreateNewId()), CancellationToken.None); } catch (InvalidDataException ex) { exceptionThrown = true; Assert.Equal(expected, ex.Message); } Assert.True(exceptionThrown); exceptionThrown = false; try { // test sync one var unused = loader.LoadTextAndVersionSynchronously(workspace, DocumentId.CreateNewId(ProjectId.CreateNewId()), CancellationToken.None); } catch (InvalidDataException ex) { exceptionThrown = true; Assert.Equal(expected, ex.Message); } Assert.True(exceptionThrown); } [Fact] [WorkItem(18697, "https://github.com/dotnet/roslyn/issues/18697")] public void TestWithSyntaxTree() { // get one to get to syntax tree factory using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var solution = workspace.CurrentSolution; var dummyProject = solution.AddProject("dummy", "dummy", LanguageNames.CSharp); var factory = dummyProject.LanguageServices.SyntaxTreeFactory; // create the origin tree var strongTree = factory.ParseSyntaxTree("dummy", dummyProject.ParseOptions, SourceText.From("// emtpy"), CancellationToken.None); // create recoverable tree off the original tree var recoverableTree = factory.CreateRecoverableTree( dummyProject.Id, strongTree.FilePath, strongTree.Options, new ConstantValueSource<TextAndVersion>(TextAndVersion.Create(strongTree.GetText(), VersionStamp.Create(), strongTree.FilePath)), strongTree.GetText().Encoding, strongTree.GetRoot()); // create new tree before it ever getting root node var newTree = recoverableTree.WithFilePath("different/dummy"); // this shouldn't throw _ = newTree.GetRoot(); } [Fact] public void TestUpdateDocumentsOrder() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); VersionStamp GetVersion() => solution.GetProject(pid).Version; ImmutableArray<DocumentId> GetDocumentIds() => solution.GetProject(pid).DocumentIds.ToImmutableArray(); ImmutableArray<SyntaxTree> GetSyntaxTrees() { return solution.GetProject(pid).GetCompilationAsync().Result.SyntaxTrees.ToImmutableArray(); } solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp); var text1 = "public class Test1 {}"; var did1 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did1, "test1.cs", text1); var text2 = "public class Test2 {}"; var did2 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did2, "test2.cs", text2); var text3 = "public class Test3 {}"; var did3 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did3, "test3.cs", text3); var text4 = "public class Test4 {}"; var did4 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did4, "test4.cs", text4); var text5 = "public class Test5 {}"; var did5 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did5, "test5.cs", text5); var oldVersion = GetVersion(); solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did4, did3, did2, did1 })); var newVersion = GetVersion(); // Make sure we have a new version because the order changed. Assert.NotEqual(oldVersion, newVersion); var documentIds = GetDocumentIds(); Assert.Equal(did5, documentIds[0]); Assert.Equal(did4, documentIds[1]); Assert.Equal(did3, documentIds[2]); Assert.Equal(did2, documentIds[3]); Assert.Equal(did1, documentIds[4]); var syntaxTrees = GetSyntaxTrees(); Assert.Equal(documentIds.Count(), syntaxTrees.Count()); Assert.Equal("test5.cs", syntaxTrees[0].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test4.cs", syntaxTrees[1].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test3.cs", syntaxTrees[2].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test2.cs", syntaxTrees[3].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test1.cs", syntaxTrees[4].FilePath, StringComparer.OrdinalIgnoreCase); solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did4, did3, did2, did1 })); var newSameVersion = GetVersion(); // Make sure we have the same new version because the order hasn't changed. Assert.Equal(newVersion, newSameVersion); } [Fact] public void TestUpdateDocumentsOrderExceptions() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp); var text1 = "public class Test1 {}"; var did1 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did1, "test1.cs", text1); var text2 = "public class Test2 {}"; var did2 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did2, "test2.cs", text2); var text3 = "public class Test3 {}"; var did3 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did3, "test3.cs", text3); var text4 = "public class Test4 {}"; var did4 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did4, "test4.cs", text4); var text5 = "public class Test5 {}"; var did5 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did5, "test5.cs", text5); solution = solution.RemoveDocument(did5); Assert.Throws<ArgumentException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.Create<DocumentId>())); Assert.Throws<ArgumentNullException>(() => solution = solution.WithProjectDocumentsOrder(pid, null)); Assert.Throws<InvalidOperationException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did3, did2, did1 }))); Assert.Throws<ArgumentException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did3, did2, did1 }))); } [Theory] [CombinatorialData] public async Task TestAddingEditorConfigFileWithDiagnosticSeverity([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName) { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", languageName); solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension); var originalSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var originalCompilation = await solution.GetProject(projectId).GetCompilationAsync(); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var newSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var project = solution.GetProject(projectId); var newCompilation = await project.GetCompilationAsync(); Assert.Same(originalSyntaxTree, newSyntaxTree); Assert.NotSame(originalCompilation, newCompilation); Assert.NotEqual(originalCompilation.Options, newCompilation.Options); var provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.True(provider.TryGetDiagnosticValue(newSyntaxTree, "CA1234", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); } [Theory] [CombinatorialData] public async Task TestAddingAndRemovingEditorConfigFileWithDiagnosticSeverity([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName) { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", languageName); solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var syntaxTreeAfterAddingEditorConfig = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var project = solution.GetProject(projectId); var provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.True(provider.TryGetDiagnosticValue(syntaxTreeAfterAddingEditorConfig, "CA1234", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); solution = solution.RemoveAnalyzerConfigDocument(editorConfigDocumentId); project = solution.GetProject(projectId); var syntaxTreeAfterRemovingEditorConfig = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.False(provider.TryGetDiagnosticValue(syntaxTreeAfterAddingEditorConfig, "CA1234", CancellationToken.None, out _)); var finalCompilation = await project.GetCompilationAsync(); Assert.True(finalCompilation.ContainsSyntaxTree(syntaxTreeAfterRemovingEditorConfig)); } [Theory] [CombinatorialData] public async Task TestChangingAnEditorConfigFile([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName, bool useRecoverableTrees) { using var workspace = useRecoverableTrees ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace(); var solution = workspace.CurrentSolution; var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", languageName); solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var syntaxTreeBeforeEditorConfigChange = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var project = solution.GetProject(projectId); var provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.Equal(provider, (await project.GetCompilationAsync()).Options.SyntaxTreeOptionsProvider); Assert.True(provider.TryGetDiagnosticValue(syntaxTreeBeforeEditorConfigChange, "CA1234", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); solution = solution.WithAnalyzerConfigDocumentTextLoader( editorConfigDocumentId, TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA6789.severity = error"), VersionStamp.Default)), PreservationMode.PreserveValue); var syntaxTreeAfterEditorConfigChange = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); project = solution.GetProject(projectId); provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.Equal(provider, (await project.GetCompilationAsync()).Options.SyntaxTreeOptionsProvider); Assert.True(provider.TryGetDiagnosticValue(syntaxTreeBeforeEditorConfigChange, "CA6789", CancellationToken.None, out severity)); Assert.Equal(ReportDiagnostic.Error, severity); var finalCompilation = await project.GetCompilationAsync(); Assert.True(finalCompilation.ContainsSyntaxTree(syntaxTreeAfterEditorConfigChange)); } [Fact] public void TestAddingAndRemovingGlobalEditorConfigFileWithDiagnosticSeverity() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", LanguageNames.CSharp); solution = solution.AddDocument(sourceDocumentId, "Test.cs", "", filePath: @"Z:\Test.cs"); var originalProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider; Assert.False(originalProvider.TryGetGlobalDiagnosticValue("CA1234", default, out _)); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".globalconfig", filePath: @"Z:\.globalconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("is_global = true\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var newProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider; Assert.True(newProvider.TryGetGlobalDiagnosticValue("CA1234", default, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); solution = solution.RemoveAnalyzerConfigDocument(editorConfigDocumentId); var finalProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider; Assert.False(finalProvider.TryGetGlobalDiagnosticValue("CA1234", default, out _)); } [Fact] [WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")] public async Task TestAddingEditorConfigFileWithIsGeneratedCodeOption() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", LanguageNames.CSharp) .WithProjectMetadataReferences(projectId, new[] { TestMetadata.Net451.mscorlib }) .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithNullableContextOptions(NullableContextOptions.Enable)); var src = @" class C { void M(C? c) { _ = c.ToString(); // warning CS8602: Dereference of a possibly null reference. } }"; solution = solution.AddDocument(sourceDocumentId, "Test.cs", src, filePath: @"Z:\Test.cs"); var originalSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var originalCompilation = await solution.GetProject(projectId).GetCompilationAsync(); // warning CS8602: Dereference of a possibly null reference. var diagnostics = originalCompilation.GetDiagnostics(); var diagnostic = Assert.Single(diagnostics); Assert.Equal("CS8602", diagnostic.Id); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ngenerated_code = true"), VersionStamp.Default))))); var newSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var newCompilation = await solution.GetProject(projectId).GetCompilationAsync(); Assert.Same(originalSyntaxTree, newSyntaxTree); Assert.NotSame(originalCompilation, newCompilation); Assert.NotEqual(originalCompilation.Options, newCompilation.Options); // warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // Auto-generated code requires an explicit '#nullable' directive in source. diagnostics = newCompilation.GetDiagnostics(); diagnostic = Assert.Single(diagnostics); Assert.Contains("CS8669", diagnostic.Id); } [Fact] public void NoCompilationProjectsHaveNullSyntaxTreesAndSemanticModels() { using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) }); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", NoCompilationConstants.LanguageName); solution = solution.AddDocument(documentId, "Test.cs", "", filePath: @"Z:\Test.txt"); var document = solution.GetDocument(documentId)!; Assert.False(document.TryGetSyntaxTree(out _)); Assert.Null(document.GetSyntaxTreeAsync().Result); Assert.Null(document.GetSyntaxTreeSynchronously(CancellationToken.None)); Assert.False(document.TryGetSemanticModel(out _)); Assert.Null(document.GetSemanticModelAsync().Result); } [Fact] public void ChangingFilePathOfFileInNoCompilationProjectWorks() { using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) }); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", NoCompilationConstants.LanguageName); solution = solution.AddDocument(documentId, "Test.cs", "", filePath: @"Z:\Test.txt"); Assert.Null(solution.GetDocument(documentId)!.GetSyntaxTreeAsync().Result); solution = solution.WithDocumentFilePath(documentId, @"Z:\NewPath.txt"); Assert.Null(solution.GetDocument(documentId)!.GetSyntaxTreeAsync().Result); } [Fact] public void AddingAndRemovingProjectsUpdatesFilePathMap() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); const string editorConfigFilePath = @"Z:\.editorconfig"; var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Default, "Test", "Test", LanguageNames.CSharp) .WithAnalyzerConfigDocuments(new[] { DocumentInfo.Create(editorConfigDocumentId, ".editorconfig", filePath: editorConfigFilePath) }); solution = solution.AddProject(projectInfo); Assert.Equal(editorConfigDocumentId, Assert.Single(solution.GetDocumentIdsWithFilePath(editorConfigFilePath))); solution = solution.RemoveProject(projectId); Assert.Empty(solution.GetDocumentIdsWithFilePath(editorConfigFilePath)); } private static void GetMultipleProjects( out Project csBrokenProject, out Project vbNormalProject, out Project dependsOnBrokenProject, out Project dependsOnVbNormalProject, out Project transitivelyDependsOnBrokenProjects, out Project transitivelyDependsOnNormalProjects) { var workspace = new AdhocWorkspace(); csBrokenProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "CSharpProject", "CSharpProject", LanguageNames.CSharp).WithHasAllInformation(hasAllInformation: false)); vbNormalProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic)); dependsOnBrokenProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(csBrokenProject.Id), new ProjectReference(vbNormalProject.Id) })); dependsOnVbNormalProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "CSharpProject", "CSharpProject", LanguageNames.CSharp, projectReferences: new[] { new ProjectReference(vbNormalProject.Id) })); transitivelyDependsOnBrokenProjects = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "CSharpProject", "CSharpProject", LanguageNames.CSharp, projectReferences: new[] { new ProjectReference(dependsOnBrokenProject.Id) })); transitivelyDependsOnNormalProjects = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(dependsOnVbNormalProject.Id) })); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestOptionChangesForLanguagesNotInSolution() { // Create an empty solution with no projects. using var workspace = CreateWorkspace(); var s0 = workspace.CurrentSolution; var optionService = workspace.Services.GetRequiredService<IOptionService>(); // Apply an option change to a C# option. var option = GenerationOptions.PlaceSystemNamespaceFirst; var defaultValue = option.DefaultValue; var changedValue = !defaultValue; var options = s0.Options.WithChangedOption(option, LanguageNames.CSharp, changedValue); // Verify option change is preserved even if the solution has no project with that language. var s1 = s0.WithOptions(options); VerifyOptionSet(s1.Options); // Verify option value is preserved on adding a project for a different language. var s2 = s1.AddProject("P1", "A1", LanguageNames.VisualBasic).Solution; VerifyOptionSet(s2.Options); // Verify option value is preserved on roundtriping the option set (serialize and deserialize). var s3 = s2.AddProject("P2", "A2", LanguageNames.CSharp).Solution; var roundTripOptionSet = SerializeAndDeserialize((SerializableOptionSet)s3.Options, optionService); VerifyOptionSet(roundTripOptionSet); // Verify option value is preserved on removing a project. var s4 = s3.RemoveProject(s3.Projects.Single(p => p.Name == "P2").Id); VerifyOptionSet(s4.Options); return; void VerifyOptionSet(OptionSet optionSet) { Assert.Equal(changedValue, optionSet.GetOption(option, LanguageNames.CSharp)); Assert.Equal(defaultValue, optionSet.GetOption(option, LanguageNames.VisualBasic)); } static SerializableOptionSet SerializeAndDeserialize(SerializableOptionSet optionSet, IOptionService optionService) { using var stream = new MemoryStream(); using var writer = new ObjectWriter(stream); optionSet.Serialize(writer, CancellationToken.None); stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); return SerializableOptionSet.Deserialize(reader, optionService, CancellationToken.None); } } [Theory] [CombinatorialData] public async Task TestUpdatedDocumentTextIsObservablyConstantAsync(bool recoverable) { using var workspace = recoverable ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace(); var pid = ProjectId.CreateNewId(); var text = SourceText.From("public class C { }"); var version = VersionStamp.Create(); var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version))); var projInfo = ProjectInfo.Create( pid, version: VersionStamp.Default, name: "TestProject", assemblyName: "TestProject.dll", language: LanguageNames.CSharp, documents: new[] { docInfo }); var solution = workspace.CurrentSolution.AddProject(projInfo); var doc = solution.GetDocument(docInfo.Id); // change document var root = await doc.GetSyntaxRootAsync(); var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation()); Assert.NotSame(root, newRoot); var newDoc = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot).GetDocument(doc.Id); Assert.NotSame(doc, newDoc); var newDocText = await newDoc.GetTextAsync(); var sameText = await newDoc.GetTextAsync(); Assert.Same(newDocText, sameText); var newDocTree = await newDoc.GetSyntaxTreeAsync(); var treeText = newDocTree.GetText(); Assert.Same(newDocText, treeText); } [Fact] public async Task ReplacingTextMultipleTimesDoesNotRootIntermediateCopiesIfCompilationNotAskedFor() { // This test replicates the pattern of some operation changing a bunch of files, but the files aren't kept open. // In Visual Studio we do large refactorings by opening files with an invisible editor, making changes, and closing // again. This process means we'll queue up intermediate changes to those files, but we don't want to hold onto // the intermediate edits when we don't really need to since the final version will be all that matters. using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); // Fetch the compilation, so further edits are going to be incremental updates of this one var originalCompilation = await solution.Projects.Single().GetCompilationAsync(); // Create a source text we'll release and ensure it disappears. We'll also make sure we don't accidentally root // that solution in the middle. var sourceTextToRelease = ObjectReference.CreateFromFactory(static () => SourceText.From(Guid.NewGuid().ToString())); var solutionWithSourceTextToRelease = sourceTextToRelease.GetObjectReference( static (sourceText, document) => document.Project.Solution.WithDocumentText(document.Id, sourceText, PreservationMode.PreserveIdentity), solution.GetDocument(documentId)); // Change it again, this time by editing the text loader; this replicates us closing a file, and we don't want to pin the changes from the // prior change. var finalSolution = solutionWithSourceTextToRelease.GetObjectReference( static (s, documentId) => s.WithDocumentTextLoader(documentId, new TestTextLoader(Guid.NewGuid().ToString()), PreservationMode.PreserveValue), documentId).GetReference(); // The text in the middle shouldn't be held at all, since we replaced it. solutionWithSourceTextToRelease.ReleaseStrongReference(); sourceTextToRelease.AssertReleased(); GC.KeepAlive(finalSolution); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Persistence; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.VisualStudio.Threading; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using CS = Microsoft.CodeAnalysis.CSharp; using static Microsoft.CodeAnalysis.UnitTests.SolutionTestHelpers; namespace Microsoft.CodeAnalysis.UnitTests { [UseExportProvider] [Trait(Traits.Feature, Traits.Features.Workspace)] public class SolutionTests : TestBase { #nullable enable private static readonly MetadataReference s_mscorlib = TestMetadata.Net451.mscorlib; private static readonly DocumentId s_unrelatedDocumentId = DocumentId.CreateNewId(ProjectId.CreateNewId()); private static Workspace CreateWorkspaceWithProjectAndDocuments() { var projectId = ProjectId.CreateNewId(); var workspace = CreateWorkspace(); Assert.True(workspace.TryApplyChanges(workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp) .AddDocument(DocumentId.CreateNewId(projectId), "goo.cs", "public class Goo { }") .AddAdditionalDocument(DocumentId.CreateNewId(projectId), "add.txt", "text") .AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From("config"), filePath: "/a/b"))); return workspace; } private static IEnumerable<T> EmptyEnumerable<T>() { yield break; } // Returns an enumerable that can only be enumerated once. private static IEnumerable<T> OnceEnumerable<T>(params T[] items) => OnceEnumerableImpl(new StrongBox<int>(), items); private static IEnumerable<T> OnceEnumerableImpl<T>(StrongBox<int> counter, T[] items) { Assert.Equal(0, counter.Value); counter.Value++; foreach (var item in items) { yield return item; } } [Fact] public void RemoveDocument_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveDocument(null!)); Assert.Throws<InvalidOperationException>(() => solution.RemoveDocument(s_unrelatedDocumentId)); } [Fact] public void RemoveDocuments_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveDocuments(default)); Assert.Throws<InvalidOperationException>(() => solution.RemoveDocuments(ImmutableArray.Create(s_unrelatedDocumentId))); Assert.Throws<ArgumentNullException>(() => solution.RemoveDocuments(ImmutableArray.Create((DocumentId)null!))); } [Fact] public void RemoveAdditionalDocument_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocument(null!)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAdditionalDocument(s_unrelatedDocumentId)); } [Fact] public void RemoveAdditionalDocuments_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocuments(default)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAdditionalDocuments(ImmutableArray.Create(s_unrelatedDocumentId))); Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocuments(ImmutableArray.Create((DocumentId)null!))); } [Fact] public void RemoveAnalyzerConfigDocument_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocument(null!)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerConfigDocument(s_unrelatedDocumentId)); } [Fact] public void RemoveAnalyzerConfigDocuments_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocuments(default)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerConfigDocuments(ImmutableArray.Create(s_unrelatedDocumentId))); Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocuments(ImmutableArray.Create((DocumentId)null!))); } [Fact] public void WithDocumentName() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var name = "new name"; var newSolution1 = solution.WithDocumentName(documentId, name); Assert.Equal(name, newSolution1.GetDocument(documentId)!.Name); var newSolution2 = newSolution1.WithDocumentName(documentId, name); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentName(documentId, name: null!)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentName(null!, name)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentName(s_unrelatedDocumentId, name)); } [Fact] public void WithDocumentFolders() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var folders = new[] { "folder1", "folder2" }; var newSolution1 = solution.WithDocumentFolders(documentId, folders); Assert.Equal(folders, newSolution1.GetDocument(documentId)!.Folders); var newSolution2 = newSolution1.WithDocumentFolders(documentId, folders); Assert.Same(newSolution2, newSolution1); // empty: var newSolution3 = solution.WithDocumentFolders(documentId, new string[0]); Assert.Equal(new string[0], newSolution3.GetDocument(documentId)!.Folders); var newSolution4 = solution.WithDocumentFolders(documentId, ImmutableArray<string>.Empty); Assert.Same(newSolution3, newSolution4); var newSolution5 = solution.WithDocumentFolders(documentId, null); Assert.Same(newSolution3, newSolution5); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFolders(documentId, folders: new string[] { null! })); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFolders(null!, folders)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentFolders(s_unrelatedDocumentId, folders)); } [Fact] [WorkItem(34837, "https://github.com/dotnet/roslyn/issues/34837")] [WorkItem(37125, "https://github.com/dotnet/roslyn/issues/37125")] public void WithDocumentFilePath() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var path = "new path"; var newSolution1 = solution.WithDocumentFilePath(documentId, path); Assert.Equal(path, newSolution1.GetDocument(documentId)!.FilePath); AssertEx.Equal(new[] { documentId }, newSolution1.GetDocumentIdsWithFilePath(path)); var newSolution2 = newSolution1.WithDocumentFilePath(documentId, path); Assert.Same(newSolution1, newSolution2); // empty path (TODO https://github.com/dotnet/roslyn/issues/37125): var newSolution3 = solution.WithDocumentFilePath(documentId, ""); Assert.Equal("", newSolution3.GetDocument(documentId)!.FilePath); Assert.Empty(newSolution3.GetDocumentIdsWithFilePath("")); // TODO: https://github.com/dotnet/roslyn/issues/37125 Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFilePath(documentId, filePath: null!)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFilePath(null!, path)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentFilePath(s_unrelatedDocumentId, path)); } [Fact] public void WithSourceCodeKind() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); Assert.Same(solution, solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Regular)); var newSolution1 = solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Script); Assert.Equal(SourceCodeKind.Script, newSolution1.GetDocument(documentId)!.SourceCodeKind); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentSourceCodeKind(documentId, (SourceCodeKind)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentSourceCodeKind(null!, SourceCodeKind.Script)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentSourceCodeKind(s_unrelatedDocumentId, SourceCodeKind.Script)); } [Fact, Obsolete] public void WithSourceCodeKind_Obsolete() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var newSolution = solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Interactive); Assert.Equal(SourceCodeKind.Script, newSolution.GetDocument(documentId)!.SourceCodeKind); } [Fact] public void WithDocumentSyntaxRoot() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var root = CS.SyntaxFactory.ParseSyntaxTree("class NewClass {}").GetRoot(); var newSolution1 = solution.WithDocumentSyntaxRoot(documentId, root, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetSyntaxRoot(out var actualRoot)); Assert.Equal(root.ToString(), actualRoot!.ToString()); // the actual root has a new parent SyntaxTree: Assert.NotSame(root, actualRoot); var newSolution2 = newSolution1.WithDocumentSyntaxRoot(documentId, actualRoot); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentSyntaxRoot(documentId, root, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentSyntaxRoot(null!, root)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentSyntaxRoot(s_unrelatedDocumentId, root)); } [Fact] [WorkItem(37125, "https://github.com/dotnet/roslyn/issues/41940")] public async Task WithDocumentSyntaxRoot_AnalyzerConfigWithoutFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(DocumentId.CreateNewId(projectId), "goo.cs", "public class Goo { }") .AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From("config")); var project = solution.GetProject(projectId)!; var compilation = (await project.GetCompilationAsync())!; var tree = compilation.SyntaxTrees.Single(); var provider = compilation.Options.SyntaxTreeOptionsProvider!; Assert.Throws<ArgumentException>(() => provider.TryGetDiagnosticValue(tree, "CA1234", CancellationToken.None, out _)); } [Fact] public void WithDocumentText_SourceText() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(documentId, text, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity)); } [Fact] public void WithDocumentText_TextAndVersion() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default); var newSolution1 = solution.WithDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText)); Assert.True(newSolution1.GetDocument(documentId)!.TryGetTextVersion(out var actualVersion)); Assert.Same(textAndVersion.Text, actualText); Assert.Equal(textAndVersion.Version, actualVersion); var newSolution2 = newSolution1.WithDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(documentId, textAndVersion, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity)); } [Fact] public void WithDocumentText_MultipleDocuments() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithDocumentText(new[] { documentId }, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithDocumentText(new[] { documentId }, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); // documents not in solution are skipped: https://github.com/dotnet/roslyn/issues/42029 Assert.Same(solution, solution.WithDocumentText(new DocumentId[] { null! }, text)); Assert.Same(solution, solution.WithDocumentText(new DocumentId[] { s_unrelatedDocumentId }, text)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId[])null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(new[] { documentId }, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(new[] { documentId }, text, (PreservationMode)(-1))); } [Fact] public void WithAdditionalDocumentText_SourceText() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AdditionalDocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithAdditionalDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithAdditionalDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentText(documentId, text, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity)); } [Fact] public void WithAdditionalDocumentText_TextAndVersion() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AdditionalDocumentIds.Single(); var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default); var newSolution1 = solution.WithAdditionalDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText)); Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetTextVersion(out var actualVersion)); Assert.Same(textAndVersion.Text, actualText); Assert.Equal(textAndVersion.Version, actualVersion); var newSolution2 = newSolution1.WithAdditionalDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentText(documentId, textAndVersion, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity)); } [Fact] public void WithAnalyzerConfigDocumentText_SourceText() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithAnalyzerConfigDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithAnalyzerConfigDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentText(documentId, text, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity)); } [Fact] public void WithAnalyzerConfigDocumentText_TextAndVersion() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single(); var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default); var newSolution1 = solution.WithAnalyzerConfigDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText)); Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetTextVersion(out var actualVersion)); Assert.Same(textAndVersion.Text, actualText); Assert.Equal(textAndVersion.Version, actualVersion); var newSolution2 = newSolution1.WithAnalyzerConfigDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentText(documentId, textAndVersion, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity)); } [Fact] public void WithDocumentTextLoader() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var loader = new TestTextLoader("new text"); var newSolution1 = solution.WithDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.Equal("new text", newSolution1.GetDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString()); // Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028 var newSolution2 = solution.WithDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.NotSame(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentTextLoader(documentId, loader, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity)); } [Fact] public void WithAdditionalDocumentTextLoader() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AdditionalDocumentIds.Single(); var loader = new TestTextLoader("new text"); var newSolution1 = solution.WithAdditionalDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.Equal("new text", newSolution1.GetAdditionalDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString()); // Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028 var newSolution2 = solution.WithAdditionalDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.NotSame(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentTextLoader(documentId, loader, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity)); } [Fact] public void WithAnalyzerConfigDocumentTextLoader() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single(); var loader = new TestTextLoader("new text"); var newSolution1 = solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.Equal("new text", newSolution1.GetAnalyzerConfigDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString()); // Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028 var newSolution2 = solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.NotSame(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity)); } [Fact] public void WithProjectAssemblyName() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var assemblyName = "\0<>a/b/*.dll"; var newSolution = solution.WithProjectAssemblyName(projectId, assemblyName); Assert.Equal(assemblyName, newSolution.GetProject(projectId)!.AssemblyName); Assert.Same(newSolution, newSolution.WithProjectAssemblyName(projectId, assemblyName)); Assert.Throws<ArgumentNullException>("assemblyName", () => solution.WithProjectAssemblyName(projectId, null!)); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectAssemblyName(null!, "x.dll")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectAssemblyName(ProjectId.CreateNewId(), "x.dll")); } [Fact] public void WithProjectOutputFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.dll"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectOutputFilePath(projectId, value), s => s.GetProject(projectId)!.OutputFilePath, (string?)path, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectOutputFilePath(null!, "x.dll")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectOutputFilePath(ProjectId.CreateNewId(), "x.dll")); } [Fact] public void WithProjectOutputRefFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.dll"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectOutputRefFilePath(projectId, value), s => s.GetProject(projectId)!.OutputRefFilePath, (string?)path, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectOutputRefFilePath(null!, "x.dll")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectOutputRefFilePath(ProjectId.CreateNewId(), "x.dll")); } [Fact] public void WithProjectCompilationOutputInfo() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.dll"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectCompilationOutputInfo(projectId, value), s => s.GetProject(projectId)!.CompilationOutputInfo, new CompilationOutputInfo(path), defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectCompilationOutputInfo(null!, new CompilationOutputInfo("x.dll"))); Assert.Throws<InvalidOperationException>(() => solution.WithProjectCompilationOutputInfo(ProjectId.CreateNewId(), new CompilationOutputInfo("x.dll"))); } [Fact] public void WithProjectDefaultNamespace() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var defaultNamespace = "\0<>a/b/*"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectDefaultNamespace(projectId, value), s => s.GetProject(projectId)!.DefaultNamespace, (string?)defaultNamespace, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectDefaultNamespace(null!, "x")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectDefaultNamespace(ProjectId.CreateNewId(), "x")); } [Fact] public void WithProjectName() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var projectName = "\0<>a/b/*"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectName(projectId, value), s => s.GetProject(projectId)!.Name, projectName, defaultThrows: true); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectName(null!, "x")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectName(ProjectId.CreateNewId(), "x")); } [Fact] public void WithProjectFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.csproj"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectFilePath(projectId, value), s => s.GetProject(projectId)!.FilePath, (string?)path, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectFilePath(null!, "x")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectFilePath(ProjectId.CreateNewId(), "x")); } [Fact] public void WithProjectCompilationOptionsExceptionHandling() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); var options = new CSharpCompilationOptions(OutputKind.NetModule); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectCompilationOptions(null!, options)); Assert.Throws<InvalidOperationException>(() => solution.WithProjectCompilationOptions(ProjectId.CreateNewId(), options)); } [Theory] [CombinatorialData] public void WithProjectCompilationOptionsReplacesSyntaxTreeOptionProvider([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName) { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", languageName); // We always have a non-null SyntaxTreeOptionsProvider for C# and VB projects var originalSyntaxTreeOptionsProvider = solution.Projects.Single().CompilationOptions!.SyntaxTreeOptionsProvider; Assert.NotNull(originalSyntaxTreeOptionsProvider); var defaultOptions = solution.Projects.Single().LanguageServices.GetRequiredService<ICompilationFactoryService>().GetDefaultCompilationOptions(); Assert.Null(defaultOptions.SyntaxTreeOptionsProvider); solution = solution.WithProjectCompilationOptions(projectId, defaultOptions); // The CompilationOptions we replaced with didn't have a SyntaxTreeOptionsProvider, but we would have placed it // back. The SyntaxTreeOptionsProvider should behave the same as the prior one and thus should be equal. var newSyntaxTreeOptionsProvider = solution.Projects.Single().CompilationOptions!.SyntaxTreeOptionsProvider; Assert.NotNull(newSyntaxTreeOptionsProvider); Assert.Equal(originalSyntaxTreeOptionsProvider, newSyntaxTreeOptionsProvider); } [Fact] public void WithProjectParseOptions() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); var options = new CSharpParseOptions(CS.LanguageVersion.CSharp1); SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectParseOptions(projectId, value), s => s.GetProject(projectId)!.ParseOptions!, (ParseOptions)options, defaultThrows: true); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectParseOptions(null!, options)); Assert.Throws<InvalidOperationException>(() => solution.WithProjectParseOptions(ProjectId.CreateNewId(), options)); } [Fact] public void WithProjectReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var projectId2 = ProjectId.CreateNewId(); solution = solution.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp); var projectRef = new ProjectReference(projectId2); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithProjectReferences(projectId, value), opt => opt.GetProject(projectId)!.AllProjectReferences, projectRef, allowDuplicates: false); var projectRefs = (IEnumerable<ProjectReference>)ImmutableArray.Create( new ProjectReference(projectId2), new ProjectReference(projectId2, ImmutableArray.Create("alias")), new ProjectReference(projectId2, embedInteropTypes: true)); var solution2 = solution.WithProjectReferences(projectId, projectRefs); Assert.Same(projectRefs, solution2.GetProject(projectId)!.AllProjectReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectReferences(null!, new[] { projectRef })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(ProjectId.CreateNewId(), new[] { projectRef })); // cycles: Assert.Throws<InvalidOperationException>(() => solution2.WithProjectReferences(projectId2, new[] { new ProjectReference(projectId) })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(projectId, new[] { new ProjectReference(projectId) })); } [Fact] [WorkItem(42406, "https://github.com/dotnet/roslyn/issues/42406")] public void WithProjectReferences_ProjectNotInSolution() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var externalProjectRef = new ProjectReference(ProjectId.CreateNewId()); var projectRefs = (IEnumerable<ProjectReference>)ImmutableArray.Create(externalProjectRef); var newSolution1 = solution.WithProjectReferences(projectId, projectRefs); Assert.Same(projectRefs, newSolution1.GetProject(projectId)!.AllProjectReferences); // project reference is not included: Assert.Empty(newSolution1.GetProject(projectId)!.ProjectReferences); } [Fact] public void AddProjectReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var projectId2 = ProjectId.CreateNewId(); var projectId3 = ProjectId.CreateNewId(); solution = solution .AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp) .AddProject(projectId3, "proj3", "proj3.dll", LanguageNames.CSharp); var projectRef2 = new ProjectReference(projectId2); var projectRef3 = new ProjectReference(projectId3); var externalProjectRef = new ProjectReference(ProjectId.CreateNewId()); solution = solution.AddProjectReference(projectId3, projectRef2); var solution2 = solution.AddProjectReferences(projectId, EmptyEnumerable<ProjectReference>()); Assert.Same(solution, solution2); var e = OnceEnumerable(projectRef2, externalProjectRef); var solution3 = solution.AddProjectReferences(projectId, e); AssertEx.Equal(new[] { projectRef2 }, solution3.GetProject(projectId)!.ProjectReferences); AssertEx.Equal(new[] { projectRef2, externalProjectRef }, solution3.GetProject(projectId)!.AllProjectReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.AddProjectReferences(null!, new[] { projectRef2 })); Assert.Throws<ArgumentNullException>("projectReferences", () => solution.AddProjectReferences(projectId, null!)); Assert.Throws<ArgumentNullException>("projectReferences[0]", () => solution.AddProjectReferences(projectId, new ProjectReference[] { null! })); Assert.Throws<ArgumentException>("projectReferences[1]", () => solution.AddProjectReferences(projectId, new[] { projectRef2, projectRef2 })); Assert.Throws<ArgumentException>("projectReferences[1]", () => solution.AddProjectReferences(projectId, new[] { new ProjectReference(projectId2), new ProjectReference(projectId2) })); // dup: Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(projectId3, new[] { projectRef2 })); // cycles: Assert.Throws<InvalidOperationException>(() => solution3.AddProjectReferences(projectId2, new[] { projectRef3 })); Assert.Throws<InvalidOperationException>(() => solution3.AddProjectReferences(projectId, new[] { new ProjectReference(projectId) })); } [Fact] public void RemoveProjectReference() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var projectId2 = ProjectId.CreateNewId(); solution = solution.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp); var projectRef2 = new ProjectReference(projectId2); var externalProjectRef = new ProjectReference(ProjectId.CreateNewId()); solution = solution.WithProjectReferences(projectId, new[] { projectRef2, externalProjectRef }); // remove reference to a project that's not part of the solution: var solution2 = solution.RemoveProjectReference(projectId, externalProjectRef); AssertEx.Equal(new[] { projectRef2 }, solution2.GetProject(projectId)!.AllProjectReferences); // remove reference to a project that's part of the solution: var solution3 = solution.RemoveProjectReference(projectId, projectRef2); AssertEx.Equal(new[] { externalProjectRef }, solution3.GetProject(projectId)!.AllProjectReferences); var solution4 = solution3.RemoveProjectReference(projectId, externalProjectRef); Assert.Empty(solution4.GetProject(projectId)!.AllProjectReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveProjectReference(null!, projectRef2)); Assert.Throws<ArgumentNullException>("projectReference", () => solution.RemoveProjectReference(projectId, null!)); // removing a reference that's not in the list: Assert.Throws<ArgumentException>("projectReference", () => solution.RemoveProjectReference(projectId, new ProjectReference(ProjectId.CreateNewId()))); // project not in solution: Assert.Throws<InvalidOperationException>(() => solution.RemoveProjectReference(ProjectId.CreateNewId(), projectRef2)); } [Fact] public void ProjectReferences_Submissions() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId0 = ProjectId.CreateNewId(); var submissionId1 = ProjectId.CreateNewId(); var submissionId2 = ProjectId.CreateNewId(); var submissionId3 = ProjectId.CreateNewId(); solution = solution .AddProject(projectId0, "non-submission", "non-submission.dll", LanguageNames.CSharp) .AddProject(ProjectInfo.Create(submissionId1, VersionStamp.Default, name: "submission1", assemblyName: "submission1.dll", LanguageNames.CSharp, isSubmission: true)) .AddProject(ProjectInfo.Create(submissionId2, VersionStamp.Default, name: "submission2", assemblyName: "submission2.dll", LanguageNames.CSharp, isSubmission: true)) .AddProject(ProjectInfo.Create(submissionId3, VersionStamp.Default, name: "submission3", assemblyName: "submission3.dll", LanguageNames.CSharp, isSubmission: true)) .AddProjectReference(submissionId2, new ProjectReference(submissionId1)) .WithProjectReferences(submissionId2, new[] { new ProjectReference(submissionId1) }); // submission may be referenced from multiple submissions (forming a tree): _ = solution.AddProjectReferences(submissionId3, new[] { new ProjectReference(submissionId1) }); _ = solution.WithProjectReferences(submissionId3, new[] { new ProjectReference(submissionId1) }); // submission may reference a non-submission project: _ = solution.AddProjectReferences(submissionId3, new[] { new ProjectReference(projectId0) }); _ = solution.WithProjectReferences(submissionId3, new[] { new ProjectReference(projectId0) }); // submission can't reference multiple submissions: Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(submissionId2, new[] { new ProjectReference(submissionId3) })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(submissionId1, new[] { new ProjectReference(submissionId2), new ProjectReference(submissionId3) })); // non-submission project can't reference a submission: Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(projectId0, new[] { new ProjectReference(submissionId1) })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(projectId0, new[] { new ProjectReference(submissionId1) })); } [Fact] public void WithProjectMetadataReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var metadataRef = (MetadataReference)new TestMetadataReference(); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithProjectMetadataReferences(projectId, value), opt => opt.GetProject(projectId)!.MetadataReferences, metadataRef, allowDuplicates: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectMetadataReferences(null!, new[] { metadataRef })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectMetadataReferences(ProjectId.CreateNewId(), new[] { metadataRef })); } [Fact] public void AddMetadataReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var solution2 = solution.AddMetadataReferences(projectId, EmptyEnumerable<MetadataReference>()); Assert.Same(solution, solution2); var metadataRef1 = new TestMetadataReference(); var metadataRef2 = new TestMetadataReference(); var solution3 = solution.AddMetadataReferences(projectId, OnceEnumerable(metadataRef1, metadataRef2)); AssertEx.Equal(new[] { metadataRef1, metadataRef2 }, solution3.GetProject(projectId)!.MetadataReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.AddMetadataReferences(null!, new[] { metadataRef1 })); Assert.Throws<ArgumentNullException>("metadataReferences", () => solution.AddMetadataReferences(projectId, null!)); Assert.Throws<ArgumentNullException>("metadataReferences[0]", () => solution.AddMetadataReferences(projectId, new MetadataReference[] { null! })); Assert.Throws<ArgumentException>("metadataReferences[1]", () => solution.AddMetadataReferences(projectId, new[] { metadataRef1, metadataRef1 })); // dup: Assert.Throws<InvalidOperationException>(() => solution3.AddMetadataReferences(projectId, new[] { metadataRef1 })); } [Fact] public void RemoveMetadataReference() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var metadataRef1 = new TestMetadataReference(); var metadataRef2 = new TestMetadataReference(); solution = solution.WithProjectMetadataReferences(projectId, new[] { metadataRef1, metadataRef2 }); var solution2 = solution.RemoveMetadataReference(projectId, metadataRef1); AssertEx.Equal(new[] { metadataRef2 }, solution2.GetProject(projectId)!.MetadataReferences); var solution3 = solution2.RemoveMetadataReference(projectId, metadataRef2); Assert.Empty(solution3.GetProject(projectId)!.MetadataReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveMetadataReference(null!, metadataRef1)); Assert.Throws<ArgumentNullException>("metadataReference", () => solution.RemoveMetadataReference(projectId, null!)); // removing a reference that's not in the list: Assert.Throws<InvalidOperationException>(() => solution.RemoveMetadataReference(projectId, new TestMetadataReference())); // project not in solution: Assert.Throws<InvalidOperationException>(() => solution.RemoveMetadataReference(ProjectId.CreateNewId(), metadataRef1)); } [Fact] public void WithProjectAnalyzerReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var analyzerRef = (AnalyzerReference)new TestAnalyzerReference(); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithProjectAnalyzerReferences(projectId, value), opt => opt.GetProject(projectId)!.AnalyzerReferences, analyzerRef, allowDuplicates: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectAnalyzerReferences(null!, new[] { analyzerRef })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectAnalyzerReferences(ProjectId.CreateNewId(), new[] { analyzerRef })); } [Fact] public void AddAnalyzerReferences_Project() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var solution2 = solution.AddAnalyzerReferences(projectId, EmptyEnumerable<AnalyzerReference>()); Assert.Same(solution, solution2); var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); var solution3 = solution.AddAnalyzerReferences(projectId, OnceEnumerable(analyzerRef1, analyzerRef2)); AssertEx.Equal(new[] { analyzerRef1, analyzerRef2 }, solution3.GetProject(projectId)!.AnalyzerReferences); var solution4 = solution3.AddAnalyzerReferences(projectId, new AnalyzerReference[0]); Assert.Same(solution, solution2); Assert.Throws<ArgumentNullException>("projectId", () => solution.AddAnalyzerReferences(null!, new[] { analyzerRef1 })); Assert.Throws<ArgumentNullException>("analyzerReferences", () => solution.AddAnalyzerReferences(projectId, null!)); Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => solution.AddAnalyzerReferences(projectId, new AnalyzerReference[] { null! })); Assert.Throws<ArgumentException>("analyzerReferences[1]", () => solution.AddAnalyzerReferences(projectId, new[] { analyzerRef1, analyzerRef1 })); // dup: Assert.Throws<InvalidOperationException>(() => solution3.AddAnalyzerReferences(projectId, new[] { analyzerRef1 })); } [Fact] public void RemoveAnalyzerReference_Project() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); solution = solution.WithProjectAnalyzerReferences(projectId, new[] { analyzerRef1, analyzerRef2 }); var solution2 = solution.RemoveAnalyzerReference(projectId, analyzerRef1); AssertEx.Equal(new[] { analyzerRef2 }, solution2.GetProject(projectId)!.AnalyzerReferences); var solution3 = solution2.RemoveAnalyzerReference(projectId, analyzerRef2); Assert.Empty(solution3.GetProject(projectId)!.AnalyzerReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveAnalyzerReference(null!, analyzerRef1)); Assert.Throws<ArgumentNullException>("analyzerReference", () => solution.RemoveAnalyzerReference(projectId, null!)); // removing a reference that's not in the list: Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(projectId, new TestAnalyzerReference())); // project not in solution: Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(ProjectId.CreateNewId(), analyzerRef1)); } [Fact] public void WithAnalyzerReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var analyzerRef = (AnalyzerReference)new TestAnalyzerReference(); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithAnalyzerReferences(value), opt => opt.AnalyzerReferences, analyzerRef, allowDuplicates: false); } [Fact] public void AddAnalyzerReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var solution2 = solution.AddAnalyzerReferences(EmptyEnumerable<AnalyzerReference>()); Assert.Same(solution, solution2); var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); var solution3 = solution.AddAnalyzerReferences(OnceEnumerable(analyzerRef1, analyzerRef2)); AssertEx.Equal(new[] { analyzerRef1, analyzerRef2 }, solution3.AnalyzerReferences); var solution4 = solution3.AddAnalyzerReferences(new AnalyzerReference[0]); Assert.Same(solution, solution2); Assert.Throws<ArgumentNullException>("analyzerReferences", () => solution.AddAnalyzerReferences(null!)); Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => solution.AddAnalyzerReferences(new AnalyzerReference[] { null! })); Assert.Throws<ArgumentException>("analyzerReferences[1]", () => solution.AddAnalyzerReferences(new[] { analyzerRef1, analyzerRef1 })); // dup: Assert.Throws<InvalidOperationException>(() => solution3.AddAnalyzerReferences(new[] { analyzerRef1 })); } [Fact] public void RemoveAnalyzerReference() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); solution = solution.WithAnalyzerReferences(new[] { analyzerRef1, analyzerRef2 }); var solution2 = solution.RemoveAnalyzerReference(analyzerRef1); AssertEx.Equal(new[] { analyzerRef2 }, solution2.AnalyzerReferences); var solution3 = solution2.RemoveAnalyzerReference(analyzerRef2); Assert.Empty(solution3.AnalyzerReferences); Assert.Throws<ArgumentNullException>("analyzerReference", () => solution.RemoveAnalyzerReference(null!)); // removing a reference that's not in the list: Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(new TestAnalyzerReference())); } #nullable disable [Fact] public void TestAddProject() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); solution = solution.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp); Assert.True(solution.ProjectIds.Any(), "Solution was expected to have projects"); Assert.NotNull(pid); var project = solution.GetProject(pid); Assert.False(project.HasDocuments); } [Fact] public void TestUpdateAssemblyName() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); solution = solution.WithProjectAssemblyName(project1, "bar"); var project = solution.GetProject(project1); Assert.Equal("bar", project.AssemblyName); } [Fact] [WorkItem(543964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543964")] public void MultipleProjectsWithSameDisplayName() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); var project2 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "name", "assemblyName", LanguageNames.CSharp); solution = solution.AddProject(project2, "name", "assemblyName", LanguageNames.CSharp); Assert.Equal(2, solution.GetProjectsByName("name").Count()); } [Fact] public async Task TestAddFirstDocumentAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", "public class Goo { }"); // verify project & document Assert.NotNull(pid); var project = solution.GetProject(pid); Assert.NotNull(project); Assert.True(solution.ContainsProject(pid), "Solution was expected to have project " + pid); Assert.True(project.HasDocuments, "Project was expected to have documents"); Assert.Equal(project, solution.GetProject(pid)); Assert.NotNull(did); var document = solution.GetDocument(did); Assert.True(project.ContainsDocument(did), "Project was expected to have document " + did); Assert.Equal(document, project.GetDocument(did)); Assert.Equal(document, solution.GetDocument(did)); var semantics = await document.GetSemanticModelAsync(); Assert.NotNull(semantics); await ValidateSolutionAndCompilationsAsync(solution); var pid2 = solution.Projects.Single().Id; var did2 = DocumentId.CreateNewId(pid2); solution = solution.AddDocument(did2, "bar.cs", "public class Bar { }"); // verify project & document var project2 = solution.GetProject(pid2); Assert.NotNull(project2); Assert.NotNull(did2); var document2 = solution.GetDocument(did2); Assert.True(project2.ContainsDocument(did2), "Project was expected to have document " + did2); Assert.Equal(document2, project2.GetDocument(did2)); Assert.Equal(document2, solution.GetDocument(did2)); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task AddTwoDocumentsForSingleProject() { var projectId = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); var project = Assert.Single(solution.Projects); var document1 = project.GetDocument(documentInfo1.Id); var document2 = project.GetDocument(documentInfo2.Id); Assert.NotSame(document1, document2); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task AddTwoDocumentsForTwoProjects() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); var project1 = solution.GetProject(projectId1); var project2 = solution.GetProject(projectId2); var document1 = project1.GetDocument(documentInfo1.Id); var document2 = project2.GetDocument(documentInfo2.Id); Assert.NotSame(document1, document2); Assert.NotSame(document1.Project, document2.Project); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public void AddTwoDocumentsWithMissingProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs"); // We're only adding the first project, but not the second one using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp); Assert.ThrowsAny<InvalidOperationException>(() => solution.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2))); } [Fact] public void RemoveZeroDocuments() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Same(solution, solution.RemoveDocuments(ImmutableArray<DocumentId>.Empty)); } [Fact] public async Task RemoveTwoDocuments() { var projectId = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "project1", "project1.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); solution = solution.RemoveDocuments(ImmutableArray.Create(documentInfo1.Id, documentInfo2.Id)); var finalProject = solution.Projects.Single(); Assert.Empty(finalProject.Documents); Assert.Empty((await finalProject.GetCompilationAsync()).SyntaxTrees); } [Fact] public void RemoveTwoDocumentsFromDifferentProjects() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); Assert.All(solution.Projects, p => Assert.Single(p.Documents)); solution = solution.RemoveDocuments(ImmutableArray.Create(documentInfo1.Id, documentInfo2.Id)); Assert.All(solution.Projects, p => Assert.Empty(p.Documents)); } [Fact] public void RemoveDocumentFromUnrelatedProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddDocument(documentInfo1); // This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveDocument // API due to https://github.com/dotnet/roslyn/issues/41211. Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveDocuments(ImmutableArray.Create(documentInfo1.Id))); } [Fact] public void RemoveAdditionalDocumentFromUnrelatedProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.txt"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddAdditionalDocument(documentInfo1); // This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveAdditionalDocument // API due to https://github.com/dotnet/roslyn/issues/41211. Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveAdditionalDocuments(ImmutableArray.Create(documentInfo1.Id))); } [Fact] public void RemoveAnalyzerConfigDocumentFromUnrelatedProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), ".editorconfig"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddAnalyzerConfigDocuments(ImmutableArray.Create(documentInfo1)); // This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveAdditionalDocument // API due to https://github.com/dotnet/roslyn/issues/41211. Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveAnalyzerConfigDocuments(ImmutableArray.Create(documentInfo1.Id))); } [Fact] public async Task TestOneCSharpProjectAsync() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject("goo", "goo.dll", LanguageNames.CSharp) .AddMetadataReference(s_mscorlib) .AddDocument("goo.cs", "public class Goo { }") .Project.Solution; await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task TestTwoCSharpProjectsAsync() { using var workspace = CreateWorkspace(); var pm1 = ProjectId.CreateNewId(); var pm2 = ProjectId.CreateNewId(); var doc1 = DocumentId.CreateNewId(pm1); var doc2 = DocumentId.CreateNewId(pm2); var solution = workspace.CurrentSolution .AddProject(pm1, "goo", "goo.dll", LanguageNames.CSharp) .AddProject(pm2, "bar", "bar.dll", LanguageNames.CSharp) .AddProjectReference(pm2, new ProjectReference(pm1)) .AddDocument(doc1, "goo.cs", "public class Goo { }") .AddDocument(doc2, "bar.cs", "public class Bar : Goo { }"); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task TestCrossLanguageProjectsAsync() { var pm1 = ProjectId.CreateNewId(); var pm2 = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(pm1, "goo", "goo.dll", LanguageNames.CSharp) .AddMetadataReference(pm1, s_mscorlib) .AddProject(pm2, "bar", "bar.dll", LanguageNames.VisualBasic) .AddMetadataReference(pm2, s_mscorlib) .AddProjectReference(pm2, new ProjectReference(pm1)) .AddDocument(DocumentId.CreateNewId(pm1), "goo.cs", "public class X { }") .AddDocument(DocumentId.CreateNewId(pm2), "bar.vb", "Public Class Y\r\nInherits X\r\nEnd Class"); await ValidateSolutionAndCompilationsAsync(solution); } private static async Task ValidateSolutionAndCompilationsAsync(Solution solution) { foreach (var project in solution.Projects) { Assert.True(solution.ContainsProject(project.Id), "Solution was expected to have project " + project.Id); Assert.Equal(project, solution.GetProject(project.Id)); // these won't always be unique in real-world but should be for these tests Assert.Equal(project, solution.GetProjectsByName(project.Name).FirstOrDefault()); var compilation = await project.GetCompilationAsync(); Assert.NotNull(compilation); // check that the options are the same Assert.Equal(project.CompilationOptions, compilation.Options); // check that all known metadata references are present in the compilation foreach (var meta in project.MetadataReferences) { Assert.True(compilation.References.Contains(meta), "Compilation references were expected to contain " + meta); } // check that all project-to-project reference metadata is present in the compilation foreach (var referenced in project.ProjectReferences) { if (solution.ContainsProject(referenced.ProjectId)) { var referencedMetadata = await solution.State.GetMetadataReferenceAsync(referenced, solution.GetProjectState(project.Id), CancellationToken.None); Assert.NotNull(referencedMetadata); if (referencedMetadata is CompilationReference compilationReference) { compilation.References.Single(r => { var cr = r as CompilationReference; return cr != null && cr.Compilation == compilationReference.Compilation; }); } } } // check that the syntax trees are the same var docs = project.Documents.ToList(); var trees = compilation.SyntaxTrees.ToList(); Assert.Equal(docs.Count, trees.Count); foreach (var doc in docs) { Assert.True(trees.Contains(await doc.GetSyntaxTreeAsync()), "trees list was expected to contain the syntax tree of doc"); } } } #if false [Fact(Skip = "641963")] public void TestDeepProjectReferenceTree() { int projectCount = 5; var solution = CreateSolutionWithProjectDependencyChain(projectCount); ProjectId[] projectIds = solution.ProjectIds.ToArray(); Compilation compilation; for (int i = 0; i < projectCount; i++) { Assert.False(solution.GetProject(projectIds[i]).TryGetCompilation(out compilation)); } var top = solution.GetCompilationAsync(projectIds.Last(), CancellationToken.None).Result; var partialSolution = solution.GetPartialSolution(); for (int i = 0; i < projectCount; i++) { // While holding a compilation, we also hold its references, plus one further level // of references alive. However, the references are only partial Declaration // compilations var isPartialAvailable = i >= projectCount - 3; var isFinalAvailable = i == projectCount - 1; var projectId = projectIds[i]; Assert.Equal(isFinalAvailable, solution.GetProject(projectId).TryGetCompilation(out compilation)); Assert.Equal(isPartialAvailable, partialSolution.ProjectIds.Contains(projectId) && partialSolution.GetProject(projectId).TryGetCompilation(out compilation)); } } #endif [WorkItem(636431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636431")] [Fact] public async Task TestProjectDependencyLoadingAsync() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var solution = workspace.CurrentSolution; var projectIds = Enumerable.Range(0, 5).Select(i => ProjectId.CreateNewId()).ToArray(); for (var i = 0; i < projectIds.Length; i++) { solution = solution.AddProject(projectIds[i], i.ToString(), i.ToString(), LanguageNames.CSharp); if (i >= 1) { solution = solution.AddProjectReference(projectIds[i], new ProjectReference(projectIds[i - 1])); } } await solution.GetProject(projectIds[0]).GetCompilationAsync(CancellationToken.None); await solution.GetProject(projectIds[2]).GetCompilationAsync(CancellationToken.None); } [Fact] public async Task TestAddMetadataReferencesAsync() { var mefReference = TestMetadata.Net451.SystemCore; using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); solution = solution.AddMetadataReference(project1, s_mscorlib); solution = solution.AddMetadataReference(project1, mefReference); var assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(mefReference); var namespacesAndTypes = assemblyReference.GlobalNamespace.GetAllNamespacesAndTypes(CancellationToken.None); var foundSymbol = from symbol in namespacesAndTypes where symbol.Name.Equals("Enumerable") select symbol; Assert.Equal(1, foundSymbol.Count()); solution = solution.RemoveMetadataReference(project1, mefReference); assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(mefReference); Assert.Null(assemblyReference); await ValidateSolutionAndCompilationsAsync(solution); } private class MockDiagnosticAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext analysisContext) { } } [Fact] public void TestProjectDiagnosticAnalyzers() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); Assert.Empty(solution.Projects.Single().AnalyzerReferences); DiagnosticAnalyzer analyzer = new MockDiagnosticAnalyzer(); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer)); // Test AddAnalyzer var newSolution = solution.AddAnalyzerReference(project1, analyzerReference); var actualAnalyzerReferences = newSolution.Projects.Single().AnalyzerReferences; Assert.Equal(1, actualAnalyzerReferences.Count); Assert.Equal(analyzerReference, actualAnalyzerReferences[0]); var actualAnalyzers = actualAnalyzerReferences[0].GetAnalyzersForAllLanguages(); Assert.Equal(1, actualAnalyzers.Length); Assert.Equal(analyzer, actualAnalyzers[0]); // Test ProjectChanges var changes = newSolution.GetChanges(solution).GetProjectChanges().Single(); var addedAnalyzerReference = changes.GetAddedAnalyzerReferences().Single(); Assert.Equal(analyzerReference, addedAnalyzerReference); var removedAnalyzerReferences = changes.GetRemovedAnalyzerReferences(); Assert.Empty(removedAnalyzerReferences); solution = newSolution; // Test RemoveAnalyzer solution = solution.RemoveAnalyzerReference(project1, analyzerReference); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Empty(actualAnalyzerReferences); // Test AddAnalyzers analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer)); DiagnosticAnalyzer secondAnalyzer = new MockDiagnosticAnalyzer(); var secondAnalyzerReference = new AnalyzerImageReference(ImmutableArray.Create(secondAnalyzer)); var analyzerReferences = new[] { analyzerReference, secondAnalyzerReference }; solution = solution.AddAnalyzerReferences(project1, analyzerReferences); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Equal(2, actualAnalyzerReferences.Count); Assert.Equal(analyzerReference, actualAnalyzerReferences[0]); Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]); solution = solution.RemoveAnalyzerReference(project1, analyzerReference); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Equal(1, actualAnalyzerReferences.Count); Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[0]); // Test WithAnalyzers solution = solution.WithProjectAnalyzerReferences(project1, analyzerReferences); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Equal(2, actualAnalyzerReferences.Count); Assert.Equal(analyzerReference, actualAnalyzerReferences[0]); Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]); } [Fact] public void TestProjectParseOptions() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); solution = solution.AddMetadataReference(project1, s_mscorlib); // Parse Options var oldParseOptions = solution.GetProject(project1).ParseOptions; var newParseOptions = new CSharpParseOptions(preprocessorSymbols: new[] { "AFTER" }); solution = solution.WithProjectParseOptions(project1, newParseOptions); var newUpdatedParseOptions = solution.GetProject(project1).ParseOptions; Assert.NotEqual(oldParseOptions, newUpdatedParseOptions); Assert.Same(newParseOptions, newUpdatedParseOptions); } [Fact] public async Task TestRemoveProjectAsync() { using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp); Assert.True(sol.ProjectIds.Any(), "Solution was expected to have projects"); Assert.NotNull(pid); var project = sol.GetProject(pid); Assert.False(project.HasDocuments); var sol2 = sol.RemoveProject(pid); Assert.False(sol2.ProjectIds.Any()); await ValidateSolutionAndCompilationsAsync(sol); } [Fact] public async Task TestRemoveProjectWithReferencesAsync() { using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); var pid2 = ProjectId.CreateNewId(); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp) .AddProjectReference(pid2, new ProjectReference(pid)); Assert.Equal(2, sol.Projects.Count()); // remove the project that is being referenced // this should leave a dangling reference var sol2 = sol.RemoveProject(pid); Assert.False(sol2.ContainsProject(pid)); Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2); Assert.Equal(1, sol2.Projects.Count()); Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 project pid2 was expected to contain project reference " + pid); await ValidateSolutionAndCompilationsAsync(sol2); } [Fact] public async Task TestRemoveProjectWithReferencesAndAddItBackAsync() { using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); var pid2 = ProjectId.CreateNewId(); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp) .AddProjectReference(pid2, new ProjectReference(pid)); Assert.Equal(2, sol.Projects.Count()); // remove the project that is being referenced var sol2 = sol.RemoveProject(pid); Assert.False(sol2.ContainsProject(pid)); Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2); Assert.Equal(1, sol2.Projects.Count()); Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 pid2 was expected to contain " + pid); var sol3 = sol2.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp); Assert.True(sol3.ContainsProject(pid), "sol3 was expected to contain " + pid); Assert.True(sol3.ContainsProject(pid2), "sol3 was expected to contain " + pid2); Assert.Equal(2, sol3.Projects.Count()); await ValidateSolutionAndCompilationsAsync(sol3); } [Fact] public async Task TestGetSyntaxRootAsync() { var text = "public class Goo { }"; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var document = sol.GetDocument(did); Assert.False(document.TryGetSyntaxRoot(out _)); var root = await document.GetSyntaxRootAsync(); Assert.NotNull(root); Assert.Equal(text, root.ToString()); Assert.True(document.TryGetSyntaxRoot(out root)); Assert.NotNull(root); } [Fact] public async Task TestUpdateDocumentAsync() { var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); using var workspace = CreateWorkspace(); var solution1 = workspace.CurrentSolution .AddProject(projectId, "ProjectName", "AssemblyName", LanguageNames.CSharp) .AddDocument(documentId, "DocumentName", SourceText.From("class Class{}")); var document = solution1.GetDocument(documentId); var newRoot = await Formatter.FormatAsync(document).Result.GetSyntaxRootAsync(); var solution2 = solution1.WithDocumentSyntaxRoot(documentId, newRoot); Assert.NotEqual(solution1, solution2); var newText = solution2.GetDocument(documentId).GetTextAsync().Result.ToString(); Assert.Equal("class Class { }", newText); } [Fact] public void TestUpdateSyntaxTreeWithAnnotations() { var text = "public class Goo { }"; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var document = sol.GetDocument(did); var tree = document.GetSyntaxTreeAsync().Result; var root = tree.GetRoot(); var annotation = new SyntaxAnnotation(); var annotatedRoot = root.WithAdditionalAnnotations(annotation); var sol2 = sol.WithDocumentSyntaxRoot(did, annotatedRoot); var doc2 = sol2.GetDocument(did); var tree2 = doc2.GetSyntaxTreeAsync().Result; var root2 = tree2.GetRoot(); // text should not be available yet (it should be defer created from the node) // and getting the document or root should not cause it to be created. Assert.False(tree2.TryGetText(out _)); var text2 = tree2.GetText(); Assert.NotNull(text2); Assert.NotSame(tree, tree2); Assert.NotSame(annotatedRoot, root2); Assert.True(annotatedRoot.IsEquivalentTo(root2)); Assert.True(root2.HasAnnotation(annotation)); } [Fact] public void TestUpdatingFilePathUpdatesSyntaxTree() { var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); const string OldFilePath = @"Z:\OldFilePath.cs"; const string NewFilePath = @"Z:\NewFilePath.cs"; using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(documentId, "OldFilePath.cs", "public class Goo { }", filePath: OldFilePath); // scope so later asserts don't accidentally use oldDocument { var oldDocument = solution.GetDocument(documentId); Assert.Equal(OldFilePath, oldDocument.FilePath); Assert.Equal(OldFilePath, oldDocument.GetSyntaxTreeAsync().Result.FilePath); } solution = solution.WithDocumentFilePath(documentId, NewFilePath); { var newDocument = solution.GetDocument(documentId); Assert.Equal(NewFilePath, newDocument.FilePath); Assert.Equal(NewFilePath, newDocument.GetSyntaxTreeAsync().Result.FilePath); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestSyntaxRootNotKeptAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", "public class Goo { }"); var observedRoot = GetObservedSyntaxTreeRoot(sol, did); observedRoot.AssertReleased(); // re-get the tree (should recover from storage, not reparse) _ = sol.GetDocument(did).GetSyntaxRootAsync().Result; } [MethodImpl(MethodImplOptions.NoInlining)] [Fact] [WorkItem(542736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542736")] public void TestDocumentChangedOnDiskIsNotObserved() { var text1 = "public class A {}"; var text2 = "public class B {}"; var file = Temp.CreateFile().WriteAllText(text1, Encoding.UTF8); // create a solution that evicts from the cache immediately. using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8)); var observedText = GetObservedText(sol, did, text1); // change text on disk & verify it is changed file.WriteAllText(text2); var textOnDisk = file.ReadAllText(); Assert.Equal(text2, textOnDisk); // stop observing it and let GC reclaim it observedText.AssertReleased(); // if we ask for the same text again we should get the original content var observedText2 = sol.GetDocument(did).GetTextAsync().Result; Assert.Equal(text1, observedText2.ToString()); } [Fact] public void TestGetTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docText = doc.GetTextAsync().Result; Assert.NotNull(docText); Assert.Equal(text, docText.ToString()); } [Fact] public void TestGetLoadedTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8)); var doc = sol.GetDocument(did); var docText = doc.GetTextAsync().Result; Assert.NotNull(docText); Assert.Equal(text, docText.ToString()); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19427")] public void TestGetRecoveredTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the text and then wait for the references to be GC'd var observed = GetObservedText(sol, did, text); observed.AssertReleased(); // get it async and force it to recover from temporary storage var doc = sol.GetDocument(did); var docText = doc.GetTextAsync().Result; Assert.NotNull(docText); Assert.Equal(text, docText.ToString()); } [Fact] public void TestGetSyntaxTreeAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docTree = doc.GetSyntaxTreeAsync().Result; Assert.NotNull(docTree); Assert.Equal(text, docTree.GetRoot().ToString()); } [Fact] public void TestGetSyntaxTreeFromLoadedTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8)); var doc = sol.GetDocument(did); var docTree = doc.GetSyntaxTreeAsync().Result; Assert.NotNull(docTree); Assert.Equal(text, docTree.GetRoot().ToString()); } [Fact] public void TestGetSyntaxTreeFromAddedTree() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var tree = CSharp.SyntaxFactory.ParseSyntaxTree("public class C {}").GetRoot(CancellationToken.None); tree = tree.WithAdditionalAnnotations(new SyntaxAnnotation("test")); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", tree); var doc = sol.GetDocument(did); var docTree = doc.GetSyntaxRootAsync().Result; Assert.NotNull(docTree); Assert.True(tree.IsEquivalentTo(docTree)); Assert.NotNull(docTree.GetAnnotatedNodes("test").Single()); } [Fact] public async Task TestGetSyntaxRootAsync2Async() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docRoot = await doc.GetSyntaxRootAsync(); Assert.NotNull(docRoot); Assert.Equal(text, docRoot.ToString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14954")] public void TestGetRecoveredSyntaxRootAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the syntax tree root and wait for the references to be GC'd var observed = GetObservedSyntaxTreeRoot(sol, did); observed.AssertReleased(); // get it async and force it to be recovered from storage var doc = sol.GetDocument(did); var docRoot = doc.GetSyntaxRootAsync().Result; Assert.NotNull(docRoot); Assert.Equal(text, docRoot.ToString()); } [Fact] public void TestGetCompilationAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var proj = sol.GetProject(pid); var compilation = proj.GetCompilationAsync().Result; Assert.NotNull(compilation); Assert.Equal(1, compilation.SyntaxTrees.Count()); } [Fact] public void TestGetSemanticModelAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docModel = doc.GetSemanticModelAsync().Result; Assert.NotNull(docModel); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetTextDoesNotKeepTextAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the text and then wait for the references to be GC'd var observed = GetObservedText(sol, did, text); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SourceText> GetObservedText(Solution solution, DocumentId documentId, string expectedText = null) { var observedText = solution.GetDocument(documentId).GetTextAsync().Result; if (expectedText != null) { Assert.Equal(expectedText, observedText.ToString()); } return new ObjectReference<SourceText>(observedText); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetTextAsyncDoesNotKeepTextAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the text and then wait for the references to be GC'd var observed = GetObservedTextAsync(sol, did, text); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SourceText> GetObservedTextAsync(Solution solution, DocumentId documentId, string expectedText = null) { var observedText = solution.GetDocument(documentId).GetTextAsync().Result; if (expectedText != null) { Assert.Equal(expectedText, observedText.ToString()); } return new ObjectReference<SourceText>(observedText); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetSyntaxRootDoesNotKeepRootAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedSyntaxTreeRoot(sol, did); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SyntaxNode> GetObservedSyntaxTreeRoot(Solution solution, DocumentId documentId) { var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result; return new ObjectReference<SyntaxNode>(observedTree); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetSyntaxRootAsyncDoesNotKeepRootAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedSyntaxTreeRootAsync(sol, did); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SyntaxNode> GetObservedSyntaxTreeRootAsync(Solution solution, DocumentId documentId) { var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result; return new ObjectReference<SyntaxNode>(observedTree); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13506")] [WorkItem(13506, "https://github.com/dotnet/roslyn/issues/13506")] public void TestRecoverableSyntaxTreeCSharp() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = @"public class C { public void Method1() {} public void Method2() {} public void Method3() {} public void Method4() {} public void Method5() {} public void Method6() {} }"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); TestRecoverableSyntaxTree(sol, did); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestRecoverableSyntaxTreeVisualBasic() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = @"Public Class C Sub Method1() End Sub Sub Method2() End Sub Sub Method3() End Sub Sub Method4() End Sub Sub Method5() End Sub Sub Method6() End Sub End Class"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.VisualBasic) .AddDocument(did, "goo.vb", text); TestRecoverableSyntaxTree(sol, did); } private static void TestRecoverableSyntaxTree(Solution sol, DocumentId did) { // get it async and wait for it to get GC'd var observed = GetObservedSyntaxTreeRootAsync(sol, did); observed.AssertReleased(); var doc = sol.GetDocument(did); // access the tree & root again (recover it) var tree = doc.GetSyntaxTreeAsync().Result; // this should cause reparsing var root = tree.GetRoot(); // prove that the new root is correctly associated with the tree Assert.Equal(tree, root.SyntaxTree); // reset the syntax root, to make it 'refactored' by adding an attribute var newRoot = doc.GetSyntaxRootAsync().Result.WithAdditionalAnnotations(SyntaxAnnotation.ElasticAnnotation); var doc2 = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot, PreservationMode.PreserveValue).GetDocument(doc.Id); // get it async and wait for it to get GC'd var observed2 = GetObservedSyntaxTreeRootAsync(doc2.Project.Solution, did); observed2.AssertReleased(); // access the tree & root again (recover it) var tree2 = doc2.GetSyntaxTreeAsync().Result; // this should cause deserialization var root2 = tree2.GetRoot(); // prove that the new root is correctly associated with the tree Assert.Equal(tree2, root2.SyntaxTree); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetCompilationAsyncDoesNotKeepCompilationAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedCompilationAsync(sol, pid); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<Compilation> GetObservedCompilationAsync(Solution solution, ProjectId projectId) { var observed = solution.GetProject(projectId).GetCompilationAsync().Result; return new ObjectReference<Compilation>(observed); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetCompilationDoesNotKeepCompilationAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedCompilation(sol, pid); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<Compilation> GetObservedCompilation(Solution solution, ProjectId projectId) { var observed = solution.GetProject(projectId).GetCompilationAsync().Result; return new ObjectReference<Compilation>(observed); } [Fact] public void TestWorkspaceLanguageServiceOverride() { var hostServices = FeaturesTestCompositions.Features.AddParts(new[] { typeof(TestLanguageServiceA), typeof(TestLanguageServiceB), }).GetHostServices(); var ws = new AdhocWorkspace(hostServices, ServiceLayer.Host); var service = ws.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>(); Assert.NotNull(service as TestLanguageServiceA); var ws2 = new AdhocWorkspace(hostServices, "Quasimodo"); var service2 = ws2.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>(); Assert.NotNull(service2 as TestLanguageServiceB); } #if false [Fact] public void TestSolutionInfo() { var oldSolutionId = SolutionId.CreateNewId("oldId"); var oldVersion = VersionStamp.Create(); var solutionInfo = SolutionInfo.Create(oldSolutionId, oldVersion, null, null); var newSolutionId = SolutionId.CreateNewId("newId"); solutionInfo = solutionInfo.WithId(newSolutionId); Assert.NotEqual(oldSolutionId, solutionInfo.Id); Assert.Equal(newSolutionId, solutionInfo.Id); var newVersion = oldVersion.GetNewerVersion(); solutionInfo = solutionInfo.WithVersion(newVersion); Assert.NotEqual(oldVersion, solutionInfo.Version); Assert.Equal(newVersion, solutionInfo.Version); Assert.Null(solutionInfo.FilePath); var newFilePath = @"C:\test\fake.sln"; solutionInfo = solutionInfo.WithFilePath(newFilePath); Assert.Equal(newFilePath, solutionInfo.FilePath); Assert.Equal(0, solutionInfo.Projects.Count()); } #endif private interface ITestLanguageService : ILanguageService { } [ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, ServiceLayer.Default), Shared, PartNotDiscoverable] private class TestLanguageServiceA : ITestLanguageService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestLanguageServiceA() { } } [ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, "Quasimodo"), Shared, PartNotDiscoverable] private class TestLanguageServiceB : ITestLanguageService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestLanguageServiceB() { } } [Fact] [WorkItem(666263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666263")] public async Task TestDocumentFileAccessFailureMissingFile() { var workspace = new AdhocWorkspace(); var solution = workspace.CurrentSolution; WorkspaceDiagnostic diagnosticFromEvent = null; solution.Workspace.WorkspaceFailed += (sender, args) => { diagnosticFromEvent = args.Diagnostic; }; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); solution = solution.AddProject(pid, "goo", "goo", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(@"C:\doesnotexist.cs", Encoding.UTF8)) .WithDocumentFilePath(did, "document path"); var doc = solution.GetDocument(did); var text = await doc.GetTextAsync().ConfigureAwait(false); var diagnostic = await doc.State.GetLoadDiagnosticAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(@"C:\doesnotexist.cs: (0,0)-(0,0)", diagnostic.Location.GetLineSpan().ToString()); Assert.Equal(WorkspaceDiagnosticKind.Failure, diagnosticFromEvent.Kind); Assert.Equal("", text.ToString()); // Verify invariant: The compilation is guaranteed to have a syntax tree for each document of the project (even if the contnet fails to load). var compilation = await solution.State.GetCompilationAsync(doc.Project.State, CancellationToken.None).ConfigureAwait(false); var syntaxTree = compilation.SyntaxTrees.Single(); Assert.Equal("", syntaxTree.ToString()); } [Fact] public void TestGetProjectForAssemblySymbol() { var pid1 = ProjectId.CreateNewId("p1"); var pid2 = ProjectId.CreateNewId("p2"); var pid3 = ProjectId.CreateNewId("p3"); var did1 = DocumentId.CreateNewId(pid1); var did2 = DocumentId.CreateNewId(pid2); var did3 = DocumentId.CreateNewId(pid3); var text1 = @" Public Class A End Class"; var text2 = @" Public Class B End Class "; var text3 = @" public class C : B { } "; var text4 = @" public class C : A { } "; var solution = new AdhocWorkspace().CurrentSolution .AddProject(pid1, "GooA", "Goo.dll", LanguageNames.VisualBasic) .AddDocument(did1, "A.vb", text1) .AddMetadataReference(pid1, s_mscorlib) .AddProject(pid2, "GooB", "Goo2.dll", LanguageNames.VisualBasic) .AddDocument(did2, "B.vb", text2) .AddMetadataReference(pid2, s_mscorlib) .AddProject(pid3, "Bar", "Bar.dll", LanguageNames.CSharp) .AddDocument(did3, "C.cs", text3) .AddMetadataReference(pid3, s_mscorlib) .AddProjectReference(pid3, new ProjectReference(pid1)) .AddProjectReference(pid3, new ProjectReference(pid2)); var project3 = solution.GetProject(pid3); var comp3 = project3.GetCompilationAsync().Result; var classC = comp3.GetTypeByMetadataName("C"); var projectForBaseType = solution.GetProject(classC.BaseType.ContainingAssembly); Assert.Equal(pid2, projectForBaseType.Id); // switch base type to A then try again var solution2 = solution.WithDocumentText(did3, SourceText.From(text4)); project3 = solution2.GetProject(pid3); comp3 = project3.GetCompilationAsync().Result; classC = comp3.GetTypeByMetadataName("C"); projectForBaseType = solution2.GetProject(classC.BaseType.ContainingAssembly); Assert.Equal(pid1, projectForBaseType.Id); } [WorkItem(1088127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088127")] [Fact] public void TestEncodingRetainedAfterTreeChanged() { var ws = new AdhocWorkspace(); var proj = ws.AddProject("proj", LanguageNames.CSharp); var doc = ws.AddDocument(proj.Id, "a.cs", SourceText.From("public class c { }", Encoding.UTF32)); Assert.Equal(Encoding.UTF32, doc.GetTextAsync().Result.Encoding); // updating root doesn't change original encoding var root = doc.GetSyntaxRootAsync().Result; var newRoot = root.WithLeadingTrivia(root.GetLeadingTrivia().Add(CS.SyntaxFactory.Whitespace(" "))); var newDoc = doc.WithSyntaxRoot(newRoot); Assert.Equal(Encoding.UTF32, newDoc.GetTextAsync().Result.Encoding); } [Fact] public void TestProjectWithNoBrokenReferencesHasNoIncompleteReferences() { var workspace = new AdhocWorkspace(); var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp); var project2 = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(project1.Id) })); // Nothing should have incomplete references, and everything should build Assert.True(project1.HasSuccessfullyLoadedAsync().Result); Assert.True(project2.HasSuccessfullyLoadedAsync().Result); Assert.Single(project2.GetCompilationAsync().Result.ExternalReferences); } [Fact] public void TestProjectWithBrokenCrossLanguageReferenceHasIncompleteReferences() { var workspace = new AdhocWorkspace(); var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp); workspace.AddDocument(project1.Id, "Broken.cs", SourceText.From("class ")); var project2 = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(project1.Id) })); Assert.True(project1.HasSuccessfullyLoadedAsync().Result); Assert.False(project2.HasSuccessfullyLoadedAsync().Result); Assert.Empty(project2.GetCompilationAsync().Result.ExternalReferences); } [Fact] public async Task TestFrozenPartialProjectHasDifferentSemanticVersions() { using var workspace = CreateWorkspaceWithPartalSemantics(); var project = workspace.CurrentSolution.AddProject("CSharpProject", "CSharpProject", LanguageNames.CSharp); project = project.AddDocument("Extra.cs", SourceText.From("class Extra { }")).Project; var documentToFreeze = project.AddDocument("DocumentToFreeze.cs", SourceText.From("")); var frozenDocument = documentToFreeze.WithFrozenPartialSemantics(CancellationToken.None); // Because we had no compilation produced yet, we expect that only the DocumentToFreeze is in the compilation Assert.NotSame(frozenDocument, documentToFreeze); var tree = Assert.Single((await frozenDocument.Project.GetCompilationAsync()).SyntaxTrees); Assert.Equal("DocumentToFreeze.cs", tree.FilePath); // Versions should be different Assert.NotEqual( await documentToFreeze.Project.GetDependentSemanticVersionAsync(), await frozenDocument.Project.GetDependentSemanticVersionAsync()); Assert.NotEqual( await documentToFreeze.Project.GetSemanticVersionAsync(), await frozenDocument.Project.GetSemanticVersionAsync()); } [Fact] public void TestFrozenPartialProjectAlwaysIsIncomplete() { var workspace = new AdhocWorkspace(); var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp); var project2 = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(project1.Id) })); var document = workspace.AddDocument(project2.Id, "Test.cs", SourceText.From("")); // Nothing should have incomplete references, and everything should build var frozenSolution = document.WithFrozenPartialSemantics(CancellationToken.None).Project.Solution; Assert.True(frozenSolution.GetProject(project1.Id).HasSuccessfullyLoadedAsync().Result); Assert.True(frozenSolution.GetProject(project2.Id).HasSuccessfullyLoadedAsync().Result); } [Fact] public void TestProjectCompletenessWithMultipleProjects() { GetMultipleProjects(out var csBrokenProject, out var vbNormalProject, out var dependsOnBrokenProject, out var dependsOnVbNormalProject, out var transitivelyDependsOnBrokenProjects, out var transitivelyDependsOnNormalProjects); // check flag for a broken project itself Assert.False(csBrokenProject.HasSuccessfullyLoadedAsync().Result); // check flag for a normal project itself Assert.True(vbNormalProject.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that directly reference a broken project Assert.True(dependsOnBrokenProject.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that directly reference only normal project Assert.True(dependsOnVbNormalProject.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that indirectly reference a borken project // normal project -> normal project -> broken project Assert.True(transitivelyDependsOnBrokenProjects.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that indirectly reference only normal project // normal project -> normal project -> normal project Assert.True(transitivelyDependsOnNormalProjects.HasSuccessfullyLoadedAsync().Result); } [Fact] public async Task TestMassiveFileSize() { // set max file length to 1 bytes var maxLength = 1; var workspace = new AdhocWorkspace(); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(FileTextLoaderOptions.FileLengthThreshold, maxLength))); using var root = new TempRoot(); var file = root.CreateFile(prefix: "massiveFile", extension: ".cs").WriteAllText("hello"); var loader = new FileTextLoader(file.Path, Encoding.UTF8); var textLength = FileUtilities.GetFileLength(file.Path); var expected = string.Format(WorkspacesResources.File_0_size_of_1_exceeds_maximum_allowed_size_of_2, file.Path, textLength, maxLength); var exceptionThrown = false; try { // test async one var unused = await loader.LoadTextAndVersionAsync(workspace, DocumentId.CreateNewId(ProjectId.CreateNewId()), CancellationToken.None); } catch (InvalidDataException ex) { exceptionThrown = true; Assert.Equal(expected, ex.Message); } Assert.True(exceptionThrown); exceptionThrown = false; try { // test sync one var unused = loader.LoadTextAndVersionSynchronously(workspace, DocumentId.CreateNewId(ProjectId.CreateNewId()), CancellationToken.None); } catch (InvalidDataException ex) { exceptionThrown = true; Assert.Equal(expected, ex.Message); } Assert.True(exceptionThrown); } [Fact] [WorkItem(18697, "https://github.com/dotnet/roslyn/issues/18697")] public void TestWithSyntaxTree() { // get one to get to syntax tree factory using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var solution = workspace.CurrentSolution; var dummyProject = solution.AddProject("dummy", "dummy", LanguageNames.CSharp); var factory = dummyProject.LanguageServices.SyntaxTreeFactory; // create the origin tree var strongTree = factory.ParseSyntaxTree("dummy", dummyProject.ParseOptions, SourceText.From("// emtpy"), CancellationToken.None); // create recoverable tree off the original tree var recoverableTree = factory.CreateRecoverableTree( dummyProject.Id, strongTree.FilePath, strongTree.Options, new ConstantValueSource<TextAndVersion>(TextAndVersion.Create(strongTree.GetText(), VersionStamp.Create(), strongTree.FilePath)), strongTree.GetText().Encoding, strongTree.GetRoot()); // create new tree before it ever getting root node var newTree = recoverableTree.WithFilePath("different/dummy"); // this shouldn't throw _ = newTree.GetRoot(); } [Fact] public void TestUpdateDocumentsOrder() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); VersionStamp GetVersion() => solution.GetProject(pid).Version; ImmutableArray<DocumentId> GetDocumentIds() => solution.GetProject(pid).DocumentIds.ToImmutableArray(); ImmutableArray<SyntaxTree> GetSyntaxTrees() { return solution.GetProject(pid).GetCompilationAsync().Result.SyntaxTrees.ToImmutableArray(); } solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp); var text1 = "public class Test1 {}"; var did1 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did1, "test1.cs", text1); var text2 = "public class Test2 {}"; var did2 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did2, "test2.cs", text2); var text3 = "public class Test3 {}"; var did3 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did3, "test3.cs", text3); var text4 = "public class Test4 {}"; var did4 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did4, "test4.cs", text4); var text5 = "public class Test5 {}"; var did5 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did5, "test5.cs", text5); var oldVersion = GetVersion(); solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did4, did3, did2, did1 })); var newVersion = GetVersion(); // Make sure we have a new version because the order changed. Assert.NotEqual(oldVersion, newVersion); var documentIds = GetDocumentIds(); Assert.Equal(did5, documentIds[0]); Assert.Equal(did4, documentIds[1]); Assert.Equal(did3, documentIds[2]); Assert.Equal(did2, documentIds[3]); Assert.Equal(did1, documentIds[4]); var syntaxTrees = GetSyntaxTrees(); Assert.Equal(documentIds.Count(), syntaxTrees.Count()); Assert.Equal("test5.cs", syntaxTrees[0].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test4.cs", syntaxTrees[1].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test3.cs", syntaxTrees[2].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test2.cs", syntaxTrees[3].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test1.cs", syntaxTrees[4].FilePath, StringComparer.OrdinalIgnoreCase); solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did4, did3, did2, did1 })); var newSameVersion = GetVersion(); // Make sure we have the same new version because the order hasn't changed. Assert.Equal(newVersion, newSameVersion); } [Fact] public void TestUpdateDocumentsOrderExceptions() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp); var text1 = "public class Test1 {}"; var did1 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did1, "test1.cs", text1); var text2 = "public class Test2 {}"; var did2 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did2, "test2.cs", text2); var text3 = "public class Test3 {}"; var did3 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did3, "test3.cs", text3); var text4 = "public class Test4 {}"; var did4 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did4, "test4.cs", text4); var text5 = "public class Test5 {}"; var did5 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did5, "test5.cs", text5); solution = solution.RemoveDocument(did5); Assert.Throws<ArgumentException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.Create<DocumentId>())); Assert.Throws<ArgumentNullException>(() => solution = solution.WithProjectDocumentsOrder(pid, null)); Assert.Throws<InvalidOperationException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did3, did2, did1 }))); Assert.Throws<ArgumentException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did3, did2, did1 }))); } [Theory] [CombinatorialData] public async Task TestAddingEditorConfigFileWithDiagnosticSeverity([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName) { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", languageName); solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension); var originalSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var originalCompilation = await solution.GetProject(projectId).GetCompilationAsync(); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var newSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var project = solution.GetProject(projectId); var newCompilation = await project.GetCompilationAsync(); Assert.Same(originalSyntaxTree, newSyntaxTree); Assert.NotSame(originalCompilation, newCompilation); Assert.NotEqual(originalCompilation.Options, newCompilation.Options); var provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.True(provider.TryGetDiagnosticValue(newSyntaxTree, "CA1234", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); } [Theory] [CombinatorialData] public async Task TestAddingAndRemovingEditorConfigFileWithDiagnosticSeverity([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName) { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", languageName); solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var syntaxTreeAfterAddingEditorConfig = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var project = solution.GetProject(projectId); var provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.True(provider.TryGetDiagnosticValue(syntaxTreeAfterAddingEditorConfig, "CA1234", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); solution = solution.RemoveAnalyzerConfigDocument(editorConfigDocumentId); project = solution.GetProject(projectId); var syntaxTreeAfterRemovingEditorConfig = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.False(provider.TryGetDiagnosticValue(syntaxTreeAfterAddingEditorConfig, "CA1234", CancellationToken.None, out _)); var finalCompilation = await project.GetCompilationAsync(); Assert.True(finalCompilation.ContainsSyntaxTree(syntaxTreeAfterRemovingEditorConfig)); } [Theory] [CombinatorialData] public async Task TestChangingAnEditorConfigFile([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName, bool useRecoverableTrees) { using var workspace = useRecoverableTrees ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace(); var solution = workspace.CurrentSolution; var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", languageName); solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var syntaxTreeBeforeEditorConfigChange = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var project = solution.GetProject(projectId); var provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.Equal(provider, (await project.GetCompilationAsync()).Options.SyntaxTreeOptionsProvider); Assert.True(provider.TryGetDiagnosticValue(syntaxTreeBeforeEditorConfigChange, "CA1234", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); solution = solution.WithAnalyzerConfigDocumentTextLoader( editorConfigDocumentId, TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA6789.severity = error"), VersionStamp.Default)), PreservationMode.PreserveValue); var syntaxTreeAfterEditorConfigChange = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); project = solution.GetProject(projectId); provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.Equal(provider, (await project.GetCompilationAsync()).Options.SyntaxTreeOptionsProvider); Assert.True(provider.TryGetDiagnosticValue(syntaxTreeBeforeEditorConfigChange, "CA6789", CancellationToken.None, out severity)); Assert.Equal(ReportDiagnostic.Error, severity); var finalCompilation = await project.GetCompilationAsync(); Assert.True(finalCompilation.ContainsSyntaxTree(syntaxTreeAfterEditorConfigChange)); } [Fact] public void TestAddingAndRemovingGlobalEditorConfigFileWithDiagnosticSeverity() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", LanguageNames.CSharp); solution = solution.AddDocument(sourceDocumentId, "Test.cs", "", filePath: @"Z:\Test.cs"); var originalProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider; Assert.False(originalProvider.TryGetGlobalDiagnosticValue("CA1234", default, out _)); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".globalconfig", filePath: @"Z:\.globalconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("is_global = true\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var newProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider; Assert.True(newProvider.TryGetGlobalDiagnosticValue("CA1234", default, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); solution = solution.RemoveAnalyzerConfigDocument(editorConfigDocumentId); var finalProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider; Assert.False(finalProvider.TryGetGlobalDiagnosticValue("CA1234", default, out _)); } [Fact] [WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")] public async Task TestAddingEditorConfigFileWithIsGeneratedCodeOption() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", LanguageNames.CSharp) .WithProjectMetadataReferences(projectId, new[] { TestMetadata.Net451.mscorlib }) .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithNullableContextOptions(NullableContextOptions.Enable)); var src = @" class C { void M(C? c) { _ = c.ToString(); // warning CS8602: Dereference of a possibly null reference. } }"; solution = solution.AddDocument(sourceDocumentId, "Test.cs", src, filePath: @"Z:\Test.cs"); var originalSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var originalCompilation = await solution.GetProject(projectId).GetCompilationAsync(); // warning CS8602: Dereference of a possibly null reference. var diagnostics = originalCompilation.GetDiagnostics(); var diagnostic = Assert.Single(diagnostics); Assert.Equal("CS8602", diagnostic.Id); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ngenerated_code = true"), VersionStamp.Default))))); var newSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var newCompilation = await solution.GetProject(projectId).GetCompilationAsync(); Assert.Same(originalSyntaxTree, newSyntaxTree); Assert.NotSame(originalCompilation, newCompilation); Assert.NotEqual(originalCompilation.Options, newCompilation.Options); // warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // Auto-generated code requires an explicit '#nullable' directive in source. diagnostics = newCompilation.GetDiagnostics(); diagnostic = Assert.Single(diagnostics); Assert.Contains("CS8669", diagnostic.Id); } [Fact] public void NoCompilationProjectsHaveNullSyntaxTreesAndSemanticModels() { using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) }); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", NoCompilationConstants.LanguageName); solution = solution.AddDocument(documentId, "Test.cs", "", filePath: @"Z:\Test.txt"); var document = solution.GetDocument(documentId)!; Assert.False(document.TryGetSyntaxTree(out _)); Assert.Null(document.GetSyntaxTreeAsync().Result); Assert.Null(document.GetSyntaxTreeSynchronously(CancellationToken.None)); Assert.False(document.TryGetSemanticModel(out _)); Assert.Null(document.GetSemanticModelAsync().Result); } [Fact] public void ChangingFilePathOfFileInNoCompilationProjectWorks() { using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) }); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", NoCompilationConstants.LanguageName); solution = solution.AddDocument(documentId, "Test.cs", "", filePath: @"Z:\Test.txt"); Assert.Null(solution.GetDocument(documentId)!.GetSyntaxTreeAsync().Result); solution = solution.WithDocumentFilePath(documentId, @"Z:\NewPath.txt"); Assert.Null(solution.GetDocument(documentId)!.GetSyntaxTreeAsync().Result); } [Fact] public void AddingAndRemovingProjectsUpdatesFilePathMap() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); const string editorConfigFilePath = @"Z:\.editorconfig"; var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Default, "Test", "Test", LanguageNames.CSharp) .WithAnalyzerConfigDocuments(new[] { DocumentInfo.Create(editorConfigDocumentId, ".editorconfig", filePath: editorConfigFilePath) }); solution = solution.AddProject(projectInfo); Assert.Equal(editorConfigDocumentId, Assert.Single(solution.GetDocumentIdsWithFilePath(editorConfigFilePath))); solution = solution.RemoveProject(projectId); Assert.Empty(solution.GetDocumentIdsWithFilePath(editorConfigFilePath)); } private static void GetMultipleProjects( out Project csBrokenProject, out Project vbNormalProject, out Project dependsOnBrokenProject, out Project dependsOnVbNormalProject, out Project transitivelyDependsOnBrokenProjects, out Project transitivelyDependsOnNormalProjects) { var workspace = new AdhocWorkspace(); csBrokenProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "CSharpProject", "CSharpProject", LanguageNames.CSharp).WithHasAllInformation(hasAllInformation: false)); vbNormalProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic)); dependsOnBrokenProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(csBrokenProject.Id), new ProjectReference(vbNormalProject.Id) })); dependsOnVbNormalProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "CSharpProject", "CSharpProject", LanguageNames.CSharp, projectReferences: new[] { new ProjectReference(vbNormalProject.Id) })); transitivelyDependsOnBrokenProjects = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "CSharpProject", "CSharpProject", LanguageNames.CSharp, projectReferences: new[] { new ProjectReference(dependsOnBrokenProject.Id) })); transitivelyDependsOnNormalProjects = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(dependsOnVbNormalProject.Id) })); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestOptionChangesForLanguagesNotInSolution() { // Create an empty solution with no projects. using var workspace = CreateWorkspace(); var s0 = workspace.CurrentSolution; var optionService = workspace.Services.GetRequiredService<IOptionService>(); // Apply an option change to a C# option. var option = GenerationOptions.PlaceSystemNamespaceFirst; var defaultValue = option.DefaultValue; var changedValue = !defaultValue; var options = s0.Options.WithChangedOption(option, LanguageNames.CSharp, changedValue); // Verify option change is preserved even if the solution has no project with that language. var s1 = s0.WithOptions(options); VerifyOptionSet(s1.Options); // Verify option value is preserved on adding a project for a different language. var s2 = s1.AddProject("P1", "A1", LanguageNames.VisualBasic).Solution; VerifyOptionSet(s2.Options); // Verify option value is preserved on roundtriping the option set (serialize and deserialize). var s3 = s2.AddProject("P2", "A2", LanguageNames.CSharp).Solution; var roundTripOptionSet = SerializeAndDeserialize((SerializableOptionSet)s3.Options, optionService); VerifyOptionSet(roundTripOptionSet); // Verify option value is preserved on removing a project. var s4 = s3.RemoveProject(s3.Projects.Single(p => p.Name == "P2").Id); VerifyOptionSet(s4.Options); return; void VerifyOptionSet(OptionSet optionSet) { Assert.Equal(changedValue, optionSet.GetOption(option, LanguageNames.CSharp)); Assert.Equal(defaultValue, optionSet.GetOption(option, LanguageNames.VisualBasic)); } static SerializableOptionSet SerializeAndDeserialize(SerializableOptionSet optionSet, IOptionService optionService) { using var stream = new MemoryStream(); using var writer = new ObjectWriter(stream); optionSet.Serialize(writer, CancellationToken.None); stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); return SerializableOptionSet.Deserialize(reader, optionService, CancellationToken.None); } } [Theory] [CombinatorialData] public async Task TestUpdatedDocumentTextIsObservablyConstantAsync(bool recoverable) { using var workspace = recoverable ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace(); var pid = ProjectId.CreateNewId(); var text = SourceText.From("public class C { }"); var version = VersionStamp.Create(); var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version))); var projInfo = ProjectInfo.Create( pid, version: VersionStamp.Default, name: "TestProject", assemblyName: "TestProject.dll", language: LanguageNames.CSharp, documents: new[] { docInfo }); var solution = workspace.CurrentSolution.AddProject(projInfo); var doc = solution.GetDocument(docInfo.Id); // change document var root = await doc.GetSyntaxRootAsync(); var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation()); Assert.NotSame(root, newRoot); var newDoc = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot).GetDocument(doc.Id); Assert.NotSame(doc, newDoc); var newDocText = await newDoc.GetTextAsync(); var sameText = await newDoc.GetTextAsync(); Assert.Same(newDocText, sameText); var newDocTree = await newDoc.GetSyntaxTreeAsync(); var treeText = newDocTree.GetText(); Assert.Same(newDocText, treeText); } [Fact] public async Task ReplacingTextMultipleTimesDoesNotRootIntermediateCopiesIfCompilationNotAskedFor() { // This test replicates the pattern of some operation changing a bunch of files, but the files aren't kept open. // In Visual Studio we do large refactorings by opening files with an invisible editor, making changes, and closing // again. This process means we'll queue up intermediate changes to those files, but we don't want to hold onto // the intermediate edits when we don't really need to since the final version will be all that matters. using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); // Fetch the compilation, so further edits are going to be incremental updates of this one var originalCompilation = await solution.Projects.Single().GetCompilationAsync(); // Create a source text we'll release and ensure it disappears. We'll also make sure we don't accidentally root // that solution in the middle. var sourceTextToRelease = ObjectReference.CreateFromFactory(static () => SourceText.From(Guid.NewGuid().ToString())); var solutionWithSourceTextToRelease = sourceTextToRelease.GetObjectReference( static (sourceText, document) => document.Project.Solution.WithDocumentText(document.Id, sourceText, PreservationMode.PreserveIdentity), solution.GetDocument(documentId)); // Change it again, this time by editing the text loader; this replicates us closing a file, and we don't want to pin the changes from the // prior change. var finalSolution = solutionWithSourceTextToRelease.GetObjectReference( static (s, documentId) => s.WithDocumentTextLoader(documentId, new TestTextLoader(Guid.NewGuid().ToString()), PreservationMode.PreserveValue), documentId).GetReference(); // The text in the middle shouldn't be held at all, since we replaced it. solutionWithSourceTextToRelease.ReleaseStrongReference(); sourceTextToRelease.AssertReleased(); GC.KeepAlive(finalSolution); } } }
1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Workspaces/CoreTest/SolutionTests/SolutionWithSourceGeneratorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Xunit; using static Microsoft.CodeAnalysis.UnitTests.SolutionTestHelpers; namespace Microsoft.CodeAnalysis.UnitTests { [UseExportProvider] public class SolutionWithSourceGeneratorTests : TestBase { // This is used to add on the preview language version which controls incremental generators being allowed. // TODO: remove this method entirely and the calls once incremental generators are no longer preview private static Project WithPreviewLanguageVersion(Project project) { return project.WithParseOptions(((CSharpParseOptions)project.ParseOptions!).WithLanguageVersion(LanguageVersion.Preview)); } [Theory] [CombinatorialData] public async Task SourceGeneratorBasedOnAdditionalFileGeneratesSyntaxTrees( bool fetchCompilationBeforeAddingGenerator, bool useRecoverableTrees) { // This test is just the sanity test to make sure generators work at all. There's not a special scenario being // tested. using var workspace = useRecoverableTrees ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference); // Optionally fetch the compilation first, which validates that we handle both running the generator // when the file already exists, and when it is added incrementally. Compilation? originalCompilation = null; if (fetchCompilationBeforeAddingGenerator) { originalCompilation = await project.GetRequiredCompilationAsync(CancellationToken.None); } project = project.AddAdditionalDocument("Test.txt", "Hello, world!").Project; var newCompilation = await project.GetRequiredCompilationAsync(CancellationToken.None); Assert.NotSame(originalCompilation, newCompilation); var generatedTree = Assert.Single(newCompilation.SyntaxTrees); var generatorType = typeof(GenerateFileForEachAdditionalFileWithContentsCommented); Assert.Equal($"{generatorType.Assembly.GetName().Name}\\{generatorType.FullName}\\Test.generated.cs", generatedTree.FilePath); var generatedDocument = Assert.Single(await project.GetSourceGeneratedDocumentsAsync()); Assert.Same(generatedTree, await generatedDocument.GetSyntaxTreeAsync()); } [Fact] public async Task IncrementalSourceGeneratorInvokedCorrectNumberOfTimes() { using var workspace = CreateWorkspace(); var generator = new GenerateFileForEachAdditionalFileWithContentsCommented(); var analyzerReference = new TestGeneratorReference(generator); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", "Hello, world!").Project .AddAdditionalDocument("Test2.txt", "Hello, world!").Project; var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); Assert.Equal(2, compilation.SyntaxTrees.Count()); Assert.Equal(2, generator.AdditionalFilesConvertedCount); // Change one of the additional documents, and rerun; we should only reprocess that one change, since this // is an incremental generator. project = project.AdditionalDocuments.First().WithAdditionalDocumentText(SourceText.From("Changed text!")).Project; compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); Assert.Equal(2, compilation.SyntaxTrees.Count()); // We should now have converted three additional files -- the two from the original run and then the one that was changed. // The other one should have been kept constant because that didn't change. Assert.Equal(3, generator.AdditionalFilesConvertedCount); // Change one of the source documents, and rerun; we should again only reprocess that one change. project = project.AddDocument("Source.cs", SourceText.From("")).Project; compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); // We have one extra syntax tree now, but it did not require any invocations of the incremental generator. Assert.Equal(3, compilation.SyntaxTrees.Count()); Assert.Equal(3, generator.AdditionalFilesConvertedCount); } [Fact] public async Task SourceGeneratorContentStillIncludedAfterSourceFileChange() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddDocument("Hello.cs", "// Source File").Project .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var documentId = project.DocumentIds.Single(); await AssertCompilationContainsOneRegularAndOneGeneratedFile(project, documentId, "// Hello, world!"); project = project.Solution.WithDocumentText(documentId, SourceText.From("// Changed Source File")).Projects.Single(); await AssertCompilationContainsOneRegularAndOneGeneratedFile(project, documentId, "// Hello, world!"); static async Task AssertCompilationContainsOneRegularAndOneGeneratedFile(Project project, DocumentId documentId, string expectedGeneratedContents) { var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); var regularDocumentSyntaxTree = await project.GetRequiredDocument(documentId).GetRequiredSyntaxTreeAsync(CancellationToken.None); Assert.Contains(regularDocumentSyntaxTree, compilation.SyntaxTrees); var generatedSyntaxTree = Assert.Single(compilation.SyntaxTrees.Where(t => t != regularDocumentSyntaxTree)); Assert.IsType<SourceGeneratedDocument>(project.GetDocument(generatedSyntaxTree)); Assert.Equal(expectedGeneratedContents, generatedSyntaxTree.GetText().ToString()); } } [Fact] public async Task SourceGeneratorContentChangesAfterAdditionalFileChanges() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var additionalDocumentId = project.AdditionalDocumentIds.Single(); await AssertCompilationContainsGeneratedFile(project, "// Hello, world!"); project = project.Solution.WithAdditionalDocumentText(additionalDocumentId, SourceText.From("Hello, everyone!")).Projects.Single(); await AssertCompilationContainsGeneratedFile(project, "// Hello, everyone!"); static async Task AssertCompilationContainsGeneratedFile(Project project, string expectedGeneratedContents) { var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); var generatedSyntaxTree = Assert.Single(compilation.SyntaxTrees); Assert.IsType<SourceGeneratedDocument>(project.GetDocument(generatedSyntaxTree)); Assert.Equal(expectedGeneratedContents, generatedSyntaxTree.GetText().ToString()); } } [Fact] public async Task PartialCompilationsIncludeGeneratedFilesAfterFullGeneration() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddDocument("Hello.cs", "// Source File").Project .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var fullCompilation = await project.GetRequiredCompilationAsync(CancellationToken.None); Assert.Equal(2, fullCompilation.SyntaxTrees.Count()); var partialProject = project.Documents.Single().WithFrozenPartialSemantics(CancellationToken.None).Project; var partialCompilation = await partialProject.GetRequiredCompilationAsync(CancellationToken.None); Assert.Same(fullCompilation, partialCompilation); } [Fact] public async Task DocumentIdOfGeneratedDocumentsIsStable() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var projectBeforeChange = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var generatedDocumentBeforeChange = Assert.Single(await projectBeforeChange.GetSourceGeneratedDocumentsAsync()); var projectAfterChange = projectBeforeChange.Solution.WithAdditionalDocumentText( projectBeforeChange.AdditionalDocumentIds.Single(), SourceText.From("Hello, world!!!!")).Projects.Single(); var generatedDocumentAfterChange = Assert.Single(await projectAfterChange.GetSourceGeneratedDocumentsAsync()); Assert.NotSame(generatedDocumentBeforeChange, generatedDocumentAfterChange); Assert.Equal(generatedDocumentBeforeChange.Id, generatedDocumentAfterChange.Id); } [Fact] public async Task DocumentIdGuidInDifferentProjectsIsDifferent() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var solutionWithProjects = AddProjectWithReference(workspace.CurrentSolution, analyzerReference); solutionWithProjects = AddProjectWithReference(solutionWithProjects, analyzerReference); var projectIds = solutionWithProjects.ProjectIds.ToList(); var generatedDocumentsInFirstProject = await solutionWithProjects.GetRequiredProject(projectIds[0]).GetSourceGeneratedDocumentsAsync(); var generatedDocumentsInSecondProject = await solutionWithProjects.GetRequiredProject(projectIds[1]).GetSourceGeneratedDocumentsAsync(); // A DocumentId consists of a GUID and then the ProjectId it's within. Even if these two documents have the same GUID, // they'll still be not equal because of the different ProjectIds. However, we'll also assert the GUIDs should be different as well, // because otherwise things can get confusing. If nothing else, the DocumentId debugger display string shows only the GUID, so you could // easily confuse them as being the same. Assert.NotEqual(generatedDocumentsInFirstProject.Single().Id.Id, generatedDocumentsInSecondProject.Single().Id.Id); static Solution AddProjectWithReference(Solution solution, TestGeneratorReference analyzerReference) { var project = WithPreviewLanguageVersion(AddEmptyProject(solution)); project = project.AddAnalyzerReference(analyzerReference); project = project.AddAdditionalDocument("Test.txt", "Hello, world!").Project; return project.Solution; } } [Fact] public async Task CompilationsInCompilationReferencesIncludeGeneratedSourceFiles() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var solution = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", "Hello, world!").Project.Solution; var projectIdWithGenerator = solution.ProjectIds.Single(); var projectIdWithReference = ProjectId.CreateNewId(); solution = solution.AddProject(projectIdWithReference, "WithReference", "WithReference", LanguageNames.CSharp) .AddProjectReference(projectIdWithReference, new ProjectReference(projectIdWithGenerator)); var compilationWithReference = await solution.GetRequiredProject(projectIdWithReference).GetRequiredCompilationAsync(CancellationToken.None); var compilationReference = Assert.IsAssignableFrom<CompilationReference>(Assert.Single(compilationWithReference.References)); var compilationWithGenerator = await solution.GetRequiredProject(projectIdWithGenerator).GetRequiredCompilationAsync(CancellationToken.None); Assert.NotEmpty(compilationWithGenerator.SyntaxTrees); Assert.Same(compilationWithGenerator, compilationReference.Compilation); } [Fact] public async Task RequestingGeneratedDocumentsTwiceGivesSameInstance() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var generatedDocumentFirstTime = Assert.Single(await project.GetSourceGeneratedDocumentsAsync()); var tree = await generatedDocumentFirstTime.GetSyntaxTreeAsync(); // Fetch the compilation, and then wait for it to be GC'ed, then fetch it again. This ensures that // finalizing a compilation more than once doesn't recreate things incorrectly. var compilationReference = ObjectReference.CreateFromFactory(() => project.GetCompilationAsync().Result); compilationReference.AssertReleased(); var secondCompilation = await project.GetRequiredCompilationAsync(CancellationToken.None); var generatedDocumentSecondTime = Assert.Single(await project.GetSourceGeneratedDocumentsAsync()); Assert.Same(generatedDocumentFirstTime, generatedDocumentSecondTime); Assert.Same(tree, secondCompilation.SyntaxTrees.Single()); } [Fact] public async Task GetDocumentWithGeneratedTreeReturnsGeneratedDocument() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var syntaxTree = Assert.Single((await project.GetRequiredCompilationAsync(CancellationToken.None)).SyntaxTrees); var generatedDocument = Assert.IsType<SourceGeneratedDocument>(project.GetDocument(syntaxTree)); Assert.Same(syntaxTree, await generatedDocument.GetSyntaxTreeAsync()); } [Fact] public async Task GetDocumentWithGeneratedTreeForInProgressReturnsGeneratedDocument() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddDocument("RegularDocument.cs", "// Source File", filePath: "RegularDocument.cs").Project .AddAdditionalDocument("Test.txt", "Hello, world!").Project; // Ensure we've ran generators at least once await project.GetCompilationAsync(); // Produce an in-progress snapshot project = project.Documents.Single(d => d.Name == "RegularDocument.cs").WithFrozenPartialSemantics(CancellationToken.None).Project; // The generated tree should still be there; even if the regular compilation fell away we've now cached the // generated trees. var syntaxTree = Assert.Single((await project.GetRequiredCompilationAsync(CancellationToken.None)).SyntaxTrees, t => t.FilePath != "RegularDocument.cs"); var generatedDocument = Assert.IsType<SourceGeneratedDocument>(project.GetDocument(syntaxTree)); Assert.Same(syntaxTree, await generatedDocument.GetSyntaxTreeAsync()); } [Fact] public async Task TreeReusedIfGeneratedFileDoesNotChangeBetweenRuns() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new SingleFileTestGenerator("// StaticContent")); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference) .AddDocument("RegularDocument.cs", "// Source File", filePath: "RegularDocument.cs").Project .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var generatedTreeBeforeChange = await Assert.Single(await project.GetSourceGeneratedDocumentsAsync()).GetSyntaxTreeAsync(); // Mutate the regular document to produce a new compilation project = project.Documents.Single().WithText(SourceText.From("// Change")).Project; var generatedTreeAfterChange = await Assert.Single(await project.GetSourceGeneratedDocumentsAsync()).GetSyntaxTreeAsync(); Assert.Same(generatedTreeBeforeChange, generatedTreeAfterChange); } [Fact] public async Task TreeNotReusedIfParseOptionsChangeChangeBetweenRuns() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new SingleFileTestGenerator("// StaticContent")); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference) .AddDocument("RegularDocument.cs", "// Source File", filePath: "RegularDocument.cs").Project .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var generatedTreeBeforeChange = await Assert.Single(await project.GetSourceGeneratedDocumentsAsync()).GetSyntaxTreeAsync(); // Mutate the parse options to produce a new compilation Assert.NotEqual(DocumentationMode.Diagnose, project.ParseOptions!.DocumentationMode); project = project.WithParseOptions(project.ParseOptions.WithDocumentationMode(DocumentationMode.Diagnose)); var generatedTreeAfterChange = await Assert.Single(await project.GetSourceGeneratedDocumentsAsync()).GetSyntaxTreeAsync(); Assert.NotSame(generatedTreeBeforeChange, generatedTreeAfterChange); } [Theory, CombinatorialData] public async Task ChangeToDocumentThatDoesNotImpactGeneratedDocumentReusesDeclarationTree(bool generatorProducesTree) { using var workspace = CreateWorkspace(); // We'll use either a generator that produces a single tree, or no tree, to ensure we efficiently handle both cases ISourceGenerator generator = generatorProducesTree ? new SingleFileTestGenerator("// StaticContent") : new CallbackGenerator(onInit: _ => { }, onExecute: _ => { }); var analyzerReference = new TestGeneratorReference(generator); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference) .AddDocument("RegularDocument.cs", "// Source File", filePath: "RegularDocument.cs").Project; // Ensure we already have a compilation created _ = await project.GetCompilationAsync(); project = await MakeChangesToDocument(project); var compilationAfterFirstChange = await project.GetRequiredCompilationAsync(CancellationToken.None); project = await MakeChangesToDocument(project); var compilationAfterSecondChange = await project.GetRequiredCompilationAsync(CancellationToken.None); // When we produced compilationAfterSecondChange, what we would ideally like is that compilation was produced by taking // compilationAfterFirstChange and simply updating the syntax tree that changed, since the generated documents didn't change. // That allows the compiler to reuse the same declaration tree for the generated file. This is hard to observe directly, but if we reflect // into the Compilation we can see if the declaration tree is untouched. We won't look at the original compilation, since // that original one was produced by adding the generated file as the final step, so it's cache won't be reusable, since the // compiler separates the "most recently changed tree" in the declaration table for efficiency. var cachedStateAfterFirstChange = GetDeclarationManagerCachedStateForUnchangingTrees(compilationAfterFirstChange); var cachedStateAfterSecondChange = GetDeclarationManagerCachedStateForUnchangingTrees(compilationAfterSecondChange); Assert.Same(cachedStateAfterFirstChange, cachedStateAfterSecondChange); static object GetDeclarationManagerCachedStateForUnchangingTrees(Compilation compilation) { var syntaxAndDeclarationsManager = compilation.GetFieldValue("_syntaxAndDeclarations"); var state = syntaxAndDeclarationsManager.GetType().GetMethod("GetLazyState", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.Invoke(syntaxAndDeclarationsManager, null); var declarationTable = state.GetFieldValue("DeclarationTable"); return declarationTable.GetFieldValue("_cache"); } static async Task<Project> MakeChangesToDocument(Project project) { var existingText = await project.Documents.Single().GetTextAsync(); var newText = existingText.WithChanges(new TextChange(new TextSpan(existingText.Length, length: 0), " With Change")); project = project.Documents.Single().WithText(newText).Project; return project; } } [Fact] public async Task CompilationNotCreatedByFetchingGeneratedFilesIfNoGeneratorsPresent() { using var workspace = CreateWorkspace(); var project = AddEmptyProject(workspace.CurrentSolution); Assert.Empty(await project.GetSourceGeneratedDocumentsAsync()); // We shouldn't have any compilation since we didn't have to run anything Assert.False(project.TryGetCompilation(out _)); } [Fact] public async Task OpenSourceGeneratedUpdatedToBufferContentsWhenCallingGetOpenDocumentInCurrentContextWithChanges() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new SingleFileTestGenerator("// StaticContent")); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference); Assert.True(workspace.SetCurrentSolution(_ => project.Solution, WorkspaceChangeKind.SolutionChanged)); var generatedDocumentIdentity = Assert.Single(await project.GetSourceGeneratedDocumentsAsync()).Identity; var differentOpenTextContainer = SourceText.From("// Open Text").Container; workspace.OnSourceGeneratedDocumentOpened(generatedDocumentIdentity, differentOpenTextContainer); var generatedDocument = differentOpenTextContainer.CurrentText.GetOpenDocumentInCurrentContextWithChanges(); Assert.IsType<SourceGeneratedDocument>(generatedDocument); Assert.Same(differentOpenTextContainer.CurrentText, await generatedDocument!.GetTextAsync()); Assert.NotSame(workspace.CurrentSolution, generatedDocument.Project.Solution); var generatedTree = await generatedDocument.GetSyntaxTreeAsync(); var compilation = await generatedDocument.Project.GetRequiredCompilationAsync(CancellationToken.None); Assert.Contains(generatedTree, compilation.SyntaxTrees); } [Fact] public async Task OpenSourceGeneratedFileDoesNotCreateNewSnapshotIfContentsKnownToMatch() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new SingleFileTestGenerator("// StaticContent")); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference); Assert.True(workspace.SetCurrentSolution(_ => project.Solution, WorkspaceChangeKind.SolutionChanged)); var generatedDocumentIdentity = Assert.Single(await workspace.CurrentSolution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Identity; var differentOpenTextContainer = SourceText.From("// StaticContent", Encoding.UTF8).Container; workspace.OnSourceGeneratedDocumentOpened(generatedDocumentIdentity, differentOpenTextContainer); var generatedDocument = differentOpenTextContainer.CurrentText.GetOpenDocumentInCurrentContextWithChanges(); Assert.Same(workspace.CurrentSolution, generatedDocument!.Project.Solution); } [Fact] public async Task OpenSourceGeneratedFileMatchesBufferContentsEvenIfGeneratedFileIsMissingIsRemoved() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var originalAdditionalFile = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", SourceText.From("")); Assert.True(workspace.SetCurrentSolution(_ => originalAdditionalFile.Project.Solution, WorkspaceChangeKind.SolutionChanged)); var generatedDocumentIdentity = Assert.Single(await originalAdditionalFile.Project.GetSourceGeneratedDocumentsAsync()).Identity; var differentOpenTextContainer = SourceText.From("// Open Text").Container; workspace.OnSourceGeneratedDocumentOpened(generatedDocumentIdentity, differentOpenTextContainer); workspace.OnAdditionalDocumentRemoved(originalAdditionalFile.Id); // At this point there should be no generated documents, even though our file is still open Assert.Empty(await workspace.CurrentSolution.Projects.Single().GetSourceGeneratedDocumentsAsync()); var generatedDocument = differentOpenTextContainer.CurrentText.GetOpenDocumentInCurrentContextWithChanges(); Assert.IsType<SourceGeneratedDocument>(generatedDocument); Assert.Same(differentOpenTextContainer.CurrentText, await generatedDocument!.GetTextAsync()); var generatedTree = await generatedDocument.GetSyntaxTreeAsync(); var compilation = await generatedDocument.Project.GetRequiredCompilationAsync(CancellationToken.None); Assert.Contains(generatedTree, compilation.SyntaxTrees); } [Fact] public async Task OpenSourceGeneratedDocumentUpdatedAndVisibleInProjectReference() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new SingleFileTestGenerator("// StaticContent")); var solution = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference).Solution; var projectIdWithGenerator = solution.ProjectIds.Single(); solution = AddEmptyProject(solution).AddProjectReference( new ProjectReference(projectIdWithGenerator)).Solution; Assert.True(workspace.SetCurrentSolution(_ => solution, WorkspaceChangeKind.SolutionChanged)); var generatedDocumentIdentity = Assert.Single(await workspace.CurrentSolution.GetRequiredProject(projectIdWithGenerator).GetSourceGeneratedDocumentsAsync()).Identity; var differentOpenTextContainer = SourceText.From("// Open Text").Container; workspace.OnSourceGeneratedDocumentOpened(generatedDocumentIdentity, differentOpenTextContainer); var generatedDocument = differentOpenTextContainer.CurrentText.GetOpenDocumentInCurrentContextWithChanges(); AssertEx.NotNull(generatedDocument); var generatedTree = await generatedDocument.GetSyntaxTreeAsync(); // Fetch the compilation from the other project, it should have a compilation reference that // contains the generated tree var projectWithReference = generatedDocument.Project.Solution.Projects.Single(p => p.Id != projectIdWithGenerator); var compilationWithReference = await projectWithReference.GetRequiredCompilationAsync(CancellationToken.None); var compilationReference = Assert.Single(compilationWithReference.References.OfType<CompilationReference>()); Assert.Contains(generatedTree, compilationReference.Compilation.SyntaxTrees); } [Fact] public async Task OpenSourceGeneratedDocumentsUpdateIsDocumentOpenAndCloseWorks() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new SingleFileTestGenerator("// StaticContent")); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference); Assert.True(workspace.SetCurrentSolution(_ => project.Solution, WorkspaceChangeKind.SolutionChanged)); var generatedDocumentIdentity = Assert.Single(await project.GetSourceGeneratedDocumentsAsync()).Identity; var differentOpenTextContainer = SourceText.From("// Open Text").Container; workspace.OnSourceGeneratedDocumentOpened(generatedDocumentIdentity, differentOpenTextContainer); Assert.True(workspace.IsDocumentOpen(generatedDocumentIdentity.DocumentId)); workspace.OnSourceGeneratedDocumentClosed(generatedDocumentIdentity.DocumentId); Assert.False(workspace.IsDocumentOpen(generatedDocumentIdentity.DocumentId)); Assert.Null(differentOpenTextContainer.CurrentText.GetOpenDocumentInCurrentContextWithChanges()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Xunit; using static Microsoft.CodeAnalysis.UnitTests.SolutionTestHelpers; namespace Microsoft.CodeAnalysis.UnitTests { [UseExportProvider] public class SolutionWithSourceGeneratorTests : TestBase { // This is used to add on the preview language version which controls incremental generators being allowed. // TODO: remove this method entirely and the calls once incremental generators are no longer preview private static Project WithPreviewLanguageVersion(Project project) { return project.WithParseOptions(((CSharpParseOptions)project.ParseOptions!).WithLanguageVersion(LanguageVersion.Preview)); } [Theory] [CombinatorialData] public async Task SourceGeneratorBasedOnAdditionalFileGeneratesSyntaxTrees( bool fetchCompilationBeforeAddingGenerator, bool useRecoverableTrees) { // This test is just the sanity test to make sure generators work at all. There's not a special scenario being // tested. using var workspace = useRecoverableTrees ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference); // Optionally fetch the compilation first, which validates that we handle both running the generator // when the file already exists, and when it is added incrementally. Compilation? originalCompilation = null; if (fetchCompilationBeforeAddingGenerator) { originalCompilation = await project.GetRequiredCompilationAsync(CancellationToken.None); } project = project.AddAdditionalDocument("Test.txt", "Hello, world!").Project; var newCompilation = await project.GetRequiredCompilationAsync(CancellationToken.None); Assert.NotSame(originalCompilation, newCompilation); var generatedTree = Assert.Single(newCompilation.SyntaxTrees); var generatorType = typeof(GenerateFileForEachAdditionalFileWithContentsCommented); Assert.Equal($"{generatorType.Assembly.GetName().Name}\\{generatorType.FullName}\\Test.generated.cs", generatedTree.FilePath); var generatedDocument = Assert.Single(await project.GetSourceGeneratedDocumentsAsync()); Assert.Same(generatedTree, await generatedDocument.GetSyntaxTreeAsync()); } [Fact] public async Task IncrementalSourceGeneratorInvokedCorrectNumberOfTimes() { using var workspace = CreateWorkspace(); var generator = new GenerateFileForEachAdditionalFileWithContentsCommented(); var analyzerReference = new TestGeneratorReference(generator); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", "Hello, world!").Project .AddAdditionalDocument("Test2.txt", "Hello, world!").Project; var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); Assert.Equal(2, compilation.SyntaxTrees.Count()); Assert.Equal(2, generator.AdditionalFilesConvertedCount); // Change one of the additional documents, and rerun; we should only reprocess that one change, since this // is an incremental generator. project = project.AdditionalDocuments.First().WithAdditionalDocumentText(SourceText.From("Changed text!")).Project; compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); Assert.Equal(2, compilation.SyntaxTrees.Count()); // We should now have converted three additional files -- the two from the original run and then the one that was changed. // The other one should have been kept constant because that didn't change. Assert.Equal(3, generator.AdditionalFilesConvertedCount); // Change one of the source documents, and rerun; we should again only reprocess that one change. project = project.AddDocument("Source.cs", SourceText.From("")).Project; compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); // We have one extra syntax tree now, but it did not require any invocations of the incremental generator. Assert.Equal(3, compilation.SyntaxTrees.Count()); Assert.Equal(3, generator.AdditionalFilesConvertedCount); } [Fact] public async Task SourceGeneratorContentStillIncludedAfterSourceFileChange() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddDocument("Hello.cs", "// Source File").Project .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var documentId = project.DocumentIds.Single(); await AssertCompilationContainsOneRegularAndOneGeneratedFile(project, documentId, "// Hello, world!"); project = project.Solution.WithDocumentText(documentId, SourceText.From("// Changed Source File")).Projects.Single(); await AssertCompilationContainsOneRegularAndOneGeneratedFile(project, documentId, "// Hello, world!"); static async Task AssertCompilationContainsOneRegularAndOneGeneratedFile(Project project, DocumentId documentId, string expectedGeneratedContents) { var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); var regularDocumentSyntaxTree = await project.GetRequiredDocument(documentId).GetRequiredSyntaxTreeAsync(CancellationToken.None); Assert.Contains(regularDocumentSyntaxTree, compilation.SyntaxTrees); var generatedSyntaxTree = Assert.Single(compilation.SyntaxTrees.Where(t => t != regularDocumentSyntaxTree)); Assert.IsType<SourceGeneratedDocument>(project.GetDocument(generatedSyntaxTree)); Assert.Equal(expectedGeneratedContents, generatedSyntaxTree.GetText().ToString()); } } [Fact] public async Task SourceGeneratorContentChangesAfterAdditionalFileChanges() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var additionalDocumentId = project.AdditionalDocumentIds.Single(); await AssertCompilationContainsGeneratedFile(project, "// Hello, world!"); project = project.Solution.WithAdditionalDocumentText(additionalDocumentId, SourceText.From("Hello, everyone!")).Projects.Single(); await AssertCompilationContainsGeneratedFile(project, "// Hello, everyone!"); static async Task AssertCompilationContainsGeneratedFile(Project project, string expectedGeneratedContents) { var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); var generatedSyntaxTree = Assert.Single(compilation.SyntaxTrees); Assert.IsType<SourceGeneratedDocument>(project.GetDocument(generatedSyntaxTree)); Assert.Equal(expectedGeneratedContents, generatedSyntaxTree.GetText().ToString()); } } [Fact] public async Task PartialCompilationsIncludeGeneratedFilesAfterFullGeneration() { using var workspace = CreateWorkspaceWithPartalSemantics(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddDocument("Hello.cs", "// Source File").Project .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var fullCompilation = await project.GetRequiredCompilationAsync(CancellationToken.None); Assert.Equal(2, fullCompilation.SyntaxTrees.Count()); var partialProject = project.Documents.Single().WithFrozenPartialSemantics(CancellationToken.None).Project; Assert.NotSame(partialProject, project); var partialCompilation = await partialProject.GetRequiredCompilationAsync(CancellationToken.None); Assert.Same(fullCompilation, partialCompilation); } [Fact] public async Task DocumentIdOfGeneratedDocumentsIsStable() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var projectBeforeChange = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var generatedDocumentBeforeChange = Assert.Single(await projectBeforeChange.GetSourceGeneratedDocumentsAsync()); var projectAfterChange = projectBeforeChange.Solution.WithAdditionalDocumentText( projectBeforeChange.AdditionalDocumentIds.Single(), SourceText.From("Hello, world!!!!")).Projects.Single(); var generatedDocumentAfterChange = Assert.Single(await projectAfterChange.GetSourceGeneratedDocumentsAsync()); Assert.NotSame(generatedDocumentBeforeChange, generatedDocumentAfterChange); Assert.Equal(generatedDocumentBeforeChange.Id, generatedDocumentAfterChange.Id); } [Fact] public async Task DocumentIdGuidInDifferentProjectsIsDifferent() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var solutionWithProjects = AddProjectWithReference(workspace.CurrentSolution, analyzerReference); solutionWithProjects = AddProjectWithReference(solutionWithProjects, analyzerReference); var projectIds = solutionWithProjects.ProjectIds.ToList(); var generatedDocumentsInFirstProject = await solutionWithProjects.GetRequiredProject(projectIds[0]).GetSourceGeneratedDocumentsAsync(); var generatedDocumentsInSecondProject = await solutionWithProjects.GetRequiredProject(projectIds[1]).GetSourceGeneratedDocumentsAsync(); // A DocumentId consists of a GUID and then the ProjectId it's within. Even if these two documents have the same GUID, // they'll still be not equal because of the different ProjectIds. However, we'll also assert the GUIDs should be different as well, // because otherwise things can get confusing. If nothing else, the DocumentId debugger display string shows only the GUID, so you could // easily confuse them as being the same. Assert.NotEqual(generatedDocumentsInFirstProject.Single().Id.Id, generatedDocumentsInSecondProject.Single().Id.Id); static Solution AddProjectWithReference(Solution solution, TestGeneratorReference analyzerReference) { var project = WithPreviewLanguageVersion(AddEmptyProject(solution)); project = project.AddAnalyzerReference(analyzerReference); project = project.AddAdditionalDocument("Test.txt", "Hello, world!").Project; return project.Solution; } } [Fact] public async Task CompilationsInCompilationReferencesIncludeGeneratedSourceFiles() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var solution = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", "Hello, world!").Project.Solution; var projectIdWithGenerator = solution.ProjectIds.Single(); var projectIdWithReference = ProjectId.CreateNewId(); solution = solution.AddProject(projectIdWithReference, "WithReference", "WithReference", LanguageNames.CSharp) .AddProjectReference(projectIdWithReference, new ProjectReference(projectIdWithGenerator)); var compilationWithReference = await solution.GetRequiredProject(projectIdWithReference).GetRequiredCompilationAsync(CancellationToken.None); var compilationReference = Assert.IsAssignableFrom<CompilationReference>(Assert.Single(compilationWithReference.References)); var compilationWithGenerator = await solution.GetRequiredProject(projectIdWithGenerator).GetRequiredCompilationAsync(CancellationToken.None); Assert.NotEmpty(compilationWithGenerator.SyntaxTrees); Assert.Same(compilationWithGenerator, compilationReference.Compilation); } [Fact] public async Task RequestingGeneratedDocumentsTwiceGivesSameInstance() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var generatedDocumentFirstTime = Assert.Single(await project.GetSourceGeneratedDocumentsAsync()); var tree = await generatedDocumentFirstTime.GetSyntaxTreeAsync(); // Fetch the compilation, and then wait for it to be GC'ed, then fetch it again. This ensures that // finalizing a compilation more than once doesn't recreate things incorrectly. var compilationReference = ObjectReference.CreateFromFactory(() => project.GetCompilationAsync().Result); compilationReference.AssertReleased(); var secondCompilation = await project.GetRequiredCompilationAsync(CancellationToken.None); var generatedDocumentSecondTime = Assert.Single(await project.GetSourceGeneratedDocumentsAsync()); Assert.Same(generatedDocumentFirstTime, generatedDocumentSecondTime); Assert.Same(tree, secondCompilation.SyntaxTrees.Single()); } [Fact] public async Task GetDocumentWithGeneratedTreeReturnsGeneratedDocument() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var syntaxTree = Assert.Single((await project.GetRequiredCompilationAsync(CancellationToken.None)).SyntaxTrees); var generatedDocument = Assert.IsType<SourceGeneratedDocument>(project.GetDocument(syntaxTree)); Assert.Same(syntaxTree, await generatedDocument.GetSyntaxTreeAsync()); } [Fact] public async Task GetDocumentWithGeneratedTreeForInProgressReturnsGeneratedDocument() { using var workspace = CreateWorkspaceWithPartalSemantics(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var project = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddDocument("RegularDocument.cs", "// Source File", filePath: "RegularDocument.cs").Project .AddAdditionalDocument("Test.txt", "Hello, world!").Project; // Ensure we've ran generators at least once await project.GetCompilationAsync(); // Produce an in-progress snapshot project = project.Documents.Single(d => d.Name == "RegularDocument.cs").WithFrozenPartialSemantics(CancellationToken.None).Project; // The generated tree should still be there; even if the regular compilation fell away we've now cached the // generated trees. var syntaxTree = Assert.Single((await project.GetRequiredCompilationAsync(CancellationToken.None)).SyntaxTrees, t => t.FilePath != "RegularDocument.cs"); var generatedDocument = Assert.IsType<SourceGeneratedDocument>(project.GetDocument(syntaxTree)); Assert.Same(syntaxTree, await generatedDocument.GetSyntaxTreeAsync()); } [Fact] public async Task TreeReusedIfGeneratedFileDoesNotChangeBetweenRuns() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new SingleFileTestGenerator("// StaticContent")); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference) .AddDocument("RegularDocument.cs", "// Source File", filePath: "RegularDocument.cs").Project .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var generatedTreeBeforeChange = await Assert.Single(await project.GetSourceGeneratedDocumentsAsync()).GetSyntaxTreeAsync(); // Mutate the regular document to produce a new compilation project = project.Documents.Single().WithText(SourceText.From("// Change")).Project; var generatedTreeAfterChange = await Assert.Single(await project.GetSourceGeneratedDocumentsAsync()).GetSyntaxTreeAsync(); Assert.Same(generatedTreeBeforeChange, generatedTreeAfterChange); } [Fact] public async Task TreeNotReusedIfParseOptionsChangeChangeBetweenRuns() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new SingleFileTestGenerator("// StaticContent")); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference) .AddDocument("RegularDocument.cs", "// Source File", filePath: "RegularDocument.cs").Project .AddAdditionalDocument("Test.txt", "Hello, world!").Project; var generatedTreeBeforeChange = await Assert.Single(await project.GetSourceGeneratedDocumentsAsync()).GetSyntaxTreeAsync(); // Mutate the parse options to produce a new compilation Assert.NotEqual(DocumentationMode.Diagnose, project.ParseOptions!.DocumentationMode); project = project.WithParseOptions(project.ParseOptions.WithDocumentationMode(DocumentationMode.Diagnose)); var generatedTreeAfterChange = await Assert.Single(await project.GetSourceGeneratedDocumentsAsync()).GetSyntaxTreeAsync(); Assert.NotSame(generatedTreeBeforeChange, generatedTreeAfterChange); } [Theory, CombinatorialData] public async Task ChangeToDocumentThatDoesNotImpactGeneratedDocumentReusesDeclarationTree(bool generatorProducesTree) { using var workspace = CreateWorkspace(); // We'll use either a generator that produces a single tree, or no tree, to ensure we efficiently handle both cases ISourceGenerator generator = generatorProducesTree ? new SingleFileTestGenerator("// StaticContent") : new CallbackGenerator(onInit: _ => { }, onExecute: _ => { }); var analyzerReference = new TestGeneratorReference(generator); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference) .AddDocument("RegularDocument.cs", "// Source File", filePath: "RegularDocument.cs").Project; // Ensure we already have a compilation created _ = await project.GetCompilationAsync(); project = await MakeChangesToDocument(project); var compilationAfterFirstChange = await project.GetRequiredCompilationAsync(CancellationToken.None); project = await MakeChangesToDocument(project); var compilationAfterSecondChange = await project.GetRequiredCompilationAsync(CancellationToken.None); // When we produced compilationAfterSecondChange, what we would ideally like is that compilation was produced by taking // compilationAfterFirstChange and simply updating the syntax tree that changed, since the generated documents didn't change. // That allows the compiler to reuse the same declaration tree for the generated file. This is hard to observe directly, but if we reflect // into the Compilation we can see if the declaration tree is untouched. We won't look at the original compilation, since // that original one was produced by adding the generated file as the final step, so it's cache won't be reusable, since the // compiler separates the "most recently changed tree" in the declaration table for efficiency. var cachedStateAfterFirstChange = GetDeclarationManagerCachedStateForUnchangingTrees(compilationAfterFirstChange); var cachedStateAfterSecondChange = GetDeclarationManagerCachedStateForUnchangingTrees(compilationAfterSecondChange); Assert.Same(cachedStateAfterFirstChange, cachedStateAfterSecondChange); static object GetDeclarationManagerCachedStateForUnchangingTrees(Compilation compilation) { var syntaxAndDeclarationsManager = compilation.GetFieldValue("_syntaxAndDeclarations"); var state = syntaxAndDeclarationsManager.GetType().GetMethod("GetLazyState", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.Invoke(syntaxAndDeclarationsManager, null); var declarationTable = state.GetFieldValue("DeclarationTable"); return declarationTable.GetFieldValue("_cache"); } static async Task<Project> MakeChangesToDocument(Project project) { var existingText = await project.Documents.Single().GetTextAsync(); var newText = existingText.WithChanges(new TextChange(new TextSpan(existingText.Length, length: 0), " With Change")); project = project.Documents.Single().WithText(newText).Project; return project; } } [Fact] public async Task CompilationNotCreatedByFetchingGeneratedFilesIfNoGeneratorsPresent() { using var workspace = CreateWorkspace(); var project = AddEmptyProject(workspace.CurrentSolution); Assert.Empty(await project.GetSourceGeneratedDocumentsAsync()); // We shouldn't have any compilation since we didn't have to run anything Assert.False(project.TryGetCompilation(out _)); } [Fact] public async Task OpenSourceGeneratedUpdatedToBufferContentsWhenCallingGetOpenDocumentInCurrentContextWithChanges() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new SingleFileTestGenerator("// StaticContent")); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference); Assert.True(workspace.SetCurrentSolution(_ => project.Solution, WorkspaceChangeKind.SolutionChanged)); var generatedDocumentIdentity = Assert.Single(await project.GetSourceGeneratedDocumentsAsync()).Identity; var differentOpenTextContainer = SourceText.From("// Open Text").Container; workspace.OnSourceGeneratedDocumentOpened(generatedDocumentIdentity, differentOpenTextContainer); var generatedDocument = differentOpenTextContainer.CurrentText.GetOpenDocumentInCurrentContextWithChanges(); Assert.IsType<SourceGeneratedDocument>(generatedDocument); Assert.Same(differentOpenTextContainer.CurrentText, await generatedDocument!.GetTextAsync()); Assert.NotSame(workspace.CurrentSolution, generatedDocument.Project.Solution); var generatedTree = await generatedDocument.GetSyntaxTreeAsync(); var compilation = await generatedDocument.Project.GetRequiredCompilationAsync(CancellationToken.None); Assert.Contains(generatedTree, compilation.SyntaxTrees); } [Fact] public async Task OpenSourceGeneratedFileDoesNotCreateNewSnapshotIfContentsKnownToMatch() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new SingleFileTestGenerator("// StaticContent")); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference); Assert.True(workspace.SetCurrentSolution(_ => project.Solution, WorkspaceChangeKind.SolutionChanged)); var generatedDocumentIdentity = Assert.Single(await workspace.CurrentSolution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Identity; var differentOpenTextContainer = SourceText.From("// StaticContent", Encoding.UTF8).Container; workspace.OnSourceGeneratedDocumentOpened(generatedDocumentIdentity, differentOpenTextContainer); var generatedDocument = differentOpenTextContainer.CurrentText.GetOpenDocumentInCurrentContextWithChanges(); Assert.Same(workspace.CurrentSolution, generatedDocument!.Project.Solution); } [Fact] public async Task OpenSourceGeneratedFileMatchesBufferContentsEvenIfGeneratedFileIsMissingIsRemoved() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new GenerateFileForEachAdditionalFileWithContentsCommented()); var originalAdditionalFile = WithPreviewLanguageVersion(AddEmptyProject(workspace.CurrentSolution)) .AddAnalyzerReference(analyzerReference) .AddAdditionalDocument("Test.txt", SourceText.From("")); Assert.True(workspace.SetCurrentSolution(_ => originalAdditionalFile.Project.Solution, WorkspaceChangeKind.SolutionChanged)); var generatedDocumentIdentity = Assert.Single(await originalAdditionalFile.Project.GetSourceGeneratedDocumentsAsync()).Identity; var differentOpenTextContainer = SourceText.From("// Open Text").Container; workspace.OnSourceGeneratedDocumentOpened(generatedDocumentIdentity, differentOpenTextContainer); workspace.OnAdditionalDocumentRemoved(originalAdditionalFile.Id); // At this point there should be no generated documents, even though our file is still open Assert.Empty(await workspace.CurrentSolution.Projects.Single().GetSourceGeneratedDocumentsAsync()); var generatedDocument = differentOpenTextContainer.CurrentText.GetOpenDocumentInCurrentContextWithChanges(); Assert.IsType<SourceGeneratedDocument>(generatedDocument); Assert.Same(differentOpenTextContainer.CurrentText, await generatedDocument!.GetTextAsync()); var generatedTree = await generatedDocument.GetSyntaxTreeAsync(); var compilation = await generatedDocument.Project.GetRequiredCompilationAsync(CancellationToken.None); Assert.Contains(generatedTree, compilation.SyntaxTrees); } [Fact] public async Task OpenSourceGeneratedDocumentUpdatedAndVisibleInProjectReference() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new SingleFileTestGenerator("// StaticContent")); var solution = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference).Solution; var projectIdWithGenerator = solution.ProjectIds.Single(); solution = AddEmptyProject(solution).AddProjectReference( new ProjectReference(projectIdWithGenerator)).Solution; Assert.True(workspace.SetCurrentSolution(_ => solution, WorkspaceChangeKind.SolutionChanged)); var generatedDocumentIdentity = Assert.Single(await workspace.CurrentSolution.GetRequiredProject(projectIdWithGenerator).GetSourceGeneratedDocumentsAsync()).Identity; var differentOpenTextContainer = SourceText.From("// Open Text").Container; workspace.OnSourceGeneratedDocumentOpened(generatedDocumentIdentity, differentOpenTextContainer); var generatedDocument = differentOpenTextContainer.CurrentText.GetOpenDocumentInCurrentContextWithChanges(); AssertEx.NotNull(generatedDocument); var generatedTree = await generatedDocument.GetSyntaxTreeAsync(); // Fetch the compilation from the other project, it should have a compilation reference that // contains the generated tree var projectWithReference = generatedDocument.Project.Solution.Projects.Single(p => p.Id != projectIdWithGenerator); var compilationWithReference = await projectWithReference.GetRequiredCompilationAsync(CancellationToken.None); var compilationReference = Assert.Single(compilationWithReference.References.OfType<CompilationReference>()); Assert.Contains(generatedTree, compilationReference.Compilation.SyntaxTrees); } [Fact] public async Task OpenSourceGeneratedDocumentsUpdateIsDocumentOpenAndCloseWorks() { using var workspace = CreateWorkspace(); var analyzerReference = new TestGeneratorReference(new SingleFileTestGenerator("// StaticContent")); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference); Assert.True(workspace.SetCurrentSolution(_ => project.Solution, WorkspaceChangeKind.SolutionChanged)); var generatedDocumentIdentity = Assert.Single(await project.GetSourceGeneratedDocumentsAsync()).Identity; var differentOpenTextContainer = SourceText.From("// Open Text").Container; workspace.OnSourceGeneratedDocumentOpened(generatedDocumentIdentity, differentOpenTextContainer); Assert.True(workspace.IsDocumentOpen(generatedDocumentIdentity.DocumentId)); workspace.OnSourceGeneratedDocumentClosed(generatedDocumentIdentity.DocumentId); Assert.False(workspace.IsDocumentOpen(generatedDocumentIdentity.DocumentId)); Assert.Null(differentOpenTextContainer.CurrentText.GetOpenDocumentInCurrentContextWithChanges()); } [Theory, CombinatorialData] public async Task FreezingSolutionEnsuresGeneratorsDoNotRun(bool forkBeforeFreeze) { var generatorRan = false; var generator = new CallbackGenerator(onInit: _ => { }, onExecute: _ => { generatorRan = true; }); using var workspace = CreateWorkspaceWithPartalSemantics(); var analyzerReference = new TestGeneratorReference(generator); var project = AddEmptyProject(workspace.CurrentSolution) .AddAnalyzerReference(analyzerReference) .AddDocument("RegularDocument.cs", "// Source File", filePath: "RegularDocument.cs").Project; Assert.True(workspace.SetCurrentSolution(_ => project.Solution, WorkspaceChangeKind.SolutionChanged)); var documentToFreeze = workspace.CurrentSolution.Projects.Single().Documents.Single(); // The generator shouldn't have ran before any of this since we didn't do anything that would ask for a compilation Assert.False(generatorRan); if (forkBeforeFreeze) { // Forking before freezing means we'll have to do extra work to produce the final compilation, but we should still // not be running generators documentToFreeze = documentToFreeze.WithText(SourceText.From("// Changed Source File")); } var frozenDocument = documentToFreeze.WithFrozenPartialSemantics(CancellationToken.None); Assert.NotSame(frozenDocument, documentToFreeze); await frozenDocument.GetSemanticModelAsync(CancellationToken.None); Assert.False(generatorRan); } } }
1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/ExpressionEvaluator/Core/Source/FunctionResolver/MetadataResolver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal delegate void OnFunctionResolvedDelegate<TModule, TRequest>(TModule module, TRequest request, int token, int version, int ilOffset); internal sealed class MetadataResolver<TProcess, TModule, TRequest> where TProcess : class where TModule : class where TRequest : class { private readonly TModule _module; private readonly MetadataReader _reader; private readonly StringComparer _stringComparer; // for comparing strings private readonly bool _ignoreCase; // for comparing strings to strings represented with StringHandles private readonly OnFunctionResolvedDelegate<TModule, TRequest> _onFunctionResolved; internal MetadataResolver( TModule module, MetadataReader reader, bool ignoreCase, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { _module = module; _reader = reader; _stringComparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; _ignoreCase = ignoreCase; _onFunctionResolved = onFunctionResolved; } internal void Resolve(TRequest request, RequestSignature signature) { QualifiedName qualifiedTypeName; ImmutableArray<string> memberTypeParameters; GetNameAndTypeParameters(signature.MemberName, out qualifiedTypeName, out memberTypeParameters); var typeName = qualifiedTypeName.Qualifier; var memberName = qualifiedTypeName.Name; var memberParameters = signature.Parameters; var allTypeParameters = GetAllGenericTypeParameters(typeName); foreach (var typeHandle in _reader.TypeDefinitions) { var typeDef = _reader.GetTypeDefinition(typeHandle); int containingArity = CompareToTypeDefinition(typeDef, typeName); if (containingArity < 0) { continue; } // Visit methods. foreach (var methodHandle in typeDef.GetMethods()) { var methodDef = _reader.GetMethodDefinition(methodHandle); if (!IsResolvableMethod(methodDef)) { continue; } if (MatchesMethod(typeDef, methodDef, memberName, allTypeParameters, containingArity, memberTypeParameters, memberParameters)) { OnFunctionResolved(request, methodHandle); } } if (memberTypeParameters.IsEmpty) { // Visit properties. foreach (var propertyHandle in typeDef.GetProperties()) { var propertyDef = _reader.GetPropertyDefinition(propertyHandle); var accessors = propertyDef.GetAccessors(); if (MatchesPropertyOrEvent(propertyDef.Name, accessors.Getter, memberName, allTypeParameters, containingArity, memberParameters)) { OnAccessorResolved(request, accessors.Getter); OnAccessorResolved(request, accessors.Setter); } } // Visit events. foreach (var eventHandle in typeDef.GetEvents()) { var eventDef = _reader.GetEventDefinition(eventHandle); var accessors = eventDef.GetAccessors(); if (MatchesPropertyOrEvent(eventDef.Name, accessors.Adder, memberName, allTypeParameters, containingArity, memberParameters)) { OnAccessorResolved(request, accessors.Adder); OnAccessorResolved(request, accessors.Remover); } } } } } // If the signature matches the TypeDefinition, including some or all containing // types and namespaces, returns a non-negative value indicating the arity of the // containing types that were not specified in the signature; otherwise returns -1. // For instance, "C<T>.D" will return 1 matching against metadata type N.M.A<T>.B.C<U>.D, // where N.M is a namespace and A<T>, B, C<U>, D are nested types. The value 1 // is the arity of the containing types A<T>.B that were missing from the signature. // "C<T>.D" will not match C<T> or C<T>.D.E since the match must include the entire // signature, from nested TypeDefinition, out. private int CompareToTypeDefinition(TypeDefinition typeDef, Name signature) { if (signature == null) { return typeDef.GetGenericParameters().Count; } QualifiedName qualifiedName; ImmutableArray<string> typeParameters; GetNameAndTypeParameters(signature, out qualifiedName, out typeParameters); if (!MatchesTypeName(typeDef, qualifiedName.Name)) { return -1; } var declaringTypeHandle = typeDef.GetDeclaringType(); var declaringType = declaringTypeHandle.IsNil ? default : _reader.GetTypeDefinition(declaringTypeHandle); int declaringTypeParameterCount = declaringTypeHandle.IsNil ? 0 : declaringType.GetGenericParameters().Count; if (!MatchesTypeParameterCount(typeParameters, typeDef.GetGenericParameters(), declaringTypeParameterCount)) { return -1; } var qualifier = qualifiedName.Qualifier; if (declaringTypeHandle.IsNil) { // Compare namespace. return MatchesNamespace(typeDef, qualifier) ? 0 : -1; } else { // Compare declaring type. return CompareToTypeDefinition(declaringType, qualifier); } } private bool MatchesNamespace(TypeDefinition typeDef, Name signature) { if (signature == null) { return true; } var namespaceName = _reader.GetString(typeDef.Namespace); if (string.IsNullOrEmpty(namespaceName)) { return false; } var parts = namespaceName.Split('.'); for (int index = parts.Length - 1; index >= 0; index--) { if (signature == null) { return true; } var qualifiedName = signature as QualifiedName; if (qualifiedName == null) { return false; } var part = parts[index]; if (!_stringComparer.Equals(qualifiedName.Name, part)) { return false; } signature = qualifiedName.Qualifier; } return signature == null; } private bool MatchesTypeName(TypeDefinition typeDef, string name) { var typeName = RemoveAritySeparatorIfAny(_reader.GetString(typeDef.Name)); return _stringComparer.Equals(typeName, name); } private bool MatchesMethod( TypeDefinition typeDef, MethodDefinition methodDef, string methodName, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<string> methodTypeParameters, ImmutableArray<ParameterSignature> methodParameters) { if (!MatchesMethodName(methodDef, typeDef, methodName)) { return false; } if (!MatchesTypeParameterCount(methodTypeParameters, methodDef.GetGenericParameters(), offset: 0)) { return false; } if (methodParameters.IsDefault) { return true; } return MatchesParameters(methodDef, allTypeParameters, containingArity, methodTypeParameters, methodParameters); } private bool MatchesPropertyOrEvent( StringHandle memberName, MethodDefinitionHandle primaryAccessorHandle, string name, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<ParameterSignature> propertyParameters) { if (!MatchesMemberName(memberName, name)) { return false; } if (propertyParameters.IsDefault) { return true; } if (propertyParameters.Length == 0) { // Parameter-less properties/events should be specified // with no parameter list. return false; } // Match parameters against getter/adder. Not supporting // matching against setter for write-only properties. if (primaryAccessorHandle.IsNil) { return false; } var methodDef = _reader.GetMethodDefinition(primaryAccessorHandle); return MatchesParameters(methodDef, allTypeParameters, containingArity, ImmutableArray<string>.Empty, propertyParameters); } private bool MatchesMethodName(in MethodDefinition methodDef, in TypeDefinition declaringTypeDef, string name) { // special names: if ((methodDef.Attributes & MethodAttributes.RTSpecialName) != 0) { // constructor: var ctorName = (methodDef.Attributes & MethodAttributes.Static) == 0 ? WellKnownMemberNames.InstanceConstructorName : WellKnownMemberNames.StaticConstructorName; if (_reader.StringComparer.Equals(methodDef.Name, ctorName, ignoreCase: false) && MatchesTypeName(declaringTypeDef, name)) { return true; } } return MatchesMemberName(methodDef.Name, name); } private bool MatchesMemberName(in StringHandle memberName, string name) { if (_reader.StringComparer.Equals(memberName, name, _ignoreCase)) { return true; } var comparer = _ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; var metadataName = _reader.GetString(memberName); // C# local function if (GeneratedNameParser.TryParseLocalFunctionName(metadataName, out var localFunctionName)) { return comparer.Equals(name, localFunctionName); } // implicitly implemented interface member: var lastDot = metadataName.LastIndexOf('.'); if (lastDot >= 0 && comparer.Equals(metadataName.Substring(lastDot + 1), name)) { return true; } return false; } private ImmutableArray<string> GetAllGenericTypeParameters(Name typeName) { var builder = ImmutableArray.CreateBuilder<string>(); GetAllGenericTypeParameters(typeName, builder); return builder.ToImmutable(); } private void GetAllGenericTypeParameters(Name typeName, ImmutableArray<string>.Builder builder) { if (typeName == null) { return; } QualifiedName qualifiedName; ImmutableArray<string> typeParameters; GetNameAndTypeParameters(typeName, out qualifiedName, out typeParameters); GetAllGenericTypeParameters(qualifiedName.Qualifier, builder); builder.AddRange(typeParameters); } private bool MatchesParameters( MethodDefinition methodDef, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<string> methodTypeParameters, ImmutableArray<ParameterSignature> methodParameters) { ImmutableArray<ParameterSignature> parameters; try { var decoder = new MetadataDecoder(_reader, allTypeParameters, containingArity, methodTypeParameters); parameters = decoder.DecodeParameters(methodDef); } catch (NotSupportedException) { return false; } catch (BadImageFormatException) { return false; } return methodParameters.SequenceEqual(parameters, MatchesParameter); } private void OnFunctionResolved( TRequest request, MethodDefinitionHandle handle) { Debug.Assert(!handle.IsNil); _onFunctionResolved(_module, request, token: MetadataTokens.GetToken(handle), version: 1, ilOffset: 0); } private void OnAccessorResolved( TRequest request, MethodDefinitionHandle handle) { if (handle.IsNil) { return; } var methodDef = _reader.GetMethodDefinition(handle); if (IsResolvableMethod(methodDef)) { OnFunctionResolved(request, handle); } } private static bool MatchesTypeParameterCount(ImmutableArray<string> typeArguments, GenericParameterHandleCollection typeParameters, int offset) { return typeArguments.Length == typeParameters.Count - offset; } // parameterA from string signature, parameterB from metadata. private bool MatchesParameter(ParameterSignature parameterA, ParameterSignature parameterB) { return MatchesType(parameterA.Type, parameterB.Type) && parameterA.IsByRef == parameterB.IsByRef; } // typeA from string signature, typeB from metadata. private bool MatchesType(TypeSignature typeA, TypeSignature typeB) { if (typeA.Kind != typeB.Kind) { return false; } switch (typeA.Kind) { case TypeSignatureKind.GenericType: { var genericA = (GenericTypeSignature)typeA; var genericB = (GenericTypeSignature)typeB; return MatchesType(genericA.QualifiedName, genericB.QualifiedName) && genericA.TypeArguments.SequenceEqual(genericB.TypeArguments, MatchesType); } case TypeSignatureKind.QualifiedType: { var qualifiedA = (QualifiedTypeSignature)typeA; var qualifiedB = (QualifiedTypeSignature)typeB; // Metadata signature may be more qualified than the // string signature but still considered a match // (e.g.: "B<U>.C" should match N.A<T>.B<U>.C). return (qualifiedA.Qualifier == null || (qualifiedB.Qualifier != null && MatchesType(qualifiedA.Qualifier, qualifiedB.Qualifier))) && _stringComparer.Equals(qualifiedA.Name, qualifiedB.Name); } case TypeSignatureKind.ArrayType: { var arrayA = (ArrayTypeSignature)typeA; var arrayB = (ArrayTypeSignature)typeB; return MatchesType(arrayA.ElementType, arrayB.ElementType) && arrayA.Rank == arrayB.Rank; } case TypeSignatureKind.PointerType: { var pointerA = (PointerTypeSignature)typeA; var pointerB = (PointerTypeSignature)typeB; return MatchesType(pointerA.PointedAtType, pointerB.PointedAtType); } default: throw ExceptionUtilities.UnexpectedValue(typeA.Kind); } } private static void GetNameAndTypeParameters( Name name, out QualifiedName qualifiedName, out ImmutableArray<string> typeParameters) { switch (name.Kind) { case NameKind.GenericName: { var genericName = (GenericName)name; qualifiedName = genericName.QualifiedName; typeParameters = genericName.TypeParameters; } break; case NameKind.QualifiedName: { qualifiedName = (QualifiedName)name; typeParameters = ImmutableArray<string>.Empty; } break; default: throw ExceptionUtilities.UnexpectedValue(name.Kind); } } private static bool IsResolvableMethod(MethodDefinition methodDef) { return (methodDef.Attributes & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0; } private static string RemoveAritySeparatorIfAny(string typeName) { int index = typeName.LastIndexOf('`'); return (index < 0) ? typeName : typeName.Substring(0, index); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal delegate void OnFunctionResolvedDelegate<TModule, TRequest>(TModule module, TRequest request, int token, int version, int ilOffset); internal sealed class MetadataResolver<TProcess, TModule, TRequest> where TProcess : class where TModule : class where TRequest : class { private readonly TModule _module; private readonly MetadataReader _reader; private readonly StringComparer _stringComparer; // for comparing strings private readonly bool _ignoreCase; // for comparing strings to strings represented with StringHandles private readonly OnFunctionResolvedDelegate<TModule, TRequest> _onFunctionResolved; internal MetadataResolver( TModule module, MetadataReader reader, bool ignoreCase, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { _module = module; _reader = reader; _stringComparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; _ignoreCase = ignoreCase; _onFunctionResolved = onFunctionResolved; } internal void Resolve(TRequest request, RequestSignature signature) { QualifiedName qualifiedTypeName; ImmutableArray<string> memberTypeParameters; GetNameAndTypeParameters(signature.MemberName, out qualifiedTypeName, out memberTypeParameters); var typeName = qualifiedTypeName.Qualifier; var memberName = qualifiedTypeName.Name; var memberParameters = signature.Parameters; var allTypeParameters = GetAllGenericTypeParameters(typeName); foreach (var typeHandle in _reader.TypeDefinitions) { var typeDef = _reader.GetTypeDefinition(typeHandle); int containingArity = CompareToTypeDefinition(typeDef, typeName); if (containingArity < 0) { continue; } // Visit methods. foreach (var methodHandle in typeDef.GetMethods()) { var methodDef = _reader.GetMethodDefinition(methodHandle); if (!IsResolvableMethod(methodDef)) { continue; } if (MatchesMethod(typeDef, methodDef, memberName, allTypeParameters, containingArity, memberTypeParameters, memberParameters)) { OnFunctionResolved(request, methodHandle); } } if (memberTypeParameters.IsEmpty) { // Visit properties. foreach (var propertyHandle in typeDef.GetProperties()) { var propertyDef = _reader.GetPropertyDefinition(propertyHandle); var accessors = propertyDef.GetAccessors(); if (MatchesPropertyOrEvent(propertyDef.Name, accessors.Getter, memberName, allTypeParameters, containingArity, memberParameters)) { OnAccessorResolved(request, accessors.Getter); OnAccessorResolved(request, accessors.Setter); } } // Visit events. foreach (var eventHandle in typeDef.GetEvents()) { var eventDef = _reader.GetEventDefinition(eventHandle); var accessors = eventDef.GetAccessors(); if (MatchesPropertyOrEvent(eventDef.Name, accessors.Adder, memberName, allTypeParameters, containingArity, memberParameters)) { OnAccessorResolved(request, accessors.Adder); OnAccessorResolved(request, accessors.Remover); } } } } } // If the signature matches the TypeDefinition, including some or all containing // types and namespaces, returns a non-negative value indicating the arity of the // containing types that were not specified in the signature; otherwise returns -1. // For instance, "C<T>.D" will return 1 matching against metadata type N.M.A<T>.B.C<U>.D, // where N.M is a namespace and A<T>, B, C<U>, D are nested types. The value 1 // is the arity of the containing types A<T>.B that were missing from the signature. // "C<T>.D" will not match C<T> or C<T>.D.E since the match must include the entire // signature, from nested TypeDefinition, out. private int CompareToTypeDefinition(TypeDefinition typeDef, Name signature) { if (signature == null) { return typeDef.GetGenericParameters().Count; } QualifiedName qualifiedName; ImmutableArray<string> typeParameters; GetNameAndTypeParameters(signature, out qualifiedName, out typeParameters); if (!MatchesTypeName(typeDef, qualifiedName.Name)) { return -1; } var declaringTypeHandle = typeDef.GetDeclaringType(); var declaringType = declaringTypeHandle.IsNil ? default : _reader.GetTypeDefinition(declaringTypeHandle); int declaringTypeParameterCount = declaringTypeHandle.IsNil ? 0 : declaringType.GetGenericParameters().Count; if (!MatchesTypeParameterCount(typeParameters, typeDef.GetGenericParameters(), declaringTypeParameterCount)) { return -1; } var qualifier = qualifiedName.Qualifier; if (declaringTypeHandle.IsNil) { // Compare namespace. return MatchesNamespace(typeDef, qualifier) ? 0 : -1; } else { // Compare declaring type. return CompareToTypeDefinition(declaringType, qualifier); } } private bool MatchesNamespace(TypeDefinition typeDef, Name signature) { if (signature == null) { return true; } var namespaceName = _reader.GetString(typeDef.Namespace); if (string.IsNullOrEmpty(namespaceName)) { return false; } var parts = namespaceName.Split('.'); for (int index = parts.Length - 1; index >= 0; index--) { if (signature == null) { return true; } var qualifiedName = signature as QualifiedName; if (qualifiedName == null) { return false; } var part = parts[index]; if (!_stringComparer.Equals(qualifiedName.Name, part)) { return false; } signature = qualifiedName.Qualifier; } return signature == null; } private bool MatchesTypeName(TypeDefinition typeDef, string name) { var typeName = RemoveAritySeparatorIfAny(_reader.GetString(typeDef.Name)); return _stringComparer.Equals(typeName, name); } private bool MatchesMethod( TypeDefinition typeDef, MethodDefinition methodDef, string methodName, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<string> methodTypeParameters, ImmutableArray<ParameterSignature> methodParameters) { if (!MatchesMethodName(methodDef, typeDef, methodName)) { return false; } if (!MatchesTypeParameterCount(methodTypeParameters, methodDef.GetGenericParameters(), offset: 0)) { return false; } if (methodParameters.IsDefault) { return true; } return MatchesParameters(methodDef, allTypeParameters, containingArity, methodTypeParameters, methodParameters); } private bool MatchesPropertyOrEvent( StringHandle memberName, MethodDefinitionHandle primaryAccessorHandle, string name, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<ParameterSignature> propertyParameters) { if (!MatchesMemberName(memberName, name)) { return false; } if (propertyParameters.IsDefault) { return true; } if (propertyParameters.Length == 0) { // Parameter-less properties/events should be specified // with no parameter list. return false; } // Match parameters against getter/adder. Not supporting // matching against setter for write-only properties. if (primaryAccessorHandle.IsNil) { return false; } var methodDef = _reader.GetMethodDefinition(primaryAccessorHandle); return MatchesParameters(methodDef, allTypeParameters, containingArity, ImmutableArray<string>.Empty, propertyParameters); } private bool MatchesMethodName(in MethodDefinition methodDef, in TypeDefinition declaringTypeDef, string name) { // special names: if ((methodDef.Attributes & MethodAttributes.RTSpecialName) != 0) { // constructor: var ctorName = (methodDef.Attributes & MethodAttributes.Static) == 0 ? WellKnownMemberNames.InstanceConstructorName : WellKnownMemberNames.StaticConstructorName; if (_reader.StringComparer.Equals(methodDef.Name, ctorName, ignoreCase: false) && MatchesTypeName(declaringTypeDef, name)) { return true; } } return MatchesMemberName(methodDef.Name, name); } private bool MatchesMemberName(in StringHandle memberName, string name) { if (_reader.StringComparer.Equals(memberName, name, _ignoreCase)) { return true; } var comparer = _ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; var metadataName = _reader.GetString(memberName); // C# local function if (GeneratedNameParser.TryParseLocalFunctionName(metadataName, out var localFunctionName)) { return comparer.Equals(name, localFunctionName); } // implicitly implemented interface member: var lastDot = metadataName.LastIndexOf('.'); if (lastDot >= 0 && comparer.Equals(metadataName.Substring(lastDot + 1), name)) { return true; } return false; } private ImmutableArray<string> GetAllGenericTypeParameters(Name typeName) { var builder = ImmutableArray.CreateBuilder<string>(); GetAllGenericTypeParameters(typeName, builder); return builder.ToImmutable(); } private void GetAllGenericTypeParameters(Name typeName, ImmutableArray<string>.Builder builder) { if (typeName == null) { return; } QualifiedName qualifiedName; ImmutableArray<string> typeParameters; GetNameAndTypeParameters(typeName, out qualifiedName, out typeParameters); GetAllGenericTypeParameters(qualifiedName.Qualifier, builder); builder.AddRange(typeParameters); } private bool MatchesParameters( MethodDefinition methodDef, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<string> methodTypeParameters, ImmutableArray<ParameterSignature> methodParameters) { ImmutableArray<ParameterSignature> parameters; try { var decoder = new MetadataDecoder(_reader, allTypeParameters, containingArity, methodTypeParameters); parameters = decoder.DecodeParameters(methodDef); } catch (NotSupportedException) { return false; } catch (BadImageFormatException) { return false; } return methodParameters.SequenceEqual(parameters, MatchesParameter); } private void OnFunctionResolved( TRequest request, MethodDefinitionHandle handle) { Debug.Assert(!handle.IsNil); _onFunctionResolved(_module, request, token: MetadataTokens.GetToken(handle), version: 1, ilOffset: 0); } private void OnAccessorResolved( TRequest request, MethodDefinitionHandle handle) { if (handle.IsNil) { return; } var methodDef = _reader.GetMethodDefinition(handle); if (IsResolvableMethod(methodDef)) { OnFunctionResolved(request, handle); } } private static bool MatchesTypeParameterCount(ImmutableArray<string> typeArguments, GenericParameterHandleCollection typeParameters, int offset) { return typeArguments.Length == typeParameters.Count - offset; } // parameterA from string signature, parameterB from metadata. private bool MatchesParameter(ParameterSignature parameterA, ParameterSignature parameterB) { return MatchesType(parameterA.Type, parameterB.Type) && parameterA.IsByRef == parameterB.IsByRef; } // typeA from string signature, typeB from metadata. private bool MatchesType(TypeSignature typeA, TypeSignature typeB) { if (typeA.Kind != typeB.Kind) { return false; } switch (typeA.Kind) { case TypeSignatureKind.GenericType: { var genericA = (GenericTypeSignature)typeA; var genericB = (GenericTypeSignature)typeB; return MatchesType(genericA.QualifiedName, genericB.QualifiedName) && genericA.TypeArguments.SequenceEqual(genericB.TypeArguments, MatchesType); } case TypeSignatureKind.QualifiedType: { var qualifiedA = (QualifiedTypeSignature)typeA; var qualifiedB = (QualifiedTypeSignature)typeB; // Metadata signature may be more qualified than the // string signature but still considered a match // (e.g.: "B<U>.C" should match N.A<T>.B<U>.C). return (qualifiedA.Qualifier == null || (qualifiedB.Qualifier != null && MatchesType(qualifiedA.Qualifier, qualifiedB.Qualifier))) && _stringComparer.Equals(qualifiedA.Name, qualifiedB.Name); } case TypeSignatureKind.ArrayType: { var arrayA = (ArrayTypeSignature)typeA; var arrayB = (ArrayTypeSignature)typeB; return MatchesType(arrayA.ElementType, arrayB.ElementType) && arrayA.Rank == arrayB.Rank; } case TypeSignatureKind.PointerType: { var pointerA = (PointerTypeSignature)typeA; var pointerB = (PointerTypeSignature)typeB; return MatchesType(pointerA.PointedAtType, pointerB.PointedAtType); } default: throw ExceptionUtilities.UnexpectedValue(typeA.Kind); } } private static void GetNameAndTypeParameters( Name name, out QualifiedName qualifiedName, out ImmutableArray<string> typeParameters) { switch (name.Kind) { case NameKind.GenericName: { var genericName = (GenericName)name; qualifiedName = genericName.QualifiedName; typeParameters = genericName.TypeParameters; } break; case NameKind.QualifiedName: { qualifiedName = (QualifiedName)name; typeParameters = ImmutableArray<string>.Empty; } break; default: throw ExceptionUtilities.UnexpectedValue(name.Kind); } } private static bool IsResolvableMethod(MethodDefinition methodDef) { return (methodDef.Attributes & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0; } private static string RemoveAritySeparatorIfAny(string typeName) { int index = typeName.LastIndexOf('`'); return (index < 0) ? typeName : typeName.Substring(0, index); } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_TryCatch.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_TryCatch : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatchFinally_Basic() { string source = @" using System; class C { void M(int i) { /*<bind>*/try { i = 0; } catch (Exception ex) when (i > 0) { throw ex; } finally { i = 1; }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 0;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 0') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') Locals: Local_1: System.Exception ex ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.Exception ex) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(Exception ex)') Initializer: null Filter: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 0') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Handler: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw ex;') ILocalReferenceOperation: ex (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'ex') Finally: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatchFinally_Parent() { string source = @" using System; class C { void M(int i) /*<bind>*/{ try { i = 0; } catch (Exception ex) when (i > 0) { throw ex; } finally { i = 1; } }/*</bind>*/ } "; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 0;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 0') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') Locals: Local_1: System.Exception ex ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.Exception ex) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(Exception ex)') Initializer: null Filter: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 0') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Handler: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw ex;') ILocalReferenceOperation: ex (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'ex') Finally: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_SingleCatchClause() { string source = @" class C { static void Main() { /*<bind>*/try { } catch (System.IO.IOException e) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.IO.IOException e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.IO. ... xception e)') Initializer: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0168: The variable 'e' is declared but never used // catch (System.IO.IOException e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(9, 38) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_SingleCatchClauseAndFilter() { string source = @" class C { static void Main() { /*<bind>*/try { } catch (System.IO.IOException e) when (e.Message != null) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.IO.IOException e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.IO. ... xception e)') Initializer: null Filter: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'e.Message != null') Left: IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.IO.IOException) (Syntax: 'e') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_MultipleCatchClausesWithDifferentCaughtTypes() { string source = @" class C { static void Main() { /*<bind>*/try { } catch (System.IO.IOException e) { } catch (System.Exception e) when (e.Message != null) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(2): ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.IO.IOException e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.IO. ... xception e)') Initializer: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.Exception e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.Exception e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.Exception e)') Initializer: null Filter: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'e.Message != null') Left: IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'e') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0168: The variable 'e' is declared but never used // catch (System.IO.IOException e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(9, 38) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_MultipleCatchClausesWithDuplicateCaughtTypes() { string source = @" class C { static void Main() { /*<bind>*/try { } catch (System.IO.IOException e) { } catch (System.IO.IOException e) when (e.Message != null) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null, IsInvalid) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(2): ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.IO.IOException e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.IO. ... xception e)') Initializer: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null, IsInvalid) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.IO.IOException e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '(System.IO. ... xception e)') Initializer: null Filter: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'e.Message != null') Left: IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.IO.IOException) (Syntax: 'e') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0160: A previous catch clause already catches all exceptions of this or of a super type ('IOException') // catch (System.IO.IOException e) when (e.Message != null) Diagnostic(ErrorCode.ERR_UnreachableCatch, "System.IO.IOException").WithArguments("System.IO.IOException").WithLocation(12, 16), // CS0168: The variable 'e' is declared but never used // catch (System.IO.IOException e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(9, 38) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_CatchClauseWithoutExceptionLocal() { string source = @" using System; class C { static void M(string s) { /*<bind>*/try { } catch (Exception) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') ExceptionDeclarationOrExpression: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_CatchClauseWithoutCaughtTypeOrExceptionLocal() { string source = @" class C { static void M(object o) { /*<bind>*/try { } catch { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.Object) (OperationKind.CatchClause, Type: null) (Syntax: 'catch ... }') ExceptionDeclarationOrExpression: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_FinallyWithoutCatchClause() { string source = @" using System; class C { static void M(string s) { /*<bind>*/try { } finally { Console.WriteLine(s); }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(0) Finally: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s);') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's') IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.String) (Syntax: 's') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_TryBlockWithLocalDeclaration() { string source = @" using System; class C { static void M(string s) { /*<bind>*/try { int i = 0; } catch (Exception) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Int32 i IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i = 0;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') ExceptionDeclarationOrExpression: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i' is assigned but its value is never used // int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(10, 17) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_CatchClauseWithLocalDeclaration() { string source = @" using System; class C { static void M(string s) { /*<bind>*/try { } catch (Exception) { int i = 0; }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') ExceptionDeclarationOrExpression: null Filter: null Handler: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Int32 i IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i = 0;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i' is assigned but its value is never used // int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(13, 17) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_CatchFilterWithLocalDeclaration() { string source = @" using System; class C { static void M(object o) { /*<bind>*/try { } catch (Exception) when (o is string s) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') Locals: Local_1: System.String s ExceptionDeclarationOrExpression: null Filter: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is string s') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'string s') (InputType: System.Object, NarrowedType: System.String, DeclaredSymbol: System.String s, MatchesNull: False) Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_CatchFilterAndSourceWithLocalDeclaration() { string source = @" using System; class C { static void M(object o) { /*<bind>*/try { } catch (Exception e) when (o is string s) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') Locals: Local_1: System.Exception e Local_2: System.String s ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.Exception e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(Exception e)') Initializer: null Filter: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is string s') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'string s') (InputType: System.Object, NarrowedType: System.String, DeclaredSymbol: System.String s, MatchesNull: False) Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(11,26): warning CS0168: The variable 'e' is declared but never used // catch (Exception e) when (o is string s) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(11, 26) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_FinallyWithLocalDeclaration() { string source = @" class C { static void Main() { /*<bind>*/try { } finally { int i = 0; }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(0) Finally: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Int32 i IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i = 0;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i' is assigned but its value is never used // int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(11, 17) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_InvalidCaughtType() { string source = @" class C { static void Main() { try { } /*<bind>*/catch (int e) { }/*</bind>*/ } } "; string expectedOperationTree = @" ICatchClauseOperation (Exception type: System.Int32) (OperationKind.CatchClause, Type: null, IsInvalid) (Syntax: 'catch (int ... }') Locals: Local_1: System.Int32 e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.Int32 e) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '(int e)') Initializer: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0155: The type caught or thrown must be derived from System.Exception // /*<bind>*/catch (int e) Diagnostic(ErrorCode.ERR_BadExceptionType, "int").WithLocation(9, 26), // CS0168: The variable 'e' is declared but never used // /*<bind>*/catch (int e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(9, 30) }; VerifyOperationTreeAndDiagnosticsForTest<CatchClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_GetOperationForCatchClause() { string source = @" class C { static void Main() { try { } /*<bind>*/catch (System.IO.IOException e) when (e.Message != null) { }/*</bind>*/ } } "; string expectedOperationTree = @" ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.IO.IOException e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.IO. ... xception e)') Initializer: null Filter: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'e.Message != null') Left: IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.IO.IOException) (Syntax: 'e') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CatchClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_GetOperationForCatchDeclaration() { string source = @" class C { static void Main() { try { } catch /*<bind>*/(System.IO.IOException e)/*</bind>*/ when (e.Message != null) { } } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.IO. ... xception e)') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CatchDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_GetOperationForCatchFilterClause() { string source = @" using System; class C { static void M(string s) { try { } catch (Exception) /*<bind>*/when (s != null)/*</bind>*/ { } } } "; // GetOperation returns null for CatchFilterClauseSyntax Assert.Null(GetOperationTreeForTest<CatchFilterClauseSyntax>(source)); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_GetOperationForCatchFilterClauseExpression() { string source = @" using System; class C { static void M(string s) { try { } catch (Exception) when (/*<bind>*/s != null/*</bind>*/) { } } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's != null') Left: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.String) (Syntax: 's') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_GetOperationForFinallyClause() { string source = @" using System; class C { static void M(string s) { try { } /*<bind>*/finally { Console.WriteLine(s); }/*</bind>*/ } } "; // GetOperation returns null for FinallyClauseSyntax Assert.Null(GetOperationTreeForTest<FinallyClauseSyntax>(source)); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_01() { var source = @" class C { void F() /*<bind>*/{ try {} catch {} }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (0) Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_02() { var source = @" class C { void F() /*<bind>*/{ try {} finally {} }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Exit Predecessors: [B0] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_03() { var source = @" class Exception1 : System.Exception { } class Exception2 : Exception1 { } class Exception3 : Exception2 { } class Exception4 : Exception3 { } class Exception5 : Exception4 { } class C { void F(int result, bool filter1, bool filter2, bool filter3, Exception5 e5, Exception4 e4) /*<bind>*/{ try { result = -2; } catch (Exception5 e) { e5 = e; } catch (Exception4 e) when (filter1) { e4 = e; } catch (Exception3) when (filter2) { result = 3; } catch (Exception2) { result = 2; } catch when (filter3) { result = 1; } catch { result = 0; } finally { result = -1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = -2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = -2') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, Constant: -2) (Syntax: '-2') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (Exception5) { Locals: [Exception5 e] Block[B2] - Block Predecessors (0) Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception5 e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: Exception5, IsImplicit) (Syntax: '(Exception5 e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: Exception5, IsImplicit) (Syntax: '(Exception5 e)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'e5 = e;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: Exception5) (Syntax: 'e5 = e') Left: IParameterReferenceOperation: e5 (OperationKind.ParameterReference, Type: Exception5) (Syntax: 'e5') Right: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: Exception5) (Syntax: 'e') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R5} {R3} {R2} {R1} } .catch {R6} (Exception4) { Locals: [Exception4 e] .filter {R7} { Block[B3] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception4 e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: Exception4, IsImplicit) (Syntax: '(Exception4 e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: Exception4, IsImplicit) (Syntax: '(Exception4 e)') Jump if True (Regular) to Block[B4] IParameterReferenceOperation: filter1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'filter1') Leaving: {R7} Entering: {R8} Next (StructuredExceptionHandling) Block[null] } .handler {R8} { Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'e4 = e;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: Exception4) (Syntax: 'e4 = e') Left: IParameterReferenceOperation: e4 (OperationKind.ParameterReference, Type: Exception4) (Syntax: 'e4') Right: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: Exception4) (Syntax: 'e') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R8} {R6} {R3} {R2} {R1} } } .catch {R9} (Exception3) { .filter {R10} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IParameterReferenceOperation: filter2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'filter2') Leaving: {R10} Entering: {R11} Next (StructuredExceptionHandling) Block[null] } .handler {R11} { Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = 3') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R11} {R9} {R3} {R2} {R1} } } .catch {R12} (Exception2) { Block[B7] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = 2') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R12} {R3} {R2} {R1} } .catch {R13} (System.Object) { .filter {R14} { Block[B8] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IParameterReferenceOperation: filter3 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'filter3') Leaving: {R14} Entering: {R15} Next (StructuredExceptionHandling) Block[null] } .handler {R15} { Block[B9] - Block Predecessors: [B8] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = 1') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R15} {R13} {R3} {R2} {R1} } } .catch {R16} (System.Object) { Block[B10] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = 0;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = 0') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R16} {R3} {R2} {R1} } } .finally {R17} { Block[B11] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = -1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = -1') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, Constant: -1) (Syntax: '-1') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (StructuredExceptionHandling) Block[null] } Block[B12] - Exit Predecessors: [B1] [B2] [B4] [B6] [B7] [B9] [B10] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_04() { var source = @" class C { void F(bool input, int result) /*<bind>*/{ result = 1; try { if (input) input = false; } finally { result = 0; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = 1') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Entering: {R1} {R2} .try {R1, R2} { Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B5] IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Finalizing: {R3} Leaving: {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'input = false') Left: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B5] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = 0;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = 0') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_05() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i; } catch { int j; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (0) Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_06() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i; i = 1; } catch { int j; j = 2; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Locals: [System.Int32 j] Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_07() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1 e) { int j; j = 2; } finally { int i; i = 1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B6] Finalizing: {R7} Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (Exception1) { Locals: [Exception1 e] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception1 e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Next (Regular) Block[B3] Entering: {R6} .locals {R6} { Locals: [System.Int32 j] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B6] Finalizing: {R7} Leaving: {R6} {R5} {R3} {R2} {R1} } } } .finally {R7} { .locals {R8} { Locals: [System.Int32 i] Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B5] Leaving: {R8} } Block[B5] - Block Predecessors: [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B6] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_08() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1 e) { int j; } finally { int i; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Locals: [Exception1 e] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception1 e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_09() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1 e) when (filter(out var i)) { int j; j = 2; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Locals: [Exception1 e] [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception1 e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Locals: [System.Int32 j] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_10() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1 e) when (filter(out var i)) { int j; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Locals: [Exception1 e] [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception1 e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_11() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1) when (filter(out var i)) { int j; j = 2; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Locals: [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Locals: [System.Int32 j] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_12() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1) when (filter(out var i)) { int j; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Locals: [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_13() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch when (filter(out var i)) { int j; j = 2; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Locals: [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Locals: [System.Int32 j] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_14() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch when (filter(out var i)) { int j; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Locals: [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_15() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1) { int j; j = 2; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Locals: [System.Int32 j] Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_16() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1) { int j; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Block[B2] - Block Predecessors (0) Statements (0) Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_17() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch when (filter(out var i)) { int j; j = 2; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Locals: [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Locals: [System.Int32 j] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_18() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch when (filter(out var i)) { int j; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Locals: [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_19() { var source = @" class C { void F(bool input) /*<bind>*/{ try { } finally { if (input) {} } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2*2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B4] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_20() { var source = @" class C { void F(bool input) /*<bind>*/{ try { } finally { do {} while (input); } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B3] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B2] IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (StructuredExceptionHandling) Block[null] } Block[B3] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_21() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i; i = 1; } finally { int j; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_22() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ int i = 3; try {} finally {} }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 3') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_23() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ { int i = 3; try {} finally {} } { int j = 4; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 3') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B2] Leaving: {R1} Entering: {R2} } .locals {R2} { Locals: [System.Int32 j] Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'j = 4') Left: ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'j = 4') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B3] Leaving: {R2} } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_24() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i; i = 1; } finally { try {} finally {} } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_25() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F(int p) /*<bind>*/{ p = 1; { int a = 2; } p = 3; try { { int i; i = 4; } p = 5; { int j; j = 6; } } finally { } p = 7; { int b = 8; } p = 9; { int c = 10; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = 1') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 2') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = 3') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Entering: {R2} .locals {R2} { Locals: [System.Int32 i] Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 4;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 4') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = 5;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = 5') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Next (Regular) Block[B6] Entering: {R3} .locals {R3} { Locals: [System.Int32 j] Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 6;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 6') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6') Next (Regular) Block[B7] Leaving: {R3} } Block[B7] - Block Predecessors: [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = 7;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = 7') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7) (Syntax: '7') Next (Regular) Block[B8] Entering: {R4} .locals {R4} { Locals: [System.Int32 b] Block[B8] - Block Predecessors: [B7] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 8') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 8') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 8) (Syntax: '8') Next (Regular) Block[B9] Leaving: {R4} } Block[B9] - Block Predecessors: [B8] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = 9;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = 9') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 9) (Syntax: '9') Next (Regular) Block[B10] Entering: {R5} .locals {R5} { Locals: [System.Int32 c] Block[B10] - Block Predecessors: [B9] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 10') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c = 10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Next (Regular) Block[B11] Leaving: {R5} } Block[B11] - Exit Predecessors: [B10] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_26() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i = 1; return; } finally { int j = 2; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { .locals {R4} { Locals: [System.Int32 j] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'j = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B4] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_27() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i = 1; } finally { int j = 2; return; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (15,13): error CS0157: Control cannot leave the body of a finally clause // return; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "return").WithLocation(15, 13) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Locals: [System.Int32 j] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'j = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_28() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i = 1; } catch { int j = 2; return; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Locals: [System.Int32 j] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'j = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_29() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i = 1; } finally { int j; goto label1; label1: ; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_30() { var source = @" class C { void F(bool result) /*<bind>*/{ try { result = true; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,9): error CS1524: Expected catch or finally // } Diagnostic(ErrorCode.ERR_ExpectedEndTry, "}").WithLocation(9, 9) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_01() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_02() { string source = @" class P { void M(bool b) /*<bind>*/{ try { if (ThisCanThrow()) return; } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R2} {R1} Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1*2] [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_03() { string source = @" class P { bool M(bool b) /*<bind>*/{ try { return ThisCanThrow(); } catch { b = true; } return false; }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Return) Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Block Predecessors: [B2] Statements (0) Next (Return) Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_04() { string source = @" class P { void M(bool b) /*<bind>*/{ try { throw null; } catch { b = true; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_05() { string source = @" class P { void M(bool b) /*<bind>*/{ try { if (true) throw null; } catch { b = true; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R2} {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } .catch {R3} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R3} {R1} } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_06() { string source = @" class P { void M(bool b) /*<bind>*/{ try { if (false) throw null; } catch { b = true; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R2} {R1} Next (Regular) Block[B2] Block[B2] - Block [UnReachable] Predecessors: [B1] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } .catch {R3} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R3} {R1} } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_07() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch { try { if (true) throw; } catch { b = true; } } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .try {R4, R5} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R5} {R4} {R3} {R1} Next (Rethrow) Block[null] } .catch {R6} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R6} {R4} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_08() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch { try { if (false) throw; } catch { b = true; } } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .try {R4, R5} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R5} {R4} {R3} {R1} Next (Rethrow) Block[null] } .catch {R6} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R6} {R4} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_09() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); if (false) return; } catch { b = true; } }/*</bind>*/ static bool[] ThisCanThrow() => null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean[] P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R2} {R1} Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1*2] [B2] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(9,24): warning CS0162: Unreachable code detected // if (false) return; Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(9, 24) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_10() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); if (true) return; } catch { b = true; } }/*</bind>*/ static bool[] ThisCanThrow() => null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean[] P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R2} {R1} Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1*2] [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_11() { string source = @" class P { bool[] M(bool b) /*<bind>*/{ try { if (true) return ThisCanThrow(); } catch { b = true; } return null; }/*</bind>*/ static bool[] ThisCanThrow() => null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R2} {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Return) Block[B5] IInvocationOperation (System.Boolean[] P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R3} {R1} } Block[B4] - Block Predecessors: [B1] [B3] Statements (0) Next (Return) Block[B5] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean[], Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B5] - Exit Predecessors: [B2] [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_12() { string source = @" class P { bool[] M(bool b) /*<bind>*/{ try { if (false) return ThisCanThrow(); } catch { b = true; } return null; }/*</bind>*/ static bool[] ThisCanThrow() => null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R2} {R1} Next (Regular) Block[B2] Block[B2] - Block [UnReachable] Predecessors: [B1] Statements (0) Next (Return) Block[B5] IInvocationOperation (System.Boolean[] P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R3} {R1} } Block[B4] - Block Predecessors: [B1] [B3] Statements (0) Next (Return) Block[B5] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean[], Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B5] - Exit Predecessors: [B2] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(8,24): warning CS0162: Unreachable code detected // if (false) return ThisCanThrow(); Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(8, 24) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_13() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { } finally { ThisCanThrow(); } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Finalizing: {R5} Leaving: {R4} {R3} {R2} {R1} } .finally {R5} { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (StructuredExceptionHandling) Block[null] } } .catch {R6} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R6} {R1} } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_14() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { Block[B2] - Block Predecessors (0) Statements (0) Next (Regular) Block[B4] Leaving: {R5} {R3} {R2} {R1} } } .catch {R6} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R6} {R1} } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_15() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (true) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R6} Entering: {R7} Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R8} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(12,25): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch when (true) Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(12, 25) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_16() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (false) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R6} Entering: {R7} Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R8} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(12,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block // catch when (false) Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "false").WithLocation(12, 25) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_17() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (ThisCanThrow()) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R6} Entering: {R7} Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R8} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_18() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (ThisCanThrow() || true) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B6] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R6} Entering: {R7} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R6} Entering: {R7} Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (Regular) Block[B6] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Leaving: {R8} {R1} } Block[B6] - Exit Predecessors: [B1] [B4] [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_19() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (true || ThisCanThrow()) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B6] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R6} Entering: {R7} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R6} Entering: {R7} Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (Regular) Block[B6] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Leaving: {R8} {R1} } Block[B6] - Exit Predecessors: [B1] [B4] [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_20() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (ThisCanThrow() && false) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B7] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B5] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R6} Entering: {R7} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B5] - Block [UnReachable] Predecessors: [B3] Statements (0) Next (Regular) Block[B7] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B6] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B7] Leaving: {R8} {R1} } Block[B7] - Exit Predecessors: [B1] [B5] [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_21() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (false && ThisCanThrow()) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B7] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B5] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R6} Entering: {R7} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B5] - Block [UnReachable] Predecessors: [B3] Statements (0) Next (Regular) Block[B7] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B6] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B7] Leaving: {R8} {R1} } Block[B7] - Exit Predecessors: [B1] [B5] [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_22() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (0) Next (Regular) Block[B4] Leaving: {R3} {R1} } .catch {R4} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R4} {R1} } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(13,9): error CS1017: Catch clauses cannot follow the general catch clause of a try statement // catch Diagnostic(ErrorCode.ERR_TooManyCatches, "catch").WithLocation(13, 9) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_23() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (true) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R6} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(10,21): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch when (true) Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(10, 21) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_24() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (false) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R6} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(10,21): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch when (false) Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(10, 21) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_25() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (ThisCanThrow()) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R6} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_26() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (ThisCanThrow()) { } catch { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B6] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R6} Entering: {R7} Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B6] Leaving: {R7} {R5} {R3} {R2} {R1} } } .catch {R8} (System.Object) { Block[B4] - Block Predecessors (0) Statements (0) Next (Regular) Block[B6] Leaving: {R8} {R3} {R2} {R1} } } .catch {R9} (System.Object) { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Leaving: {R9} {R1} } Block[B6] - Exit Predecessors: [B1] [B3] [B4] [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_27() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (ThisCanThrow() || true) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B6] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R4} Entering: {R5} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (Regular) Block[B6] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Leaving: {R6} {R1} } Block[B6] - Exit Predecessors: [B1] [B4] [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_28() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (true || ThisCanThrow()) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B6] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R4} Entering: {R5} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (Regular) Block[B6] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Leaving: {R6} {R1} } Block[B6] - Exit Predecessors: [B1] [B4] [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_29() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (ThisCanThrow() && false) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B7] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B5] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R4} Entering: {R5} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B5] - Block [UnReachable] Predecessors: [B3] Statements (0) Next (Regular) Block[B7] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B6] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B7] Leaving: {R6} {R1} } Block[B7] - Exit Predecessors: [B1] [B5] [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_30() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (false && ThisCanThrow()) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B7] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B5] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R4} Entering: {R5} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B5] - Block [UnReachable] Predecessors: [B3] Statements (0) Next (Regular) Block[B7] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B6] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B7] Leaving: {R6} {R1} } Block[B7] - Exit Predecessors: [B1] [B5] [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_31() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch { ThisCanThrow(); } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R5} {R3} {R2} {R1} } } .catch {R6} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R6} {R1} } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_32() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch (System.NullReferenceException e) { ThisCanThrow(); } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.NullReferenceException) { Locals: [System.NullReferenceException e] Block[B2] - Block Predecessors (0) Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(System.Nul ... xception e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.NullReferenceException, IsImplicit) (Syntax: '(System.Nul ... xception e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: System.NullReferenceException, IsImplicit) (Syntax: '(System.Nul ... xception e)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R3} {R1} } .catch {R4} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R4} {R1} } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(10,46): warning CS0168: The variable 'e' is declared but never used // catch (System.NullReferenceException e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(10, 46) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_33() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch (System.NullReferenceException e) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.NullReferenceException) { Locals: [System.NullReferenceException e] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(System.Nul ... xception e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.NullReferenceException, IsImplicit) (Syntax: '(System.Nul ... xception e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: System.NullReferenceException, IsImplicit) (Syntax: '(System.Nul ... xception e)') Next (Regular) Block[B4] Leaving: {R5} {R3} {R2} {R1} } } .catch {R6} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R6} {R1} } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(12,50): warning CS0168: The variable 'e' is declared but never used // catch (System.NullReferenceException e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(12, 50) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_34() { string source = @" class P { void M(bool b) /*<bind>*/{ try { } finally { if (true) throw null; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit [UnReachable] Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_35() { string source = @" class P { void M(bool b) /*<bind>*/{ try { } finally { if (false) throw null; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B4] - Block Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_36() { string source = @" class P { void M(bool b) /*<bind>*/{ try { } finally { if (b) throw null; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B4] - Block Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_37() { string source = @" class P { void M(bool b) /*<bind>*/{ try { } finally { if (true) goto label1; throw null; label1: ; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B4] - Block Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_38() { string source = @" class P { void M(bool b) /*<bind>*/{ try { } finally { if (false) goto label1; throw null; label1: ; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B2] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit [UnReachable] Predecessors: [B1] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(11,24): warning CS0162: Unreachable code detected // if (false) goto label1; Diagnostic(ErrorCode.WRN_UnreachableCode, "goto").WithLocation(11, 24), // file.cs(13,1): warning CS0162: Unreachable code detected // label1: ; Diagnostic(ErrorCode.WRN_UnreachableCode, "label1").WithLocation(13, 1) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_39() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch { try { ThisCanThrow(); } finally { if (false) goto label1; throw; label1: ; } b = false; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .try {R4, R5} { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Finalizing: {R6} Leaving: {R5} {R4} } .finally {R6} { Block[B3] - Block Predecessors (0) Statements (0) Jump if False (Rethrow) to Block[null] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (StructuredExceptionHandling) Block[null] } Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = false') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B5] Leaving: {R3} {R1} } Block[B5] - Exit Predecessors: [B1] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw").WithLocation(19, 17), // file.cs(18,28): warning CS0162: Unreachable code detected // if (false) goto label1; Diagnostic(ErrorCode.WRN_UnreachableCode, "goto").WithLocation(18, 28), // file.cs(20,5): warning CS0162: Unreachable code detected // label1: ; Diagnostic(ErrorCode.WRN_UnreachableCode, "label1").WithLocation(20, 5), // file.cs(23,13): warning CS0162: Unreachable code detected // b = false; Diagnostic(ErrorCode.WRN_UnreachableCode, "b").WithLocation(23, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_40() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch (System.NullReferenceException) when (true) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R2} {R1} } .catch {R3} (System.NullReferenceException) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R6} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(10,53): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch (System.NullReferenceException) when (true) Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(10, 53) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_41() { string source = @" class P { void M(int x) /*<bind>*/{ try { try { throw null; } finally { x = 1; } x = 2; } finally { x = 3; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } .finally {R5} { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (StructuredExceptionHandling) Block[null] } Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Finalizing: {R6} Leaving: {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 3') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit [UnReachable] Predecessors: [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(17,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_42() { string source = @" class P { void M(int x) /*<bind>*/{ try { try { throw null; } finally { throw null; } x = 2; } finally { x = 3; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } .finally {R5} { Block[B2] - Block Predecessors (0) Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Finalizing: {R6} Leaving: {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 3') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit [UnReachable] Predecessors: [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(17,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_43() { string source = @" class P { void M(int x) /*<bind>*/{ try { try { throw null; } finally { while (true) {} } x = 2; } finally { x = 3; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } .finally {R5} { Block[B2] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B4] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B6] Finalizing: {R6} Leaving: {R2} {R1} } .finally {R6} { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 3') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (StructuredExceptionHandling) Block[null] } Block[B6] - Exit [UnReachable] Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(17,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_44() { string source = @" class P { void M() /*<bind>*/{ try { try { try { } finally { return; } } catch { } } finally { throw null; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} {R5} {R6} .try {R1, R2} { .try {R3, R4} { .try {R5, R6} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R7} {R9} Leaving: {R6} {R5} {R4} {R3} {R2} {R1} } .finally {R7} { Block[B2] - Block Predecessors (0) Statements (0) Next (Regular) Block[B5] Finalizing: {R9} Leaving: {R7} {R5} {R4} {R3} {R2} {R1} } } .catch {R8} (System.Object) { Block[B3] - Block Predecessors (0) Statements (0) Next (Regular) Block[B5] Finalizing: {R9} Leaving: {R8} {R3} {R2} {R1} } } .finally {R9} { Block[B4] - Block Predecessors (0) Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } Block[B5] - Exit [UnReachable] Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(15,21): error CS0157: Control cannot leave the body of a finally clause // return; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "return").WithLocation(15, 21) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void FinallyDispatch_01() { string source = @" class P { void M(int x) /*<bind>*/{ try { try { return; } finally { x = 1; } x = 2; } finally { x = 3; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R5} {R6} Leaving: {R4} {R3} {R2} {R1} } .finally {R5} { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (StructuredExceptionHandling) Block[null] } Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Finalizing: {R6} Leaving: {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 3') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit Predecessors: [B1] [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(17,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void FinallyDispatch_02() { string source = @" class P { void M(int x) /*<bind>*/{ try { try { return; } finally { throw null; } x = 2; } finally { x = 3; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R5} {R6} Leaving: {R4} {R3} {R2} {R1} } .finally {R5} { Block[B2] - Block Predecessors (0) Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Finalizing: {R6} Leaving: {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 3') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit [UnReachable] Predecessors: [B1] [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(17,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void FinallyDispatch_03() { string source = @" class P { void M(int x) /*<bind>*/{ try { try { return; } finally { while (true) {} } x = 2; } finally { x = 3; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B6] Finalizing: {R5} {R6} Leaving: {R4} {R3} {R2} {R1} } .finally {R5} { Block[B2] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B4] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B6] Finalizing: {R6} Leaving: {R2} {R1} } .finally {R6} { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 3') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (StructuredExceptionHandling) Block[null] } Block[B6] - Exit [UnReachable] Predecessors: [B1] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(17,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchExpressionInExceptionFilter() { string source = @" using System; class C { const string K1 = ""const1""; const string K2 = ""const2""; public void M(string msg) /*<bind>*/{ try { T(msg); } catch (Exception e) when (e.Message switch { K1 => true, K2 => true, _ => false, }) { throw new Exception(e.Message); } }/*</bind>*/ void T(string msg) { throw new Exception(msg); } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'T(msg);') Expression: IInvocationOperation ( void C.T(System.String msg)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'T(msg)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'T') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: msg) (OperationKind.Argument, Type: null) (Syntax: 'msg') IParameterReferenceOperation: msg (OperationKind.ParameterReference, Type: System.String) (Syntax: 'msg') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B13] Leaving: {R2} {R1} } .catch {R3} (System.Exception) { Locals: [System.Exception e] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Exception, IsImplicit) (Syntax: '(Exception e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: System.Exception, IsImplicit) (Syntax: '(Exception e)') Next (Regular) Block[B3] Entering: {R5} {R6} .locals {R5} { CaptureIds: [0] .locals {R6} { CaptureIds: [1] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'e.Message') Value: IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'e') Jump if False (Regular) to Block[B5] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'K1 => true') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'e.Message') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'K1') (InputType: System.String, NarrowedType: System.String) Value: IFieldReferenceOperation: System.String C.K1 (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""const1"") (Syntax: 'K1') Instance Receiver: null Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B10] Leaving: {R6} Block[B5] - Block Predecessors: [B3] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'K2 => true') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'e.Message') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'K2') (InputType: System.String, NarrowedType: System.String) Value: IFieldReferenceOperation: System.String C.K2 (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""const2"") (Syntax: 'K2') Instance Receiver: null Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B10] Leaving: {R6} Block[B7] - Block Predecessors: [B5] Statements (0) Jump if False (Regular) to Block[B9] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '_ => false') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'e.Message') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.String, NarrowedType: System.String) Leaving: {R6} Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B10] Leaving: {R6} } Block[B9] - Block Predecessors: [B7] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsImplicit) (Syntax: 'e.Message s ... }') Arguments(0) Initializer: null Block[B10] - Block Predecessors: [B4] [B6] [B8] Statements (0) Jump if True (Regular) to Block[B12] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'e.Message s ... }') Leaving: {R5} {R4} Entering: {R7} Next (Regular) Block[B11] Leaving: {R5} } Block[B11] - Block Predecessors: [B10] Statements (0) Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B12] - Block Predecessors: [B10] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.Exception..ctor(System.String message)) (OperationKind.ObjectCreation, Type: System.Exception) (Syntax: 'new Exception(e.Message)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: message) (OperationKind.Argument, Type: null) (Syntax: 'e.Message') IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'e') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null } } Block[B13] - Exit Predecessors: [B1] Statements (0) "; var expectedIoperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'T(msg);') Expression: IInvocationOperation ( void C.T(System.String msg)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'T(msg)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'T') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: msg) (OperationKind.Argument, Type: null) (Syntax: 'msg') IParameterReferenceOperation: msg (OperationKind.ParameterReference, Type: System.String) (Syntax: 'msg') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') Locals: Local_1: System.Exception e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.Exception e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(Exception e)') Initializer: null Filter: ISwitchExpressionOperation (3 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Boolean) (Syntax: 'e.Message s ... }') Value: IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'e') Arms(3): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'K1 => true') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'K1') (InputType: System.String, NarrowedType: System.String) Value: IFieldReferenceOperation: System.String C.K1 (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""const1"") (Syntax: 'K1') Instance Receiver: null Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'K2 => true') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'K2') (InputType: System.String, NarrowedType: System.String) Value: IFieldReferenceOperation: System.String C.K2 (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""const2"") (Syntax: 'K2') Instance Receiver: null Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => false') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.String, NarrowedType: System.String) Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Handler: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw new E ... e.Message);') IObjectCreationOperation (Constructor: System.Exception..ctor(System.String message)) (OperationKind.ObjectCreation, Type: System.Exception) (Syntax: 'new Exception(e.Message)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: message) (OperationKind.Argument, Type: null) (Syntax: 'e.Message') IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'e') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { }; var comp = CreateCompilation(source); VerifyOperationTreeForTest<BlockSyntax>(comp, expectedIoperationTree); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_TryCatch : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatchFinally_Basic() { string source = @" using System; class C { void M(int i) { /*<bind>*/try { i = 0; } catch (Exception ex) when (i > 0) { throw ex; } finally { i = 1; }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 0;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 0') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') Locals: Local_1: System.Exception ex ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.Exception ex) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(Exception ex)') Initializer: null Filter: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 0') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Handler: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw ex;') ILocalReferenceOperation: ex (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'ex') Finally: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatchFinally_Parent() { string source = @" using System; class C { void M(int i) /*<bind>*/{ try { i = 0; } catch (Exception ex) when (i > 0) { throw ex; } finally { i = 1; } }/*</bind>*/ } "; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 0;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 0') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') Locals: Local_1: System.Exception ex ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.Exception ex) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(Exception ex)') Initializer: null Filter: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 0') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Handler: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw ex;') ILocalReferenceOperation: ex (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'ex') Finally: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_SingleCatchClause() { string source = @" class C { static void Main() { /*<bind>*/try { } catch (System.IO.IOException e) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.IO.IOException e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.IO. ... xception e)') Initializer: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0168: The variable 'e' is declared but never used // catch (System.IO.IOException e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(9, 38) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_SingleCatchClauseAndFilter() { string source = @" class C { static void Main() { /*<bind>*/try { } catch (System.IO.IOException e) when (e.Message != null) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.IO.IOException e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.IO. ... xception e)') Initializer: null Filter: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'e.Message != null') Left: IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.IO.IOException) (Syntax: 'e') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_MultipleCatchClausesWithDifferentCaughtTypes() { string source = @" class C { static void Main() { /*<bind>*/try { } catch (System.IO.IOException e) { } catch (System.Exception e) when (e.Message != null) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(2): ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.IO.IOException e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.IO. ... xception e)') Initializer: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.Exception e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.Exception e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.Exception e)') Initializer: null Filter: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'e.Message != null') Left: IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'e') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0168: The variable 'e' is declared but never used // catch (System.IO.IOException e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(9, 38) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_MultipleCatchClausesWithDuplicateCaughtTypes() { string source = @" class C { static void Main() { /*<bind>*/try { } catch (System.IO.IOException e) { } catch (System.IO.IOException e) when (e.Message != null) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null, IsInvalid) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(2): ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.IO.IOException e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.IO. ... xception e)') Initializer: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null, IsInvalid) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.IO.IOException e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '(System.IO. ... xception e)') Initializer: null Filter: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'e.Message != null') Left: IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.IO.IOException) (Syntax: 'e') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0160: A previous catch clause already catches all exceptions of this or of a super type ('IOException') // catch (System.IO.IOException e) when (e.Message != null) Diagnostic(ErrorCode.ERR_UnreachableCatch, "System.IO.IOException").WithArguments("System.IO.IOException").WithLocation(12, 16), // CS0168: The variable 'e' is declared but never used // catch (System.IO.IOException e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(9, 38) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_CatchClauseWithoutExceptionLocal() { string source = @" using System; class C { static void M(string s) { /*<bind>*/try { } catch (Exception) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') ExceptionDeclarationOrExpression: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_CatchClauseWithoutCaughtTypeOrExceptionLocal() { string source = @" class C { static void M(object o) { /*<bind>*/try { } catch { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.Object) (OperationKind.CatchClause, Type: null) (Syntax: 'catch ... }') ExceptionDeclarationOrExpression: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_FinallyWithoutCatchClause() { string source = @" using System; class C { static void M(string s) { /*<bind>*/try { } finally { Console.WriteLine(s); }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(0) Finally: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s);') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's') IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.String) (Syntax: 's') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_TryBlockWithLocalDeclaration() { string source = @" using System; class C { static void M(string s) { /*<bind>*/try { int i = 0; } catch (Exception) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Int32 i IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i = 0;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') ExceptionDeclarationOrExpression: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i' is assigned but its value is never used // int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(10, 17) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_CatchClauseWithLocalDeclaration() { string source = @" using System; class C { static void M(string s) { /*<bind>*/try { } catch (Exception) { int i = 0; }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') ExceptionDeclarationOrExpression: null Filter: null Handler: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Int32 i IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i = 0;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i' is assigned but its value is never used // int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(13, 17) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_CatchFilterWithLocalDeclaration() { string source = @" using System; class C { static void M(object o) { /*<bind>*/try { } catch (Exception) when (o is string s) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') Locals: Local_1: System.String s ExceptionDeclarationOrExpression: null Filter: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is string s') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'string s') (InputType: System.Object, NarrowedType: System.String, DeclaredSymbol: System.String s, MatchesNull: False) Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_CatchFilterAndSourceWithLocalDeclaration() { string source = @" using System; class C { static void M(object o) { /*<bind>*/try { } catch (Exception e) when (o is string s) { }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') Locals: Local_1: System.Exception e Local_2: System.String s ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.Exception e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(Exception e)') Initializer: null Filter: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is string s') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'string s') (InputType: System.Object, NarrowedType: System.String, DeclaredSymbol: System.String s, MatchesNull: False) Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(11,26): warning CS0168: The variable 'e' is declared but never used // catch (Exception e) when (o is string s) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(11, 26) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_FinallyWithLocalDeclaration() { string source = @" class C { static void Main() { /*<bind>*/try { } finally { int i = 0; }/*</bind>*/ } } "; string expectedOperationTree = @" ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Catch clauses(0) Finally: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Int32 i IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i = 0;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0219: The variable 'i' is assigned but its value is never used // int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(11, 17) }; VerifyOperationTreeAndDiagnosticsForTest<TryStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_InvalidCaughtType() { string source = @" class C { static void Main() { try { } /*<bind>*/catch (int e) { }/*</bind>*/ } } "; string expectedOperationTree = @" ICatchClauseOperation (Exception type: System.Int32) (OperationKind.CatchClause, Type: null, IsInvalid) (Syntax: 'catch (int ... }') Locals: Local_1: System.Int32 e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.Int32 e) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '(int e)') Initializer: null Filter: null Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0155: The type caught or thrown must be derived from System.Exception // /*<bind>*/catch (int e) Diagnostic(ErrorCode.ERR_BadExceptionType, "int").WithLocation(9, 26), // CS0168: The variable 'e' is declared but never used // /*<bind>*/catch (int e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(9, 30) }; VerifyOperationTreeAndDiagnosticsForTest<CatchClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_GetOperationForCatchClause() { string source = @" class C { static void Main() { try { } /*<bind>*/catch (System.IO.IOException e) when (e.Message != null) { }/*</bind>*/ } } "; string expectedOperationTree = @" ICatchClauseOperation (Exception type: System.IO.IOException) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Syst ... }') Locals: Local_1: System.IO.IOException e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.IO. ... xception e)') Initializer: null Filter: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'e.Message != null') Left: IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.IO.IOException) (Syntax: 'e') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Handler: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CatchClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_GetOperationForCatchDeclaration() { string source = @" class C { static void Main() { try { } catch /*<bind>*/(System.IO.IOException e)/*</bind>*/ when (e.Message != null) { } } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: System.IO.IOException e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(System.IO. ... xception e)') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CatchDeclarationSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_GetOperationForCatchFilterClause() { string source = @" using System; class C { static void M(string s) { try { } catch (Exception) /*<bind>*/when (s != null)/*</bind>*/ { } } } "; // GetOperation returns null for CatchFilterClauseSyntax Assert.Null(GetOperationTreeForTest<CatchFilterClauseSyntax>(source)); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_GetOperationForCatchFilterClauseExpression() { string source = @" using System; class C { static void M(string s) { try { } catch (Exception) when (/*<bind>*/s != null/*</bind>*/) { } } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's != null') Left: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.String) (Syntax: 's') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TryCatch_GetOperationForFinallyClause() { string source = @" using System; class C { static void M(string s) { try { } /*<bind>*/finally { Console.WriteLine(s); }/*</bind>*/ } } "; // GetOperation returns null for FinallyClauseSyntax Assert.Null(GetOperationTreeForTest<FinallyClauseSyntax>(source)); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_01() { var source = @" class C { void F() /*<bind>*/{ try {} catch {} }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (0) Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_02() { var source = @" class C { void F() /*<bind>*/{ try {} finally {} }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Exit Predecessors: [B0] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_03() { var source = @" class Exception1 : System.Exception { } class Exception2 : Exception1 { } class Exception3 : Exception2 { } class Exception4 : Exception3 { } class Exception5 : Exception4 { } class C { void F(int result, bool filter1, bool filter2, bool filter3, Exception5 e5, Exception4 e4) /*<bind>*/{ try { result = -2; } catch (Exception5 e) { e5 = e; } catch (Exception4 e) when (filter1) { e4 = e; } catch (Exception3) when (filter2) { result = 3; } catch (Exception2) { result = 2; } catch when (filter3) { result = 1; } catch { result = 0; } finally { result = -1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = -2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = -2') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, Constant: -2) (Syntax: '-2') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (Exception5) { Locals: [Exception5 e] Block[B2] - Block Predecessors (0) Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception5 e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: Exception5, IsImplicit) (Syntax: '(Exception5 e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: Exception5, IsImplicit) (Syntax: '(Exception5 e)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'e5 = e;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: Exception5) (Syntax: 'e5 = e') Left: IParameterReferenceOperation: e5 (OperationKind.ParameterReference, Type: Exception5) (Syntax: 'e5') Right: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: Exception5) (Syntax: 'e') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R5} {R3} {R2} {R1} } .catch {R6} (Exception4) { Locals: [Exception4 e] .filter {R7} { Block[B3] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception4 e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: Exception4, IsImplicit) (Syntax: '(Exception4 e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: Exception4, IsImplicit) (Syntax: '(Exception4 e)') Jump if True (Regular) to Block[B4] IParameterReferenceOperation: filter1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'filter1') Leaving: {R7} Entering: {R8} Next (StructuredExceptionHandling) Block[null] } .handler {R8} { Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'e4 = e;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: Exception4) (Syntax: 'e4 = e') Left: IParameterReferenceOperation: e4 (OperationKind.ParameterReference, Type: Exception4) (Syntax: 'e4') Right: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: Exception4) (Syntax: 'e') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R8} {R6} {R3} {R2} {R1} } } .catch {R9} (Exception3) { .filter {R10} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IParameterReferenceOperation: filter2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'filter2') Leaving: {R10} Entering: {R11} Next (StructuredExceptionHandling) Block[null] } .handler {R11} { Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = 3') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R11} {R9} {R3} {R2} {R1} } } .catch {R12} (Exception2) { Block[B7] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = 2') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R12} {R3} {R2} {R1} } .catch {R13} (System.Object) { .filter {R14} { Block[B8] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B9] IParameterReferenceOperation: filter3 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'filter3') Leaving: {R14} Entering: {R15} Next (StructuredExceptionHandling) Block[null] } .handler {R15} { Block[B9] - Block Predecessors: [B8] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = 1') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R15} {R13} {R3} {R2} {R1} } } .catch {R16} (System.Object) { Block[B10] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = 0;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = 0') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B12] Finalizing: {R17} Leaving: {R16} {R3} {R2} {R1} } } .finally {R17} { Block[B11] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = -1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = -1') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, Constant: -1) (Syntax: '-1') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (StructuredExceptionHandling) Block[null] } Block[B12] - Exit Predecessors: [B1] [B2] [B4] [B6] [B7] [B9] [B10] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_04() { var source = @" class C { void F(bool input, int result) /*<bind>*/{ result = 1; try { if (input) input = false; } finally { result = 0; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = 1') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Entering: {R1} {R2} .try {R1, R2} { Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B5] IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Finalizing: {R3} Leaving: {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'input = false') Left: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B5] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = 0;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = 0') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_05() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i; } catch { int j; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (0) Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_06() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i; i = 1; } catch { int j; j = 2; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Locals: [System.Int32 j] Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_07() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1 e) { int j; j = 2; } finally { int i; i = 1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B6] Finalizing: {R7} Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (Exception1) { Locals: [Exception1 e] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception1 e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Next (Regular) Block[B3] Entering: {R6} .locals {R6} { Locals: [System.Int32 j] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B6] Finalizing: {R7} Leaving: {R6} {R5} {R3} {R2} {R1} } } } .finally {R7} { .locals {R8} { Locals: [System.Int32 i] Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B5] Leaving: {R8} } Block[B5] - Block Predecessors: [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B6] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_08() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1 e) { int j; } finally { int i; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Locals: [Exception1 e] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception1 e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_09() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1 e) when (filter(out var i)) { int j; j = 2; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Locals: [Exception1 e] [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception1 e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Locals: [System.Int32 j] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_10() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1 e) when (filter(out var i)) { int j; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Locals: [Exception1 e] [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception1 e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: Exception1, IsImplicit) (Syntax: '(Exception1 e)') Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_11() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1) when (filter(out var i)) { int j; j = 2; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Locals: [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Locals: [System.Int32 j] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_12() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1) when (filter(out var i)) { int j; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Locals: [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_13() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch when (filter(out var i)) { int j; j = 2; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Locals: [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Locals: [System.Int32 j] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_14() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch when (filter(out var i)) { int j; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Locals: [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_15() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1) { int j; j = 2; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Locals: [System.Int32 j] Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_16() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch (Exception1) { int j; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (Exception1) { Block[B2] - Block Predecessors (0) Statements (0) Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_17() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch when (filter(out var i)) { int j; j = 2; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Locals: [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Locals: [System.Int32 j] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_18() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class Exception1 : System.Exception { } class C { void F() /*<bind>*/{ try { } catch when (filter(out var i)) { int j; } }/*</bind>*/ bool filter(out int i) => throw null; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Locals: [System.Int32 i] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation ( System.Boolean C.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var i)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'filter') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B4] Leaving: {R5} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_19() { var source = @" class C { void F(bool input) /*<bind>*/{ try { } finally { if (input) {} } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2*2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B4] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_20() { var source = @" class C { void F(bool input) /*<bind>*/{ try { } finally { do {} while (input); } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B3] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B2] IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (StructuredExceptionHandling) Block[null] } Block[B3] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_21() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i; i = 1; } finally { int j; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_22() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ int i = 3; try {} finally {} }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 3') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_23() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ { int i = 3; try {} finally {} } { int j = 4; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 3') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B2] Leaving: {R1} Entering: {R2} } .locals {R2} { Locals: [System.Int32 j] Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'j = 4') Left: ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'j = 4') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B3] Leaving: {R2} } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_24() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i; i = 1; } finally { try {} finally {} } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_25() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F(int p) /*<bind>*/{ p = 1; { int a = 2; } p = 3; try { { int i; i = 4; } p = 5; { int j; j = 6; } } finally { } p = 7; { int b = 8; } p = 9; { int c = 10; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = 1') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Entering: {R1} .locals {R1} { Locals: [System.Int32 a] Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 2') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = 3') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Entering: {R2} .locals {R2} { Locals: [System.Int32 i] Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 4;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 4') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = 5;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = 5') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Next (Regular) Block[B6] Entering: {R3} .locals {R3} { Locals: [System.Int32 j] Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 6;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 6') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6') Next (Regular) Block[B7] Leaving: {R3} } Block[B7] - Block Predecessors: [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = 7;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = 7') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7) (Syntax: '7') Next (Regular) Block[B8] Entering: {R4} .locals {R4} { Locals: [System.Int32 b] Block[B8] - Block Predecessors: [B7] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 8') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 8') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 8) (Syntax: '8') Next (Regular) Block[B9] Leaving: {R4} } Block[B9] - Block Predecessors: [B8] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = 9;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = 9') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 9) (Syntax: '9') Next (Regular) Block[B10] Entering: {R5} .locals {R5} { Locals: [System.Int32 c] Block[B10] - Block Predecessors: [B9] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 10') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c = 10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Next (Regular) Block[B11] Leaving: {R5} } Block[B11] - Exit Predecessors: [B10] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_26() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i = 1; return; } finally { int j = 2; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { .locals {R4} { Locals: [System.Int32 j] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'j = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B4] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_27() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i = 1; } finally { int j = 2; return; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (15,13): error CS0157: Control cannot leave the body of a finally clause // return; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "return").WithLocation(15, 13) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Locals: [System.Int32 j] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'j = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_28() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i = 1; } catch { int j = 2; return; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Locals: [System.Int32 j] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'j = 2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_29() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F() /*<bind>*/{ try { int i = 1; } finally { int j; goto label1; label1: ; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TryFlow_30() { var source = @" class C { void F(bool result) /*<bind>*/{ try { result = true; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,9): error CS1524: Expected catch or finally // } Diagnostic(ErrorCode.ERR_ExpectedEndTry, "}").WithLocation(9, 9) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_01() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_02() { string source = @" class P { void M(bool b) /*<bind>*/{ try { if (ThisCanThrow()) return; } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R2} {R1} Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1*2] [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_03() { string source = @" class P { bool M(bool b) /*<bind>*/{ try { return ThisCanThrow(); } catch { b = true; } return false; }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Return) Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Block Predecessors: [B2] Statements (0) Next (Return) Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_04() { string source = @" class P { void M(bool b) /*<bind>*/{ try { throw null; } catch { b = true; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_05() { string source = @" class P { void M(bool b) /*<bind>*/{ try { if (true) throw null; } catch { b = true; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R2} {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } .catch {R3} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R3} {R1} } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_06() { string source = @" class P { void M(bool b) /*<bind>*/{ try { if (false) throw null; } catch { b = true; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R2} {R1} Next (Regular) Block[B2] Block[B2] - Block [UnReachable] Predecessors: [B1] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } .catch {R3} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R3} {R1} } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_07() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch { try { if (true) throw; } catch { b = true; } } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .try {R4, R5} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R5} {R4} {R3} {R1} Next (Rethrow) Block[null] } .catch {R6} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R6} {R4} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_08() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch { try { if (false) throw; } catch { b = true; } } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .try {R4, R5} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R5} {R4} {R3} {R1} Next (Rethrow) Block[null] } .catch {R6} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R6} {R4} {R3} {R1} } } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_09() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); if (false) return; } catch { b = true; } }/*</bind>*/ static bool[] ThisCanThrow() => null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean[] P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R2} {R1} Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1*2] [B2] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(9,24): warning CS0162: Unreachable code detected // if (false) return; Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(9, 24) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_10() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); if (true) return; } catch { b = true; } }/*</bind>*/ static bool[] ThisCanThrow() => null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean[] P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R2} {R1} Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1*2] [B2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_11() { string source = @" class P { bool[] M(bool b) /*<bind>*/{ try { if (true) return ThisCanThrow(); } catch { b = true; } return null; }/*</bind>*/ static bool[] ThisCanThrow() => null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R2} {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Return) Block[B5] IInvocationOperation (System.Boolean[] P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R3} {R1} } Block[B4] - Block Predecessors: [B1] [B3] Statements (0) Next (Return) Block[B5] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean[], Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B5] - Exit Predecessors: [B2] [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_12() { string source = @" class P { bool[] M(bool b) /*<bind>*/{ try { if (false) return ThisCanThrow(); } catch { b = true; } return null; }/*</bind>*/ static bool[] ThisCanThrow() => null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R2} {R1} Next (Regular) Block[B2] Block[B2] - Block [UnReachable] Predecessors: [B1] Statements (0) Next (Return) Block[B5] IInvocationOperation (System.Boolean[] P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R3} {R1} } Block[B4] - Block Predecessors: [B1] [B3] Statements (0) Next (Return) Block[B5] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean[], Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B5] - Exit Predecessors: [B2] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(8,24): warning CS0162: Unreachable code detected // if (false) return ThisCanThrow(); Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(8, 24) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_13() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { } finally { ThisCanThrow(); } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B4] Finalizing: {R5} Leaving: {R4} {R3} {R2} {R1} } .finally {R5} { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (StructuredExceptionHandling) Block[null] } } .catch {R6} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R6} {R1} } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_14() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { Block[B2] - Block Predecessors (0) Statements (0) Next (Regular) Block[B4] Leaving: {R5} {R3} {R2} {R1} } } .catch {R6} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R6} {R1} } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_15() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (true) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R6} Entering: {R7} Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R8} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(12,25): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch when (true) Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(12, 25) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_16() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (false) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R6} Entering: {R7} Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R8} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(12,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block // catch when (false) Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "false").WithLocation(12, 25) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_17() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (ThisCanThrow()) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R6} Entering: {R7} Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R8} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_18() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (ThisCanThrow() || true) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B6] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R6} Entering: {R7} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R6} Entering: {R7} Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (Regular) Block[B6] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Leaving: {R8} {R1} } Block[B6] - Exit Predecessors: [B1] [B4] [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_19() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (true || ThisCanThrow()) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B6] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R6} Entering: {R7} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R6} Entering: {R7} Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (Regular) Block[B6] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Leaving: {R8} {R1} } Block[B6] - Exit Predecessors: [B1] [B4] [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_20() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (ThisCanThrow() && false) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B7] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B5] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R6} Entering: {R7} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B5] - Block [UnReachable] Predecessors: [B3] Statements (0) Next (Regular) Block[B7] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B6] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B7] Leaving: {R8} {R1} } Block[B7] - Exit Predecessors: [B1] [B5] [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_21() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (false && ThisCanThrow()) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B7] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B5] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R6} Entering: {R7} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B5] - Block [UnReachable] Predecessors: [B3] Statements (0) Next (Regular) Block[B7] Leaving: {R7} {R5} {R3} {R2} {R1} } } } .catch {R8} (System.Object) { Block[B6] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B7] Leaving: {R8} {R1} } Block[B7] - Exit Predecessors: [B1] [B5] [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_22() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (0) Next (Regular) Block[B4] Leaving: {R3} {R1} } .catch {R4} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R4} {R1} } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(13,9): error CS1017: Catch clauses cannot follow the general catch clause of a try statement // catch Diagnostic(ErrorCode.ERR_TooManyCatches, "catch").WithLocation(13, 9) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_23() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (true) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R6} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(10,21): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch when (true) Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(10, 21) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_24() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (false) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R6} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(10,21): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch when (false) Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(10, 21) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_25() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (ThisCanThrow()) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R6} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_26() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch when (ThisCanThrow()) { } catch { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B6] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { .filter {R6} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R6} Entering: {R7} Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B6] Leaving: {R7} {R5} {R3} {R2} {R1} } } .catch {R8} (System.Object) { Block[B4] - Block Predecessors (0) Statements (0) Next (Regular) Block[B6] Leaving: {R8} {R3} {R2} {R1} } } .catch {R9} (System.Object) { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Leaving: {R9} {R1} } Block[B6] - Exit Predecessors: [B1] [B3] [B4] [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_27() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (ThisCanThrow() || true) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B6] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R4} Entering: {R5} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (Regular) Block[B6] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Leaving: {R6} {R1} } Block[B6] - Exit Predecessors: [B1] [B4] [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_28() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (true || ThisCanThrow()) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B6] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R4} Entering: {R5} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (Regular) Block[B6] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Leaving: {R6} {R1} } Block[B6] - Exit Predecessors: [B1] [B4] [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_29() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (ThisCanThrow() && false) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B7] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B5] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R4} Entering: {R5} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B5] - Block [UnReachable] Predecessors: [B3] Statements (0) Next (Regular) Block[B7] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B6] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B7] Leaving: {R6} {R1} } Block[B7] - Exit Predecessors: [B1] [B5] [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_30() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch when (false && ThisCanThrow()) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B7] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Jump if True (Regular) to Block[B5] IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Leaving: {R4} Entering: {R5} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B5] - Block [UnReachable] Predecessors: [B3] Statements (0) Next (Regular) Block[B7] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B6] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B7] Leaving: {R6} {R1} } Block[B7] - Exit Predecessors: [B1] [B5] [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_31() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch { ThisCanThrow(); } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R5} {R3} {R2} {R1} } } .catch {R6} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R6} {R1} } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_32() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch (System.NullReferenceException e) { ThisCanThrow(); } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.NullReferenceException) { Locals: [System.NullReferenceException e] Block[B2] - Block Predecessors (0) Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(System.Nul ... xception e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.NullReferenceException, IsImplicit) (Syntax: '(System.Nul ... xception e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: System.NullReferenceException, IsImplicit) (Syntax: '(System.Nul ... xception e)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R3} {R1} } .catch {R4} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R4} {R1} } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(10,46): warning CS0168: The variable 'e' is declared but never used // catch (System.NullReferenceException e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(10, 46) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_33() { string source = @" class P { void M(bool b) /*<bind>*/{ try { try { ThisCanThrow(); } catch (System.NullReferenceException e) { } } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Leaving: {R4} {R3} {R2} {R1} } .catch {R5} (System.NullReferenceException) { Locals: [System.NullReferenceException e] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(System.Nul ... xception e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.NullReferenceException, IsImplicit) (Syntax: '(System.Nul ... xception e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: System.NullReferenceException, IsImplicit) (Syntax: '(System.Nul ... xception e)') Next (Regular) Block[B4] Leaving: {R5} {R3} {R2} {R1} } } .catch {R6} (System.Object) { Block[B3] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R6} {R1} } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(12,50): warning CS0168: The variable 'e' is declared but never used // catch (System.NullReferenceException e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(12, 50) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_34() { string source = @" class P { void M(bool b) /*<bind>*/{ try { } finally { if (true) throw null; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit [UnReachable] Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_35() { string source = @" class P { void M(bool b) /*<bind>*/{ try { } finally { if (false) throw null; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B4] - Block Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_36() { string source = @" class P { void M(bool b) /*<bind>*/{ try { } finally { if (b) throw null; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B4] - Block Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_37() { string source = @" class P { void M(bool b) /*<bind>*/{ try { } finally { if (true) goto label1; throw null; label1: ; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B4] - Block Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_38() { string source = @" class P { void M(bool b) /*<bind>*/{ try { } finally { if (false) goto label1; throw null; label1: ; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B2] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit [UnReachable] Predecessors: [B1] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(11,24): warning CS0162: Unreachable code detected // if (false) goto label1; Diagnostic(ErrorCode.WRN_UnreachableCode, "goto").WithLocation(11, 24), // file.cs(13,1): warning CS0162: Unreachable code detected // label1: ; Diagnostic(ErrorCode.WRN_UnreachableCode, "label1").WithLocation(13, 1) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_39() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch { try { ThisCanThrow(); } finally { if (false) goto label1; throw; label1: ; } b = false; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .try {R4, R5} { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B4] Finalizing: {R6} Leaving: {R5} {R4} } .finally {R6} { Block[B3] - Block Predecessors (0) Statements (0) Jump if False (Rethrow) to Block[null] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (StructuredExceptionHandling) Block[null] } Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = false') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B5] Leaving: {R3} {R1} } Block[B5] - Exit Predecessors: [B1] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw").WithLocation(19, 17), // file.cs(18,28): warning CS0162: Unreachable code detected // if (false) goto label1; Diagnostic(ErrorCode.WRN_UnreachableCode, "goto").WithLocation(18, 28), // file.cs(20,5): warning CS0162: Unreachable code detected // label1: ; Diagnostic(ErrorCode.WRN_UnreachableCode, "label1").WithLocation(20, 5), // file.cs(23,13): warning CS0162: Unreachable code detected // b = false; Diagnostic(ErrorCode.WRN_UnreachableCode, "b").WithLocation(23, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_40() { string source = @" class P { void M(bool b) /*<bind>*/{ try { ThisCanThrow(); } catch (System.NullReferenceException) when (true) { } catch { b = true; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ThisCanThrow();') Expression: IInvocationOperation (System.Boolean P.ThisCanThrow()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'ThisCanThrow()') Instance Receiver: null Arguments(0) Next (Regular) Block[B5] Leaving: {R2} {R1} } .catch {R3} (System.NullReferenceException) { .filter {R4} { Block[B2] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R4} Entering: {R5} Next (StructuredExceptionHandling) Block[null] } .handler {R5} { Block[B3] - Block Predecessors: [B2] Statements (0) Next (Regular) Block[B5] Leaving: {R5} {R3} {R1} } } .catch {R6} (System.Object) { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R6} {R1} } Block[B5] - Exit Predecessors: [B1] [B3] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(10,53): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch (System.NullReferenceException) when (true) Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(10, 53) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_41() { string source = @" class P { void M(int x) /*<bind>*/{ try { try { throw null; } finally { x = 1; } x = 2; } finally { x = 3; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } .finally {R5} { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (StructuredExceptionHandling) Block[null] } Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Finalizing: {R6} Leaving: {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 3') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit [UnReachable] Predecessors: [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(17,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_42() { string source = @" class P { void M(int x) /*<bind>*/{ try { try { throw null; } finally { throw null; } x = 2; } finally { x = 3; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } .finally {R5} { Block[B2] - Block Predecessors (0) Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Finalizing: {R6} Leaving: {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 3') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit [UnReachable] Predecessors: [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(17,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_43() { string source = @" class P { void M(int x) /*<bind>*/{ try { try { throw null; } finally { while (true) {} } x = 2; } finally { x = 3; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } .finally {R5} { Block[B2] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B4] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B6] Finalizing: {R6} Leaving: {R2} {R1} } .finally {R6} { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 3') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (StructuredExceptionHandling) Block[null] } Block[B6] - Exit [UnReachable] Predecessors: [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(17,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ExceptionDispatch_44() { string source = @" class P { void M() /*<bind>*/{ try { try { try { } finally { return; } } catch { } } finally { throw null; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} {R5} {R6} .try {R1, R2} { .try {R3, R4} { .try {R5, R6} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R7} {R9} Leaving: {R6} {R5} {R4} {R3} {R2} {R1} } .finally {R7} { Block[B2] - Block Predecessors (0) Statements (0) Next (Regular) Block[B5] Finalizing: {R9} Leaving: {R7} {R5} {R4} {R3} {R2} {R1} } } .catch {R8} (System.Object) { Block[B3] - Block Predecessors (0) Statements (0) Next (Regular) Block[B5] Finalizing: {R9} Leaving: {R8} {R3} {R2} {R1} } } .finally {R9} { Block[B4] - Block Predecessors (0) Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } Block[B5] - Exit [UnReachable] Predecessors: [B1] [B2] [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(15,21): error CS0157: Control cannot leave the body of a finally clause // return; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "return").WithLocation(15, 21) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void FinallyDispatch_01() { string source = @" class P { void M(int x) /*<bind>*/{ try { try { return; } finally { x = 1; } x = 2; } finally { x = 3; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R5} {R6} Leaving: {R4} {R3} {R2} {R1} } .finally {R5} { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (StructuredExceptionHandling) Block[null] } Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Finalizing: {R6} Leaving: {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 3') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit Predecessors: [B1] [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(17,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void FinallyDispatch_02() { string source = @" class P { void M(int x) /*<bind>*/{ try { try { return; } finally { throw null; } x = 2; } finally { x = 3; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B5] Finalizing: {R5} {R6} Leaving: {R4} {R3} {R2} {R1} } .finally {R5} { Block[B2] - Block Predecessors (0) Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') } Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Finalizing: {R6} Leaving: {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 3') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (StructuredExceptionHandling) Block[null] } Block[B5] - Exit [UnReachable] Predecessors: [B1] [B3] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(17,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void FinallyDispatch_03() { string source = @" class P { void M(int x) /*<bind>*/{ try { try { return; } finally { while (true) {} } x = 2; } finally { x = 3; } }/*</bind>*/ static bool ThisCanThrow() => throw null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} {R4} .try {R1, R2} { .try {R3, R4} { Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B6] Finalizing: {R5} {R6} Leaving: {R4} {R3} {R2} {R1} } .finally {R5} { Block[B2] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (0) Next (StructuredExceptionHandling) Block[null] } Block[B4] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B6] Finalizing: {R6} Leaving: {R2} {R1} } .finally {R6} { Block[B5] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 3') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (StructuredExceptionHandling) Block[null] } Block[B6] - Exit [UnReachable] Predecessors: [B1] [B4] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(17,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(17, 13) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchExpressionInExceptionFilter() { string source = @" using System; class C { const string K1 = ""const1""; const string K2 = ""const2""; public void M(string msg) /*<bind>*/{ try { T(msg); } catch (Exception e) when (e.Message switch { K1 => true, K2 => true, _ => false, }) { throw new Exception(e.Message); } }/*</bind>*/ void T(string msg) { throw new Exception(msg); } } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'T(msg);') Expression: IInvocationOperation ( void C.T(System.String msg)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'T(msg)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'T') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: msg) (OperationKind.Argument, Type: null) (Syntax: 'msg') IParameterReferenceOperation: msg (OperationKind.ParameterReference, Type: System.String) (Syntax: 'msg') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B13] Leaving: {R2} {R1} } .catch {R3} (System.Exception) { Locals: [System.Exception e] .filter {R4} { Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '(Exception e)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Exception, IsImplicit) (Syntax: '(Exception e)') Right: ICaughtExceptionOperation (OperationKind.CaughtException, Type: System.Exception, IsImplicit) (Syntax: '(Exception e)') Next (Regular) Block[B3] Entering: {R5} {R6} .locals {R5} { CaptureIds: [0] .locals {R6} { CaptureIds: [1] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'e.Message') Value: IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'e') Jump if False (Regular) to Block[B5] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'K1 => true') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'e.Message') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'K1') (InputType: System.String, NarrowedType: System.String) Value: IFieldReferenceOperation: System.String C.K1 (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""const1"") (Syntax: 'K1') Instance Receiver: null Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B10] Leaving: {R6} Block[B5] - Block Predecessors: [B3] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'K2 => true') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'e.Message') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'K2') (InputType: System.String, NarrowedType: System.String) Value: IFieldReferenceOperation: System.String C.K2 (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""const2"") (Syntax: 'K2') Instance Receiver: null Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B10] Leaving: {R6} Block[B7] - Block Predecessors: [B5] Statements (0) Jump if False (Regular) to Block[B9] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '_ => false') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'e.Message') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.String, NarrowedType: System.String) Leaving: {R6} Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B10] Leaving: {R6} } Block[B9] - Block Predecessors: [B7] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsImplicit) (Syntax: 'e.Message s ... }') Arguments(0) Initializer: null Block[B10] - Block Predecessors: [B4] [B6] [B8] Statements (0) Jump if True (Regular) to Block[B12] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'e.Message s ... }') Leaving: {R5} {R4} Entering: {R7} Next (Regular) Block[B11] Leaving: {R5} } Block[B11] - Block Predecessors: [B10] Statements (0) Next (StructuredExceptionHandling) Block[null] } .handler {R7} { Block[B12] - Block Predecessors: [B10] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.Exception..ctor(System.String message)) (OperationKind.ObjectCreation, Type: System.Exception) (Syntax: 'new Exception(e.Message)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: message) (OperationKind.Argument, Type: null) (Syntax: 'e.Message') IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'e') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null } } Block[B13] - Exit Predecessors: [B1] Statements (0) "; var expectedIoperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') ITryOperation (OperationKind.Try, Type: null) (Syntax: 'try ... }') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'T(msg);') Expression: IInvocationOperation ( void C.T(System.String msg)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'T(msg)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'T') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: msg) (OperationKind.Argument, Type: null) (Syntax: 'msg') IParameterReferenceOperation: msg (OperationKind.ParameterReference, Type: System.String) (Syntax: 'msg') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Catch clauses(1): ICatchClauseOperation (Exception type: System.Exception) (OperationKind.CatchClause, Type: null) (Syntax: 'catch (Exce ... }') Locals: Local_1: System.Exception e ExceptionDeclarationOrExpression: IVariableDeclaratorOperation (Symbol: System.Exception e) (OperationKind.VariableDeclarator, Type: null) (Syntax: '(Exception e)') Initializer: null Filter: ISwitchExpressionOperation (3 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Boolean) (Syntax: 'e.Message s ... }') Value: IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'e') Arms(3): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'K1 => true') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'K1') (InputType: System.String, NarrowedType: System.String) Value: IFieldReferenceOperation: System.String C.K1 (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""const1"") (Syntax: 'K1') Instance Receiver: null Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'K2 => true') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'K2') (InputType: System.String, NarrowedType: System.String) Value: IFieldReferenceOperation: System.String C.K2 (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""const2"") (Syntax: 'K2') Instance Receiver: null Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => false') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.String, NarrowedType: System.String) Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Handler: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw new E ... e.Message);') IObjectCreationOperation (Constructor: System.Exception..ctor(System.String message)) (OperationKind.ObjectCreation, Type: System.Exception) (Syntax: 'new Exception(e.Message)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: message) (OperationKind.Argument, Type: null) (Syntax: 'e.Message') IPropertyReferenceOperation: System.String System.Exception.Message { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'e.Message') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Exception) (Syntax: 'e') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null Finally: null "; var expectedDiagnostics = new DiagnosticDescription[] { }; var comp = CreateCompilation(source); VerifyOperationTreeForTest<BlockSyntax>(comp, expectedIoperationTree); VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(comp, expectedGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/LineKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class LineKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public LineKeywordRecommender() : base(SyntaxKind.LineKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsPreProcessorKeywordContext; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class LineKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public LineKeywordRecommender() : base(SyntaxKind.LineKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsPreProcessorKeywordContext; } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/VisualStudio/Core/Impl/CodeModel/Collections/ExternalNamespaceEnumerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { public sealed class ExternalNamespaceEnumerator : IEnumerator, ICloneable { internal static IEnumerator Create(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId) { var newEnumerator = new ExternalNamespaceEnumerator(state, projectId, namespaceSymbolId); return (IEnumerator)ComAggregate.CreateAggregatedObject(newEnumerator); } private ExternalNamespaceEnumerator(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId) { _state = state; _projectId = projectId; _namespaceSymbolId = namespaceSymbolId; _childEnumerator = ChildrenOfNamespace(state, projectId, namespaceSymbolId).GetEnumerator(); } private readonly CodeModelState _state; private readonly ProjectId _projectId; private readonly SymbolKey _namespaceSymbolId; private readonly IEnumerator<EnvDTE.CodeElement> _childEnumerator; public object Current { get { return _childEnumerator.Current; } } public object Clone() => Create(_state, _projectId, _namespaceSymbolId); public bool MoveNext() => _childEnumerator.MoveNext(); public void Reset() => _childEnumerator.Reset(); internal static IEnumerable<EnvDTE.CodeElement> ChildrenOfNamespace(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId) { var project = state.Workspace.CurrentSolution.GetProject(projectId); if (project == null) { throw Exceptions.ThrowEFail(); } if (!(namespaceSymbolId.Resolve(project.GetCompilationAsync().Result).Symbol is INamespaceSymbol namespaceSymbol)) { throw Exceptions.ThrowEFail(); } var containingAssembly = project.GetCompilationAsync().Result.Assembly; foreach (var child in namespaceSymbol.GetMembers()) { if (child is INamespaceSymbol namespaceChild) { yield return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, namespaceChild); } else { var namedType = (INamedTypeSymbol)child; if (namedType.IsAccessibleWithin(containingAssembly)) { if (namedType.Locations.Any(l => l.IsInMetadata || l.IsInSource)) { yield return state.CodeModelService.CreateCodeType(state, projectId, namedType); } } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { public sealed class ExternalNamespaceEnumerator : IEnumerator, ICloneable { internal static IEnumerator Create(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId) { var newEnumerator = new ExternalNamespaceEnumerator(state, projectId, namespaceSymbolId); return (IEnumerator)ComAggregate.CreateAggregatedObject(newEnumerator); } private ExternalNamespaceEnumerator(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId) { _state = state; _projectId = projectId; _namespaceSymbolId = namespaceSymbolId; _childEnumerator = ChildrenOfNamespace(state, projectId, namespaceSymbolId).GetEnumerator(); } private readonly CodeModelState _state; private readonly ProjectId _projectId; private readonly SymbolKey _namespaceSymbolId; private readonly IEnumerator<EnvDTE.CodeElement> _childEnumerator; public object Current { get { return _childEnumerator.Current; } } public object Clone() => Create(_state, _projectId, _namespaceSymbolId); public bool MoveNext() => _childEnumerator.MoveNext(); public void Reset() => _childEnumerator.Reset(); internal static IEnumerable<EnvDTE.CodeElement> ChildrenOfNamespace(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId) { var project = state.Workspace.CurrentSolution.GetProject(projectId); if (project == null) { throw Exceptions.ThrowEFail(); } if (!(namespaceSymbolId.Resolve(project.GetCompilationAsync().Result).Symbol is INamespaceSymbol namespaceSymbol)) { throw Exceptions.ThrowEFail(); } var containingAssembly = project.GetCompilationAsync().Result.Assembly; foreach (var child in namespaceSymbol.GetMembers()) { if (child is INamespaceSymbol namespaceChild) { yield return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, namespaceChild); } else { var namedType = (INamedTypeSymbol)child; if (namedType.IsAccessibleWithin(containingAssembly)) { if (namedType.Locations.Any(l => l.IsInMetadata || l.IsInSource)) { yield return state.CodeModelService.CreateCodeType(state, projectId, namedType); } } } } } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/VisualStudio/Core/Def/Implementation/CallHierarchy/Finders/CallToOverrideFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders { internal class CallToOverrideFinder : AbstractCallFinder { public CallToOverrideFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider) : base(symbol, projectId, asyncListener, provider) { } public override string DisplayName => EditorFeaturesResources.Calls_To_Overrides; protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken) { var overrides = await SymbolFinder.FindOverridesAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); var callsToOverrides = new List<SymbolCallerInfo>(); foreach (var @override in overrides) { var calls = await SymbolFinder.FindCallersAsync(@override, project.Solution, documents, cancellationToken).ConfigureAwait(false); foreach (var call in calls) { if (call.IsDirect) { callsToOverrides.Add(call); } cancellationToken.ThrowIfCancellationRequested(); } } return callsToOverrides; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders { internal class CallToOverrideFinder : AbstractCallFinder { public CallToOverrideFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider) : base(symbol, projectId, asyncListener, provider) { } public override string DisplayName => EditorFeaturesResources.Calls_To_Overrides; protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken) { var overrides = await SymbolFinder.FindOverridesAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); var callsToOverrides = new List<SymbolCallerInfo>(); foreach (var @override in overrides) { var calls = await SymbolFinder.FindCallersAsync(@override, project.Solution, documents, cancellationToken).ConfigureAwait(false); foreach (var call in calls) { if (call.IsDirect) { callsToOverrides.Add(call); } cancellationToken.ThrowIfCancellationRequested(); } } return callsToOverrides; } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/CSharp/Portable/UsePatternMatching/CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching { /// <summary> /// DiagnosticAnalyzer that looks for is-tests and cast-expressions, and offers to convert them /// to use patterns. i.e. if the user has <c>obj is TestFile &amp;&amp; ((TestFile)obj).Name == "Test"</c> /// it will offer to convert that <c>obj is TestFile file &amp;&amp; file.Name == "Test"</c>. /// /// Complements <see cref="CSharpIsAndCastCheckDiagnosticAnalyzer"/> (which does the same, /// but only for code cases where the user has provided an appropriate variable name in /// code that can be used). /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { private const string CS0165 = nameof(CS0165); // Use of unassigned local variable 's' private const string CS0103 = nameof(CS0103); // Name of the variable doesn't live in context private static readonly SyntaxAnnotation s_referenceAnnotation = new SyntaxAnnotation(); public static readonly CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer Instance = new CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer(); public CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer() : base(IDEDiagnosticIds.InlineIsTypeWithoutNameCheckDiagnosticsId, EnforceOnBuildValues.InlineIsTypeWithoutName, CSharpCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck, LanguageNames.CSharp, new LocalizableResourceString( nameof(CSharpAnalyzersResources.Use_pattern_matching), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(SyntaxNodeAction, SyntaxKind.IsExpression); private void SyntaxNodeAction(SyntaxNodeAnalysisContext context) { var cancellationToken = context.CancellationToken; var semanticModel = context.SemanticModel; var syntaxTree = semanticModel.SyntaxTree; // "x is Type y" is only available in C# 7.0 and above. Don't offer this refactoring // in projects targeting a lesser version. if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp7) { return; } var styleOption = context.GetOption(CSharpCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck); if (!styleOption.Value) { // User has disabled this feature. return; } var isExpression = (BinaryExpressionSyntax)context.Node; // See if this is an 'is' expression that would be handled by the analyzer. If so // we don't need to do anything. if (CSharpIsAndCastCheckDiagnosticAnalyzer.TryGetPatternPieces( isExpression, out _, out _, out _, out _)) { return; } var (matches, _) = AnalyzeExpression(semanticModel, isExpression, cancellationToken); if (matches == null || matches.Count == 0) { return; } context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, isExpression.GetLocation(), styleOption.Notification.Severity, SpecializedCollections.EmptyCollection<Location>(), ImmutableDictionary<string, string>.Empty)); } public (HashSet<CastExpressionSyntax>, string localName) AnalyzeExpression( SemanticModel semanticModel, BinaryExpressionSyntax isExpression, CancellationToken cancellationToken) { var container = GetContainer(isExpression); if (container == null) { return default; } var expr = isExpression.Left.WalkDownParentheses(); var type = (TypeSyntax)isExpression.Right; var typeSymbol = semanticModel.GetTypeInfo(type, cancellationToken).Type; if (typeSymbol == null || typeSymbol.IsNullable()) { // not legal to write "(x is int? y)" return default; } // First, find all the potential cast locations we can replace with a reference to // our new local. var matches = new HashSet<CastExpressionSyntax>(); AddMatches(container, expr, type, matches); if (matches.Count == 0) { return default; } // Find a reasonable name for the local we're going to make. It should ideally // relate to the type the user is casting to, and it should not collide with anything // in scope. var reservedNames = semanticModel.LookupSymbols(isExpression.SpanStart) .Concat(semanticModel.GetExistingSymbols(container, cancellationToken)) .Select(s => s.Name) .ToSet(); var localName = NameGenerator.EnsureUniqueness( SyntaxGeneratorExtensions.GetLocalName(typeSymbol), reservedNames).EscapeIdentifier(); // Now, go and actually try to make the change. This will allow us to see all the // locations that we updated to see if that caused an error. var tempMatches = new HashSet<CastExpressionSyntax>(); foreach (var castExpression in matches.ToArray()) { tempMatches.Add(castExpression); var updatedSemanticModel = ReplaceMatches( semanticModel, isExpression, localName, tempMatches, cancellationToken); tempMatches.Clear(); var causesError = ReplacementCausesError(updatedSemanticModel, cancellationToken); if (causesError) { matches.Remove(castExpression); } } return (matches, localName); } private static bool ReplacementCausesError( SemanticModel updatedSemanticModel, CancellationToken cancellationToken) { var root = updatedSemanticModel.SyntaxTree.GetRoot(cancellationToken); var currentNode = root.GetAnnotatedNodes(s_referenceAnnotation).Single(); var diagnostics = updatedSemanticModel.GetDiagnostics(currentNode.Span, cancellationToken); return diagnostics.Any(d => d.Id == CS0165 || d.Id == CS0103); } public static SemanticModel ReplaceMatches( SemanticModel semanticModel, BinaryExpressionSyntax isExpression, string localName, HashSet<CastExpressionSyntax> matches, CancellationToken cancellationToken) { var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); var editor = new SyntaxEditor(root, CSharpSyntaxGenerator.Instance); // now, replace "x is Y" with "x is Y y" and put a rename-annotation on 'y' so that // the user can actually name the variable whatever they want. var newLocalName = SyntaxFactory.Identifier(localName) .WithAdditionalAnnotations(RenameAnnotation.Create()); var isPattern = SyntaxFactory.IsPatternExpression( isExpression.Left, isExpression.OperatorToken, SyntaxFactory.DeclarationPattern((TypeSyntax)isExpression.Right.WithTrailingTrivia(SyntaxFactory.Space), SyntaxFactory.SingleVariableDesignation(newLocalName))).WithTriviaFrom(isExpression); editor.ReplaceNode(isExpression, isPattern); // Now, go through all the "(Y)x" casts and replace them with just "y". var localReference = SyntaxFactory.IdentifierName(localName); foreach (var castExpression in matches) { var castRoot = castExpression.WalkUpParentheses(); editor.ReplaceNode( castRoot, localReference.WithTriviaFrom(castRoot) .WithAdditionalAnnotations(s_referenceAnnotation)); } var changedRoot = editor.GetChangedRoot(); var updatedSyntaxTree = semanticModel.SyntaxTree.WithRootAndOptions( changedRoot, semanticModel.SyntaxTree.Options); var updatedCompilation = semanticModel.Compilation.ReplaceSyntaxTree( semanticModel.SyntaxTree, updatedSyntaxTree); #pragma warning disable RS1030 // Do not invoke Compilation.GetSemanticModel() method within a diagnostic analyzer return updatedCompilation.GetSemanticModel(updatedSyntaxTree); #pragma warning restore RS1030 // Do not invoke Compilation.GetSemanticModel() method within a diagnostic analyzer } private static SyntaxNode GetContainer(BinaryExpressionSyntax isExpression) { for (SyntaxNode current = isExpression; current != null; current = current.Parent) { switch (current) { case StatementSyntax statement: return statement; case LambdaExpressionSyntax lambda: return lambda.Body; case ArrowExpressionClauseSyntax arrowExpression: return arrowExpression.Expression; case EqualsValueClauseSyntax equalsValue: return equalsValue.Value; } } return null; } private void AddMatches( SyntaxNode node, ExpressionSyntax expr, TypeSyntax type, HashSet<CastExpressionSyntax> matches) { // Don't bother recursing down nodes that are before the type in the is-expression. if (node.Span.End >= type.Span.End) { if (node.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression)) { if (SyntaxFactory.AreEquivalent(castExpression.Type, type) && SyntaxFactory.AreEquivalent(castExpression.Expression.WalkDownParentheses(), expr)) { matches.Add(castExpression); } } foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) { AddMatches(child.AsNode(), expr, type, matches); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching { /// <summary> /// DiagnosticAnalyzer that looks for is-tests and cast-expressions, and offers to convert them /// to use patterns. i.e. if the user has <c>obj is TestFile &amp;&amp; ((TestFile)obj).Name == "Test"</c> /// it will offer to convert that <c>obj is TestFile file &amp;&amp; file.Name == "Test"</c>. /// /// Complements <see cref="CSharpIsAndCastCheckDiagnosticAnalyzer"/> (which does the same, /// but only for code cases where the user has provided an appropriate variable name in /// code that can be used). /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { private const string CS0165 = nameof(CS0165); // Use of unassigned local variable 's' private const string CS0103 = nameof(CS0103); // Name of the variable doesn't live in context private static readonly SyntaxAnnotation s_referenceAnnotation = new SyntaxAnnotation(); public static readonly CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer Instance = new CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer(); public CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer() : base(IDEDiagnosticIds.InlineIsTypeWithoutNameCheckDiagnosticsId, EnforceOnBuildValues.InlineIsTypeWithoutName, CSharpCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck, LanguageNames.CSharp, new LocalizableResourceString( nameof(CSharpAnalyzersResources.Use_pattern_matching), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(SyntaxNodeAction, SyntaxKind.IsExpression); private void SyntaxNodeAction(SyntaxNodeAnalysisContext context) { var cancellationToken = context.CancellationToken; var semanticModel = context.SemanticModel; var syntaxTree = semanticModel.SyntaxTree; // "x is Type y" is only available in C# 7.0 and above. Don't offer this refactoring // in projects targeting a lesser version. if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp7) { return; } var styleOption = context.GetOption(CSharpCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck); if (!styleOption.Value) { // User has disabled this feature. return; } var isExpression = (BinaryExpressionSyntax)context.Node; // See if this is an 'is' expression that would be handled by the analyzer. If so // we don't need to do anything. if (CSharpIsAndCastCheckDiagnosticAnalyzer.TryGetPatternPieces( isExpression, out _, out _, out _, out _)) { return; } var (matches, _) = AnalyzeExpression(semanticModel, isExpression, cancellationToken); if (matches == null || matches.Count == 0) { return; } context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, isExpression.GetLocation(), styleOption.Notification.Severity, SpecializedCollections.EmptyCollection<Location>(), ImmutableDictionary<string, string>.Empty)); } public (HashSet<CastExpressionSyntax>, string localName) AnalyzeExpression( SemanticModel semanticModel, BinaryExpressionSyntax isExpression, CancellationToken cancellationToken) { var container = GetContainer(isExpression); if (container == null) { return default; } var expr = isExpression.Left.WalkDownParentheses(); var type = (TypeSyntax)isExpression.Right; var typeSymbol = semanticModel.GetTypeInfo(type, cancellationToken).Type; if (typeSymbol == null || typeSymbol.IsNullable()) { // not legal to write "(x is int? y)" return default; } // First, find all the potential cast locations we can replace with a reference to // our new local. var matches = new HashSet<CastExpressionSyntax>(); AddMatches(container, expr, type, matches); if (matches.Count == 0) { return default; } // Find a reasonable name for the local we're going to make. It should ideally // relate to the type the user is casting to, and it should not collide with anything // in scope. var reservedNames = semanticModel.LookupSymbols(isExpression.SpanStart) .Concat(semanticModel.GetExistingSymbols(container, cancellationToken)) .Select(s => s.Name) .ToSet(); var localName = NameGenerator.EnsureUniqueness( SyntaxGeneratorExtensions.GetLocalName(typeSymbol), reservedNames).EscapeIdentifier(); // Now, go and actually try to make the change. This will allow us to see all the // locations that we updated to see if that caused an error. var tempMatches = new HashSet<CastExpressionSyntax>(); foreach (var castExpression in matches.ToArray()) { tempMatches.Add(castExpression); var updatedSemanticModel = ReplaceMatches( semanticModel, isExpression, localName, tempMatches, cancellationToken); tempMatches.Clear(); var causesError = ReplacementCausesError(updatedSemanticModel, cancellationToken); if (causesError) { matches.Remove(castExpression); } } return (matches, localName); } private static bool ReplacementCausesError( SemanticModel updatedSemanticModel, CancellationToken cancellationToken) { var root = updatedSemanticModel.SyntaxTree.GetRoot(cancellationToken); var currentNode = root.GetAnnotatedNodes(s_referenceAnnotation).Single(); var diagnostics = updatedSemanticModel.GetDiagnostics(currentNode.Span, cancellationToken); return diagnostics.Any(d => d.Id == CS0165 || d.Id == CS0103); } public static SemanticModel ReplaceMatches( SemanticModel semanticModel, BinaryExpressionSyntax isExpression, string localName, HashSet<CastExpressionSyntax> matches, CancellationToken cancellationToken) { var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); var editor = new SyntaxEditor(root, CSharpSyntaxGenerator.Instance); // now, replace "x is Y" with "x is Y y" and put a rename-annotation on 'y' so that // the user can actually name the variable whatever they want. var newLocalName = SyntaxFactory.Identifier(localName) .WithAdditionalAnnotations(RenameAnnotation.Create()); var isPattern = SyntaxFactory.IsPatternExpression( isExpression.Left, isExpression.OperatorToken, SyntaxFactory.DeclarationPattern((TypeSyntax)isExpression.Right.WithTrailingTrivia(SyntaxFactory.Space), SyntaxFactory.SingleVariableDesignation(newLocalName))).WithTriviaFrom(isExpression); editor.ReplaceNode(isExpression, isPattern); // Now, go through all the "(Y)x" casts and replace them with just "y". var localReference = SyntaxFactory.IdentifierName(localName); foreach (var castExpression in matches) { var castRoot = castExpression.WalkUpParentheses(); editor.ReplaceNode( castRoot, localReference.WithTriviaFrom(castRoot) .WithAdditionalAnnotations(s_referenceAnnotation)); } var changedRoot = editor.GetChangedRoot(); var updatedSyntaxTree = semanticModel.SyntaxTree.WithRootAndOptions( changedRoot, semanticModel.SyntaxTree.Options); var updatedCompilation = semanticModel.Compilation.ReplaceSyntaxTree( semanticModel.SyntaxTree, updatedSyntaxTree); #pragma warning disable RS1030 // Do not invoke Compilation.GetSemanticModel() method within a diagnostic analyzer return updatedCompilation.GetSemanticModel(updatedSyntaxTree); #pragma warning restore RS1030 // Do not invoke Compilation.GetSemanticModel() method within a diagnostic analyzer } private static SyntaxNode GetContainer(BinaryExpressionSyntax isExpression) { for (SyntaxNode current = isExpression; current != null; current = current.Parent) { switch (current) { case StatementSyntax statement: return statement; case LambdaExpressionSyntax lambda: return lambda.Body; case ArrowExpressionClauseSyntax arrowExpression: return arrowExpression.Expression; case EqualsValueClauseSyntax equalsValue: return equalsValue.Value; } } return null; } private void AddMatches( SyntaxNode node, ExpressionSyntax expr, TypeSyntax type, HashSet<CastExpressionSyntax> matches) { // Don't bother recursing down nodes that are before the type in the is-expression. if (node.Span.End >= type.Span.End) { if (node.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression)) { if (SyntaxFactory.AreEquivalent(castExpression.Type, type) && SyntaxFactory.AreEquivalent(castExpression.Expression.WalkDownParentheses(), expr)) { matches.Add(castExpression); } } foreach (var child in node.ChildNodesAndTokens()) { if (child.IsNode) { AddMatches(child.AsNode(), expr, type, matches); } } } } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/PseudoVariableTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class PseudoVariableTests : ExpressionCompilerTestBase { [Fact] public void UnrecognizedVariable() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; Evaluate(runtime, "C.M", "$v", out error); Assert.Equal("error CS0103: The name '$v' does not exist in the current context", error); }); } [Fact] public void GlobalName() { var source = @"class C { static void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "global::$exception", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0400: The type or namespace name '$exception' could not be found in the global namespace (are you missing an assembly reference?)", error); } [Fact] public void QualifiedName() { var source = @"class C { void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( "this.$exception", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); Assert.Equal("error CS1061: 'C' does not contain a definition for '$exception' and no accessible extension method '$exception' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)", error); }); } /// <summary> /// Generate call to intrinsic method for $exception, /// $stowedexception. /// </summary> [Fact] public void Exception() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ExceptionAlias(typeof(System.IO.IOException)), ExceptionAlias(typeof(InvalidOperationException), stowed: true)); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "(System.Exception)$exception ?? $stowedexception", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 25 (0x19) .maxstack 2 IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: castclass ""System.IO.IOException"" IL_000a: dup IL_000b: brtrue.s IL_0018 IL_000d: pop IL_000e: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetStowedException()"" IL_0013: castclass ""System.InvalidOperationException"" IL_0018: ret }"); }); } [Fact] public void ReturnValue() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ReturnValueAlias(type: typeof(object)), ReturnValueAlias(2, typeof(string))); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "$ReturnValue ?? $ReturnValue2", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 22 (0x16) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: dup IL_0007: brtrue.s IL_0015 IL_0009: pop IL_000a: ldc.i4.2 IL_000b: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0010: castclass ""string"" IL_0015: ret }"); // Value type $ReturnValue. context = CreateMethodContext( runtime, "C.M"); aliases = ImmutableArray.Create( ReturnValueAlias(type: typeof(int?))); testData = new CompilationTestData(); result = context.CompileExpression( "((int?)$ReturnValue).HasValue", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 20 (0x14) .maxstack 1 .locals init (int? V_0) IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: unbox.any ""int?"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: call ""bool int?.HasValue.get"" IL_0013: ret }"); }); } /// <summary> /// Negative index should be treated as separate tokens. /// </summary> [Fact] public void ReturnValueNegative() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; var testData = Evaluate( runtime, "C.M", "(int)$ReturnValue-2", out error, ReturnValueAlias()); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: unbox.any ""int"" IL_000b: ldc.i4.2 IL_000c: sub IL_000d: ret }"); }); } /// <summary> /// Dev12 syntax "[0-9]+#" not supported. /// </summary> [WorkItem(1071347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1071347")] [Fact] public void ObjectId_EarlierSyntax() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; context.CompileExpression( "23#", out error); Assert.Equal("error CS2043: 'id#' syntax is no longer supported. Use '$id' instead.", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void ObjectId() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( ObjectIdAlias(23, typeof(string)), ObjectIdAlias(4, typeof(Type))); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)$23 ?? $4.BaseType", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 40 (0x28) .maxstack 2 IL_0000: ldstr ""$23"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""string"" IL_000f: dup IL_0010: brtrue.s IL_0027 IL_0012: pop IL_0013: ldstr ""$4"" IL_0018: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_001d: castclass ""System.Type"" IL_0022: callvirt ""System.Type System.Type.BaseType.get"" IL_0027: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1101017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101017")] public void NestedGenericValueType() { var source = @"class C { internal struct S<T> { internal T F; } static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "C+S`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); context.CompileExpression( "s.F + 1", DkmEvaluationFlags.TreatAsExpression, aliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, null, // preferredUICulture testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 23 (0x17) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: unbox.any ""C.S<int>"" IL_000f: ldfld ""int C.S<int>.F"" IL_0014: ldc.i4.1 IL_0015: add IL_0016: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void ArrayType() { var source = @"class C { object F; static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("a", "C[]"), VariableAlias("b", "System.Int32[,], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); context.CompileExpression( "a[b[1, 0]].F", DkmEvaluationFlags.TreatAsExpression, aliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 44 (0x2c) .maxstack 4 IL_0000: ldstr ""a"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""C[]"" IL_000f: ldstr ""b"" IL_0014: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0019: castclass ""int[,]"" IL_001e: ldc.i4.1 IL_001f: ldc.i4.0 IL_0020: call ""int[*,*].Get"" IL_0025: ldelem.ref IL_0026: ldfld ""object C.F"" IL_002b: ret }"); }); } /// <summary> /// The assembly-qualified type name may be from an /// unrecognized assembly. For instance, if the type was /// defined in a previous evaluation, say an anonymous /// type (e.g.: evaluate "o" after "var o = new { P = 1 };"). /// </summary> [Fact] public void UnrecognizedAssembly() { var source = @"struct S<T> { internal T F; } class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { string error; var testData = new CompilationTestData(); // Unrecognized type. var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("o", "T, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24AB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); context.CompileExpression( "o.P", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal("error CS0648: '' is a type not supported by the language", error); // Unrecognized array element type. aliases = ImmutableArray.Create( VariableAlias("a", "T[], 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24AB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); context.CompileExpression( "a[0].P", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal("error CS0648: '' is a type not supported by the language", error); // Unrecognized generic type argument. aliases = ImmutableArray.Create( VariableAlias("s", "S`1[[T, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24AB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]")); context.CompileExpression( "s.F", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal("error CS0648: '' is a type not supported by the language", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void Variables() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { CheckVariable(runtime, "$exception", ExceptionAlias(), valid: true); CheckVariable(runtime, "$stowedexception", ExceptionAlias(stowed: true), valid: true); CheckVariable(runtime, "$Exception", ExceptionAlias(), valid: false); CheckVariable(runtime, "$STOWEDEXCEPTION", ExceptionAlias(stowed: true), valid: false); CheckVariable(runtime, "$ReturnValue", ReturnValueAlias(), valid: true); CheckVariable(runtime, "$RETURNVALUE", ReturnValueAlias(), valid: false); CheckVariable(runtime, "$returnvalue", ReturnValueAlias(), valid: true); // Lowercase $ReturnValue supported. CheckVariable(runtime, "$ReturnValue0", ReturnValueAlias(0), valid: true); CheckVariable(runtime, "$returnvalue21", ReturnValueAlias(21), valid: true); CheckVariable(runtime, "$ReturnValue3A", ReturnValueAlias(0x3a), valid: false); CheckVariable(runtime, "$33", ObjectIdAlias(33), valid: true); CheckVariable(runtime, "$03", ObjectIdAlias(3), valid: false); CheckVariable(runtime, "$3A", ObjectIdAlias(0x3a), valid: false); CheckVariable(runtime, "$0", ObjectIdAlias(1), valid: false); CheckVariable(runtime, "$", ObjectIdAlias(1), valid: false); CheckVariable(runtime, "$Unknown", VariableAlias("x"), valid: false); }); } private void CheckVariable(RuntimeInstance runtime, string variableName, Alias alias, bool valid) { string error; var testData = Evaluate(runtime, "C.M", variableName, out error, alias); if (valid) { var expectedNames = new[] { "<>x.<>m0()" }; var actualNames = testData.GetMethodsByName().Keys; AssertEx.SetEqual(expectedNames, actualNames); } else { Assert.Equal(error, string.Format("error CS0103: The name '{0}' does not exist in the current context", variableName)); } } [Fact] public void CheckViability() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; var testData = Evaluate( runtime, "C.M", "$ReturnValue1<object>", out error, ReturnValueAlias(1)); Assert.Equal("error CS0307: The variable '$ReturnValue1' cannot be used with type arguments", error); testData = Evaluate( runtime, "C.M", "$ReturnValue2()", out error, ReturnValueAlias(2)); Assert.Equal("error CS0149: Method name expected", error); }); } /// <summary> /// $exception may be accessed from closure class. /// </summary> [Fact] public void ExceptionInDisplayClass() { var source = @"using System; class C { static object F(System.Func<object> f) { return f(); } static void M(object o) { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; var testData = Evaluate( runtime, "C.M", "F(() => o ?? $exception)", out error, ExceptionAlias()); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""object <>x.<>c__DisplayClass0_0.o"" IL_0006: dup IL_0007: brtrue.s IL_000f IL_0009: pop IL_000a: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_000f: ret }"); }); } [Fact] public void AssignException() { var source = @"class C { static void M(System.Exception e) { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ExceptionAlias()); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); context.CompileAssignment( target: "e", expr: "$exception.InnerException ?? $exception", aliases: aliases, formatter: DebuggerDiagnosticFormatter.Instance, resultProperties: out resultProperties, error: out error, missingAssemblyIdentities: out missingAssemblyIdentities, preferredUICulture: EnsureEnglishUICulture.PreferredOrNull, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 22 (0x16) .maxstack 2 IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: callvirt ""System.Exception System.Exception.InnerException.get"" IL_000a: dup IL_000b: brtrue.s IL_0013 IL_000d: pop IL_000e: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0013: starg.s V_0 IL_0015: ret }"); }); } [Fact] public void AssignToException() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; Evaluate(runtime, "C.M", "$exception = null", out error, ExceptionAlias()); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1100849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1100849")] public void PassByRef() { var source = @"class C { static T F<T>(ref T t) { t = default(T); return t; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.F"); var aliases = ImmutableArray.Create( ExceptionAlias(), ReturnValueAlias(), ObjectIdAlias(1), VariableAlias("x", typeof(int))); string error; // $exception context.CompileExpression( "$exception = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref $exception)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // Object at address context.CompileExpression( "@0x123 = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref @0x123)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // $ReturnValue context.CompileExpression( "$ReturnValue = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref $ReturnValue)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // Object id context.CompileExpression( "$1 = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref $1)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // Declared variable var testData = new CompilationTestData(); context.CompileExpression( "x = 1", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 3 .locals init (T V_0, int V_1) IL_0000: ldstr ""x"" IL_0005: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)"" IL_000a: ldc.i4.1 IL_000b: dup IL_000c: stloc.1 IL_000d: stind.i4 IL_000e: ldloc.1 IL_000f: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression( "F(ref x)", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 1 .locals init (T V_0) IL_0000: ldstr ""x"" IL_0005: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)"" IL_000a: call ""int C.F<int>(ref int)"" IL_000f: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void ValueType() { var source = @"struct S { internal object F; } class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "S")); string error; var testData = new CompilationTestData(); context.CompileExpression( "s.F = 1", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 25 (0x19) .maxstack 3 .locals init (object V_0) IL_0000: ldstr ""s"" IL_0005: call ""S Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<S>(string)"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: dup IL_0011: stloc.0 IL_0012: stfld ""object S.F"" IL_0017: ldloc.0 IL_0018: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void CompoundAssignment() { var source = @"struct S { internal int F; } class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "S")); string error; var testData = new CompilationTestData(); context.CompileExpression( "s.F += 2", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 24 (0x18) .maxstack 3 .locals init (int V_0) IL_0000: ldstr ""s"" IL_0005: call ""S Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<S>(string)"" IL_000a: ldflda ""int S.F"" IL_000f: dup IL_0010: ldind.i4 IL_0011: ldc.i4.2 IL_0012: add IL_0013: dup IL_0014: stloc.0 IL_0015: stind.i4 IL_0016: ldloc.0 IL_0017: ret }"); }); } /// <summary> /// Assembly-qualified type names from the debugger refer to runtime assemblies /// which may be different versions than the assembly references in metadata. /// </summary> [WorkItem(1087458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087458")] [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void DifferentAssemblyVersion() { var sourceA = @"public class A<T> { }"; var sourceB = @"class B<T> { } class C { static void M() { var o = new A<object>(); } }"; const string assemblyNameA = "397300B0-A"; const string assemblyNameB = "397300B0-B"; var publicKeyA = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD }); var compilationA1 = CreateCompilation( new AssemblyIdentity(assemblyNameA, new Version(1, 1, 1, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true), new[] { sourceA }, references: new[] { MscorlibRef_v20 }, options: TestOptions.DebugDll.WithDelaySign(true)); var compilationB1 = CreateCompilation( new AssemblyIdentity(assemblyNameB, new Version(1, 2, 2, 2)), new[] { sourceB }, references: new[] { MscorlibRef_v20, compilationA1.EmitToImageReference() }, options: TestOptions.DebugDll); // Use mscorlib v4.0.0.0 and A v2.1.2.1 at runtime. var compilationA2 = CreateCompilation( new AssemblyIdentity(assemblyNameA, new Version(2, 1, 2, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true), new[] { sourceA }, references: new[] { MscorlibRef_v20 }, options: TestOptions.DebugDll.WithDelaySign(true)); WithRuntimeInstance(compilationB1, new[] { MscorlibRef, compilationA2.EmitToImageReference() }, runtime => { // typeof(Exception), typeof(A<B<object>>), typeof(B<A<object>[]>) var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ExceptionAlias("System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), ObjectIdAlias(1, "A`1[[B`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], 397300B0-B, Version=1.2.2.2, Culture=neutral, PublicKeyToken=null]], 397300B0-A, Version=2.1.2.1, Culture=neutral, PublicKeyToken=1f8a32457d187bf3"), ObjectIdAlias(2, "B`1[[A`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]][], 397300B0-A, Version=2.1.2.1, Culture=neutral, PublicKeyToken=1f8a32457d187bf3]], 397300B0-B, Version=1.2.2.2, Culture=neutral, PublicKeyToken=null")); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)$exception ?? (object)$1 ?? $2", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 44 (0x2c) .maxstack 2 .locals init (A<object> V_0) //o IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: dup IL_0006: brtrue.s IL_002b IL_0008: pop IL_0009: ldstr ""$1"" IL_000e: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0013: castclass ""A<B<object>>"" IL_0018: dup IL_0019: brtrue.s IL_002b IL_001b: pop IL_001c: ldstr ""$2"" IL_0021: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0026: castclass ""B<A<object>[]>"" IL_002b: ret }"); }); } /// <summary> /// The assembly-qualified type may reference an assembly /// outside of the current module and its references. /// </summary> [WorkItem(1092680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1092680")] [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void TypeOutsideModule() { var sourceA = @"using System; public class A<T> { public static void M(Action f) { object o; try { f(); } catch (Exception) { } } }"; var sourceB = @"using System; class E : Exception { internal object F; } class B { static void Main() { A<int>.M(() => { throw new E(); }); } }"; var assemblyNameA = "0A93FF0B-31A2-47C8-B24D-16A2D77AB5C5"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: assemblyNameA); var moduleA = compilationA.ToModuleInstance(); var assemblyNameB = "9BAC6622-86EB-4EC5-94A1-9A1E6D0C24B9"; var compilationB = CreateCompilation(sourceB, options: TestOptions.DebugExe, references: new[] { moduleA.GetReference() }, assemblyName: assemblyNameB); var moduleB = compilationB.ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { MscorlibRef.ToModuleInstance() , moduleA, moduleB, ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance() }); var context = CreateMethodContext(runtime, "A.M"); var aliases = ImmutableArray.Create( ExceptionAlias("E, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24B9, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), ObjectIdAlias(1, "A`1[[B, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24B9, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], 0A93FF0B-31A2-47C8-B24D-16A2D77AB5C5, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); string error; var testData = new CompilationTestData(); context.CompileExpression( "$exception", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T>.<>m0").VerifyIL( @"{ // Code size 11 (0xb) .maxstack 1 .locals init (object V_0) //o IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: castclass ""E"" IL_000a: ret }"); ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; testData = new CompilationTestData(); context.CompileAssignment( "o", "$1", aliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); Assert.Null(error); testData.GetMethodData("<>x<T>.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 1 .locals init (object V_0) //o IL_0000: ldstr ""$1"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""A<B>"" IL_000f: stloc.0 IL_0010: ret }"); } [WorkItem(1140387, "DevDiv")] [Fact] public void ReturnValueOfPointerType() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create(ReturnValueAlias(type: typeof(int*))); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "$ReturnValue", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(SpecialType.System_Int32, ((PointerTypeSymbol)((MethodSymbol)methodData.Method).ReturnType).PointedAtType.SpecialType); methodData.VerifyIL( @"{ // Code size 17 (0x11) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: unbox.any ""System.IntPtr"" IL_000b: call ""void* System.IntPtr.op_Explicit(System.IntPtr)"" IL_0010: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1140387, "DevDiv")] public void UserVariableOfPointerType() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create(VariableAlias("p", typeof(char*))); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "p", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(SpecialType.System_Char, ((PointerTypeSymbol)((MethodSymbol)methodData.Method).ReturnType).PointedAtType.SpecialType); methodData.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 1 IL_0000: ldstr ""p"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: unbox.any ""System.IntPtr"" IL_000f: call ""void* System.IntPtr.op_Explicit(System.IntPtr)"" IL_0014: ret }"); }); } private CompilationTestData Evaluate( RuntimeInstance runtime, string methodName, string expr, out string error, params Alias[] aliases) { var context = CreateMethodContext(runtime, methodName); var testData = new CompilationTestData(); var result = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, ImmutableArray.Create(aliases), out error, testData); return testData; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class PseudoVariableTests : ExpressionCompilerTestBase { [Fact] public void UnrecognizedVariable() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; Evaluate(runtime, "C.M", "$v", out error); Assert.Equal("error CS0103: The name '$v' does not exist in the current context", error); }); } [Fact] public void GlobalName() { var source = @"class C { static void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "global::$exception", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0400: The type or namespace name '$exception' could not be found in the global namespace (are you missing an assembly reference?)", error); } [Fact] public void QualifiedName() { var source = @"class C { void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( "this.$exception", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); Assert.Equal("error CS1061: 'C' does not contain a definition for '$exception' and no accessible extension method '$exception' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)", error); }); } /// <summary> /// Generate call to intrinsic method for $exception, /// $stowedexception. /// </summary> [Fact] public void Exception() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ExceptionAlias(typeof(System.IO.IOException)), ExceptionAlias(typeof(InvalidOperationException), stowed: true)); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "(System.Exception)$exception ?? $stowedexception", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 25 (0x19) .maxstack 2 IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: castclass ""System.IO.IOException"" IL_000a: dup IL_000b: brtrue.s IL_0018 IL_000d: pop IL_000e: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetStowedException()"" IL_0013: castclass ""System.InvalidOperationException"" IL_0018: ret }"); }); } [Fact] public void ReturnValue() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ReturnValueAlias(type: typeof(object)), ReturnValueAlias(2, typeof(string))); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "$ReturnValue ?? $ReturnValue2", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 22 (0x16) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: dup IL_0007: brtrue.s IL_0015 IL_0009: pop IL_000a: ldc.i4.2 IL_000b: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0010: castclass ""string"" IL_0015: ret }"); // Value type $ReturnValue. context = CreateMethodContext( runtime, "C.M"); aliases = ImmutableArray.Create( ReturnValueAlias(type: typeof(int?))); testData = new CompilationTestData(); result = context.CompileExpression( "((int?)$ReturnValue).HasValue", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 20 (0x14) .maxstack 1 .locals init (int? V_0) IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: unbox.any ""int?"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: call ""bool int?.HasValue.get"" IL_0013: ret }"); }); } /// <summary> /// Negative index should be treated as separate tokens. /// </summary> [Fact] public void ReturnValueNegative() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; var testData = Evaluate( runtime, "C.M", "(int)$ReturnValue-2", out error, ReturnValueAlias()); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: unbox.any ""int"" IL_000b: ldc.i4.2 IL_000c: sub IL_000d: ret }"); }); } /// <summary> /// Dev12 syntax "[0-9]+#" not supported. /// </summary> [WorkItem(1071347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1071347")] [Fact] public void ObjectId_EarlierSyntax() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; context.CompileExpression( "23#", out error); Assert.Equal("error CS2043: 'id#' syntax is no longer supported. Use '$id' instead.", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void ObjectId() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( ObjectIdAlias(23, typeof(string)), ObjectIdAlias(4, typeof(Type))); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)$23 ?? $4.BaseType", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 40 (0x28) .maxstack 2 IL_0000: ldstr ""$23"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""string"" IL_000f: dup IL_0010: brtrue.s IL_0027 IL_0012: pop IL_0013: ldstr ""$4"" IL_0018: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_001d: castclass ""System.Type"" IL_0022: callvirt ""System.Type System.Type.BaseType.get"" IL_0027: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1101017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101017")] public void NestedGenericValueType() { var source = @"class C { internal struct S<T> { internal T F; } static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "C+S`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); context.CompileExpression( "s.F + 1", DkmEvaluationFlags.TreatAsExpression, aliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, null, // preferredUICulture testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 23 (0x17) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: unbox.any ""C.S<int>"" IL_000f: ldfld ""int C.S<int>.F"" IL_0014: ldc.i4.1 IL_0015: add IL_0016: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void ArrayType() { var source = @"class C { object F; static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("a", "C[]"), VariableAlias("b", "System.Int32[,], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); context.CompileExpression( "a[b[1, 0]].F", DkmEvaluationFlags.TreatAsExpression, aliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 44 (0x2c) .maxstack 4 IL_0000: ldstr ""a"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""C[]"" IL_000f: ldstr ""b"" IL_0014: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0019: castclass ""int[,]"" IL_001e: ldc.i4.1 IL_001f: ldc.i4.0 IL_0020: call ""int[*,*].Get"" IL_0025: ldelem.ref IL_0026: ldfld ""object C.F"" IL_002b: ret }"); }); } /// <summary> /// The assembly-qualified type name may be from an /// unrecognized assembly. For instance, if the type was /// defined in a previous evaluation, say an anonymous /// type (e.g.: evaluate "o" after "var o = new { P = 1 };"). /// </summary> [Fact] public void UnrecognizedAssembly() { var source = @"struct S<T> { internal T F; } class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { string error; var testData = new CompilationTestData(); // Unrecognized type. var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("o", "T, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24AB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); context.CompileExpression( "o.P", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal("error CS0648: '' is a type not supported by the language", error); // Unrecognized array element type. aliases = ImmutableArray.Create( VariableAlias("a", "T[], 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24AB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); context.CompileExpression( "a[0].P", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal("error CS0648: '' is a type not supported by the language", error); // Unrecognized generic type argument. aliases = ImmutableArray.Create( VariableAlias("s", "S`1[[T, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24AB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]")); context.CompileExpression( "s.F", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal("error CS0648: '' is a type not supported by the language", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void Variables() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { CheckVariable(runtime, "$exception", ExceptionAlias(), valid: true); CheckVariable(runtime, "$stowedexception", ExceptionAlias(stowed: true), valid: true); CheckVariable(runtime, "$Exception", ExceptionAlias(), valid: false); CheckVariable(runtime, "$STOWEDEXCEPTION", ExceptionAlias(stowed: true), valid: false); CheckVariable(runtime, "$ReturnValue", ReturnValueAlias(), valid: true); CheckVariable(runtime, "$RETURNVALUE", ReturnValueAlias(), valid: false); CheckVariable(runtime, "$returnvalue", ReturnValueAlias(), valid: true); // Lowercase $ReturnValue supported. CheckVariable(runtime, "$ReturnValue0", ReturnValueAlias(0), valid: true); CheckVariable(runtime, "$returnvalue21", ReturnValueAlias(21), valid: true); CheckVariable(runtime, "$ReturnValue3A", ReturnValueAlias(0x3a), valid: false); CheckVariable(runtime, "$33", ObjectIdAlias(33), valid: true); CheckVariable(runtime, "$03", ObjectIdAlias(3), valid: false); CheckVariable(runtime, "$3A", ObjectIdAlias(0x3a), valid: false); CheckVariable(runtime, "$0", ObjectIdAlias(1), valid: false); CheckVariable(runtime, "$", ObjectIdAlias(1), valid: false); CheckVariable(runtime, "$Unknown", VariableAlias("x"), valid: false); }); } private void CheckVariable(RuntimeInstance runtime, string variableName, Alias alias, bool valid) { string error; var testData = Evaluate(runtime, "C.M", variableName, out error, alias); if (valid) { var expectedNames = new[] { "<>x.<>m0()" }; var actualNames = testData.GetMethodsByName().Keys; AssertEx.SetEqual(expectedNames, actualNames); } else { Assert.Equal(error, string.Format("error CS0103: The name '{0}' does not exist in the current context", variableName)); } } [Fact] public void CheckViability() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; var testData = Evaluate( runtime, "C.M", "$ReturnValue1<object>", out error, ReturnValueAlias(1)); Assert.Equal("error CS0307: The variable '$ReturnValue1' cannot be used with type arguments", error); testData = Evaluate( runtime, "C.M", "$ReturnValue2()", out error, ReturnValueAlias(2)); Assert.Equal("error CS0149: Method name expected", error); }); } /// <summary> /// $exception may be accessed from closure class. /// </summary> [Fact] public void ExceptionInDisplayClass() { var source = @"using System; class C { static object F(System.Func<object> f) { return f(); } static void M(object o) { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; var testData = Evaluate( runtime, "C.M", "F(() => o ?? $exception)", out error, ExceptionAlias()); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""object <>x.<>c__DisplayClass0_0.o"" IL_0006: dup IL_0007: brtrue.s IL_000f IL_0009: pop IL_000a: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_000f: ret }"); }); } [Fact] public void AssignException() { var source = @"class C { static void M(System.Exception e) { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ExceptionAlias()); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); context.CompileAssignment( target: "e", expr: "$exception.InnerException ?? $exception", aliases: aliases, formatter: DebuggerDiagnosticFormatter.Instance, resultProperties: out resultProperties, error: out error, missingAssemblyIdentities: out missingAssemblyIdentities, preferredUICulture: EnsureEnglishUICulture.PreferredOrNull, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 22 (0x16) .maxstack 2 IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: callvirt ""System.Exception System.Exception.InnerException.get"" IL_000a: dup IL_000b: brtrue.s IL_0013 IL_000d: pop IL_000e: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0013: starg.s V_0 IL_0015: ret }"); }); } [Fact] public void AssignToException() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; Evaluate(runtime, "C.M", "$exception = null", out error, ExceptionAlias()); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1100849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1100849")] public void PassByRef() { var source = @"class C { static T F<T>(ref T t) { t = default(T); return t; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.F"); var aliases = ImmutableArray.Create( ExceptionAlias(), ReturnValueAlias(), ObjectIdAlias(1), VariableAlias("x", typeof(int))); string error; // $exception context.CompileExpression( "$exception = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref $exception)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // Object at address context.CompileExpression( "@0x123 = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref @0x123)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // $ReturnValue context.CompileExpression( "$ReturnValue = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref $ReturnValue)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // Object id context.CompileExpression( "$1 = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref $1)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // Declared variable var testData = new CompilationTestData(); context.CompileExpression( "x = 1", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 3 .locals init (T V_0, int V_1) IL_0000: ldstr ""x"" IL_0005: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)"" IL_000a: ldc.i4.1 IL_000b: dup IL_000c: stloc.1 IL_000d: stind.i4 IL_000e: ldloc.1 IL_000f: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression( "F(ref x)", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 1 .locals init (T V_0) IL_0000: ldstr ""x"" IL_0005: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)"" IL_000a: call ""int C.F<int>(ref int)"" IL_000f: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void ValueType() { var source = @"struct S { internal object F; } class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "S")); string error; var testData = new CompilationTestData(); context.CompileExpression( "s.F = 1", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 25 (0x19) .maxstack 3 .locals init (object V_0) IL_0000: ldstr ""s"" IL_0005: call ""S Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<S>(string)"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: dup IL_0011: stloc.0 IL_0012: stfld ""object S.F"" IL_0017: ldloc.0 IL_0018: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void CompoundAssignment() { var source = @"struct S { internal int F; } class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "S")); string error; var testData = new CompilationTestData(); context.CompileExpression( "s.F += 2", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 24 (0x18) .maxstack 3 .locals init (int V_0) IL_0000: ldstr ""s"" IL_0005: call ""S Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<S>(string)"" IL_000a: ldflda ""int S.F"" IL_000f: dup IL_0010: ldind.i4 IL_0011: ldc.i4.2 IL_0012: add IL_0013: dup IL_0014: stloc.0 IL_0015: stind.i4 IL_0016: ldloc.0 IL_0017: ret }"); }); } /// <summary> /// Assembly-qualified type names from the debugger refer to runtime assemblies /// which may be different versions than the assembly references in metadata. /// </summary> [WorkItem(1087458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087458")] [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void DifferentAssemblyVersion() { var sourceA = @"public class A<T> { }"; var sourceB = @"class B<T> { } class C { static void M() { var o = new A<object>(); } }"; const string assemblyNameA = "397300B0-A"; const string assemblyNameB = "397300B0-B"; var publicKeyA = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD }); var compilationA1 = CreateCompilation( new AssemblyIdentity(assemblyNameA, new Version(1, 1, 1, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true), new[] { sourceA }, references: new[] { MscorlibRef_v20 }, options: TestOptions.DebugDll.WithDelaySign(true)); var compilationB1 = CreateCompilation( new AssemblyIdentity(assemblyNameB, new Version(1, 2, 2, 2)), new[] { sourceB }, references: new[] { MscorlibRef_v20, compilationA1.EmitToImageReference() }, options: TestOptions.DebugDll); // Use mscorlib v4.0.0.0 and A v2.1.2.1 at runtime. var compilationA2 = CreateCompilation( new AssemblyIdentity(assemblyNameA, new Version(2, 1, 2, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true), new[] { sourceA }, references: new[] { MscorlibRef_v20 }, options: TestOptions.DebugDll.WithDelaySign(true)); WithRuntimeInstance(compilationB1, new[] { MscorlibRef, compilationA2.EmitToImageReference() }, runtime => { // typeof(Exception), typeof(A<B<object>>), typeof(B<A<object>[]>) var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ExceptionAlias("System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), ObjectIdAlias(1, "A`1[[B`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], 397300B0-B, Version=1.2.2.2, Culture=neutral, PublicKeyToken=null]], 397300B0-A, Version=2.1.2.1, Culture=neutral, PublicKeyToken=1f8a32457d187bf3"), ObjectIdAlias(2, "B`1[[A`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]][], 397300B0-A, Version=2.1.2.1, Culture=neutral, PublicKeyToken=1f8a32457d187bf3]], 397300B0-B, Version=1.2.2.2, Culture=neutral, PublicKeyToken=null")); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)$exception ?? (object)$1 ?? $2", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 44 (0x2c) .maxstack 2 .locals init (A<object> V_0) //o IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: dup IL_0006: brtrue.s IL_002b IL_0008: pop IL_0009: ldstr ""$1"" IL_000e: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0013: castclass ""A<B<object>>"" IL_0018: dup IL_0019: brtrue.s IL_002b IL_001b: pop IL_001c: ldstr ""$2"" IL_0021: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0026: castclass ""B<A<object>[]>"" IL_002b: ret }"); }); } /// <summary> /// The assembly-qualified type may reference an assembly /// outside of the current module and its references. /// </summary> [WorkItem(1092680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1092680")] [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void TypeOutsideModule() { var sourceA = @"using System; public class A<T> { public static void M(Action f) { object o; try { f(); } catch (Exception) { } } }"; var sourceB = @"using System; class E : Exception { internal object F; } class B { static void Main() { A<int>.M(() => { throw new E(); }); } }"; var assemblyNameA = "0A93FF0B-31A2-47C8-B24D-16A2D77AB5C5"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: assemblyNameA); var moduleA = compilationA.ToModuleInstance(); var assemblyNameB = "9BAC6622-86EB-4EC5-94A1-9A1E6D0C24B9"; var compilationB = CreateCompilation(sourceB, options: TestOptions.DebugExe, references: new[] { moduleA.GetReference() }, assemblyName: assemblyNameB); var moduleB = compilationB.ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { MscorlibRef.ToModuleInstance() , moduleA, moduleB, ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance() }); var context = CreateMethodContext(runtime, "A.M"); var aliases = ImmutableArray.Create( ExceptionAlias("E, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24B9, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), ObjectIdAlias(1, "A`1[[B, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24B9, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], 0A93FF0B-31A2-47C8-B24D-16A2D77AB5C5, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); string error; var testData = new CompilationTestData(); context.CompileExpression( "$exception", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T>.<>m0").VerifyIL( @"{ // Code size 11 (0xb) .maxstack 1 .locals init (object V_0) //o IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: castclass ""E"" IL_000a: ret }"); ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; testData = new CompilationTestData(); context.CompileAssignment( "o", "$1", aliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); Assert.Null(error); testData.GetMethodData("<>x<T>.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 1 .locals init (object V_0) //o IL_0000: ldstr ""$1"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""A<B>"" IL_000f: stloc.0 IL_0010: ret }"); } [WorkItem(1140387, "DevDiv")] [Fact] public void ReturnValueOfPointerType() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create(ReturnValueAlias(type: typeof(int*))); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "$ReturnValue", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(SpecialType.System_Int32, ((PointerTypeSymbol)((MethodSymbol)methodData.Method).ReturnType).PointedAtType.SpecialType); methodData.VerifyIL( @"{ // Code size 17 (0x11) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: unbox.any ""System.IntPtr"" IL_000b: call ""void* System.IntPtr.op_Explicit(System.IntPtr)"" IL_0010: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1140387, "DevDiv")] public void UserVariableOfPointerType() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create(VariableAlias("p", typeof(char*))); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "p", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(SpecialType.System_Char, ((PointerTypeSymbol)((MethodSymbol)methodData.Method).ReturnType).PointedAtType.SpecialType); methodData.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 1 IL_0000: ldstr ""p"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: unbox.any ""System.IntPtr"" IL_000f: call ""void* System.IntPtr.op_Explicit(System.IntPtr)"" IL_0014: ret }"); }); } private CompilationTestData Evaluate( RuntimeInstance runtime, string methodName, string expr, out string error, params Alias[] aliases) { var context = CreateMethodContext(runtime, methodName); var testData = new CompilationTestData(); var result = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, ImmutableArray.Create(aliases), out error, testData); return testData; } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/VisualStudio/Core/Def/Implementation/DesignerAttribute/InProcDesignerAttributeIncrementalAnalyzerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.DesignerAttribute; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.VisualStudio.LanguageServices.Implementation.DesignerAttribute { /// <remarks>Note: this is explicitly <b>not</b> exported. We don't want the Workspace /// to automatically load this. Instead, VS waits until it is ready /// and then calls into the service to tell it to start analyzing the solution. At that point we'll get /// created and added to the solution crawler. /// </remarks> internal sealed class InProcDesignerAttributeIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly IDesignerAttributeListener _listener; public InProcDesignerAttributeIncrementalAnalyzerProvider(IDesignerAttributeListener listener) { _listener = listener; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new InProcDesignerAttributeIncrementalAnalyzer(_listener); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.DesignerAttribute; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.VisualStudio.LanguageServices.Implementation.DesignerAttribute { /// <remarks>Note: this is explicitly <b>not</b> exported. We don't want the Workspace /// to automatically load this. Instead, VS waits until it is ready /// and then calls into the service to tell it to start analyzing the solution. At that point we'll get /// created and added to the solution crawler. /// </remarks> internal sealed class InProcDesignerAttributeIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly IDesignerAttributeListener _listener; public InProcDesignerAttributeIncrementalAnalyzerProvider(IDesignerAttributeListener listener) { _listener = listener; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new InProcDesignerAttributeIncrementalAnalyzer(_listener); } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Workspaces/Core/Portable/Workspace/WorkspaceDiagnosticDescriptors.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis { internal sealed class WorkspaceDiagnosticDescriptors { internal static readonly DiagnosticDescriptor ErrorReadingFileContent; internal const string ErrorReadingFileContentId = "IDE1100"; static WorkspaceDiagnosticDescriptors() { ErrorReadingFileContent = new DiagnosticDescriptor( id: ErrorReadingFileContentId, title: new LocalizableResourceString(nameof(WorkspacesResources.Workspace_error), WorkspacesResources.ResourceManager, typeof(WorkspacesResources)), messageFormat: new LocalizableResourceString(nameof(WorkspacesResources.Error_reading_content_of_source_file_0_1), WorkspacesResources.ResourceManager, typeof(WorkspacesResources)), category: WorkspacesResources.Workspace_error, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, customTags: new[] { WellKnownDiagnosticTags.NotConfigurable }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis { internal sealed class WorkspaceDiagnosticDescriptors { internal static readonly DiagnosticDescriptor ErrorReadingFileContent; internal const string ErrorReadingFileContentId = "IDE1100"; static WorkspaceDiagnosticDescriptors() { ErrorReadingFileContent = new DiagnosticDescriptor( id: ErrorReadingFileContentId, title: new LocalizableResourceString(nameof(WorkspacesResources.Workspace_error), WorkspacesResources.ResourceManager, typeof(WorkspacesResources)), messageFormat: new LocalizableResourceString(nameof(WorkspacesResources.Error_reading_content_of_source_file_0_1), WorkspacesResources.ResourceManager, typeof(WorkspacesResources)), category: WorkspacesResources.Workspace_error, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, customTags: new[] { WellKnownDiagnosticTags.NotConfigurable }); } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/EditorFeatures/Core/Shared/Extensions/ITextSelectionExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class ITextSelectionExtensions { public static NormalizedSnapshotSpanCollection GetSnapshotSpansOnBuffer(this ITextSelection selection, ITextBuffer subjectBuffer) { Contract.ThrowIfNull(selection); Contract.ThrowIfNull(subjectBuffer); var list = new List<SnapshotSpan>(); foreach (var snapshotSpan in selection.SelectedSpans) { list.AddRange(selection.TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, subjectBuffer)); } return new NormalizedSnapshotSpanCollection(list); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class ITextSelectionExtensions { public static NormalizedSnapshotSpanCollection GetSnapshotSpansOnBuffer(this ITextSelection selection, ITextBuffer subjectBuffer) { Contract.ThrowIfNull(selection); Contract.ThrowIfNull(subjectBuffer); var list = new List<SnapshotSpan>(); foreach (var snapshotSpan in selection.SelectedSpans) { list.AddRange(selection.TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, subjectBuffer)); } return new NormalizedSnapshotSpanCollection(list); } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenIncrementTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Globalization; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenIncrementTests : CSharpTestBase { //{0} is a numeric type //{1} is some value //{2} is one greater than {1} private const string NUMERIC_INCREMENT_TEMPLATE = @" class C {{ static void Main() {{ {0} x = {1}; {0} y = x++; System.Console.WriteLine(x); System.Console.WriteLine(y); x = {1}; y = ++x; System.Console.WriteLine(x); System.Console.WriteLine(y); x = {2}; y = x--; System.Console.WriteLine(x); System.Console.WriteLine(y); x = {2}; y = --x; System.Console.WriteLine(x); System.Console.WriteLine(y); }} }} "; //{0} is some value, {1} is one greater private const string NUMERIC_OUTPUT_TEMPLATE = @" {1} {0} {1} {1} {0} {1} {0} {0} "; [Fact] public void TestIncrementInt() { TestIncrementCompilationAndOutput<int>(int.MaxValue, int.MinValue); } [Fact] public void TestIncrementUInt() { TestIncrementCompilationAndOutput<uint>(uint.MaxValue, uint.MinValue); } [Fact] public void TestIncrementLong() { TestIncrementCompilationAndOutput<long>(long.MaxValue, long.MinValue); } [Fact] public void TestIncrementULong() { TestIncrementCompilationAndOutput<ulong>(ulong.MaxValue, ulong.MinValue); } [Fact] public void TestIncrementSByte() { TestIncrementCompilationAndOutput<sbyte>(sbyte.MaxValue, sbyte.MinValue); } [Fact] public void TestIncrementByte() { TestIncrementCompilationAndOutput<byte>(byte.MaxValue, byte.MinValue); } [Fact] public void TestIncrementShort() { TestIncrementCompilationAndOutput<short>(short.MaxValue, short.MinValue); } [Fact] public void TestIncrementUShort() { TestIncrementCompilationAndOutput<int>(int.MaxValue, int.MinValue); } [Fact] public void TestIncrementFloat() { TestIncrementCompilationAndOutput<float>(0, 1); } [Fact] [WorkItem(32576, "https://github.com/dotnet/roslyn/issues/32576")] public void TestIncrementDecimal() { TestIncrementCompilationAndOutput<decimal>(-1, 0); } [Fact] public void TestIncrementDouble() { TestIncrementCompilationAndOutput<double>(-0.5, 0.5); } [Fact] public void TestIncrementChar() { string source = string.Format(NUMERIC_INCREMENT_TEMPLATE, typeof(char).FullName, "'a'", "'b'"); string expectedOutput = string.Format(NUMERIC_OUTPUT_TEMPLATE, 'a', 'b'); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestIncrementEnum() { string source = @" class C { enum E { A = 13, B, } static void Main() { E x = E.A; E y = x++; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.A; y = ++x; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.B; y = x--; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.B; y = --x; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.B; y = x++; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.B; y = ++x; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.A; y = x--; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.A; y = --x; System.Console.WriteLine(x); System.Console.WriteLine(y); } } "; string expectedOutput = @" B A B B A B A A 15 B 15 15 12 A 12 12 "; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestIncrementNonLocal() { string source = @" class C { int field; double[] arrayField; uint Property { get; set; } static char staticField; static short[] staticArrayField; static sbyte StaticProperty { get; set; } static void Main() { C c = new C(); c.field = 2; int fieldTmp = c.field++; System.Console.WriteLine(c.field); System.Console.WriteLine(fieldTmp); c.arrayField = new double[] { 3, 4 }; double arrayFieldTmp = ++c.arrayField[0]; System.Console.WriteLine(c.arrayField[0]); System.Console.WriteLine(arrayFieldTmp); c.Property = 5; uint propertyTmp = c.Property--; System.Console.WriteLine(c.Property); System.Console.WriteLine(propertyTmp); C.staticField = 'b'; char staticFieldTmp = --C.staticField; System.Console.WriteLine(C.staticField); System.Console.WriteLine(staticFieldTmp); C.staticArrayField = new short[] { 6, 7 }; short staticArrayFieldTmp = C.staticArrayField[1]++; System.Console.WriteLine(C.staticArrayField[1]); System.Console.WriteLine(staticArrayFieldTmp); C.StaticProperty = 8; sbyte staticPropertyTmp = C.StaticProperty++; System.Console.WriteLine(C.StaticProperty); System.Console.WriteLine(staticPropertyTmp); } } "; string expectedOutput = @" 3 2 4 4 4 5 a a 8 7 9 8 "; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestIncrementIL() { string source = @" class C { enum E { A, B } static void Main() { sbyte a = 1; byte b = 1; short c = 1; ushort d = 1; int e = 1; uint f = 1; long g = 1; ulong h = 1; char i = (char)1; float j = 1; decimal k = 1; double l = 1; E m = E.A; sbyte a2; byte b2; short c2; ushort d2; int e2; uint f2; long g2; ulong h2; char i2; float j2; decimal k2; double l2; E m2; a2 = a++; System.Console.WriteLine(a2); a2 = ++a; System.Console.WriteLine(a2); a2 = a--; System.Console.WriteLine(a2); a2 = --a; System.Console.WriteLine(a2); b2 = b++; System.Console.WriteLine(b2); b2 = ++b; System.Console.WriteLine(b2); b2 = b--; System.Console.WriteLine(b2); b2 = --b; System.Console.WriteLine(b2); c2 = c++; System.Console.WriteLine(c2); c2 = ++c; System.Console.WriteLine(c2); c2 = c--; System.Console.WriteLine(c2); c2 = --c; System.Console.WriteLine(c2); d2 = d++; System.Console.WriteLine(d2); d2 = ++d; System.Console.WriteLine(d2); d2 = d--; System.Console.WriteLine(d2); d2 = --d; System.Console.WriteLine(d2); e2 = e++; System.Console.WriteLine(e2); e2 = ++e; System.Console.WriteLine(e2); e2 = e--; System.Console.WriteLine(e2); e2 = --e; System.Console.WriteLine(e2); f2 = f++; System.Console.WriteLine(f2); f2 = ++f; System.Console.WriteLine(f2); f2 = f--; System.Console.WriteLine(f2); f2 = --f; System.Console.WriteLine(f2); g2 = g++; System.Console.WriteLine(g2); g2 = ++g; System.Console.WriteLine(g2); g2 = g--; System.Console.WriteLine(g2); g2 = --g; System.Console.WriteLine(g2); h2 = h++; System.Console.WriteLine(h2); h2 = ++h; System.Console.WriteLine(h2); h2 = h--; System.Console.WriteLine(h2); h2 = --h; System.Console.WriteLine(h2); i2 = i++; System.Console.WriteLine(i2); i2 = ++i; System.Console.WriteLine(i2); i2 = i--; System.Console.WriteLine(i2); i2 = --i; System.Console.WriteLine(i2); j2 = j++; System.Console.WriteLine(j2); j2 = ++j; System.Console.WriteLine(j2); j2 = j--; System.Console.WriteLine(j2); j2 = --j; System.Console.WriteLine(j2); k2 = k++; System.Console.WriteLine(k2); k2 = ++k; System.Console.WriteLine(k2); k2 = k--; System.Console.WriteLine(k2); k2 = --k; System.Console.WriteLine(k2); l2 = l++; System.Console.WriteLine(l2); l2 = ++l; System.Console.WriteLine(l2); l2 = l--; System.Console.WriteLine(l2); l2 = --l; System.Console.WriteLine(l2); m2 = m++; System.Console.WriteLine(m2); m2 = ++m; System.Console.WriteLine(m2); m2 = m--; System.Console.WriteLine(m2); m2 = --m; System.Console.WriteLine(m2); } } "; var compilation = CompileAndVerify(source); compilation.VerifyIL("C.Main", @" { // Code size 754 (0x2f2) .maxstack 3 .locals init (sbyte V_0, //a byte V_1, //b short V_2, //c ushort V_3, //d int V_4, //e uint V_5, //f long V_6, //g ulong V_7, //h char V_8, //i float V_9, //j decimal V_10, //k double V_11, //l C.E V_12) //m IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.1 IL_0003: stloc.1 IL_0004: ldc.i4.1 IL_0005: stloc.2 IL_0006: ldc.i4.1 IL_0007: stloc.3 IL_0008: ldc.i4.1 IL_0009: stloc.s V_4 IL_000b: ldc.i4.1 IL_000c: stloc.s V_5 IL_000e: ldc.i4.1 IL_000f: conv.i8 IL_0010: stloc.s V_6 IL_0012: ldc.i4.1 IL_0013: conv.i8 IL_0014: stloc.s V_7 IL_0016: ldc.i4.1 IL_0017: stloc.s V_8 IL_0019: ldc.r4 1 IL_001e: stloc.s V_9 IL_0020: ldsfld ""decimal decimal.One"" IL_0025: stloc.s V_10 IL_0027: ldc.r8 1 IL_0030: stloc.s V_11 IL_0032: ldc.i4.0 IL_0033: stloc.s V_12 IL_0035: ldloc.0 IL_0036: dup IL_0037: ldc.i4.1 IL_0038: add IL_0039: conv.i1 IL_003a: stloc.0 IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ldloc.0 IL_0041: ldc.i4.1 IL_0042: add IL_0043: conv.i1 IL_0044: dup IL_0045: stloc.0 IL_0046: call ""void System.Console.WriteLine(int)"" IL_004b: ldloc.0 IL_004c: dup IL_004d: ldc.i4.1 IL_004e: sub IL_004f: conv.i1 IL_0050: stloc.0 IL_0051: call ""void System.Console.WriteLine(int)"" IL_0056: ldloc.0 IL_0057: ldc.i4.1 IL_0058: sub IL_0059: conv.i1 IL_005a: dup IL_005b: stloc.0 IL_005c: call ""void System.Console.WriteLine(int)"" IL_0061: ldloc.1 IL_0062: dup IL_0063: ldc.i4.1 IL_0064: add IL_0065: conv.u1 IL_0066: stloc.1 IL_0067: call ""void System.Console.WriteLine(int)"" IL_006c: ldloc.1 IL_006d: ldc.i4.1 IL_006e: add IL_006f: conv.u1 IL_0070: dup IL_0071: stloc.1 IL_0072: call ""void System.Console.WriteLine(int)"" IL_0077: ldloc.1 IL_0078: dup IL_0079: ldc.i4.1 IL_007a: sub IL_007b: conv.u1 IL_007c: stloc.1 IL_007d: call ""void System.Console.WriteLine(int)"" IL_0082: ldloc.1 IL_0083: ldc.i4.1 IL_0084: sub IL_0085: conv.u1 IL_0086: dup IL_0087: stloc.1 IL_0088: call ""void System.Console.WriteLine(int)"" IL_008d: ldloc.2 IL_008e: dup IL_008f: ldc.i4.1 IL_0090: add IL_0091: conv.i2 IL_0092: stloc.2 IL_0093: call ""void System.Console.WriteLine(int)"" IL_0098: ldloc.2 IL_0099: ldc.i4.1 IL_009a: add IL_009b: conv.i2 IL_009c: dup IL_009d: stloc.2 IL_009e: call ""void System.Console.WriteLine(int)"" IL_00a3: ldloc.2 IL_00a4: dup IL_00a5: ldc.i4.1 IL_00a6: sub IL_00a7: conv.i2 IL_00a8: stloc.2 IL_00a9: call ""void System.Console.WriteLine(int)"" IL_00ae: ldloc.2 IL_00af: ldc.i4.1 IL_00b0: sub IL_00b1: conv.i2 IL_00b2: dup IL_00b3: stloc.2 IL_00b4: call ""void System.Console.WriteLine(int)"" IL_00b9: ldloc.3 IL_00ba: dup IL_00bb: ldc.i4.1 IL_00bc: add IL_00bd: conv.u2 IL_00be: stloc.3 IL_00bf: call ""void System.Console.WriteLine(int)"" IL_00c4: ldloc.3 IL_00c5: ldc.i4.1 IL_00c6: add IL_00c7: conv.u2 IL_00c8: dup IL_00c9: stloc.3 IL_00ca: call ""void System.Console.WriteLine(int)"" IL_00cf: ldloc.3 IL_00d0: dup IL_00d1: ldc.i4.1 IL_00d2: sub IL_00d3: conv.u2 IL_00d4: stloc.3 IL_00d5: call ""void System.Console.WriteLine(int)"" IL_00da: ldloc.3 IL_00db: ldc.i4.1 IL_00dc: sub IL_00dd: conv.u2 IL_00de: dup IL_00df: stloc.3 IL_00e0: call ""void System.Console.WriteLine(int)"" IL_00e5: ldloc.s V_4 IL_00e7: dup IL_00e8: ldc.i4.1 IL_00e9: add IL_00ea: stloc.s V_4 IL_00ec: call ""void System.Console.WriteLine(int)"" IL_00f1: ldloc.s V_4 IL_00f3: ldc.i4.1 IL_00f4: add IL_00f5: dup IL_00f6: stloc.s V_4 IL_00f8: call ""void System.Console.WriteLine(int)"" IL_00fd: ldloc.s V_4 IL_00ff: dup IL_0100: ldc.i4.1 IL_0101: sub IL_0102: stloc.s V_4 IL_0104: call ""void System.Console.WriteLine(int)"" IL_0109: ldloc.s V_4 IL_010b: ldc.i4.1 IL_010c: sub IL_010d: dup IL_010e: stloc.s V_4 IL_0110: call ""void System.Console.WriteLine(int)"" IL_0115: ldloc.s V_5 IL_0117: dup IL_0118: ldc.i4.1 IL_0119: add IL_011a: stloc.s V_5 IL_011c: call ""void System.Console.WriteLine(uint)"" IL_0121: ldloc.s V_5 IL_0123: ldc.i4.1 IL_0124: add IL_0125: dup IL_0126: stloc.s V_5 IL_0128: call ""void System.Console.WriteLine(uint)"" IL_012d: ldloc.s V_5 IL_012f: dup IL_0130: ldc.i4.1 IL_0131: sub IL_0132: stloc.s V_5 IL_0134: call ""void System.Console.WriteLine(uint)"" IL_0139: ldloc.s V_5 IL_013b: ldc.i4.1 IL_013c: sub IL_013d: dup IL_013e: stloc.s V_5 IL_0140: call ""void System.Console.WriteLine(uint)"" IL_0145: ldloc.s V_6 IL_0147: dup IL_0148: ldc.i4.1 IL_0149: conv.i8 IL_014a: add IL_014b: stloc.s V_6 IL_014d: call ""void System.Console.WriteLine(long)"" IL_0152: ldloc.s V_6 IL_0154: ldc.i4.1 IL_0155: conv.i8 IL_0156: add IL_0157: dup IL_0158: stloc.s V_6 IL_015a: call ""void System.Console.WriteLine(long)"" IL_015f: ldloc.s V_6 IL_0161: dup IL_0162: ldc.i4.1 IL_0163: conv.i8 IL_0164: sub IL_0165: stloc.s V_6 IL_0167: call ""void System.Console.WriteLine(long)"" IL_016c: ldloc.s V_6 IL_016e: ldc.i4.1 IL_016f: conv.i8 IL_0170: sub IL_0171: dup IL_0172: stloc.s V_6 IL_0174: call ""void System.Console.WriteLine(long)"" IL_0179: ldloc.s V_7 IL_017b: dup IL_017c: ldc.i4.1 IL_017d: conv.i8 IL_017e: add IL_017f: stloc.s V_7 IL_0181: call ""void System.Console.WriteLine(ulong)"" IL_0186: ldloc.s V_7 IL_0188: ldc.i4.1 IL_0189: conv.i8 IL_018a: add IL_018b: dup IL_018c: stloc.s V_7 IL_018e: call ""void System.Console.WriteLine(ulong)"" IL_0193: ldloc.s V_7 IL_0195: dup IL_0196: ldc.i4.1 IL_0197: conv.i8 IL_0198: sub IL_0199: stloc.s V_7 IL_019b: call ""void System.Console.WriteLine(ulong)"" IL_01a0: ldloc.s V_7 IL_01a2: ldc.i4.1 IL_01a3: conv.i8 IL_01a4: sub IL_01a5: dup IL_01a6: stloc.s V_7 IL_01a8: call ""void System.Console.WriteLine(ulong)"" IL_01ad: ldloc.s V_8 IL_01af: dup IL_01b0: ldc.i4.1 IL_01b1: add IL_01b2: conv.u2 IL_01b3: stloc.s V_8 IL_01b5: call ""void System.Console.WriteLine(char)"" IL_01ba: ldloc.s V_8 IL_01bc: ldc.i4.1 IL_01bd: add IL_01be: conv.u2 IL_01bf: dup IL_01c0: stloc.s V_8 IL_01c2: call ""void System.Console.WriteLine(char)"" IL_01c7: ldloc.s V_8 IL_01c9: dup IL_01ca: ldc.i4.1 IL_01cb: sub IL_01cc: conv.u2 IL_01cd: stloc.s V_8 IL_01cf: call ""void System.Console.WriteLine(char)"" IL_01d4: ldloc.s V_8 IL_01d6: ldc.i4.1 IL_01d7: sub IL_01d8: conv.u2 IL_01d9: dup IL_01da: stloc.s V_8 IL_01dc: call ""void System.Console.WriteLine(char)"" IL_01e1: ldloc.s V_9 IL_01e3: dup IL_01e4: ldc.r4 1 IL_01e9: add IL_01ea: stloc.s V_9 IL_01ec: call ""void System.Console.WriteLine(float)"" IL_01f1: ldloc.s V_9 IL_01f3: ldc.r4 1 IL_01f8: add IL_01f9: dup IL_01fa: stloc.s V_9 IL_01fc: call ""void System.Console.WriteLine(float)"" IL_0201: ldloc.s V_9 IL_0203: dup IL_0204: ldc.r4 1 IL_0209: sub IL_020a: stloc.s V_9 IL_020c: call ""void System.Console.WriteLine(float)"" IL_0211: ldloc.s V_9 IL_0213: ldc.r4 1 IL_0218: sub IL_0219: dup IL_021a: stloc.s V_9 IL_021c: call ""void System.Console.WriteLine(float)"" IL_0221: ldloc.s V_10 IL_0223: dup IL_0224: call ""decimal decimal.op_Increment(decimal)"" IL_0229: stloc.s V_10 IL_022b: call ""void System.Console.WriteLine(decimal)"" IL_0230: ldloc.s V_10 IL_0232: call ""decimal decimal.op_Increment(decimal)"" IL_0237: dup IL_0238: stloc.s V_10 IL_023a: call ""void System.Console.WriteLine(decimal)"" IL_023f: ldloc.s V_10 IL_0241: dup IL_0242: call ""decimal decimal.op_Decrement(decimal)"" IL_0247: stloc.s V_10 IL_0249: call ""void System.Console.WriteLine(decimal)"" IL_024e: ldloc.s V_10 IL_0250: call ""decimal decimal.op_Decrement(decimal)"" IL_0255: dup IL_0256: stloc.s V_10 IL_0258: call ""void System.Console.WriteLine(decimal)"" IL_025d: ldloc.s V_11 IL_025f: dup IL_0260: ldc.r8 1 IL_0269: add IL_026a: stloc.s V_11 IL_026c: call ""void System.Console.WriteLine(double)"" IL_0271: ldloc.s V_11 IL_0273: ldc.r8 1 IL_027c: add IL_027d: dup IL_027e: stloc.s V_11 IL_0280: call ""void System.Console.WriteLine(double)"" IL_0285: ldloc.s V_11 IL_0287: dup IL_0288: ldc.r8 1 IL_0291: sub IL_0292: stloc.s V_11 IL_0294: call ""void System.Console.WriteLine(double)"" IL_0299: ldloc.s V_11 IL_029b: ldc.r8 1 IL_02a4: sub IL_02a5: dup IL_02a6: stloc.s V_11 IL_02a8: call ""void System.Console.WriteLine(double)"" IL_02ad: ldloc.s V_12 IL_02af: dup IL_02b0: ldc.i4.1 IL_02b1: add IL_02b2: stloc.s V_12 IL_02b4: box ""C.E"" IL_02b9: call ""void System.Console.WriteLine(object)"" IL_02be: ldloc.s V_12 IL_02c0: ldc.i4.1 IL_02c1: add IL_02c2: dup IL_02c3: stloc.s V_12 IL_02c5: box ""C.E"" IL_02ca: call ""void System.Console.WriteLine(object)"" IL_02cf: ldloc.s V_12 IL_02d1: dup IL_02d2: ldc.i4.1 IL_02d3: sub IL_02d4: stloc.s V_12 IL_02d6: box ""C.E"" IL_02db: call ""void System.Console.WriteLine(object)"" IL_02e0: ldloc.s V_12 IL_02e2: ldc.i4.1 IL_02e3: sub IL_02e4: dup IL_02e5: stloc.s V_12 IL_02e7: box ""C.E"" IL_02ec: call ""void System.Console.WriteLine(object)"" IL_02f1: ret } "); } [WorkItem(540718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540718")] [Fact] public void GenConditionalBranchTempForInc() { var source = @"using System; class Test { void M(int i) { if (i++ == 0) { return; } } } "; base.CompileAndVerify(source). VerifyIL("Test.M", @" { // Code size 8 (0x8) .maxstack 3 IL_0000: ldarg.1 IL_0001: dup IL_0002: ldc.i4.1 IL_0003: add IL_0004: starg.s V_1 IL_0006: pop IL_0007: ret } " ); } [WorkItem(540718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540718")] [Fact] public void IncrementField() { var source = @" using System; class Test { private int i = 0; void M() { this.i++; ++this.i; this.i+=1; } } "; base.CompileAndVerify(source). VerifyIL("Test.M", @" { // Code size 43 (0x2b) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld ""int Test.i"" IL_0007: ldc.i4.1 IL_0008: add IL_0009: stfld ""int Test.i"" IL_000e: ldarg.0 IL_000f: ldarg.0 IL_0010: ldfld ""int Test.i"" IL_0015: ldc.i4.1 IL_0016: add IL_0017: stfld ""int Test.i"" IL_001c: ldarg.0 IL_001d: ldarg.0 IL_001e: ldfld ""int Test.i"" IL_0023: ldc.i4.1 IL_0024: add IL_0025: stfld ""int Test.i"" IL_002a: ret } " ); } [WorkItem(540723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540723")] [Fact] public void MissingIncInFinallyBlock() { var source = @"using System; class My { static void Main() { int i = 0; try { } finally { i++; } Console.Write(i); } } "; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(540810, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540810")] [Fact] public void NestedIncrement() { var source = @" using System; class My { static void Main() { int[] a = { 0 }; int i = 0; a[i++]++; Console.Write(a[0]); Console.Write(i); } } "; CompileAndVerify(source, expectedOutput: "11"); } [WorkItem(540810, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540810")] [Fact] public void IncrementSideEffects() { var source = @" class Class { static int[] array = new int[1]; static void Main() { System.Console.WriteLine(Array()[Zero()]++); System.Console.WriteLine(++Array()[Zero()]); System.Console.WriteLine(Array()[Zero()]--); System.Console.WriteLine(--Array()[Zero()]); } static int Zero() { System.Console.WriteLine(""Zero""); return 0; } static int[] Array() { System.Console.WriteLine(""Array""); return array; } } "; CompileAndVerify(source, expectedOutput: @" Array Zero 0 Array Zero 2 Array Zero 2 Array Zero 0"); } private void TestIncrementCompilationAndOutput<T>(T value, T valuePlusOne) where T : struct { Type type = typeof(T); Assert.True(type.IsPrimitive || type == typeof(decimal), string.Format("Type {0} is neither primitive nor decimal", type)); // Explicitly provide InvariantCulture to use the proper C# decimal separator '.' in the source regardless of the current culture string source = string.Format(CultureInfo.InvariantCulture, NUMERIC_INCREMENT_TEMPLATE, type.FullName, value, valuePlusOne); string expectedOutput = string.Format(CultureInfo.InvariantCulture, NUMERIC_OUTPUT_TEMPLATE, value, valuePlusOne); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(720742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720742")] [Fact] public void IncrementRefVal() { var source = @" using System; public class Test { public static void Main() { short x = 3; var r = __makeref(x); __refvalue(r, short) += 7; __refvalue(r, short)++; ++ __refvalue(r,short); System.Console.WriteLine( __refvalue(r, short)); } } "; base.CompileAndVerify(source, expectedOutput: "12"). VerifyIL("Test.Main", @" { // Code size 57 (0x39) .maxstack 4 .locals init (short V_0) //x IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: mkrefany ""short"" IL_0009: dup IL_000a: refanyval ""short"" IL_000f: dup IL_0010: ldind.i2 IL_0011: ldc.i4.7 IL_0012: add IL_0013: conv.i2 IL_0014: stind.i2 IL_0015: dup IL_0016: refanyval ""short"" IL_001b: dup IL_001c: ldind.i2 IL_001d: ldc.i4.1 IL_001e: add IL_001f: conv.i2 IL_0020: stind.i2 IL_0021: dup IL_0022: refanyval ""short"" IL_0027: dup IL_0028: ldind.i2 IL_0029: ldc.i4.1 IL_002a: add IL_002b: conv.i2 IL_002c: stind.i2 IL_002d: refanyval ""short"" IL_0032: ldind.i2 IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Globalization; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenIncrementTests : CSharpTestBase { //{0} is a numeric type //{1} is some value //{2} is one greater than {1} private const string NUMERIC_INCREMENT_TEMPLATE = @" class C {{ static void Main() {{ {0} x = {1}; {0} y = x++; System.Console.WriteLine(x); System.Console.WriteLine(y); x = {1}; y = ++x; System.Console.WriteLine(x); System.Console.WriteLine(y); x = {2}; y = x--; System.Console.WriteLine(x); System.Console.WriteLine(y); x = {2}; y = --x; System.Console.WriteLine(x); System.Console.WriteLine(y); }} }} "; //{0} is some value, {1} is one greater private const string NUMERIC_OUTPUT_TEMPLATE = @" {1} {0} {1} {1} {0} {1} {0} {0} "; [Fact] public void TestIncrementInt() { TestIncrementCompilationAndOutput<int>(int.MaxValue, int.MinValue); } [Fact] public void TestIncrementUInt() { TestIncrementCompilationAndOutput<uint>(uint.MaxValue, uint.MinValue); } [Fact] public void TestIncrementLong() { TestIncrementCompilationAndOutput<long>(long.MaxValue, long.MinValue); } [Fact] public void TestIncrementULong() { TestIncrementCompilationAndOutput<ulong>(ulong.MaxValue, ulong.MinValue); } [Fact] public void TestIncrementSByte() { TestIncrementCompilationAndOutput<sbyte>(sbyte.MaxValue, sbyte.MinValue); } [Fact] public void TestIncrementByte() { TestIncrementCompilationAndOutput<byte>(byte.MaxValue, byte.MinValue); } [Fact] public void TestIncrementShort() { TestIncrementCompilationAndOutput<short>(short.MaxValue, short.MinValue); } [Fact] public void TestIncrementUShort() { TestIncrementCompilationAndOutput<int>(int.MaxValue, int.MinValue); } [Fact] public void TestIncrementFloat() { TestIncrementCompilationAndOutput<float>(0, 1); } [Fact] [WorkItem(32576, "https://github.com/dotnet/roslyn/issues/32576")] public void TestIncrementDecimal() { TestIncrementCompilationAndOutput<decimal>(-1, 0); } [Fact] public void TestIncrementDouble() { TestIncrementCompilationAndOutput<double>(-0.5, 0.5); } [Fact] public void TestIncrementChar() { string source = string.Format(NUMERIC_INCREMENT_TEMPLATE, typeof(char).FullName, "'a'", "'b'"); string expectedOutput = string.Format(NUMERIC_OUTPUT_TEMPLATE, 'a', 'b'); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestIncrementEnum() { string source = @" class C { enum E { A = 13, B, } static void Main() { E x = E.A; E y = x++; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.A; y = ++x; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.B; y = x--; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.B; y = --x; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.B; y = x++; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.B; y = ++x; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.A; y = x--; System.Console.WriteLine(x); System.Console.WriteLine(y); x = E.A; y = --x; System.Console.WriteLine(x); System.Console.WriteLine(y); } } "; string expectedOutput = @" B A B B A B A A 15 B 15 15 12 A 12 12 "; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestIncrementNonLocal() { string source = @" class C { int field; double[] arrayField; uint Property { get; set; } static char staticField; static short[] staticArrayField; static sbyte StaticProperty { get; set; } static void Main() { C c = new C(); c.field = 2; int fieldTmp = c.field++; System.Console.WriteLine(c.field); System.Console.WriteLine(fieldTmp); c.arrayField = new double[] { 3, 4 }; double arrayFieldTmp = ++c.arrayField[0]; System.Console.WriteLine(c.arrayField[0]); System.Console.WriteLine(arrayFieldTmp); c.Property = 5; uint propertyTmp = c.Property--; System.Console.WriteLine(c.Property); System.Console.WriteLine(propertyTmp); C.staticField = 'b'; char staticFieldTmp = --C.staticField; System.Console.WriteLine(C.staticField); System.Console.WriteLine(staticFieldTmp); C.staticArrayField = new short[] { 6, 7 }; short staticArrayFieldTmp = C.staticArrayField[1]++; System.Console.WriteLine(C.staticArrayField[1]); System.Console.WriteLine(staticArrayFieldTmp); C.StaticProperty = 8; sbyte staticPropertyTmp = C.StaticProperty++; System.Console.WriteLine(C.StaticProperty); System.Console.WriteLine(staticPropertyTmp); } } "; string expectedOutput = @" 3 2 4 4 4 5 a a 8 7 9 8 "; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestIncrementIL() { string source = @" class C { enum E { A, B } static void Main() { sbyte a = 1; byte b = 1; short c = 1; ushort d = 1; int e = 1; uint f = 1; long g = 1; ulong h = 1; char i = (char)1; float j = 1; decimal k = 1; double l = 1; E m = E.A; sbyte a2; byte b2; short c2; ushort d2; int e2; uint f2; long g2; ulong h2; char i2; float j2; decimal k2; double l2; E m2; a2 = a++; System.Console.WriteLine(a2); a2 = ++a; System.Console.WriteLine(a2); a2 = a--; System.Console.WriteLine(a2); a2 = --a; System.Console.WriteLine(a2); b2 = b++; System.Console.WriteLine(b2); b2 = ++b; System.Console.WriteLine(b2); b2 = b--; System.Console.WriteLine(b2); b2 = --b; System.Console.WriteLine(b2); c2 = c++; System.Console.WriteLine(c2); c2 = ++c; System.Console.WriteLine(c2); c2 = c--; System.Console.WriteLine(c2); c2 = --c; System.Console.WriteLine(c2); d2 = d++; System.Console.WriteLine(d2); d2 = ++d; System.Console.WriteLine(d2); d2 = d--; System.Console.WriteLine(d2); d2 = --d; System.Console.WriteLine(d2); e2 = e++; System.Console.WriteLine(e2); e2 = ++e; System.Console.WriteLine(e2); e2 = e--; System.Console.WriteLine(e2); e2 = --e; System.Console.WriteLine(e2); f2 = f++; System.Console.WriteLine(f2); f2 = ++f; System.Console.WriteLine(f2); f2 = f--; System.Console.WriteLine(f2); f2 = --f; System.Console.WriteLine(f2); g2 = g++; System.Console.WriteLine(g2); g2 = ++g; System.Console.WriteLine(g2); g2 = g--; System.Console.WriteLine(g2); g2 = --g; System.Console.WriteLine(g2); h2 = h++; System.Console.WriteLine(h2); h2 = ++h; System.Console.WriteLine(h2); h2 = h--; System.Console.WriteLine(h2); h2 = --h; System.Console.WriteLine(h2); i2 = i++; System.Console.WriteLine(i2); i2 = ++i; System.Console.WriteLine(i2); i2 = i--; System.Console.WriteLine(i2); i2 = --i; System.Console.WriteLine(i2); j2 = j++; System.Console.WriteLine(j2); j2 = ++j; System.Console.WriteLine(j2); j2 = j--; System.Console.WriteLine(j2); j2 = --j; System.Console.WriteLine(j2); k2 = k++; System.Console.WriteLine(k2); k2 = ++k; System.Console.WriteLine(k2); k2 = k--; System.Console.WriteLine(k2); k2 = --k; System.Console.WriteLine(k2); l2 = l++; System.Console.WriteLine(l2); l2 = ++l; System.Console.WriteLine(l2); l2 = l--; System.Console.WriteLine(l2); l2 = --l; System.Console.WriteLine(l2); m2 = m++; System.Console.WriteLine(m2); m2 = ++m; System.Console.WriteLine(m2); m2 = m--; System.Console.WriteLine(m2); m2 = --m; System.Console.WriteLine(m2); } } "; var compilation = CompileAndVerify(source); compilation.VerifyIL("C.Main", @" { // Code size 754 (0x2f2) .maxstack 3 .locals init (sbyte V_0, //a byte V_1, //b short V_2, //c ushort V_3, //d int V_4, //e uint V_5, //f long V_6, //g ulong V_7, //h char V_8, //i float V_9, //j decimal V_10, //k double V_11, //l C.E V_12) //m IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.1 IL_0003: stloc.1 IL_0004: ldc.i4.1 IL_0005: stloc.2 IL_0006: ldc.i4.1 IL_0007: stloc.3 IL_0008: ldc.i4.1 IL_0009: stloc.s V_4 IL_000b: ldc.i4.1 IL_000c: stloc.s V_5 IL_000e: ldc.i4.1 IL_000f: conv.i8 IL_0010: stloc.s V_6 IL_0012: ldc.i4.1 IL_0013: conv.i8 IL_0014: stloc.s V_7 IL_0016: ldc.i4.1 IL_0017: stloc.s V_8 IL_0019: ldc.r4 1 IL_001e: stloc.s V_9 IL_0020: ldsfld ""decimal decimal.One"" IL_0025: stloc.s V_10 IL_0027: ldc.r8 1 IL_0030: stloc.s V_11 IL_0032: ldc.i4.0 IL_0033: stloc.s V_12 IL_0035: ldloc.0 IL_0036: dup IL_0037: ldc.i4.1 IL_0038: add IL_0039: conv.i1 IL_003a: stloc.0 IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ldloc.0 IL_0041: ldc.i4.1 IL_0042: add IL_0043: conv.i1 IL_0044: dup IL_0045: stloc.0 IL_0046: call ""void System.Console.WriteLine(int)"" IL_004b: ldloc.0 IL_004c: dup IL_004d: ldc.i4.1 IL_004e: sub IL_004f: conv.i1 IL_0050: stloc.0 IL_0051: call ""void System.Console.WriteLine(int)"" IL_0056: ldloc.0 IL_0057: ldc.i4.1 IL_0058: sub IL_0059: conv.i1 IL_005a: dup IL_005b: stloc.0 IL_005c: call ""void System.Console.WriteLine(int)"" IL_0061: ldloc.1 IL_0062: dup IL_0063: ldc.i4.1 IL_0064: add IL_0065: conv.u1 IL_0066: stloc.1 IL_0067: call ""void System.Console.WriteLine(int)"" IL_006c: ldloc.1 IL_006d: ldc.i4.1 IL_006e: add IL_006f: conv.u1 IL_0070: dup IL_0071: stloc.1 IL_0072: call ""void System.Console.WriteLine(int)"" IL_0077: ldloc.1 IL_0078: dup IL_0079: ldc.i4.1 IL_007a: sub IL_007b: conv.u1 IL_007c: stloc.1 IL_007d: call ""void System.Console.WriteLine(int)"" IL_0082: ldloc.1 IL_0083: ldc.i4.1 IL_0084: sub IL_0085: conv.u1 IL_0086: dup IL_0087: stloc.1 IL_0088: call ""void System.Console.WriteLine(int)"" IL_008d: ldloc.2 IL_008e: dup IL_008f: ldc.i4.1 IL_0090: add IL_0091: conv.i2 IL_0092: stloc.2 IL_0093: call ""void System.Console.WriteLine(int)"" IL_0098: ldloc.2 IL_0099: ldc.i4.1 IL_009a: add IL_009b: conv.i2 IL_009c: dup IL_009d: stloc.2 IL_009e: call ""void System.Console.WriteLine(int)"" IL_00a3: ldloc.2 IL_00a4: dup IL_00a5: ldc.i4.1 IL_00a6: sub IL_00a7: conv.i2 IL_00a8: stloc.2 IL_00a9: call ""void System.Console.WriteLine(int)"" IL_00ae: ldloc.2 IL_00af: ldc.i4.1 IL_00b0: sub IL_00b1: conv.i2 IL_00b2: dup IL_00b3: stloc.2 IL_00b4: call ""void System.Console.WriteLine(int)"" IL_00b9: ldloc.3 IL_00ba: dup IL_00bb: ldc.i4.1 IL_00bc: add IL_00bd: conv.u2 IL_00be: stloc.3 IL_00bf: call ""void System.Console.WriteLine(int)"" IL_00c4: ldloc.3 IL_00c5: ldc.i4.1 IL_00c6: add IL_00c7: conv.u2 IL_00c8: dup IL_00c9: stloc.3 IL_00ca: call ""void System.Console.WriteLine(int)"" IL_00cf: ldloc.3 IL_00d0: dup IL_00d1: ldc.i4.1 IL_00d2: sub IL_00d3: conv.u2 IL_00d4: stloc.3 IL_00d5: call ""void System.Console.WriteLine(int)"" IL_00da: ldloc.3 IL_00db: ldc.i4.1 IL_00dc: sub IL_00dd: conv.u2 IL_00de: dup IL_00df: stloc.3 IL_00e0: call ""void System.Console.WriteLine(int)"" IL_00e5: ldloc.s V_4 IL_00e7: dup IL_00e8: ldc.i4.1 IL_00e9: add IL_00ea: stloc.s V_4 IL_00ec: call ""void System.Console.WriteLine(int)"" IL_00f1: ldloc.s V_4 IL_00f3: ldc.i4.1 IL_00f4: add IL_00f5: dup IL_00f6: stloc.s V_4 IL_00f8: call ""void System.Console.WriteLine(int)"" IL_00fd: ldloc.s V_4 IL_00ff: dup IL_0100: ldc.i4.1 IL_0101: sub IL_0102: stloc.s V_4 IL_0104: call ""void System.Console.WriteLine(int)"" IL_0109: ldloc.s V_4 IL_010b: ldc.i4.1 IL_010c: sub IL_010d: dup IL_010e: stloc.s V_4 IL_0110: call ""void System.Console.WriteLine(int)"" IL_0115: ldloc.s V_5 IL_0117: dup IL_0118: ldc.i4.1 IL_0119: add IL_011a: stloc.s V_5 IL_011c: call ""void System.Console.WriteLine(uint)"" IL_0121: ldloc.s V_5 IL_0123: ldc.i4.1 IL_0124: add IL_0125: dup IL_0126: stloc.s V_5 IL_0128: call ""void System.Console.WriteLine(uint)"" IL_012d: ldloc.s V_5 IL_012f: dup IL_0130: ldc.i4.1 IL_0131: sub IL_0132: stloc.s V_5 IL_0134: call ""void System.Console.WriteLine(uint)"" IL_0139: ldloc.s V_5 IL_013b: ldc.i4.1 IL_013c: sub IL_013d: dup IL_013e: stloc.s V_5 IL_0140: call ""void System.Console.WriteLine(uint)"" IL_0145: ldloc.s V_6 IL_0147: dup IL_0148: ldc.i4.1 IL_0149: conv.i8 IL_014a: add IL_014b: stloc.s V_6 IL_014d: call ""void System.Console.WriteLine(long)"" IL_0152: ldloc.s V_6 IL_0154: ldc.i4.1 IL_0155: conv.i8 IL_0156: add IL_0157: dup IL_0158: stloc.s V_6 IL_015a: call ""void System.Console.WriteLine(long)"" IL_015f: ldloc.s V_6 IL_0161: dup IL_0162: ldc.i4.1 IL_0163: conv.i8 IL_0164: sub IL_0165: stloc.s V_6 IL_0167: call ""void System.Console.WriteLine(long)"" IL_016c: ldloc.s V_6 IL_016e: ldc.i4.1 IL_016f: conv.i8 IL_0170: sub IL_0171: dup IL_0172: stloc.s V_6 IL_0174: call ""void System.Console.WriteLine(long)"" IL_0179: ldloc.s V_7 IL_017b: dup IL_017c: ldc.i4.1 IL_017d: conv.i8 IL_017e: add IL_017f: stloc.s V_7 IL_0181: call ""void System.Console.WriteLine(ulong)"" IL_0186: ldloc.s V_7 IL_0188: ldc.i4.1 IL_0189: conv.i8 IL_018a: add IL_018b: dup IL_018c: stloc.s V_7 IL_018e: call ""void System.Console.WriteLine(ulong)"" IL_0193: ldloc.s V_7 IL_0195: dup IL_0196: ldc.i4.1 IL_0197: conv.i8 IL_0198: sub IL_0199: stloc.s V_7 IL_019b: call ""void System.Console.WriteLine(ulong)"" IL_01a0: ldloc.s V_7 IL_01a2: ldc.i4.1 IL_01a3: conv.i8 IL_01a4: sub IL_01a5: dup IL_01a6: stloc.s V_7 IL_01a8: call ""void System.Console.WriteLine(ulong)"" IL_01ad: ldloc.s V_8 IL_01af: dup IL_01b0: ldc.i4.1 IL_01b1: add IL_01b2: conv.u2 IL_01b3: stloc.s V_8 IL_01b5: call ""void System.Console.WriteLine(char)"" IL_01ba: ldloc.s V_8 IL_01bc: ldc.i4.1 IL_01bd: add IL_01be: conv.u2 IL_01bf: dup IL_01c0: stloc.s V_8 IL_01c2: call ""void System.Console.WriteLine(char)"" IL_01c7: ldloc.s V_8 IL_01c9: dup IL_01ca: ldc.i4.1 IL_01cb: sub IL_01cc: conv.u2 IL_01cd: stloc.s V_8 IL_01cf: call ""void System.Console.WriteLine(char)"" IL_01d4: ldloc.s V_8 IL_01d6: ldc.i4.1 IL_01d7: sub IL_01d8: conv.u2 IL_01d9: dup IL_01da: stloc.s V_8 IL_01dc: call ""void System.Console.WriteLine(char)"" IL_01e1: ldloc.s V_9 IL_01e3: dup IL_01e4: ldc.r4 1 IL_01e9: add IL_01ea: stloc.s V_9 IL_01ec: call ""void System.Console.WriteLine(float)"" IL_01f1: ldloc.s V_9 IL_01f3: ldc.r4 1 IL_01f8: add IL_01f9: dup IL_01fa: stloc.s V_9 IL_01fc: call ""void System.Console.WriteLine(float)"" IL_0201: ldloc.s V_9 IL_0203: dup IL_0204: ldc.r4 1 IL_0209: sub IL_020a: stloc.s V_9 IL_020c: call ""void System.Console.WriteLine(float)"" IL_0211: ldloc.s V_9 IL_0213: ldc.r4 1 IL_0218: sub IL_0219: dup IL_021a: stloc.s V_9 IL_021c: call ""void System.Console.WriteLine(float)"" IL_0221: ldloc.s V_10 IL_0223: dup IL_0224: call ""decimal decimal.op_Increment(decimal)"" IL_0229: stloc.s V_10 IL_022b: call ""void System.Console.WriteLine(decimal)"" IL_0230: ldloc.s V_10 IL_0232: call ""decimal decimal.op_Increment(decimal)"" IL_0237: dup IL_0238: stloc.s V_10 IL_023a: call ""void System.Console.WriteLine(decimal)"" IL_023f: ldloc.s V_10 IL_0241: dup IL_0242: call ""decimal decimal.op_Decrement(decimal)"" IL_0247: stloc.s V_10 IL_0249: call ""void System.Console.WriteLine(decimal)"" IL_024e: ldloc.s V_10 IL_0250: call ""decimal decimal.op_Decrement(decimal)"" IL_0255: dup IL_0256: stloc.s V_10 IL_0258: call ""void System.Console.WriteLine(decimal)"" IL_025d: ldloc.s V_11 IL_025f: dup IL_0260: ldc.r8 1 IL_0269: add IL_026a: stloc.s V_11 IL_026c: call ""void System.Console.WriteLine(double)"" IL_0271: ldloc.s V_11 IL_0273: ldc.r8 1 IL_027c: add IL_027d: dup IL_027e: stloc.s V_11 IL_0280: call ""void System.Console.WriteLine(double)"" IL_0285: ldloc.s V_11 IL_0287: dup IL_0288: ldc.r8 1 IL_0291: sub IL_0292: stloc.s V_11 IL_0294: call ""void System.Console.WriteLine(double)"" IL_0299: ldloc.s V_11 IL_029b: ldc.r8 1 IL_02a4: sub IL_02a5: dup IL_02a6: stloc.s V_11 IL_02a8: call ""void System.Console.WriteLine(double)"" IL_02ad: ldloc.s V_12 IL_02af: dup IL_02b0: ldc.i4.1 IL_02b1: add IL_02b2: stloc.s V_12 IL_02b4: box ""C.E"" IL_02b9: call ""void System.Console.WriteLine(object)"" IL_02be: ldloc.s V_12 IL_02c0: ldc.i4.1 IL_02c1: add IL_02c2: dup IL_02c3: stloc.s V_12 IL_02c5: box ""C.E"" IL_02ca: call ""void System.Console.WriteLine(object)"" IL_02cf: ldloc.s V_12 IL_02d1: dup IL_02d2: ldc.i4.1 IL_02d3: sub IL_02d4: stloc.s V_12 IL_02d6: box ""C.E"" IL_02db: call ""void System.Console.WriteLine(object)"" IL_02e0: ldloc.s V_12 IL_02e2: ldc.i4.1 IL_02e3: sub IL_02e4: dup IL_02e5: stloc.s V_12 IL_02e7: box ""C.E"" IL_02ec: call ""void System.Console.WriteLine(object)"" IL_02f1: ret } "); } [WorkItem(540718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540718")] [Fact] public void GenConditionalBranchTempForInc() { var source = @"using System; class Test { void M(int i) { if (i++ == 0) { return; } } } "; base.CompileAndVerify(source). VerifyIL("Test.M", @" { // Code size 8 (0x8) .maxstack 3 IL_0000: ldarg.1 IL_0001: dup IL_0002: ldc.i4.1 IL_0003: add IL_0004: starg.s V_1 IL_0006: pop IL_0007: ret } " ); } [WorkItem(540718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540718")] [Fact] public void IncrementField() { var source = @" using System; class Test { private int i = 0; void M() { this.i++; ++this.i; this.i+=1; } } "; base.CompileAndVerify(source). VerifyIL("Test.M", @" { // Code size 43 (0x2b) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld ""int Test.i"" IL_0007: ldc.i4.1 IL_0008: add IL_0009: stfld ""int Test.i"" IL_000e: ldarg.0 IL_000f: ldarg.0 IL_0010: ldfld ""int Test.i"" IL_0015: ldc.i4.1 IL_0016: add IL_0017: stfld ""int Test.i"" IL_001c: ldarg.0 IL_001d: ldarg.0 IL_001e: ldfld ""int Test.i"" IL_0023: ldc.i4.1 IL_0024: add IL_0025: stfld ""int Test.i"" IL_002a: ret } " ); } [WorkItem(540723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540723")] [Fact] public void MissingIncInFinallyBlock() { var source = @"using System; class My { static void Main() { int i = 0; try { } finally { i++; } Console.Write(i); } } "; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(540810, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540810")] [Fact] public void NestedIncrement() { var source = @" using System; class My { static void Main() { int[] a = { 0 }; int i = 0; a[i++]++; Console.Write(a[0]); Console.Write(i); } } "; CompileAndVerify(source, expectedOutput: "11"); } [WorkItem(540810, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540810")] [Fact] public void IncrementSideEffects() { var source = @" class Class { static int[] array = new int[1]; static void Main() { System.Console.WriteLine(Array()[Zero()]++); System.Console.WriteLine(++Array()[Zero()]); System.Console.WriteLine(Array()[Zero()]--); System.Console.WriteLine(--Array()[Zero()]); } static int Zero() { System.Console.WriteLine(""Zero""); return 0; } static int[] Array() { System.Console.WriteLine(""Array""); return array; } } "; CompileAndVerify(source, expectedOutput: @" Array Zero 0 Array Zero 2 Array Zero 2 Array Zero 0"); } private void TestIncrementCompilationAndOutput<T>(T value, T valuePlusOne) where T : struct { Type type = typeof(T); Assert.True(type.IsPrimitive || type == typeof(decimal), string.Format("Type {0} is neither primitive nor decimal", type)); // Explicitly provide InvariantCulture to use the proper C# decimal separator '.' in the source regardless of the current culture string source = string.Format(CultureInfo.InvariantCulture, NUMERIC_INCREMENT_TEMPLATE, type.FullName, value, valuePlusOne); string expectedOutput = string.Format(CultureInfo.InvariantCulture, NUMERIC_OUTPUT_TEMPLATE, value, valuePlusOne); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(720742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720742")] [Fact] public void IncrementRefVal() { var source = @" using System; public class Test { public static void Main() { short x = 3; var r = __makeref(x); __refvalue(r, short) += 7; __refvalue(r, short)++; ++ __refvalue(r,short); System.Console.WriteLine( __refvalue(r, short)); } } "; base.CompileAndVerify(source, expectedOutput: "12"). VerifyIL("Test.Main", @" { // Code size 57 (0x39) .maxstack 4 .locals init (short V_0) //x IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: mkrefany ""short"" IL_0009: dup IL_000a: refanyval ""short"" IL_000f: dup IL_0010: ldind.i2 IL_0011: ldc.i4.7 IL_0012: add IL_0013: conv.i2 IL_0014: stind.i2 IL_0015: dup IL_0016: refanyval ""short"" IL_001b: dup IL_001c: ldind.i2 IL_001d: ldc.i4.1 IL_001e: add IL_001f: conv.i2 IL_0020: stind.i2 IL_0021: dup IL_0022: refanyval ""short"" IL_0027: dup IL_0028: ldind.i2 IL_0029: ldc.i4.1 IL_002a: add IL_002b: conv.i2 IL_002c: stind.i2 IL_002d: refanyval ""short"" IL_0032: ldind.i2 IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " ); } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/Core/Portable/UpgradeProject/AbstractUpgradeProjectCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.UpgradeProject { internal abstract partial class AbstractUpgradeProjectCodeFixProvider : CodeFixProvider { public abstract string SuggestedVersion(ImmutableArray<Diagnostic> diagnostics); public abstract Solution UpgradeProject(Project project, string version); public abstract bool IsUpgrade(Project project, string newVersion); public abstract string UpgradeThisProjectResource { get; } public abstract string UpgradeAllProjectsResource { get; } public override FixAllProvider GetFixAllProvider() { // This code fix uses a dedicated action for fixing all instances in a solution return null; } public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostics = context.Diagnostics; context.RegisterFixes(GetUpgradeProjectCodeActions(context), diagnostics); return Task.CompletedTask; } protected ImmutableArray<CodeAction> GetUpgradeProjectCodeActions(CodeFixContext context) { var project = context.Document.Project; var solution = project.Solution; var newVersion = SuggestedVersion(context.Diagnostics); var result = new List<CodeAction>(); var language = project.Language; var upgradeableProjects = solution.Projects.Where(p => CanUpgrade(p, language, newVersion)).AsImmutable(); if (upgradeableProjects.Length == 0) { return ImmutableArray<CodeAction>.Empty; } var fixOneProjectTitle = string.Format(UpgradeThisProjectResource, newVersion); var fixOneProject = new ProjectOptionsChangeAction(fixOneProjectTitle, _ => Task.FromResult(UpgradeProject(project, newVersion))); result.Add(fixOneProject); if (upgradeableProjects.Length > 1) { var fixAllProjectsTitle = string.Format(UpgradeAllProjectsResource, newVersion); var fixAllProjects = new ProjectOptionsChangeAction(fixAllProjectsTitle, ct => Task.FromResult(UpgradeAllProjects(solution, language, newVersion, ct))); result.Add(fixAllProjects); } return result.AsImmutable(); } public Solution UpgradeAllProjects(Solution solution, string language, string version, CancellationToken cancellationToken) { var currentSolution = solution; foreach (var projectId in solution.Projects.Select(p => p.Id)) { cancellationToken.ThrowIfCancellationRequested(); var currentProject = currentSolution.GetProject(projectId); if (CanUpgrade(currentProject, language, version)) { currentSolution = UpgradeProject(currentProject, version); } } return currentSolution; } private bool CanUpgrade(Project project, string language, string version) => project.Language == language && IsUpgrade(project, version); } internal class ProjectOptionsChangeAction : SolutionChangeAction { public ProjectOptionsChangeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, equivalenceKey: null) { } protected override Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync(CancellationToken cancellationToken) => SpecializedTasks.EmptyEnumerable<CodeActionOperation>(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.UpgradeProject { internal abstract partial class AbstractUpgradeProjectCodeFixProvider : CodeFixProvider { public abstract string SuggestedVersion(ImmutableArray<Diagnostic> diagnostics); public abstract Solution UpgradeProject(Project project, string version); public abstract bool IsUpgrade(Project project, string newVersion); public abstract string UpgradeThisProjectResource { get; } public abstract string UpgradeAllProjectsResource { get; } public override FixAllProvider GetFixAllProvider() { // This code fix uses a dedicated action for fixing all instances in a solution return null; } public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostics = context.Diagnostics; context.RegisterFixes(GetUpgradeProjectCodeActions(context), diagnostics); return Task.CompletedTask; } protected ImmutableArray<CodeAction> GetUpgradeProjectCodeActions(CodeFixContext context) { var project = context.Document.Project; var solution = project.Solution; var newVersion = SuggestedVersion(context.Diagnostics); var result = new List<CodeAction>(); var language = project.Language; var upgradeableProjects = solution.Projects.Where(p => CanUpgrade(p, language, newVersion)).AsImmutable(); if (upgradeableProjects.Length == 0) { return ImmutableArray<CodeAction>.Empty; } var fixOneProjectTitle = string.Format(UpgradeThisProjectResource, newVersion); var fixOneProject = new ProjectOptionsChangeAction(fixOneProjectTitle, _ => Task.FromResult(UpgradeProject(project, newVersion))); result.Add(fixOneProject); if (upgradeableProjects.Length > 1) { var fixAllProjectsTitle = string.Format(UpgradeAllProjectsResource, newVersion); var fixAllProjects = new ProjectOptionsChangeAction(fixAllProjectsTitle, ct => Task.FromResult(UpgradeAllProjects(solution, language, newVersion, ct))); result.Add(fixAllProjects); } return result.AsImmutable(); } public Solution UpgradeAllProjects(Solution solution, string language, string version, CancellationToken cancellationToken) { var currentSolution = solution; foreach (var projectId in solution.Projects.Select(p => p.Id)) { cancellationToken.ThrowIfCancellationRequested(); var currentProject = currentSolution.GetProject(projectId); if (CanUpgrade(currentProject, language, version)) { currentSolution = UpgradeProject(currentProject, version); } } return currentSolution; } private bool CanUpgrade(Project project, string language, string version) => project.Language == language && IsUpgrade(project, version); } internal class ProjectOptionsChangeAction : SolutionChangeAction { public ProjectOptionsChangeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, equivalenceKey: null) { } protected override Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync(CancellationToken cancellationToken) => SpecializedTasks.EmptyEnumerable<CodeActionOperation>(); } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/Core/Portable/AddImport/Remote/IRemoteMissingImportDiscoveryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.AddImport { internal interface IRemoteMissingImportDiscoveryService { internal interface ICallback { ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(RemoteServiceCallbackId callbackId, string source, string name, int arity, CancellationToken cancellationToken); ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(RemoteServiceCallbackId callbackId, string source, string name, CancellationToken cancellationToken); ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(RemoteServiceCallbackId callbackId, string name, int arity, CancellationToken cancellationToken); } ValueTask<ImmutableArray<AddImportFixData>> GetFixesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, string diagnosticId, int maxResults, bool allowInHiddenRegions, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken); ValueTask<ImmutableArray<AddImportFixData>> GetUniqueFixesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId id, TextSpan span, ImmutableArray<string> diagnosticIds, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.AddImport { internal interface IRemoteMissingImportDiscoveryService { internal interface ICallback { ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(RemoteServiceCallbackId callbackId, string source, string name, int arity, CancellationToken cancellationToken); ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(RemoteServiceCallbackId callbackId, string source, string name, CancellationToken cancellationToken); ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(RemoteServiceCallbackId callbackId, string name, int arity, CancellationToken cancellationToken); } ValueTask<ImmutableArray<AddImportFixData>> GetFixesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, string diagnosticId, int maxResults, bool allowInHiddenRegions, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken); ValueTask<ImmutableArray<AddImportFixData>> GetUniqueFixesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId id, TextSpan span, ImmutableArray<string> diagnosticIds, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/Core/Portable/SolutionCrawler/SolutionCrawlerLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Diagnostics.EngineV2; using Microsoft.CodeAnalysis.Internal.Log; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal static class SolutionCrawlerLogger { private const string Id = nameof(Id); private const string Kind = nameof(Kind); private const string Analyzer = nameof(Analyzer); private const string DocumentCount = nameof(DocumentCount); private const string Languages = nameof(Languages); private const string HighPriority = nameof(HighPriority); private const string Enabled = nameof(Enabled); private const string AnalyzerCount = nameof(AnalyzerCount); private const string PersistentStorage = nameof(PersistentStorage); private const string GlobalOperation = nameof(GlobalOperation); private const string HigherPriority = nameof(HigherPriority); private const string LowerPriority = nameof(LowerPriority); private const string TopLevel = nameof(TopLevel); private const string MemberLevel = nameof(MemberLevel); private const string NewWorkItem = nameof(NewWorkItem); private const string UpdateWorkItem = nameof(UpdateWorkItem); private const string ProjectEnqueue = nameof(ProjectEnqueue); private const string ResetStates = nameof(ResetStates); private const string ProjectNotExist = nameof(ProjectNotExist); private const string DocumentNotExist = nameof(DocumentNotExist); private const string ProcessProject = nameof(ProcessProject); private const string OpenDocument = nameof(OpenDocument); private const string CloseDocument = nameof(CloseDocument); private const string SolutionHash = nameof(SolutionHash); private const string ProcessDocument = nameof(ProcessDocument); private const string ProcessDocumentCancellation = nameof(ProcessDocumentCancellation); private const string ProcessProjectCancellation = nameof(ProcessProjectCancellation); private const string ActiveFileEnqueue = nameof(ActiveFileEnqueue); private const string ActiveFileProcessDocument = nameof(ActiveFileProcessDocument); private const string ActiveFileProcessDocumentCancellation = nameof(ActiveFileProcessDocumentCancellation); private const string Max = "Maximum"; private const string Min = "Minimum"; private const string Median = nameof(Median); private const string Mean = nameof(Mean); private const string Mode = nameof(Mode); private const string Range = nameof(Range); private const string Count = nameof(Count); public static void LogRegistration(int correlationId, Workspace workspace) { Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Register, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Kind] = workspace.Kind; })); } public static void LogUnregistration(int correlationId) { Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Unregister, KeyValueLogMessage.Create(m => { m[Id] = correlationId; })); } public static void LogReanalyze( int correlationId, IIncrementalAnalyzer analyzer, int documentCount, string languages, bool highPriority) { Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Reanalyze, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Analyzer] = analyzer.ToString(); m[DocumentCount] = documentCount; m[HighPriority] = highPriority; m[Languages] = languages; })); } public static void LogOptionChanged(int correlationId, bool value) { Logger.Log(FunctionId.WorkCoordinator_SolutionCrawlerOption, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Enabled] = value; })); } public static void LogAnalyzers(int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered, bool onlyHighPriorityAnalyzer) { if (onlyHighPriorityAnalyzer) { LogAnalyzersWorker( FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzers, FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzer, correlationId, workspace, reordered); } else { LogAnalyzersWorker( FunctionId.IncrementalAnalyzerProcessor_Analyzers, FunctionId.IncrementalAnalyzerProcessor_Analyzer, correlationId, workspace, reordered); } } private static void LogAnalyzersWorker( FunctionId analyzersId, FunctionId analyzerId, int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered) { if (workspace.Kind == WorkspaceKind.Preview) { return; } // log registered analyzers. Logger.Log(analyzersId, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[AnalyzerCount] = reordered.Length; })); foreach (var analyzer in reordered) { Logger.Log(analyzerId, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Analyzer] = analyzer.ToString(); })); } } public static void LogWorkCoordinatorShutdownTimeout(int correlationId) { Logger.Log(FunctionId.WorkCoordinator_ShutdownTimeout, KeyValueLogMessage.Create(m => { m[Id] = correlationId; })); } public static void LogWorkspaceEvent(LogAggregator logAggregator, int kind) => logAggregator.IncreaseCount(kind); public static void LogWorkCoordinatorShutdown(int correlationId, LogAggregator logAggregator) { Logger.Log(FunctionId.WorkCoordinator_Shutdown, KeyValueLogMessage.Create(m => { m[Id] = correlationId; foreach (var kv in logAggregator) { var change = ((WorkspaceChangeKind)kv.Key).ToString(); m[change] = kv.Value.GetCount(); } })); } public static void LogGlobalOperation(LogAggregator logAggregator) => logAggregator.IncreaseCount(GlobalOperation); public static void LogActiveFileEnqueue(LogAggregator logAggregator) => logAggregator.IncreaseCount(ActiveFileEnqueue); public static void LogWorkItemEnqueue(LogAggregator logAggregator, ProjectId _) => logAggregator.IncreaseCount(ProjectEnqueue); public static void LogWorkItemEnqueue( LogAggregator logAggregator, string language, DocumentId? documentId, InvocationReasons reasons, bool lowPriority, SyntaxPath? activeMember, bool added) { logAggregator.IncreaseCount(language); logAggregator.IncreaseCount(added ? NewWorkItem : UpdateWorkItem); if (documentId != null) { logAggregator.IncreaseCount(activeMember == null ? TopLevel : MemberLevel); if (lowPriority) { logAggregator.IncreaseCount(LowerPriority); logAggregator.IncreaseCount(ValueTuple.Create(LowerPriority, documentId.Id)); } } foreach (var reason in reasons) { logAggregator.IncreaseCount(reason); } } public static void LogHigherPriority(LogAggregator logAggregator, Guid documentId) { logAggregator.IncreaseCount(HigherPriority); logAggregator.IncreaseCount(ValueTuple.Create(HigherPriority, documentId)); } public static void LogResetStates(LogAggregator logAggregator) => logAggregator.IncreaseCount(ResetStates); public static void LogIncrementalAnalyzerProcessorStatistics(int correlationId, Solution solution, LogAggregator logAggregator, ImmutableArray<IIncrementalAnalyzer> analyzers) { Logger.Log(FunctionId.IncrementalAnalyzerProcessor_Shutdown, KeyValueLogMessage.Create(m => { var solutionHash = GetSolutionHash(solution); m[Id] = correlationId; m[SolutionHash] = solutionHash.ToString(); var statMap = new Dictionary<string, List<int>>(); foreach (var (key, counter) in logAggregator) { if (key is string stringKey) { m[stringKey] = counter.GetCount(); continue; } if (key is ValueTuple<string, Guid> propertyNameAndId) { var list = statMap.GetOrAdd(propertyNameAndId.Item1, _ => new List<int>()); list.Add(counter.GetCount()); continue; } throw ExceptionUtilities.Unreachable; } foreach (var (propertyName, propertyValues) in statMap) { var result = LogAggregator.GetStatistics(propertyValues); m[CreateProperty(propertyName, Max)] = result.Maximum; m[CreateProperty(propertyName, Min)] = result.Minimum; m[CreateProperty(propertyName, Median)] = result.Median!.Value; m[CreateProperty(propertyName, Mean)] = result.Mean; m[CreateProperty(propertyName, Mode)] = result.Mode!.Value; m[CreateProperty(propertyName, Range)] = result.Range; m[CreateProperty(propertyName, Count)] = result.Count; } })); foreach (var analyzer in analyzers) { if (analyzer is DiagnosticIncrementalAnalyzer diagIncrementalAnalyzer) { diagIncrementalAnalyzer.LogAnalyzerCountSummary(); break; } } } private static int GetSolutionHash(Solution solution) { if (solution != null && solution.FilePath != null) { return solution.FilePath.ToLowerInvariant().GetHashCode(); } return 0; } private static string CreateProperty(string parent, string child) => parent + "." + child; public static void LogProcessCloseDocument(LogAggregator logAggregator, Guid documentId) { logAggregator.IncreaseCount(CloseDocument); logAggregator.IncreaseCount(ValueTuple.Create(CloseDocument, documentId)); } public static void LogProcessOpenDocument(LogAggregator logAggregator, Guid documentId) { logAggregator.IncreaseCount(OpenDocument); logAggregator.IncreaseCount(ValueTuple.Create(OpenDocument, documentId)); } public static void LogProcessActiveFileDocument(LogAggregator logAggregator, Guid _, bool processed) { if (processed) { logAggregator.IncreaseCount(ActiveFileProcessDocument); } else { logAggregator.IncreaseCount(ActiveFileProcessDocumentCancellation); } } public static void LogProcessDocument(LogAggregator logAggregator, Guid documentId, bool processed) { if (processed) { logAggregator.IncreaseCount(ProcessDocument); } else { logAggregator.IncreaseCount(ProcessDocumentCancellation); } logAggregator.IncreaseCount(ValueTuple.Create(ProcessDocument, documentId)); } public static void LogProcessDocumentNotExist(LogAggregator logAggregator) => logAggregator.IncreaseCount(DocumentNotExist); public static void LogProcessProject(LogAggregator logAggregator, Guid projectId, bool processed) { if (processed) { logAggregator.IncreaseCount(ProcessProject); } else { logAggregator.IncreaseCount(ProcessProjectCancellation); } logAggregator.IncreaseCount(ValueTuple.Create(ProcessProject, projectId)); } public static void LogProcessProjectNotExist(LogAggregator logAggregator) => logAggregator.IncreaseCount(ProjectNotExist); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Diagnostics.EngineV2; using Microsoft.CodeAnalysis.Internal.Log; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal static class SolutionCrawlerLogger { private const string Id = nameof(Id); private const string Kind = nameof(Kind); private const string Analyzer = nameof(Analyzer); private const string DocumentCount = nameof(DocumentCount); private const string Languages = nameof(Languages); private const string HighPriority = nameof(HighPriority); private const string Enabled = nameof(Enabled); private const string AnalyzerCount = nameof(AnalyzerCount); private const string PersistentStorage = nameof(PersistentStorage); private const string GlobalOperation = nameof(GlobalOperation); private const string HigherPriority = nameof(HigherPriority); private const string LowerPriority = nameof(LowerPriority); private const string TopLevel = nameof(TopLevel); private const string MemberLevel = nameof(MemberLevel); private const string NewWorkItem = nameof(NewWorkItem); private const string UpdateWorkItem = nameof(UpdateWorkItem); private const string ProjectEnqueue = nameof(ProjectEnqueue); private const string ResetStates = nameof(ResetStates); private const string ProjectNotExist = nameof(ProjectNotExist); private const string DocumentNotExist = nameof(DocumentNotExist); private const string ProcessProject = nameof(ProcessProject); private const string OpenDocument = nameof(OpenDocument); private const string CloseDocument = nameof(CloseDocument); private const string SolutionHash = nameof(SolutionHash); private const string ProcessDocument = nameof(ProcessDocument); private const string ProcessDocumentCancellation = nameof(ProcessDocumentCancellation); private const string ProcessProjectCancellation = nameof(ProcessProjectCancellation); private const string ActiveFileEnqueue = nameof(ActiveFileEnqueue); private const string ActiveFileProcessDocument = nameof(ActiveFileProcessDocument); private const string ActiveFileProcessDocumentCancellation = nameof(ActiveFileProcessDocumentCancellation); private const string Max = "Maximum"; private const string Min = "Minimum"; private const string Median = nameof(Median); private const string Mean = nameof(Mean); private const string Mode = nameof(Mode); private const string Range = nameof(Range); private const string Count = nameof(Count); public static void LogRegistration(int correlationId, Workspace workspace) { Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Register, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Kind] = workspace.Kind; })); } public static void LogUnregistration(int correlationId) { Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Unregister, KeyValueLogMessage.Create(m => { m[Id] = correlationId; })); } public static void LogReanalyze( int correlationId, IIncrementalAnalyzer analyzer, int documentCount, string languages, bool highPriority) { Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Reanalyze, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Analyzer] = analyzer.ToString(); m[DocumentCount] = documentCount; m[HighPriority] = highPriority; m[Languages] = languages; })); } public static void LogOptionChanged(int correlationId, bool value) { Logger.Log(FunctionId.WorkCoordinator_SolutionCrawlerOption, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Enabled] = value; })); } public static void LogAnalyzers(int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered, bool onlyHighPriorityAnalyzer) { if (onlyHighPriorityAnalyzer) { LogAnalyzersWorker( FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzers, FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzer, correlationId, workspace, reordered); } else { LogAnalyzersWorker( FunctionId.IncrementalAnalyzerProcessor_Analyzers, FunctionId.IncrementalAnalyzerProcessor_Analyzer, correlationId, workspace, reordered); } } private static void LogAnalyzersWorker( FunctionId analyzersId, FunctionId analyzerId, int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered) { if (workspace.Kind == WorkspaceKind.Preview) { return; } // log registered analyzers. Logger.Log(analyzersId, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[AnalyzerCount] = reordered.Length; })); foreach (var analyzer in reordered) { Logger.Log(analyzerId, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Analyzer] = analyzer.ToString(); })); } } public static void LogWorkCoordinatorShutdownTimeout(int correlationId) { Logger.Log(FunctionId.WorkCoordinator_ShutdownTimeout, KeyValueLogMessage.Create(m => { m[Id] = correlationId; })); } public static void LogWorkspaceEvent(LogAggregator logAggregator, int kind) => logAggregator.IncreaseCount(kind); public static void LogWorkCoordinatorShutdown(int correlationId, LogAggregator logAggregator) { Logger.Log(FunctionId.WorkCoordinator_Shutdown, KeyValueLogMessage.Create(m => { m[Id] = correlationId; foreach (var kv in logAggregator) { var change = ((WorkspaceChangeKind)kv.Key).ToString(); m[change] = kv.Value.GetCount(); } })); } public static void LogGlobalOperation(LogAggregator logAggregator) => logAggregator.IncreaseCount(GlobalOperation); public static void LogActiveFileEnqueue(LogAggregator logAggregator) => logAggregator.IncreaseCount(ActiveFileEnqueue); public static void LogWorkItemEnqueue(LogAggregator logAggregator, ProjectId _) => logAggregator.IncreaseCount(ProjectEnqueue); public static void LogWorkItemEnqueue( LogAggregator logAggregator, string language, DocumentId? documentId, InvocationReasons reasons, bool lowPriority, SyntaxPath? activeMember, bool added) { logAggregator.IncreaseCount(language); logAggregator.IncreaseCount(added ? NewWorkItem : UpdateWorkItem); if (documentId != null) { logAggregator.IncreaseCount(activeMember == null ? TopLevel : MemberLevel); if (lowPriority) { logAggregator.IncreaseCount(LowerPriority); logAggregator.IncreaseCount(ValueTuple.Create(LowerPriority, documentId.Id)); } } foreach (var reason in reasons) { logAggregator.IncreaseCount(reason); } } public static void LogHigherPriority(LogAggregator logAggregator, Guid documentId) { logAggregator.IncreaseCount(HigherPriority); logAggregator.IncreaseCount(ValueTuple.Create(HigherPriority, documentId)); } public static void LogResetStates(LogAggregator logAggregator) => logAggregator.IncreaseCount(ResetStates); public static void LogIncrementalAnalyzerProcessorStatistics(int correlationId, Solution solution, LogAggregator logAggregator, ImmutableArray<IIncrementalAnalyzer> analyzers) { Logger.Log(FunctionId.IncrementalAnalyzerProcessor_Shutdown, KeyValueLogMessage.Create(m => { var solutionHash = GetSolutionHash(solution); m[Id] = correlationId; m[SolutionHash] = solutionHash.ToString(); var statMap = new Dictionary<string, List<int>>(); foreach (var (key, counter) in logAggregator) { if (key is string stringKey) { m[stringKey] = counter.GetCount(); continue; } if (key is ValueTuple<string, Guid> propertyNameAndId) { var list = statMap.GetOrAdd(propertyNameAndId.Item1, _ => new List<int>()); list.Add(counter.GetCount()); continue; } throw ExceptionUtilities.Unreachable; } foreach (var (propertyName, propertyValues) in statMap) { var result = LogAggregator.GetStatistics(propertyValues); m[CreateProperty(propertyName, Max)] = result.Maximum; m[CreateProperty(propertyName, Min)] = result.Minimum; m[CreateProperty(propertyName, Median)] = result.Median!.Value; m[CreateProperty(propertyName, Mean)] = result.Mean; m[CreateProperty(propertyName, Mode)] = result.Mode!.Value; m[CreateProperty(propertyName, Range)] = result.Range; m[CreateProperty(propertyName, Count)] = result.Count; } })); foreach (var analyzer in analyzers) { if (analyzer is DiagnosticIncrementalAnalyzer diagIncrementalAnalyzer) { diagIncrementalAnalyzer.LogAnalyzerCountSummary(); break; } } } private static int GetSolutionHash(Solution solution) { if (solution != null && solution.FilePath != null) { return solution.FilePath.ToLowerInvariant().GetHashCode(); } return 0; } private static string CreateProperty(string parent, string child) => parent + "." + child; public static void LogProcessCloseDocument(LogAggregator logAggregator, Guid documentId) { logAggregator.IncreaseCount(CloseDocument); logAggregator.IncreaseCount(ValueTuple.Create(CloseDocument, documentId)); } public static void LogProcessOpenDocument(LogAggregator logAggregator, Guid documentId) { logAggregator.IncreaseCount(OpenDocument); logAggregator.IncreaseCount(ValueTuple.Create(OpenDocument, documentId)); } public static void LogProcessActiveFileDocument(LogAggregator logAggregator, Guid _, bool processed) { if (processed) { logAggregator.IncreaseCount(ActiveFileProcessDocument); } else { logAggregator.IncreaseCount(ActiveFileProcessDocumentCancellation); } } public static void LogProcessDocument(LogAggregator logAggregator, Guid documentId, bool processed) { if (processed) { logAggregator.IncreaseCount(ProcessDocument); } else { logAggregator.IncreaseCount(ProcessDocumentCancellation); } logAggregator.IncreaseCount(ValueTuple.Create(ProcessDocument, documentId)); } public static void LogProcessDocumentNotExist(LogAggregator logAggregator) => logAggregator.IncreaseCount(DocumentNotExist); public static void LogProcessProject(LogAggregator logAggregator, Guid projectId, bool processed) { if (processed) { logAggregator.IncreaseCount(ProcessProject); } else { logAggregator.IncreaseCount(ProcessProjectCancellation); } logAggregator.IncreaseCount(ValueTuple.Create(ProcessProject, projectId)); } public static void LogProcessProjectNotExist(LogAggregator logAggregator) => logAggregator.IncreaseCount(ProjectNotExist); } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Compilers/Core/Portable/InternalUtilities/ThreeState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents an optional bool as a single byte. /// </summary> internal enum ThreeState : byte { Unknown = 0, False = 1, True = 2, } internal static class ThreeStateHelpers { public static ThreeState ToThreeState(this bool value) { return value ? ThreeState.True : ThreeState.False; } public static bool HasValue(this ThreeState value) { return value != ThreeState.Unknown; } public static bool Value(this ThreeState value) { Debug.Assert(value != ThreeState.Unknown); return value == ThreeState.True; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents an optional bool as a single byte. /// </summary> internal enum ThreeState : byte { Unknown = 0, False = 1, True = 2, } internal static class ThreeStateHelpers { public static ThreeState ToThreeState(this bool value) { return value ? ThreeState.True : ThreeState.False; } public static bool HasValue(this ThreeState value) { return value != ThreeState.Unknown; } public static bool Value(this ThreeState value) { Debug.Assert(value != ThreeState.Unknown); return value == ThreeState.True; } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/EditorFeatures/Core/Implementation/InlineRename/RenameTrackingSpan.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal struct RenameTrackingSpan { public readonly ITrackingSpan TrackingSpan; public readonly RenameSpanKind Type; public RenameTrackingSpan(ITrackingSpan trackingSpan, RenameSpanKind type) { this.TrackingSpan = trackingSpan; this.Type = type; } } internal enum RenameSpanKind { None, Reference, UnresolvedConflict, Complexified } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal struct RenameTrackingSpan { public readonly ITrackingSpan TrackingSpan; public readonly RenameSpanKind Type; public RenameTrackingSpan(ITrackingSpan trackingSpan, RenameSpanKind type) { this.TrackingSpan = trackingSpan; this.Type = type; } } internal enum RenameSpanKind { None, Reference, UnresolvedConflict, Complexified } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/ImmutableArrayExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal static class ImmutableArrayExtensions { internal static int IndexOf<TItem, TArg>(this ImmutableArray<TItem> array, Func<TItem, TArg, bool> predicate, TArg arg) { for (int i = 0; i < array.Length; i++) { if (predicate(array[i], arg)) { return i; } } return -1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal static class ImmutableArrayExtensions { internal static int IndexOf<TItem, TArg>(this ImmutableArray<TItem> array, Func<TItem, TArg, bool> predicate, TArg arg) { for (int i = 0; i < array.Length; i++) { if (predicate(array[i], arg)) { return i; } } return -1; } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ModuleKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ModuleKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ModuleKeywordRecommender() : base(SyntaxKind.ModuleKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsTypeAttributeContext(cancellationToken)) { var token = context.LeftToken; var type = token.GetAncestor<MemberDeclarationSyntax>(); return type == null || type.IsParentKind(SyntaxKind.CompilationUnit); } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ModuleKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ModuleKeywordRecommender() : base(SyntaxKind.ModuleKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsTypeAttributeContext(cancellationToken)) { var token = context.LeftToken; var type = token.GetAncestor<MemberDeclarationSyntax>(); return type == null || type.IsParentKind(SyntaxKind.CompilationUnit); } return false; } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/InteractiveWindow_InProc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using ThreadHelper = Microsoft.VisualStudio.Shell.ThreadHelper; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { /// <summary> /// Provides a means of accessing the <see cref="IInteractiveWindow"/> service in the Visual Studio host. /// </summary> /// <remarks> /// This object exists in the Visual Studio host and is marhsalled across the process boundary. /// </remarks> internal abstract class InteractiveWindow_InProc : TextViewWindow_InProc { private static readonly Func<string, string, bool> s_contains = (expected, actual) => actual.Contains(expected); private static readonly Func<string, string, bool> s_endsWith = (expected, actual) => actual.EndsWith(expected); private const string NewLineFollowedByReplSubmissionText = "\n. "; private const string ReplSubmissionText = ". "; private const string ReplPromptText = "> "; private readonly string _viewCommand; private readonly Guid _windowId; private IInteractiveWindow? _interactiveWindow; protected InteractiveWindow_InProc(string viewCommand, Guid windowId) { _viewCommand = viewCommand; _windowId = windowId; } public void Initialize() { // We have to show the window at least once to ensure the interactive service is loaded. ShowWindow(waitForPrompt: false); CloseWindow(); _interactiveWindow = AcquireInteractiveWindow(); Contract.ThrowIfNull(_interactiveWindow); } protected abstract IInteractiveWindow AcquireInteractiveWindow(); public bool IsInitializing { get { Contract.ThrowIfNull(_interactiveWindow); return InvokeOnUIThread(cancellationToken => _interactiveWindow.IsInitializing); } } public string GetReplText() { Contract.ThrowIfNull(_interactiveWindow); return InvokeOnUIThread(cancellationToken => _interactiveWindow.TextView.TextBuffer.CurrentSnapshot.GetText()); } protected override bool HasActiveTextView() { Contract.ThrowIfNull(_interactiveWindow); return InvokeOnUIThread(cancellationToken => _interactiveWindow.TextView) is object; } protected override IWpfTextView GetActiveTextView() { Contract.ThrowIfNull(_interactiveWindow); return InvokeOnUIThread(cancellationToken => _interactiveWindow.TextView); } /// <summary> /// Gets the contents of the REPL window without the prompt text. /// </summary> public string GetReplTextWithoutPrompt() { var replText = GetReplText(); // find last prompt and remove var lastPromptIndex = replText.LastIndexOf(ReplPromptText); if (lastPromptIndex > 0) { replText = replText.Substring(0, lastPromptIndex); } // it's possible for the editor text to contain a trailing newline, remove it return replText.EndsWith(Environment.NewLine) ? replText.Substring(0, replText.Length - Environment.NewLine.Length) : replText; } /// <summary> /// Gets the last output from the REPL. /// </summary> public string GetLastReplOutput() { // TODO: This may be flaky if the last submission contains ReplPromptText var replText = GetReplTextWithoutPrompt(); var lastPromptIndex = replText.LastIndexOf(ReplPromptText); if (lastPromptIndex > 0) replText = replText.Substring(lastPromptIndex, replText.Length - lastPromptIndex); var lastSubmissionIndex = replText.LastIndexOf(NewLineFollowedByReplSubmissionText); if (lastSubmissionIndex > 0) { replText = replText.Substring(lastSubmissionIndex, replText.Length - lastSubmissionIndex); } else if (!replText.StartsWith(ReplPromptText)) { return replText; } var firstNewLineIndex = replText.IndexOf(Environment.NewLine); if (firstNewLineIndex <= 0) { return replText; } firstNewLineIndex += Environment.NewLine.Length; return replText.Substring(firstNewLineIndex, replText.Length - firstNewLineIndex); } /// <summary> /// Gets the last input from the REPL. /// </summary> public string GetLastReplInput() { // TODO: This may be flaky if the last submission contains ReplPromptText or ReplSubmissionText var replText = GetReplText(); var lastPromptIndex = replText.LastIndexOf(ReplPromptText); replText = replText.Substring(lastPromptIndex + ReplPromptText.Length); var lastSubmissionTextIndex = replText.LastIndexOf(NewLineFollowedByReplSubmissionText); int firstNewLineIndex; if (lastSubmissionTextIndex < 0) { firstNewLineIndex = replText.IndexOf(Environment.NewLine); } else { firstNewLineIndex = replText.IndexOf(Environment.NewLine, lastSubmissionTextIndex); } var lastReplInputWithReplSubmissionText = (firstNewLineIndex <= 0) ? replText : replText.Substring(0, firstNewLineIndex); return lastReplInputWithReplSubmissionText.Replace(ReplSubmissionText, string.Empty); } public void Reset(bool waitForPrompt = true) { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var interactiveWindow = AcquireInteractiveWindow(); var operations = (IInteractiveWindowOperations)interactiveWindow; var result = await operations.ResetAsync(); Contract.ThrowIfFalse(result.IsSuccessful); }); if (waitForPrompt) { WaitForReplPrompt(); } } public void SubmitText(string text) { Contract.ThrowIfNull(_interactiveWindow); using var cts = new CancellationTokenSource(Helper.HangMitigatingTimeout); _interactiveWindow.SubmitAsync(new[] { text }).WithCancellation(cts.Token).Wait(); } public void CloseWindow() { InvokeOnUIThread(cancellationToken => { var shell = GetGlobalService<SVsUIShell, IVsUIShell>(); if (ErrorHandler.Succeeded(shell.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fFrameOnly, _windowId, out var windowFrame))) { ErrorHandler.ThrowOnFailure(windowFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave)); } }); } public void ShowWindow(bool waitForPrompt = true) { ExecuteCommand(_viewCommand); if (waitForPrompt) { WaitForReplPrompt(); } } public void WaitForReplPrompt() => WaitForPredicate(GetReplText, ReplPromptText, s_endsWith, "end with"); public void WaitForReplOutput(string outputText) => WaitForPredicate(GetReplText, outputText + Environment.NewLine + ReplPromptText, s_endsWith, "end with"); public void ClearScreen() => ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ClearScreen); public void InsertCode(string text) { Contract.ThrowIfNull(_interactiveWindow); InvokeOnUIThread(cancellationToken => _interactiveWindow.InsertCode(text)); } public void WaitForLastReplOutput(string outputText) => WaitForPredicate(GetLastReplOutput, outputText, s_contains, "contain"); public void WaitForLastReplOutputContains(string outputText) => WaitForPredicate(GetLastReplOutput, outputText, s_contains, "contain"); public void WaitForLastReplInputContains(string outputText) => WaitForPredicate(GetLastReplInput, outputText, s_contains, "contain"); private void WaitForPredicate(Func<string> getValue, string expectedValue, Func<string, string, bool> valueComparer, string verb) { var beginTime = DateTime.UtcNow; while (true) { var actualValue = getValue(); if (valueComparer(expectedValue, actualValue)) { return; } if (DateTime.UtcNow > beginTime + Helper.HangMitigatingTimeout) { throw new Exception( $"Unable to find expected content in REPL within {Helper.HangMitigatingTimeout.TotalMilliseconds} milliseconds and no exceptions were thrown.{Environment.NewLine}" + $"Buffer content is expected to {verb}: {Environment.NewLine}" + $"[[{expectedValue}]]" + $"Actual content:{Environment.NewLine}" + $"[[{actualValue}]]"); } Thread.Sleep(50); } } protected override ITextBuffer GetBufferContainingCaret(IWpfTextView view) { Contract.ThrowIfNull(_interactiveWindow); return InvokeOnUIThread(cancellationToken => _interactiveWindow.TextView.TextBuffer); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using ThreadHelper = Microsoft.VisualStudio.Shell.ThreadHelper; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { /// <summary> /// Provides a means of accessing the <see cref="IInteractiveWindow"/> service in the Visual Studio host. /// </summary> /// <remarks> /// This object exists in the Visual Studio host and is marhsalled across the process boundary. /// </remarks> internal abstract class InteractiveWindow_InProc : TextViewWindow_InProc { private static readonly Func<string, string, bool> s_contains = (expected, actual) => actual.Contains(expected); private static readonly Func<string, string, bool> s_endsWith = (expected, actual) => actual.EndsWith(expected); private const string NewLineFollowedByReplSubmissionText = "\n. "; private const string ReplSubmissionText = ". "; private const string ReplPromptText = "> "; private readonly string _viewCommand; private readonly Guid _windowId; private IInteractiveWindow? _interactiveWindow; protected InteractiveWindow_InProc(string viewCommand, Guid windowId) { _viewCommand = viewCommand; _windowId = windowId; } public void Initialize() { // We have to show the window at least once to ensure the interactive service is loaded. ShowWindow(waitForPrompt: false); CloseWindow(); _interactiveWindow = AcquireInteractiveWindow(); Contract.ThrowIfNull(_interactiveWindow); } protected abstract IInteractiveWindow AcquireInteractiveWindow(); public bool IsInitializing { get { Contract.ThrowIfNull(_interactiveWindow); return InvokeOnUIThread(cancellationToken => _interactiveWindow.IsInitializing); } } public string GetReplText() { Contract.ThrowIfNull(_interactiveWindow); return InvokeOnUIThread(cancellationToken => _interactiveWindow.TextView.TextBuffer.CurrentSnapshot.GetText()); } protected override bool HasActiveTextView() { Contract.ThrowIfNull(_interactiveWindow); return InvokeOnUIThread(cancellationToken => _interactiveWindow.TextView) is object; } protected override IWpfTextView GetActiveTextView() { Contract.ThrowIfNull(_interactiveWindow); return InvokeOnUIThread(cancellationToken => _interactiveWindow.TextView); } /// <summary> /// Gets the contents of the REPL window without the prompt text. /// </summary> public string GetReplTextWithoutPrompt() { var replText = GetReplText(); // find last prompt and remove var lastPromptIndex = replText.LastIndexOf(ReplPromptText); if (lastPromptIndex > 0) { replText = replText.Substring(0, lastPromptIndex); } // it's possible for the editor text to contain a trailing newline, remove it return replText.EndsWith(Environment.NewLine) ? replText.Substring(0, replText.Length - Environment.NewLine.Length) : replText; } /// <summary> /// Gets the last output from the REPL. /// </summary> public string GetLastReplOutput() { // TODO: This may be flaky if the last submission contains ReplPromptText var replText = GetReplTextWithoutPrompt(); var lastPromptIndex = replText.LastIndexOf(ReplPromptText); if (lastPromptIndex > 0) replText = replText.Substring(lastPromptIndex, replText.Length - lastPromptIndex); var lastSubmissionIndex = replText.LastIndexOf(NewLineFollowedByReplSubmissionText); if (lastSubmissionIndex > 0) { replText = replText.Substring(lastSubmissionIndex, replText.Length - lastSubmissionIndex); } else if (!replText.StartsWith(ReplPromptText)) { return replText; } var firstNewLineIndex = replText.IndexOf(Environment.NewLine); if (firstNewLineIndex <= 0) { return replText; } firstNewLineIndex += Environment.NewLine.Length; return replText.Substring(firstNewLineIndex, replText.Length - firstNewLineIndex); } /// <summary> /// Gets the last input from the REPL. /// </summary> public string GetLastReplInput() { // TODO: This may be flaky if the last submission contains ReplPromptText or ReplSubmissionText var replText = GetReplText(); var lastPromptIndex = replText.LastIndexOf(ReplPromptText); replText = replText.Substring(lastPromptIndex + ReplPromptText.Length); var lastSubmissionTextIndex = replText.LastIndexOf(NewLineFollowedByReplSubmissionText); int firstNewLineIndex; if (lastSubmissionTextIndex < 0) { firstNewLineIndex = replText.IndexOf(Environment.NewLine); } else { firstNewLineIndex = replText.IndexOf(Environment.NewLine, lastSubmissionTextIndex); } var lastReplInputWithReplSubmissionText = (firstNewLineIndex <= 0) ? replText : replText.Substring(0, firstNewLineIndex); return lastReplInputWithReplSubmissionText.Replace(ReplSubmissionText, string.Empty); } public void Reset(bool waitForPrompt = true) { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var interactiveWindow = AcquireInteractiveWindow(); var operations = (IInteractiveWindowOperations)interactiveWindow; var result = await operations.ResetAsync(); Contract.ThrowIfFalse(result.IsSuccessful); }); if (waitForPrompt) { WaitForReplPrompt(); } } public void SubmitText(string text) { Contract.ThrowIfNull(_interactiveWindow); using var cts = new CancellationTokenSource(Helper.HangMitigatingTimeout); _interactiveWindow.SubmitAsync(new[] { text }).WithCancellation(cts.Token).Wait(); } public void CloseWindow() { InvokeOnUIThread(cancellationToken => { var shell = GetGlobalService<SVsUIShell, IVsUIShell>(); if (ErrorHandler.Succeeded(shell.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fFrameOnly, _windowId, out var windowFrame))) { ErrorHandler.ThrowOnFailure(windowFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave)); } }); } public void ShowWindow(bool waitForPrompt = true) { ExecuteCommand(_viewCommand); if (waitForPrompt) { WaitForReplPrompt(); } } public void WaitForReplPrompt() => WaitForPredicate(GetReplText, ReplPromptText, s_endsWith, "end with"); public void WaitForReplOutput(string outputText) => WaitForPredicate(GetReplText, outputText + Environment.NewLine + ReplPromptText, s_endsWith, "end with"); public void ClearScreen() => ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ClearScreen); public void InsertCode(string text) { Contract.ThrowIfNull(_interactiveWindow); InvokeOnUIThread(cancellationToken => _interactiveWindow.InsertCode(text)); } public void WaitForLastReplOutput(string outputText) => WaitForPredicate(GetLastReplOutput, outputText, s_contains, "contain"); public void WaitForLastReplOutputContains(string outputText) => WaitForPredicate(GetLastReplOutput, outputText, s_contains, "contain"); public void WaitForLastReplInputContains(string outputText) => WaitForPredicate(GetLastReplInput, outputText, s_contains, "contain"); private void WaitForPredicate(Func<string> getValue, string expectedValue, Func<string, string, bool> valueComparer, string verb) { var beginTime = DateTime.UtcNow; while (true) { var actualValue = getValue(); if (valueComparer(expectedValue, actualValue)) { return; } if (DateTime.UtcNow > beginTime + Helper.HangMitigatingTimeout) { throw new Exception( $"Unable to find expected content in REPL within {Helper.HangMitigatingTimeout.TotalMilliseconds} milliseconds and no exceptions were thrown.{Environment.NewLine}" + $"Buffer content is expected to {verb}: {Environment.NewLine}" + $"[[{expectedValue}]]" + $"Actual content:{Environment.NewLine}" + $"[[{actualValue}]]"); } Thread.Sleep(50); } } protected override ITextBuffer GetBufferContainingCaret(IWpfTextView view) { Contract.ThrowIfNull(_interactiveWindow); return InvokeOnUIThread(cancellationToken => _interactiveWindow.TextView.TextBuffer); } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Compilers/Test/Core/Assert/EqualityTesting.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { /// <summary> /// Helpers for testing equality APIs. /// Gives us more control than calling Assert.Equals. /// </summary> public static class EqualityTesting { public static void AssertEqual<T>(IEquatable<T> x, IEquatable<T> y) { Assert.True(x.Equals(y)); Assert.True(((object)x).Equals(y)); Assert.Equal(x.GetHashCode(), y.GetHashCode()); } public static void AssertNotEqual<T>(IEquatable<T> x, IEquatable<T> y) { Assert.False(x.Equals(y)); Assert.False(((object)x).Equals(y)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { /// <summary> /// Helpers for testing equality APIs. /// Gives us more control than calling Assert.Equals. /// </summary> public static class EqualityTesting { public static void AssertEqual<T>(IEquatable<T> x, IEquatable<T> y) { Assert.True(x.Equals(y)); Assert.True(((object)x).Equals(y)); Assert.Equal(x.GetHashCode(), y.GetHashCode()); } public static void AssertNotEqual<T>(IEquatable<T> x, IEquatable<T> y) { Assert.False(x.Equals(y)); Assert.False(((object)x).Equals(y)); } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/ExpressionEvaluator/Core/Source/ResultProvider/Formatter.Values.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.ObjectModel; using System.Diagnostics; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { [Flags] internal enum GetValueFlags { None = 0x0, IncludeTypeName = 0x1, IncludeObjectId = 0x2, } // This class provides implementation for the "displaying values as strings" aspect of the Formatter component. internal abstract partial class Formatter { private string GetValueString(DkmClrValue value, DkmInspectionContext inspectionContext, ObjectDisplayOptions options, GetValueFlags flags) { if (value.IsError()) { return (string)value.HostObjectValue; } if (UsesHexadecimalNumbers(inspectionContext)) { options |= ObjectDisplayOptions.UseHexadecimalNumbers; } var lmrType = value.Type.GetLmrType(); if (IsPredefinedType(lmrType) && !lmrType.IsObject()) { if (lmrType.IsString()) { var stringValue = (string)value.HostObjectValue; if (stringValue == null) { return _nullString; } return IncludeObjectId( value, FormatString(stringValue, options), flags); } else if (lmrType.IsCharacter()) { // check if HostObjectValue is null, since any of these types might actually be a synthetic value as well. if (value.HostObjectValue == null) { return _hostValueNotFoundString; } return IncludeObjectId( value, FormatLiteral((char)value.HostObjectValue, options | ObjectDisplayOptions.IncludeCodePoints), flags); } else { return IncludeObjectId( value, FormatPrimitive(value, options & ~(ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters), inspectionContext), flags); } } else if (value.IsNull && !lmrType.IsPointer) { return _nullString; } else if (lmrType.IsEnum) { return IncludeObjectId( value, GetEnumDisplayString(lmrType, value, options, (flags & GetValueFlags.IncludeTypeName) != 0, inspectionContext), flags); } else if (lmrType.IsArray) { return IncludeObjectId( value, GetArrayDisplayString(value.Type.AppDomain, lmrType, value.ArrayDimensions, value.ArrayLowerBounds, options), flags); } else if (lmrType.IsPointer) { // NOTE: the HostObjectValue will have a size corresponding to the process bitness // and FormatPrimitive will adjust accordingly. var tmp = FormatPrimitive(value, ObjectDisplayOptions.UseHexadecimalNumbers, inspectionContext); // Always in hex. Debug.Assert(tmp != null); return tmp; } else if (lmrType.IsNullable()) { var nullableValue = value.GetNullableValue(inspectionContext); // It should be impossible to nest nullables, so this recursion should introduce only a single extra stack frame. return nullableValue == null ? _nullString : GetValueString(nullableValue, inspectionContext, ObjectDisplayOptions.None, GetValueFlags.IncludeTypeName); } else if (lmrType.IsIntPtr()) { // check if HostObjectValue is null, since any of these types might actually be a synthetic value as well. if (value.HostObjectValue == null) { return _hostValueNotFoundString; } if (IntPtr.Size == 8) { var intPtr = ((IntPtr)value.HostObjectValue).ToInt64(); return FormatPrimitiveObject(intPtr, ObjectDisplayOptions.UseHexadecimalNumbers); } else { var intPtr = ((IntPtr)value.HostObjectValue).ToInt32(); return FormatPrimitiveObject(intPtr, ObjectDisplayOptions.UseHexadecimalNumbers); } } else if (lmrType.IsUIntPtr()) { // check if HostObjectValue is null, since any of these types might actually be a synthetic value as well. if (value.HostObjectValue == null) { return _hostValueNotFoundString; } if (UIntPtr.Size == 8) { var uIntPtr = ((UIntPtr)value.HostObjectValue).ToUInt64(); return FormatPrimitiveObject(uIntPtr, ObjectDisplayOptions.UseHexadecimalNumbers); } else { var uIntPtr = ((UIntPtr)value.HostObjectValue).ToUInt32(); return FormatPrimitiveObject(uIntPtr, ObjectDisplayOptions.UseHexadecimalNumbers); } } else { int cardinality; if (lmrType.IsTupleCompatible(out cardinality) && (cardinality > 1)) { var values = ArrayBuilder<string>.GetInstance(); if (value.TryGetTupleFieldValues(cardinality, values, inspectionContext)) { return IncludeObjectId( value, GetTupleExpression(values.ToArrayAndFree()), flags); } values.Free(); } } // "value.EvaluateToString()" will check "Call string-conversion function on objects in variables windows" // (Tools > Options setting) and call "value.ToString()" if appropriate. return IncludeObjectId( value, string.Format(_defaultFormat, value.EvaluateToString(inspectionContext) ?? inspectionContext.GetTypeName(value.Type, CustomTypeInfo: null, FormatSpecifiers: NoFormatSpecifiers)), flags); } /// <summary> /// Gets the string representation of a character literal without including the numeric code point. /// </summary> private string GetValueStringForCharacter(DkmClrValue value, DkmInspectionContext inspectionContext, ObjectDisplayOptions options) { Debug.Assert(value.Type.GetLmrType().IsCharacter()); if (UsesHexadecimalNumbers(inspectionContext)) { options |= ObjectDisplayOptions.UseHexadecimalNumbers; } // check if HostObjectValue is null, since any of these types might actually be a synthetic value as well. if (value.HostObjectValue == null) { return _hostValueNotFoundString; } var charTemp = FormatLiteral((char)value.HostObjectValue, options); Debug.Assert(charTemp != null); return charTemp; } private bool HasUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext) { return GetUnderlyingString(value, inspectionContext) != null; } private string GetUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext) { var dataItem = value.GetDataItem<RawStringDataItem>(); if (dataItem != null) { return dataItem.RawString; } string underlyingString = GetUnderlyingStringImpl(value, inspectionContext); dataItem = new RawStringDataItem(underlyingString); value.SetDataItem(DkmDataCreationDisposition.CreateNew, dataItem); return underlyingString; } private string GetUnderlyingStringImpl(DkmClrValue value, DkmInspectionContext inspectionContext) { Debug.Assert(!value.IsError()); if (value.IsNull) { return null; } var lmrType = value.Type.GetLmrType(); if (lmrType.IsEnum || lmrType.IsArray || lmrType.IsPointer) { return null; } if (lmrType.IsNullable()) { var nullableValue = value.GetNullableValue(inspectionContext); return nullableValue != null ? GetUnderlyingStringImpl(nullableValue, inspectionContext) : null; } if (lmrType.IsString()) { return (string)value.HostObjectValue; } else if (!IsPredefinedType(lmrType)) { // Check for special cased non-primitives that have underlying strings if (lmrType.IsType("System.Data.SqlTypes", "SqlString")) { var fieldValue = value.GetFieldValue(InternalWellKnownMemberNames.SqlStringValue, inspectionContext); return fieldValue.HostObjectValue as string; } else if (lmrType.IsOrInheritsFrom("System.Xml.Linq", "XNode")) { return value.EvaluateToString(inspectionContext); } } return null; } #pragma warning disable CA1200 // Avoid using cref tags with a prefix /// <remarks> /// The corresponding native code is in EEUserStringBuilder::ErrTryAppendConstantEnum. /// The corresponding roslyn code is in /// <see cref="M:Microsoft.CodeAnalysis.SymbolDisplay.AbstractSymbolDisplayVisitor`1.AddEnumConstantValue(Microsoft.CodeAnalysis.INamedTypeSymbol, System.Object, System.Boolean)"/>. /// NOTE: no curlies for enum values. /// </remarks> #pragma warning restore CA1200 // Avoid using cref tags with a prefix private string GetEnumDisplayString(Type lmrType, DkmClrValue value, ObjectDisplayOptions options, bool includeTypeName, DkmInspectionContext inspectionContext) { Debug.Assert(lmrType.IsEnum); Debug.Assert(value != null); object underlyingValue = value.HostObjectValue; // check if HostObjectValue is null, since any of these types might actually be a synthetic value as well. if (underlyingValue == null) { return _hostValueNotFoundString; } string displayString; var fields = ArrayBuilder<EnumField>.GetInstance(); FillEnumFields(fields, lmrType); // We will normalize/extend all enum values to ulong to ensure that we are always comparing the full underlying value. ulong valueForComparison = ConvertEnumUnderlyingTypeToUInt64(underlyingValue, Type.GetTypeCode(lmrType)); var typeToDisplayOpt = includeTypeName ? lmrType : null; if (valueForComparison != 0 && IsFlagsEnum(lmrType)) { displayString = GetNamesForFlagsEnumValue(fields, underlyingValue, valueForComparison, options, typeToDisplayOpt); } else { displayString = GetNameForEnumValue(fields, underlyingValue, valueForComparison, options, typeToDisplayOpt); } fields.Free(); return displayString ?? FormatPrimitive(value, options, inspectionContext); } private static void FillEnumFields(ArrayBuilder<EnumField> fields, Type lmrType) { var fieldInfos = lmrType.GetFields(); var enumTypeCode = Type.GetTypeCode(lmrType); foreach (var info in fieldInfos) { if (!info.IsSpecialName) // Skip __value. { fields.Add(new EnumField(info.Name, ConvertEnumUnderlyingTypeToUInt64(info.GetRawConstantValue(), enumTypeCode))); } } fields.Sort(EnumField.Comparer); } protected static void FillUsedEnumFields(ArrayBuilder<EnumField> usedFields, ArrayBuilder<EnumField> fields, ulong underlyingValue) { var remaining = underlyingValue; foreach (var field in fields) { var fieldValue = field.Value; if (fieldValue == 0) continue; // Otherwise, we'd tack the zero flag onto everything. if ((remaining & fieldValue) == fieldValue) { remaining -= fieldValue; usedFields.Add(field); if (remaining == 0) break; } } // The value contained extra bit flags that didn't correspond to any enum field. We will // report "no fields used" here so the Formatter will just display the underlying value. if (remaining != 0) { usedFields.Clear(); } } private static bool IsFlagsEnum(Type lmrType) { Debug.Assert(lmrType.IsEnum); var attributes = lmrType.GetCustomAttributesData(); foreach (var attribute in attributes) { // NOTE: AttributeType is not available in 2.0 if (attribute.Constructor.DeclaringType.FullName == "System.FlagsAttribute") { return true; } } return false; } private static bool UsesHexadecimalNumbers(DkmInspectionContext inspectionContext) { Debug.Assert(inspectionContext != null); return inspectionContext.Radix == 16; } /// <summary> /// Convert a boxed primitive (generally of the backing type of an enum) into a ulong. /// </summary> protected static ulong ConvertEnumUnderlyingTypeToUInt64(object value, TypeCode typeCode) { Debug.Assert(value != null); unchecked { switch (typeCode) { case TypeCode.SByte: return (ulong)(sbyte)value; case TypeCode.Int16: return (ulong)(short)value; case TypeCode.Int32: return (ulong)(int)value; case TypeCode.Int64: return (ulong)(long)value; case TypeCode.Byte: return (byte)value; case TypeCode.UInt16: return (ushort)value; case TypeCode.UInt32: return (uint)value; case TypeCode.UInt64: return (ulong)value; default: throw ExceptionUtilities.UnexpectedValue(typeCode); } } } private string GetEditableValue(DkmClrValue value, DkmInspectionContext inspectionContext, DkmClrCustomTypeInfo customTypeInfo) { if (value.IsError()) { return null; } if (value.EvalFlags.Includes(DkmEvaluationResultFlags.ReadOnly)) { return null; } var type = value.Type.GetLmrType(); if (type.IsEnum) { return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.None, GetValueFlags.IncludeTypeName); } else if (type.IsDecimal()) { return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.IncludeTypeSuffix, GetValueFlags.None); } // The legacy EE didn't special-case strings or chars (when ",nq" was used, // you had to manually add quotes when editing) but it makes sense to // always automatically quote (non-null) strings and chars when editing. else if (type.IsString()) { if (!value.IsNull) { return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters, GetValueFlags.None); } } else if (type.IsCharacter()) { return this.GetValueStringForCharacter(value, inspectionContext, ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters); } return null; } private string FormatPrimitive(DkmClrValue value, ObjectDisplayOptions options, DkmInspectionContext inspectionContext) { Debug.Assert(value != null); // check if HostObjectValue is null, since any of these types might actually be a synthetic value as well. if (value.HostObjectValue == null) { return _hostValueNotFoundString; } // DateTime is primitive in VB but not in C#. object obj; if (value.Type.GetLmrType().IsDateTime()) { var dateDataValue = value.GetPropertyValue("Ticks", inspectionContext); obj = new DateTime((long)dateDataValue.HostObjectValue); } else { obj = value.HostObjectValue; } return FormatPrimitiveObject(obj, options); } private static string IncludeObjectId(DkmClrValue value, string valueStr, GetValueFlags flags) { Debug.Assert(valueStr != null); return (flags & GetValueFlags.IncludeObjectId) == 0 ? valueStr : value.IncludeObjectId(valueStr); } #region Language-specific value formatting behavior internal abstract string GetArrayDisplayString(DkmClrAppDomain appDomain, Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options); internal abstract string GetArrayIndexExpression(string[] indices); internal abstract string GetCastExpression(string argument, string type, DkmClrCastExpressionOptions options); internal abstract string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt); internal abstract string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt); internal abstract string GetObjectCreationExpression(string type, string[] arguments); internal abstract string GetTupleExpression(string[] values); internal abstract string FormatLiteral(char c, ObjectDisplayOptions options); internal abstract string FormatLiteral(int value, ObjectDisplayOptions options); internal abstract string FormatPrimitiveObject(object value, ObjectDisplayOptions options); internal abstract string FormatString(string str, ObjectDisplayOptions options); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.ObjectModel; using System.Diagnostics; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { [Flags] internal enum GetValueFlags { None = 0x0, IncludeTypeName = 0x1, IncludeObjectId = 0x2, } // This class provides implementation for the "displaying values as strings" aspect of the Formatter component. internal abstract partial class Formatter { private string GetValueString(DkmClrValue value, DkmInspectionContext inspectionContext, ObjectDisplayOptions options, GetValueFlags flags) { if (value.IsError()) { return (string)value.HostObjectValue; } if (UsesHexadecimalNumbers(inspectionContext)) { options |= ObjectDisplayOptions.UseHexadecimalNumbers; } var lmrType = value.Type.GetLmrType(); if (IsPredefinedType(lmrType) && !lmrType.IsObject()) { if (lmrType.IsString()) { var stringValue = (string)value.HostObjectValue; if (stringValue == null) { return _nullString; } return IncludeObjectId( value, FormatString(stringValue, options), flags); } else if (lmrType.IsCharacter()) { // check if HostObjectValue is null, since any of these types might actually be a synthetic value as well. if (value.HostObjectValue == null) { return _hostValueNotFoundString; } return IncludeObjectId( value, FormatLiteral((char)value.HostObjectValue, options | ObjectDisplayOptions.IncludeCodePoints), flags); } else { return IncludeObjectId( value, FormatPrimitive(value, options & ~(ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters), inspectionContext), flags); } } else if (value.IsNull && !lmrType.IsPointer) { return _nullString; } else if (lmrType.IsEnum) { return IncludeObjectId( value, GetEnumDisplayString(lmrType, value, options, (flags & GetValueFlags.IncludeTypeName) != 0, inspectionContext), flags); } else if (lmrType.IsArray) { return IncludeObjectId( value, GetArrayDisplayString(value.Type.AppDomain, lmrType, value.ArrayDimensions, value.ArrayLowerBounds, options), flags); } else if (lmrType.IsPointer) { // NOTE: the HostObjectValue will have a size corresponding to the process bitness // and FormatPrimitive will adjust accordingly. var tmp = FormatPrimitive(value, ObjectDisplayOptions.UseHexadecimalNumbers, inspectionContext); // Always in hex. Debug.Assert(tmp != null); return tmp; } else if (lmrType.IsNullable()) { var nullableValue = value.GetNullableValue(inspectionContext); // It should be impossible to nest nullables, so this recursion should introduce only a single extra stack frame. return nullableValue == null ? _nullString : GetValueString(nullableValue, inspectionContext, ObjectDisplayOptions.None, GetValueFlags.IncludeTypeName); } else if (lmrType.IsIntPtr()) { // check if HostObjectValue is null, since any of these types might actually be a synthetic value as well. if (value.HostObjectValue == null) { return _hostValueNotFoundString; } if (IntPtr.Size == 8) { var intPtr = ((IntPtr)value.HostObjectValue).ToInt64(); return FormatPrimitiveObject(intPtr, ObjectDisplayOptions.UseHexadecimalNumbers); } else { var intPtr = ((IntPtr)value.HostObjectValue).ToInt32(); return FormatPrimitiveObject(intPtr, ObjectDisplayOptions.UseHexadecimalNumbers); } } else if (lmrType.IsUIntPtr()) { // check if HostObjectValue is null, since any of these types might actually be a synthetic value as well. if (value.HostObjectValue == null) { return _hostValueNotFoundString; } if (UIntPtr.Size == 8) { var uIntPtr = ((UIntPtr)value.HostObjectValue).ToUInt64(); return FormatPrimitiveObject(uIntPtr, ObjectDisplayOptions.UseHexadecimalNumbers); } else { var uIntPtr = ((UIntPtr)value.HostObjectValue).ToUInt32(); return FormatPrimitiveObject(uIntPtr, ObjectDisplayOptions.UseHexadecimalNumbers); } } else { int cardinality; if (lmrType.IsTupleCompatible(out cardinality) && (cardinality > 1)) { var values = ArrayBuilder<string>.GetInstance(); if (value.TryGetTupleFieldValues(cardinality, values, inspectionContext)) { return IncludeObjectId( value, GetTupleExpression(values.ToArrayAndFree()), flags); } values.Free(); } } // "value.EvaluateToString()" will check "Call string-conversion function on objects in variables windows" // (Tools > Options setting) and call "value.ToString()" if appropriate. return IncludeObjectId( value, string.Format(_defaultFormat, value.EvaluateToString(inspectionContext) ?? inspectionContext.GetTypeName(value.Type, CustomTypeInfo: null, FormatSpecifiers: NoFormatSpecifiers)), flags); } /// <summary> /// Gets the string representation of a character literal without including the numeric code point. /// </summary> private string GetValueStringForCharacter(DkmClrValue value, DkmInspectionContext inspectionContext, ObjectDisplayOptions options) { Debug.Assert(value.Type.GetLmrType().IsCharacter()); if (UsesHexadecimalNumbers(inspectionContext)) { options |= ObjectDisplayOptions.UseHexadecimalNumbers; } // check if HostObjectValue is null, since any of these types might actually be a synthetic value as well. if (value.HostObjectValue == null) { return _hostValueNotFoundString; } var charTemp = FormatLiteral((char)value.HostObjectValue, options); Debug.Assert(charTemp != null); return charTemp; } private bool HasUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext) { return GetUnderlyingString(value, inspectionContext) != null; } private string GetUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext) { var dataItem = value.GetDataItem<RawStringDataItem>(); if (dataItem != null) { return dataItem.RawString; } string underlyingString = GetUnderlyingStringImpl(value, inspectionContext); dataItem = new RawStringDataItem(underlyingString); value.SetDataItem(DkmDataCreationDisposition.CreateNew, dataItem); return underlyingString; } private string GetUnderlyingStringImpl(DkmClrValue value, DkmInspectionContext inspectionContext) { Debug.Assert(!value.IsError()); if (value.IsNull) { return null; } var lmrType = value.Type.GetLmrType(); if (lmrType.IsEnum || lmrType.IsArray || lmrType.IsPointer) { return null; } if (lmrType.IsNullable()) { var nullableValue = value.GetNullableValue(inspectionContext); return nullableValue != null ? GetUnderlyingStringImpl(nullableValue, inspectionContext) : null; } if (lmrType.IsString()) { return (string)value.HostObjectValue; } else if (!IsPredefinedType(lmrType)) { // Check for special cased non-primitives that have underlying strings if (lmrType.IsType("System.Data.SqlTypes", "SqlString")) { var fieldValue = value.GetFieldValue(InternalWellKnownMemberNames.SqlStringValue, inspectionContext); return fieldValue.HostObjectValue as string; } else if (lmrType.IsOrInheritsFrom("System.Xml.Linq", "XNode")) { return value.EvaluateToString(inspectionContext); } } return null; } #pragma warning disable CA1200 // Avoid using cref tags with a prefix /// <remarks> /// The corresponding native code is in EEUserStringBuilder::ErrTryAppendConstantEnum. /// The corresponding roslyn code is in /// <see cref="M:Microsoft.CodeAnalysis.SymbolDisplay.AbstractSymbolDisplayVisitor`1.AddEnumConstantValue(Microsoft.CodeAnalysis.INamedTypeSymbol, System.Object, System.Boolean)"/>. /// NOTE: no curlies for enum values. /// </remarks> #pragma warning restore CA1200 // Avoid using cref tags with a prefix private string GetEnumDisplayString(Type lmrType, DkmClrValue value, ObjectDisplayOptions options, bool includeTypeName, DkmInspectionContext inspectionContext) { Debug.Assert(lmrType.IsEnum); Debug.Assert(value != null); object underlyingValue = value.HostObjectValue; // check if HostObjectValue is null, since any of these types might actually be a synthetic value as well. if (underlyingValue == null) { return _hostValueNotFoundString; } string displayString; var fields = ArrayBuilder<EnumField>.GetInstance(); FillEnumFields(fields, lmrType); // We will normalize/extend all enum values to ulong to ensure that we are always comparing the full underlying value. ulong valueForComparison = ConvertEnumUnderlyingTypeToUInt64(underlyingValue, Type.GetTypeCode(lmrType)); var typeToDisplayOpt = includeTypeName ? lmrType : null; if (valueForComparison != 0 && IsFlagsEnum(lmrType)) { displayString = GetNamesForFlagsEnumValue(fields, underlyingValue, valueForComparison, options, typeToDisplayOpt); } else { displayString = GetNameForEnumValue(fields, underlyingValue, valueForComparison, options, typeToDisplayOpt); } fields.Free(); return displayString ?? FormatPrimitive(value, options, inspectionContext); } private static void FillEnumFields(ArrayBuilder<EnumField> fields, Type lmrType) { var fieldInfos = lmrType.GetFields(); var enumTypeCode = Type.GetTypeCode(lmrType); foreach (var info in fieldInfos) { if (!info.IsSpecialName) // Skip __value. { fields.Add(new EnumField(info.Name, ConvertEnumUnderlyingTypeToUInt64(info.GetRawConstantValue(), enumTypeCode))); } } fields.Sort(EnumField.Comparer); } protected static void FillUsedEnumFields(ArrayBuilder<EnumField> usedFields, ArrayBuilder<EnumField> fields, ulong underlyingValue) { var remaining = underlyingValue; foreach (var field in fields) { var fieldValue = field.Value; if (fieldValue == 0) continue; // Otherwise, we'd tack the zero flag onto everything. if ((remaining & fieldValue) == fieldValue) { remaining -= fieldValue; usedFields.Add(field); if (remaining == 0) break; } } // The value contained extra bit flags that didn't correspond to any enum field. We will // report "no fields used" here so the Formatter will just display the underlying value. if (remaining != 0) { usedFields.Clear(); } } private static bool IsFlagsEnum(Type lmrType) { Debug.Assert(lmrType.IsEnum); var attributes = lmrType.GetCustomAttributesData(); foreach (var attribute in attributes) { // NOTE: AttributeType is not available in 2.0 if (attribute.Constructor.DeclaringType.FullName == "System.FlagsAttribute") { return true; } } return false; } private static bool UsesHexadecimalNumbers(DkmInspectionContext inspectionContext) { Debug.Assert(inspectionContext != null); return inspectionContext.Radix == 16; } /// <summary> /// Convert a boxed primitive (generally of the backing type of an enum) into a ulong. /// </summary> protected static ulong ConvertEnumUnderlyingTypeToUInt64(object value, TypeCode typeCode) { Debug.Assert(value != null); unchecked { switch (typeCode) { case TypeCode.SByte: return (ulong)(sbyte)value; case TypeCode.Int16: return (ulong)(short)value; case TypeCode.Int32: return (ulong)(int)value; case TypeCode.Int64: return (ulong)(long)value; case TypeCode.Byte: return (byte)value; case TypeCode.UInt16: return (ushort)value; case TypeCode.UInt32: return (uint)value; case TypeCode.UInt64: return (ulong)value; default: throw ExceptionUtilities.UnexpectedValue(typeCode); } } } private string GetEditableValue(DkmClrValue value, DkmInspectionContext inspectionContext, DkmClrCustomTypeInfo customTypeInfo) { if (value.IsError()) { return null; } if (value.EvalFlags.Includes(DkmEvaluationResultFlags.ReadOnly)) { return null; } var type = value.Type.GetLmrType(); if (type.IsEnum) { return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.None, GetValueFlags.IncludeTypeName); } else if (type.IsDecimal()) { return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.IncludeTypeSuffix, GetValueFlags.None); } // The legacy EE didn't special-case strings or chars (when ",nq" was used, // you had to manually add quotes when editing) but it makes sense to // always automatically quote (non-null) strings and chars when editing. else if (type.IsString()) { if (!value.IsNull) { return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters, GetValueFlags.None); } } else if (type.IsCharacter()) { return this.GetValueStringForCharacter(value, inspectionContext, ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters); } return null; } private string FormatPrimitive(DkmClrValue value, ObjectDisplayOptions options, DkmInspectionContext inspectionContext) { Debug.Assert(value != null); // check if HostObjectValue is null, since any of these types might actually be a synthetic value as well. if (value.HostObjectValue == null) { return _hostValueNotFoundString; } // DateTime is primitive in VB but not in C#. object obj; if (value.Type.GetLmrType().IsDateTime()) { var dateDataValue = value.GetPropertyValue("Ticks", inspectionContext); obj = new DateTime((long)dateDataValue.HostObjectValue); } else { obj = value.HostObjectValue; } return FormatPrimitiveObject(obj, options); } private static string IncludeObjectId(DkmClrValue value, string valueStr, GetValueFlags flags) { Debug.Assert(valueStr != null); return (flags & GetValueFlags.IncludeObjectId) == 0 ? valueStr : value.IncludeObjectId(valueStr); } #region Language-specific value formatting behavior internal abstract string GetArrayDisplayString(DkmClrAppDomain appDomain, Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options); internal abstract string GetArrayIndexExpression(string[] indices); internal abstract string GetCastExpression(string argument, string type, DkmClrCastExpressionOptions options); internal abstract string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt); internal abstract string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt); internal abstract string GetObjectCreationExpression(string type, string[] arguments); internal abstract string GetTupleExpression(string[] values); internal abstract string FormatLiteral(char c, ObjectDisplayOptions options); internal abstract string FormatLiteral(int value, ObjectDisplayOptions options); internal abstract string FormatPrimitiveObject(object value, ObjectDisplayOptions options); internal abstract string FormatString(string str, ObjectDisplayOptions options); #endregion } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceVariableService.State_Parameter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; namespace Microsoft.CodeAnalysis.IntroduceVariable { internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax> { private partial class State { private bool IsInParameterContext( CancellationToken cancellationToken) { if (!_service.IsInParameterInitializer(Expression)) { return false; } // The default value for a parameter is a constant. So we always allow it unless it // happens to capture one of the method's type parameters. var bindingMap = GetSemanticMap(cancellationToken); if (bindingMap.AllReferencedSymbols.OfType<ITypeParameterSymbol>() .Where(tp => tp.TypeParameterKind == TypeParameterKind.Method) .Any()) { return false; } return true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; namespace Microsoft.CodeAnalysis.IntroduceVariable { internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax> { private partial class State { private bool IsInParameterContext( CancellationToken cancellationToken) { if (!_service.IsInParameterInitializer(Expression)) { return false; } // The default value for a parameter is a constant. So we always allow it unless it // happens to capture one of the method's type parameters. var bindingMap = GetSemanticMap(cancellationToken); if (bindingMap.AllReferencedSymbols.OfType<ITypeParameterSymbol>() .Where(tp => tp.TypeParameterKind == TypeParameterKind.Method) .Any()) { return false; } return true; } } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/Core/Portable/LanguageServiceIndexFormat/SymbolMoniker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat { internal sealed class SymbolMoniker { public string Scheme { get; } public string Identifier { get; } public SymbolMoniker(string scheme, string identifier) { this.Scheme = scheme; this.Identifier = identifier; } public static SymbolMoniker? TryCreate(ISymbol symbol) { // This uses the existing format that earlier prototypes of the Roslyn LSIF tool implemented; a different format may make more sense long term, but changing the // moniker makes it difficult for other systems that have older LSIF indexes to the connect the two indexes together. // Skip all local things that cannot escape outside of a single file: downstream consumers simply treat this as meaning a references/definition result // doesn't need to be stitched together across files or multiple projects or repositories. if (symbol.Kind is SymbolKind.Local or SymbolKind.RangeVariable or SymbolKind.Label or SymbolKind.Alias) { return null; } // Skip built in-operators. We could pick some sort of moniker for these, but I doubt anybody really needs to search for all uses of // + in the world's projects at once. if (symbol is IMethodSymbol method && method.MethodKind == MethodKind.BuiltinOperator) { return null; } // TODO: some symbols for things some things in crefs don't have a ContainingAssembly. We'll skip those for now but do // want those to work. if (symbol.Kind != SymbolKind.Namespace && symbol.ContainingAssembly == null) { return null; } // Namespaces are special: they're just a name that exists in the ether between compilations if (symbol.Kind == SymbolKind.Namespace) { return new SymbolMoniker(WellKnownSymbolMonikerSchemes.DotnetNamespace, symbol.ToDisplayString()); } var symbolMoniker = symbol.ContainingAssembly.Name + "#"; if (symbol.Kind == SymbolKind.Parameter) { symbolMoniker += GetRequiredDocumentationCommentId(symbol.ContainingSymbol) + "#" + symbol.Name; } else { symbolMoniker += GetRequiredDocumentationCommentId(symbol); } return new SymbolMoniker(WellKnownSymbolMonikerSchemes.DotnetXmlDoc, symbolMoniker); static string GetRequiredDocumentationCommentId(ISymbol symbol) { symbol = symbol.OriginalDefinition; var documentationCommentId = symbol.GetDocumentationCommentId(); if (documentationCommentId == null) { throw new Exception($"Unable to get documentation comment ID for {symbol.ToDisplayString()}"); } return documentationCommentId; } } } }
// Licensed to the .NET Foundation under one or more 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.LanguageServerIndexFormat { internal sealed class SymbolMoniker { public string Scheme { get; } public string Identifier { get; } public SymbolMoniker(string scheme, string identifier) { this.Scheme = scheme; this.Identifier = identifier; } public static SymbolMoniker? TryCreate(ISymbol symbol) { // This uses the existing format that earlier prototypes of the Roslyn LSIF tool implemented; a different format may make more sense long term, but changing the // moniker makes it difficult for other systems that have older LSIF indexes to the connect the two indexes together. // Skip all local things that cannot escape outside of a single file: downstream consumers simply treat this as meaning a references/definition result // doesn't need to be stitched together across files or multiple projects or repositories. if (symbol.Kind is SymbolKind.Local or SymbolKind.RangeVariable or SymbolKind.Label or SymbolKind.Alias) { return null; } // Skip built in-operators. We could pick some sort of moniker for these, but I doubt anybody really needs to search for all uses of // + in the world's projects at once. if (symbol is IMethodSymbol method && method.MethodKind == MethodKind.BuiltinOperator) { return null; } // TODO: some symbols for things some things in crefs don't have a ContainingAssembly. We'll skip those for now but do // want those to work. if (symbol.Kind != SymbolKind.Namespace && symbol.ContainingAssembly == null) { return null; } // Namespaces are special: they're just a name that exists in the ether between compilations if (symbol.Kind == SymbolKind.Namespace) { return new SymbolMoniker(WellKnownSymbolMonikerSchemes.DotnetNamespace, symbol.ToDisplayString()); } var symbolMoniker = symbol.ContainingAssembly.Name + "#"; if (symbol.Kind == SymbolKind.Parameter) { symbolMoniker += GetRequiredDocumentationCommentId(symbol.ContainingSymbol) + "#" + symbol.Name; } else { symbolMoniker += GetRequiredDocumentationCommentId(symbol); } return new SymbolMoniker(WellKnownSymbolMonikerSchemes.DotnetXmlDoc, symbolMoniker); static string GetRequiredDocumentationCommentId(ISymbol symbol) { symbol = symbol.OriginalDefinition; var documentationCommentId = symbol.GetDocumentationCommentId(); if (documentationCommentId == null) { throw new Exception($"Unable to get documentation comment ID for {symbol.ToDisplayString()}"); } return documentationCommentId; } } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Compilers/Core/Portable/NativePdbWriter/SymWriterMetadataProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Reflection; using System.Reflection.Metadata.Ecma335; using Microsoft.DiaSymReader; namespace Microsoft.Cci { internal sealed class SymWriterMetadataProvider : ISymWriterMetadataProvider { private readonly MetadataWriter _writer; private int _lastTypeDef; private string _lastTypeDefName; private string _lastTypeDefNamespace; internal SymWriterMetadataProvider(MetadataWriter writer) { _writer = writer; } // typeDefinitionToken is token returned by GetMethodProps or GetNestedClassProps public bool TryGetTypeDefinitionInfo(int typeDefinitionToken, out string namespaceName, out string typeName, out TypeAttributes attributes) { if (typeDefinitionToken == 0) { namespaceName = null; typeName = null; attributes = 0; return false; } // The typeDef name should be fully qualified ITypeDefinition t = _writer.GetTypeDefinition(typeDefinitionToken); if (_lastTypeDef == typeDefinitionToken) { typeName = _lastTypeDefName; namespaceName = _lastTypeDefNamespace; } else { int generation = (t is INamedTypeDefinition namedType) ? _writer.Module.GetTypeDefinitionGeneration(namedType) : 0; typeName = MetadataWriter.GetMangledName((INamedTypeReference)t, generation); INamespaceTypeDefinition namespaceTypeDef; if ((namespaceTypeDef = t.AsNamespaceTypeDefinition(_writer.Context)) != null) { namespaceName = namespaceTypeDef.NamespaceName; } else { namespaceName = null; } _lastTypeDef = typeDefinitionToken; _lastTypeDefName = typeName; _lastTypeDefNamespace = namespaceName; } attributes = _writer.GetTypeAttributes(t.GetResolvedType(_writer.Context)); return true; } // methodDefinitionToken is the token passed to OpenMethod. The token is remembered until the corresponding CloseMethod, which passes it to TryGetMethodInfo. public bool TryGetMethodInfo(int methodDefinitionToken, out string methodName, out int declaringTypeToken) { IMethodDefinition m = _writer.GetMethodDefinition(methodDefinitionToken); methodName = m.Name; declaringTypeToken = MetadataTokens.GetToken(_writer.GetTypeHandle(m.GetContainingType(_writer.Context))); return true; } public bool TryGetEnclosingType(int nestedTypeToken, out int enclosingTypeToken) { INestedTypeReference nt = _writer.GetNestedTypeReference(nestedTypeToken); if (nt == null) { enclosingTypeToken = 0; return false; } enclosingTypeToken = MetadataTokens.GetToken(_writer.GetTypeHandle(nt.GetContainingType(_writer.Context))); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Reflection; using System.Reflection.Metadata.Ecma335; using Microsoft.DiaSymReader; namespace Microsoft.Cci { internal sealed class SymWriterMetadataProvider : ISymWriterMetadataProvider { private readonly MetadataWriter _writer; private int _lastTypeDef; private string _lastTypeDefName; private string _lastTypeDefNamespace; internal SymWriterMetadataProvider(MetadataWriter writer) { _writer = writer; } // typeDefinitionToken is token returned by GetMethodProps or GetNestedClassProps public bool TryGetTypeDefinitionInfo(int typeDefinitionToken, out string namespaceName, out string typeName, out TypeAttributes attributes) { if (typeDefinitionToken == 0) { namespaceName = null; typeName = null; attributes = 0; return false; } // The typeDef name should be fully qualified ITypeDefinition t = _writer.GetTypeDefinition(typeDefinitionToken); if (_lastTypeDef == typeDefinitionToken) { typeName = _lastTypeDefName; namespaceName = _lastTypeDefNamespace; } else { int generation = (t is INamedTypeDefinition namedType) ? _writer.Module.GetTypeDefinitionGeneration(namedType) : 0; typeName = MetadataWriter.GetMangledName((INamedTypeReference)t, generation); INamespaceTypeDefinition namespaceTypeDef; if ((namespaceTypeDef = t.AsNamespaceTypeDefinition(_writer.Context)) != null) { namespaceName = namespaceTypeDef.NamespaceName; } else { namespaceName = null; } _lastTypeDef = typeDefinitionToken; _lastTypeDefName = typeName; _lastTypeDefNamespace = namespaceName; } attributes = _writer.GetTypeAttributes(t.GetResolvedType(_writer.Context)); return true; } // methodDefinitionToken is the token passed to OpenMethod. The token is remembered until the corresponding CloseMethod, which passes it to TryGetMethodInfo. public bool TryGetMethodInfo(int methodDefinitionToken, out string methodName, out int declaringTypeToken) { IMethodDefinition m = _writer.GetMethodDefinition(methodDefinitionToken); methodName = m.Name; declaringTypeToken = MetadataTokens.GetToken(_writer.GetTypeHandle(m.GetContainingType(_writer.Context))); return true; } public bool TryGetEnclosingType(int nestedTypeToken, out int enclosingTypeToken) { INestedTypeReference nt = _writer.GetNestedTypeReference(nestedTypeToken); if (nt == null) { enclosingTypeToken = 0; return false; } enclosingTypeToken = MetadataTokens.GetToken(_writer.GetTypeHandle(nt.GetContainingType(_writer.Context))); return true; } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Workspaces/Core/Portable/Options/OptionsExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CodeStyle; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { internal static class OptionsExtensions { public static Option<CodeStyleOption<T>> ToPublicOption<T>(this Option2<CodeStyleOption2<T>> option) { RoslynDebug.Assert(option != null); var codeStyleOption = new CodeStyleOption<T>(option.DefaultValue); var optionDefinition = new OptionDefinition(option.Feature, option.Group, option.Name, defaultValue: codeStyleOption, type: typeof(CodeStyleOption<T>), isPerLanguage: false); return new Option<CodeStyleOption<T>>(optionDefinition, option.StorageLocations.As<OptionStorageLocation>()); } public static PerLanguageOption<CodeStyleOption<T>> ToPublicOption<T>(this PerLanguageOption2<CodeStyleOption2<T>> option) { RoslynDebug.Assert(option != null); var codeStyleOption = new CodeStyleOption<T>(option.DefaultValue); var optionDefinition = new OptionDefinition(option.Feature, option.Group, option.Name, defaultValue: codeStyleOption, type: typeof(CodeStyleOption<T>), isPerLanguage: true); return new PerLanguageOption<CodeStyleOption<T>>(optionDefinition, option.StorageLocations.As<OptionStorageLocation>()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CodeStyle; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { internal static class OptionsExtensions { public static Option<CodeStyleOption<T>> ToPublicOption<T>(this Option2<CodeStyleOption2<T>> option) { RoslynDebug.Assert(option != null); var codeStyleOption = new CodeStyleOption<T>(option.DefaultValue); var optionDefinition = new OptionDefinition(option.Feature, option.Group, option.Name, defaultValue: codeStyleOption, type: typeof(CodeStyleOption<T>), isPerLanguage: false); return new Option<CodeStyleOption<T>>(optionDefinition, option.StorageLocations.As<OptionStorageLocation>()); } public static PerLanguageOption<CodeStyleOption<T>> ToPublicOption<T>(this PerLanguageOption2<CodeStyleOption2<T>> option) { RoslynDebug.Assert(option != null); var codeStyleOption = new CodeStyleOption<T>(option.DefaultValue); var optionDefinition = new OptionDefinition(option.Feature, option.Group, option.Name, defaultValue: codeStyleOption, type: typeof(CodeStyleOption<T>), isPerLanguage: true); return new PerLanguageOption<CodeStyleOption<T>>(optionDefinition, option.StorageLocations.As<OptionStorageLocation>()); } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Workspaces/Core/Portable/Classification/ISemanticClassificationCacheService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Classification { /// <summary> /// Service that can retrieve semantic classifications for a document cached during a previous session. This is /// intended to help populate semantic classifications for a host during the time while a solution is loading and /// semantics may be incomplete or unavailable. /// </summary> internal interface ISemanticClassificationCacheService : IWorkspaceService { /// <summary> /// Tries to get cached semantic classifications for the specified document and the specified <paramref /// name="textSpan"/>. Will return a <c>default</c> array not able to. An empty array indicates that there /// were cached classifications, but none that intersected the provided <paramref name="textSpan"/>. /// </summary> /// <param name="checksum">Pass in <see cref="DocumentStateChecksums.Text"/>. This will ensure that the cached /// classifications are only returned if they match the content the file currently has.</param> Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync( DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken); } [ExportWorkspaceService(typeof(ISemanticClassificationCacheService)), Shared] internal class DefaultSemanticClassificationCacheService : ISemanticClassificationCacheService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultSemanticClassificationCacheService() { } public Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync(DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Default<ImmutableArray<ClassifiedSpan>>(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Classification { /// <summary> /// Service that can retrieve semantic classifications for a document cached during a previous session. This is /// intended to help populate semantic classifications for a host during the time while a solution is loading and /// semantics may be incomplete or unavailable. /// </summary> internal interface ISemanticClassificationCacheService : IWorkspaceService { /// <summary> /// Tries to get cached semantic classifications for the specified document and the specified <paramref /// name="textSpan"/>. Will return a <c>default</c> array not able to. An empty array indicates that there /// were cached classifications, but none that intersected the provided <paramref name="textSpan"/>. /// </summary> /// <param name="checksum">Pass in <see cref="DocumentStateChecksums.Text"/>. This will ensure that the cached /// classifications are only returned if they match the content the file currently has.</param> Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync( DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken); } [ExportWorkspaceService(typeof(ISemanticClassificationCacheService)), Shared] internal class DefaultSemanticClassificationCacheService : ISemanticClassificationCacheService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultSemanticClassificationCacheService() { } public Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync(DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Default<ImmutableArray<ClassifiedSpan>>(); } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/CSharp/Portable/ConvertNumericLiteral/CSharpConvertNumericLiteralCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertNumericLiteral; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertNumericLiteral { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertNumericLiteral), Shared] internal sealed class CSharpConvertNumericLiteralCodeRefactoringProvider : AbstractConvertNumericLiteralCodeRefactoringProvider<LiteralExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertNumericLiteralCodeRefactoringProvider() { } protected override (string hexPrefix, string binaryPrefix) GetNumericLiteralPrefixes() => (hexPrefix: "0x", binaryPrefix: "0b"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertNumericLiteral; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertNumericLiteral { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertNumericLiteral), Shared] internal sealed class CSharpConvertNumericLiteralCodeRefactoringProvider : AbstractConvertNumericLiteralCodeRefactoringProvider<LiteralExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertNumericLiteralCodeRefactoringProvider() { } protected override (string hexPrefix, string binaryPrefix) GetNumericLiteralPrefixes() => (hexPrefix: "0x", binaryPrefix: "0b"); } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/Core/Portable/EditAndContinue/Remote/RemoteEditAndContinueServiceProxy.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Facade used to call remote <see cref="IRemoteEditAndContinueService"/> methods. /// Encapsulates all RPC logic as well as dispatching to the local service if the remote service is disabled. /// THe facade is useful for targeted testing of serialization/deserialization of EnC service calls. /// </summary> internal readonly partial struct RemoteEditAndContinueServiceProxy { [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteEditAndContinueService)), Shared] internal sealed class CallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteEditAndContinueService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CallbackDispatcher() { } public ValueTask<ImmutableArray<ActiveStatementSpan>> GetSpansAsync(RemoteServiceCallbackId callbackId, DocumentId? documentId, string filePath, CancellationToken cancellationToken) => ((ActiveStatementSpanProviderCallback)GetCallback(callbackId)).GetSpansAsync(documentId, filePath, cancellationToken); public ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => ((EditSessionCallback)GetCallback(callbackId)).GetActiveStatementsAsync(cancellationToken); public ValueTask<ManagedEditAndContinueAvailability> GetAvailabilityAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken) => ((EditSessionCallback)GetCallback(callbackId)).GetAvailabilityAsync(mvid, cancellationToken); public ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => ((EditSessionCallback)GetCallback(callbackId)).GetCapabilitiesAsync(cancellationToken); public ValueTask PrepareModuleForUpdateAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken) => ((EditSessionCallback)GetCallback(callbackId)).PrepareModuleForUpdateAsync(mvid, cancellationToken); } private sealed class EditSessionCallback { private readonly IManagedEditAndContinueDebuggerService _debuggerService; public EditSessionCallback(IManagedEditAndContinueDebuggerService debuggerService) { _debuggerService = debuggerService; } public async ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) { try { return await _debuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; } } public async ValueTask<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid mvid, CancellationToken cancellationToken) { try { return await _debuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.InternalError, e.Message); } } public async ValueTask PrepareModuleForUpdateAsync(Guid mvid, CancellationToken cancellationToken) { try { await _debuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // nop } } public async ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) { try { return await _debuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<string>.Empty; } } } public readonly Workspace Workspace; public RemoteEditAndContinueServiceProxy(Workspace workspace) { Workspace = workspace; } private IEditAndContinueWorkspaceService GetLocalService() => Workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask<RemoteDebuggingSessionProxy?> StartDebuggingSessionAsync( Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var sessionId = await GetLocalService().StartDebuggingSessionAsync(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false); return new RemoteDebuggingSessionProxy(Workspace, LocalConnection.Instance, sessionId); } // need to keep the providers alive until the edit session ends: var connection = client.CreateConnection<IRemoteEditAndContinueService>( callbackTarget: new EditSessionCallback(debuggerService)); var sessionIdOpt = await connection.TryInvokeAsync( solution, async (service, solutionInfo, callbackId, cancellationToken) => await service.StartDebuggingSessionAsync(solutionInfo, callbackId, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); if (sessionIdOpt.HasValue) { return new RemoteDebuggingSessionProxy(Workspace, connection, sessionIdOpt.Value); } connection.Dispose(); return null; } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, Document designTimeDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var diagnostics = await GetLocalService().GetDocumentDiagnosticsAsync(document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (designTimeDocument != document) { diagnostics = diagnostics.SelectAsArray(diagnostic => RemapLocation(designTimeDocument, DiagnosticData.Create(diagnostic, document.Project))); } return diagnostics; } var diagnosticData = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DiagnosticData>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetDocumentDiagnosticsAsync(solutionInfo, callbackId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (!diagnosticData.HasValue) { return ImmutableArray<Diagnostic>.Empty; } var project = document.Project; using var _ = ArrayBuilder<Diagnostic>.GetInstance(out var result); foreach (var data in diagnosticData.Value) { Debug.Assert(data.DataLocation != null); Diagnostic diagnostic; // Workaround for solution crawler not supporting mapped locations to make Razor work. // We pretend the diagnostic is in the original document, but use the mapped line span. // Razor will ignore the column (which will be off because #line directives can't currently map columns) and only use the line number. if (designTimeDocument != document && data.DataLocation.IsMapped) { diagnostic = RemapLocation(designTimeDocument, data); } else { diagnostic = await data.ToDiagnosticAsync(document.Project, cancellationToken).ConfigureAwait(false); } result.Add(diagnostic); } return result.ToImmutable(); } private static Diagnostic RemapLocation(Document designTimeDocument, DiagnosticData data) { Debug.Assert(data.DataLocation != null); Debug.Assert(designTimeDocument.FilePath != null); var mappedSpan = data.DataLocation.GetFileLinePositionSpan(); var location = Location.Create(designTimeDocument.FilePath, textSpan: default, mappedSpan.Span); return data.ToDiagnostic(location, ImmutableArray<Location>.Empty); } public async ValueTask OnSourceFileUpdatedAsync(Document document, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().OnSourceFileUpdated(document); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( document.Project.Solution, (service, solutionInfo, cancellationToken) => service.OnSourceFileUpdatedAsync(solutionInfo, document.Id, cancellationToken), cancellationToken).ConfigureAwait(false); } private sealed class LocalConnection : IDisposable { public static readonly LocalConnection Instance = new(); public void Dispose() { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Facade used to call remote <see cref="IRemoteEditAndContinueService"/> methods. /// Encapsulates all RPC logic as well as dispatching to the local service if the remote service is disabled. /// THe facade is useful for targeted testing of serialization/deserialization of EnC service calls. /// </summary> internal readonly partial struct RemoteEditAndContinueServiceProxy { [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteEditAndContinueService)), Shared] internal sealed class CallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteEditAndContinueService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CallbackDispatcher() { } public ValueTask<ImmutableArray<ActiveStatementSpan>> GetSpansAsync(RemoteServiceCallbackId callbackId, DocumentId? documentId, string filePath, CancellationToken cancellationToken) => ((ActiveStatementSpanProviderCallback)GetCallback(callbackId)).GetSpansAsync(documentId, filePath, cancellationToken); public ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => ((EditSessionCallback)GetCallback(callbackId)).GetActiveStatementsAsync(cancellationToken); public ValueTask<ManagedEditAndContinueAvailability> GetAvailabilityAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken) => ((EditSessionCallback)GetCallback(callbackId)).GetAvailabilityAsync(mvid, cancellationToken); public ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => ((EditSessionCallback)GetCallback(callbackId)).GetCapabilitiesAsync(cancellationToken); public ValueTask PrepareModuleForUpdateAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken) => ((EditSessionCallback)GetCallback(callbackId)).PrepareModuleForUpdateAsync(mvid, cancellationToken); } private sealed class EditSessionCallback { private readonly IManagedEditAndContinueDebuggerService _debuggerService; public EditSessionCallback(IManagedEditAndContinueDebuggerService debuggerService) { _debuggerService = debuggerService; } public async ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) { try { return await _debuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; } } public async ValueTask<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid mvid, CancellationToken cancellationToken) { try { return await _debuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.InternalError, e.Message); } } public async ValueTask PrepareModuleForUpdateAsync(Guid mvid, CancellationToken cancellationToken) { try { await _debuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // nop } } public async ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) { try { return await _debuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<string>.Empty; } } } public readonly Workspace Workspace; public RemoteEditAndContinueServiceProxy(Workspace workspace) { Workspace = workspace; } private IEditAndContinueWorkspaceService GetLocalService() => Workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask<RemoteDebuggingSessionProxy?> StartDebuggingSessionAsync( Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var sessionId = await GetLocalService().StartDebuggingSessionAsync(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false); return new RemoteDebuggingSessionProxy(Workspace, LocalConnection.Instance, sessionId); } // need to keep the providers alive until the edit session ends: var connection = client.CreateConnection<IRemoteEditAndContinueService>( callbackTarget: new EditSessionCallback(debuggerService)); var sessionIdOpt = await connection.TryInvokeAsync( solution, async (service, solutionInfo, callbackId, cancellationToken) => await service.StartDebuggingSessionAsync(solutionInfo, callbackId, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); if (sessionIdOpt.HasValue) { return new RemoteDebuggingSessionProxy(Workspace, connection, sessionIdOpt.Value); } connection.Dispose(); return null; } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, Document designTimeDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var diagnostics = await GetLocalService().GetDocumentDiagnosticsAsync(document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (designTimeDocument != document) { diagnostics = diagnostics.SelectAsArray(diagnostic => RemapLocation(designTimeDocument, DiagnosticData.Create(diagnostic, document.Project))); } return diagnostics; } var diagnosticData = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DiagnosticData>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetDocumentDiagnosticsAsync(solutionInfo, callbackId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (!diagnosticData.HasValue) { return ImmutableArray<Diagnostic>.Empty; } var project = document.Project; using var _ = ArrayBuilder<Diagnostic>.GetInstance(out var result); foreach (var data in diagnosticData.Value) { Debug.Assert(data.DataLocation != null); Diagnostic diagnostic; // Workaround for solution crawler not supporting mapped locations to make Razor work. // We pretend the diagnostic is in the original document, but use the mapped line span. // Razor will ignore the column (which will be off because #line directives can't currently map columns) and only use the line number. if (designTimeDocument != document && data.DataLocation.IsMapped) { diagnostic = RemapLocation(designTimeDocument, data); } else { diagnostic = await data.ToDiagnosticAsync(document.Project, cancellationToken).ConfigureAwait(false); } result.Add(diagnostic); } return result.ToImmutable(); } private static Diagnostic RemapLocation(Document designTimeDocument, DiagnosticData data) { Debug.Assert(data.DataLocation != null); Debug.Assert(designTimeDocument.FilePath != null); var mappedSpan = data.DataLocation.GetFileLinePositionSpan(); var location = Location.Create(designTimeDocument.FilePath, textSpan: default, mappedSpan.Span); return data.ToDiagnostic(location, ImmutableArray<Location>.Empty); } public async ValueTask OnSourceFileUpdatedAsync(Document document, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().OnSourceFileUpdated(document); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( document.Project.Solution, (service, solutionInfo, cancellationToken) => service.OnSourceFileUpdatedAsync(solutionInfo, document.Id, cancellationToken), cancellationToken).ConfigureAwait(false); } private sealed class LocalConnection : IDisposable { public static readonly LocalConnection Instance = new(); public void Dispose() { } } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/EditorFeatures/Core.Wpf/Peek/PeekableItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek { internal abstract class PeekableItem : IPeekableItem { protected readonly IPeekResultFactory PeekResultFactory; protected PeekableItem(IPeekResultFactory peekResultFactory) => this.PeekResultFactory = peekResultFactory; public string DisplayName => // This is unused, and was supposed to have been removed from IPeekableItem. null; public abstract IEnumerable<IPeekRelationship> Relationships { get; } public abstract IPeekResultSource GetOrCreateResultSource(string relationshipName); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek { internal abstract class PeekableItem : IPeekableItem { protected readonly IPeekResultFactory PeekResultFactory; protected PeekableItem(IPeekResultFactory peekResultFactory) => this.PeekResultFactory = peekResultFactory; public string DisplayName => // This is unused, and was supposed to have been removed from IPeekableItem. null; public abstract IEnumerable<IPeekRelationship> Relationships { get; } public abstract IPeekResultSource GetOrCreateResultSource(string relationshipName); } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Compilers/Core/Portable/Syntax/CommonSyntaxNodeRemover.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace Microsoft.CodeAnalysis.Syntax { internal static class CommonSyntaxNodeRemover { public static void GetSeparatorInfo( SyntaxNodeOrTokenList nodesAndSeparators, int nodeIndex, int endOfLineKind, out bool nextTokenIsSeparator, out bool nextSeparatorBelongsToNode) { // remove preceding separator if any, except for the case where // the following separator immediately touches the item in the list // and is followed by a newline. // // In that case, we consider the next token to be more closely // associated with the item, and it should be removed. // // For example, if you have: // // Goo(a, // a stuff // b, // b stuff // c); // // If we're removing 'b', we should remove the comma after it. // // If there is no next comma, or the next comma is not on the // same line, then just remove the preceding comma if there is // one. If there is no next or previous comma there's nothing // in the list that needs to be fixed up. var node = nodesAndSeparators[nodeIndex].AsNode(); Debug.Assert(node is object); nextTokenIsSeparator = nodeIndex + 1 < nodesAndSeparators.Count && nodesAndSeparators[nodeIndex + 1].IsToken; nextSeparatorBelongsToNode = nextTokenIsSeparator && nodesAndSeparators[nodeIndex + 1].AsToken() is var nextSeparator && !nextSeparator.HasLeadingTrivia && !ContainsEndOfLine(node.GetTrailingTrivia(), endOfLineKind) && ContainsEndOfLine(nextSeparator.TrailingTrivia, endOfLineKind); } private static bool ContainsEndOfLine(SyntaxTriviaList triviaList, int endOfLineKind) => triviaList.IndexOf(endOfLineKind) >= 0; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace Microsoft.CodeAnalysis.Syntax { internal static class CommonSyntaxNodeRemover { public static void GetSeparatorInfo( SyntaxNodeOrTokenList nodesAndSeparators, int nodeIndex, int endOfLineKind, out bool nextTokenIsSeparator, out bool nextSeparatorBelongsToNode) { // remove preceding separator if any, except for the case where // the following separator immediately touches the item in the list // and is followed by a newline. // // In that case, we consider the next token to be more closely // associated with the item, and it should be removed. // // For example, if you have: // // Goo(a, // a stuff // b, // b stuff // c); // // If we're removing 'b', we should remove the comma after it. // // If there is no next comma, or the next comma is not on the // same line, then just remove the preceding comma if there is // one. If there is no next or previous comma there's nothing // in the list that needs to be fixed up. var node = nodesAndSeparators[nodeIndex].AsNode(); Debug.Assert(node is object); nextTokenIsSeparator = nodeIndex + 1 < nodesAndSeparators.Count && nodesAndSeparators[nodeIndex + 1].IsToken; nextSeparatorBelongsToNode = nextTokenIsSeparator && nodesAndSeparators[nodeIndex + 1].AsToken() is var nextSeparator && !nextSeparator.HasLeadingTrivia && !ContainsEndOfLine(node.GetTrailingTrivia(), endOfLineKind) && ContainsEndOfLine(nextSeparator.TrailingTrivia, endOfLineKind); } private static bool ContainsEndOfLine(SyntaxTriviaList triviaList, int endOfLineKind) => triviaList.IndexOf(endOfLineKind) >= 0; } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Compilers/Core/CodeAnalysisTest/RealParserTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class RealParserTests { /// <summary> /// Test some specific floating-point literals that have been shown to be problematic /// in some implementation. /// </summary> [Fact] public static void TestTroublesomeDoubles() { //// https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx CheckOneDouble("0.6822871999174", 0x3FE5D54BF743FD1Bul); //// Common problem numbers CheckOneDouble("2.2250738585072011e-308", 0x000FFFFFFFFFFFFFul); CheckOneDouble("2.2250738585072012e-308", 0x0010000000000000ul); //// http://www.exploringbinary.com/bigcomp-deciding-truncated-near-halfway-conversions/ CheckOneDouble("1.3694713649464322631e-11", 0x3DAE1D703BB5749Dul); CheckOneDouble("9.3170532238714134438e+16", 0x4374B021AFD9F651ul); //// https://connect.microsoft.com/VisualStudio/feedback/details/914964/double-round-trip-conversion-via-a-string-is-not-safe CheckOneDouble("0.84551240822557006", 0x3FEB0E7009B61CE0ul); // This value has a non-terminating binary fraction. It has a 0 at bit 54 // followed by 120 ones. //// http://www.exploringbinary.com/a-bug-in-the-bigcomp-function-of-david-gays-strtod/ CheckOneDouble("1.8254370818746402660437411213933955878019332885742187", 0x3FFD34FD8378EA83ul); //// http://www.exploringbinary.com/decimal-to-floating-point-needs-arbitrary-precision CheckOneDouble("7.8459735791271921e+65", 0x4D9DCD0089C1314Eul); CheckOneDouble("3.08984926168550152811e-32", 0x39640DE48676653Bul); //// other values from https://github.com/dotnet/roslyn/issues/4221 CheckOneDouble("0.6822871999174000000", 0x3FE5D54BF743FD1Bul); CheckOneDouble("0.6822871999174000001", 0x3FE5D54BF743FD1Bul); // A handful of selected values for which double.Parse has been observed to produce an incorrect result CheckOneDouble("88.7448699245e+188", 0x675fde6aee647ed2ul); CheckOneDouble("02.0500496671303857e-88", 0x2dba19a3cf32cd7ful); CheckOneDouble("1.15362842193e193", 0x68043a6fcda86331ul); CheckOneDouble("65.9925719e-190", 0x18dd672e04e96a79ul); CheckOneDouble("0.4619024460e-158", 0x1f103c1e5abd7c87ul); CheckOneDouble("61.8391820096448e147", 0x5ed35849885ad12bul); CheckOneDouble("0.2e+127", 0x5a27a2ecc414a03ful); CheckOneDouble("0.8e+127", 0x5a47a2ecc414a03ful); CheckOneDouble("35.27614496323756e-307", 0x0083d141335ce6c7ul); CheckOneDouble("3.400034617466e190", 0x677e863a216ab367ul); CheckOneDouble("0.78393577148319e-254", 0x0b2d6d5379bc932dul); CheckOneDouble("0.947231e+100", 0x54b152a10483a38ful); CheckOneDouble("4.e126", 0x5a37a2ecc414a03ful); CheckOneDouble("6.235271922748e-165", 0x1dd6faeba4fc9f91ul); CheckOneDouble("3.497444198362024e-82", 0x2f053b8036dd4203ul); CheckOneDouble("8.e+126", 0x5a47a2ecc414a03ful); CheckOneDouble("10.027247729e+91", 0x53089cc2d930ed3ful); CheckOneDouble("4.6544819e-192", 0x18353c5d35ceaaadul); CheckOneDouble("5.e+125", 0x5a07a2ecc414a03ful); CheckOneDouble("6.96768e68", 0x4e39d8352ee997f9ul); CheckOneDouble("0.73433e-145", 0x21cd57b723dc17bful); CheckOneDouble("31.076044256878e259", 0x76043627aa7248dful); CheckOneDouble("0.8089124675e-201", 0x162fb3bf98f037f7ul); CheckOneDouble("88.7453407049700914e-144", 0x227150a674c218e3ul); CheckOneDouble("32.401089401e-65", 0x32c10fa88084d643ul); CheckOneDouble("0.734277884753e-209", 0x14834fdfb6248755ul); CheckOneDouble("8.3435e+153", 0x5fe3e9c5b617dc39ul); CheckOneDouble("30.379e-129", 0x25750ec799af9efful); CheckOneDouble("78.638509299e141", 0x5d99cb8c0a72cd05ul); CheckOneDouble("30.096884930e-42", 0x3784f976b4d47d63ul); //// values from http://www.icir.org/vern/papers/testbase-report.pdf table 1 (less than half ULP - round down) CheckOneDouble("69e+267", 0x77C0B7CB60C994DAul); CheckOneDouble("999e-026", 0x3B282782AFE1869Eul); CheckOneDouble("7861e-034", 0x39AFE3544145E9D8ul); CheckOneDouble("75569e-254", 0x0C35A462D91C6AB3ul); CheckOneDouble("928609e-261", 0x0AFBE2DD66200BEFul); CheckOneDouble("9210917e+080", 0x51FDA232347E6032ul); CheckOneDouble("84863171e+114", 0x59406E98F5EC8F37ul); CheckOneDouble("653777767e+273", 0x7A720223F2B3A881ul); CheckOneDouble("5232604057e-298", 0x041465B896C24520ul); CheckOneDouble("27235667517e-109", 0x2B77D41824D64FB2ul); CheckOneDouble("653532977297e-123", 0x28D925A0AABCDC68ul); CheckOneDouble("3142213164987e-294", 0x057D3409DFBCA26Ful); CheckOneDouble("46202199371337e-072", 0x33D28F9EDFBD341Ful); CheckOneDouble("231010996856685e-073", 0x33C28F9EDFBD341Ful); CheckOneDouble("9324754620109615e+212", 0x6F43AE60753AF6CAul); CheckOneDouble("78459735791271921e+049", 0x4D9DCD0089C1314Eul); CheckOneDouble("272104041512242479e+200", 0x6D13BBB4BF05F087ul); CheckOneDouble("6802601037806061975e+198", 0x6CF3BBB4BF05F087ul); CheckOneDouble("20505426358836677347e-221", 0x161012954B6AABBAul); CheckOneDouble("836168422905420598437e-234", 0x13B20403A628A9CAul); CheckOneDouble("4891559871276714924261e+222", 0x7286ECAF7694A3C7ul); //// values from http://www.icir.org/vern/papers/testbase-report.pdf table 2 (greater than half ULP - round up) CheckOneDouble("85e-037", 0x38A698CCDC60015Aul); CheckOneDouble("623e+100", 0x554640A62F3A83DFul); CheckOneDouble("3571e+263", 0x77462644C61D41AAul); CheckOneDouble("81661e+153", 0x60B7CA8E3D68578Eul); CheckOneDouble("920657e-023", 0x3C653A9985DBDE6Cul); CheckOneDouble("4603285e-024", 0x3C553A9985DBDE6Cul); CheckOneDouble("87575437e-309", 0x016E07320602056Cul); CheckOneDouble("245540327e+122", 0x5B01B6231E18C5CBul); CheckOneDouble("6138508175e+120", 0x5AE1B6231E18C5CBul); CheckOneDouble("83356057653e+193", 0x6A4544E6DAEE2A18ul); CheckOneDouble("619534293513e+124", 0x5C210C20303FE0F1ul); CheckOneDouble("2335141086879e+218", 0x6FC340A1C932C1EEul); CheckOneDouble("36167929443327e-159", 0x21BCE77C2B3328FCul); CheckOneDouble("609610927149051e-255", 0x0E104273B18918B1ul); CheckOneDouble("3743626360493413e-165", 0x20E8823A57ADBEF9ul); CheckOneDouble("94080055902682397e-242", 0x11364981E39E66CAul); CheckOneDouble("899810892172646163e+283", 0x7E6ADF51FA055E03ul); CheckOneDouble("7120190517612959703e+120", 0x5CC3220DCD5899FDul); CheckOneDouble("25188282901709339043e-252", 0x0FA4059AF3DB2A84ul); CheckOneDouble("308984926168550152811e-052", 0x39640DE48676653Bul); CheckOneDouble("6372891218502368041059e+064", 0x51C067047DBB38FEul); // http://www.exploringbinary.com/incorrect-decimal-to-floating-point-conversion-in-sqlite/ CheckOneDouble("1e-23", 0x3B282DB34012B251ul); CheckOneDouble("8.533e+68", 0x4E3FA69165A8EEA2ul); CheckOneDouble("4.1006e-184", 0x19DBE0D1C7EA60C9ul); CheckOneDouble("9.998e+307", 0x7FE1CC0A350CA87Bul); CheckOneDouble("9.9538452227e-280", 0x0602117AE45CDE43ul); CheckOneDouble("6.47660115e-260", 0x0A1FDD9E333BADADul); CheckOneDouble("7.4e+47", 0x49E033D7ECA0ADEFul); CheckOneDouble("5.92e+48", 0x4A1033D7ECA0ADEFul); CheckOneDouble("7.35e+66", 0x4DD172B70EABABA9ul); CheckOneDouble("8.32116e+55", 0x4B8B2628393E02CDul); } /// <summary> /// Test round tripping for some specific floating-point values constructed to test the edge cases of conversion implementations. /// </summary> [Fact] public static void TestSpecificDoubles() { CheckOneDouble("0.0", 0x0000000000000000ul); // Verify the smallest denormals: for (ulong i = 0x0000000000000001ul; i != 0x0000000000000100ul; ++i) { TestRoundTripDouble(i); } // Verify the largest denormals and the smallest normals: for (ulong i = 0x000fffffffffff00ul; i != 0x0010000000000100ul; ++i) { TestRoundTripDouble(i); } // Verify the largest normals: for (ulong i = 0x7fefffffffffff00ul; i != 0x7ff0000000000000ul; ++i) { TestRoundTripDouble(i); } // Verify all representable powers of two and nearby values: for (int pow = -1022; pow <= 1023; pow++) { ulong twoToThePow = ((ulong)(pow + 1023)) << 52; TestRoundTripDouble(twoToThePow); TestRoundTripDouble(twoToThePow + 1); TestRoundTripDouble(twoToThePow - 1); } // Verify all representable powers of ten and nearby values: for (int pow = -323; pow <= 308; pow++) { var s = $"1.0e{pow}"; double value; RealParser.TryParseDouble(s, out value); var tenToThePow = (ulong)BitConverter.DoubleToInt64Bits(value); CheckOneDouble(s, value); TestRoundTripDouble(tenToThePow + 1); TestRoundTripDouble(tenToThePow - 1); } // Verify a few large integer values: TestRoundTripDouble((double)long.MaxValue); TestRoundTripDouble((double)ulong.MaxValue); // Verify small and large exactly representable integers: CheckOneDouble("1", 0x3ff0000000000000); CheckOneDouble("2", 0x4000000000000000); CheckOneDouble("3", 0x4008000000000000); CheckOneDouble("4", 0x4010000000000000); CheckOneDouble("5", 0x4014000000000000); CheckOneDouble("6", 0x4018000000000000); CheckOneDouble("7", 0x401C000000000000); CheckOneDouble("8", 0x4020000000000000); CheckOneDouble("9007199254740984", 0x433ffffffffffff8); CheckOneDouble("9007199254740985", 0x433ffffffffffff9); CheckOneDouble("9007199254740986", 0x433ffffffffffffa); CheckOneDouble("9007199254740987", 0x433ffffffffffffb); CheckOneDouble("9007199254740988", 0x433ffffffffffffc); CheckOneDouble("9007199254740989", 0x433ffffffffffffd); CheckOneDouble("9007199254740990", 0x433ffffffffffffe); CheckOneDouble("9007199254740991", 0x433fffffffffffff); // 2^53 - 1 // Verify the smallest and largest denormal values: CheckOneDouble("5.0e-324", 0x0000000000000001); CheckOneDouble("1.0e-323", 0x0000000000000002); CheckOneDouble("1.5e-323", 0x0000000000000003); CheckOneDouble("2.0e-323", 0x0000000000000004); CheckOneDouble("2.5e-323", 0x0000000000000005); CheckOneDouble("3.0e-323", 0x0000000000000006); CheckOneDouble("3.5e-323", 0x0000000000000007); CheckOneDouble("4.0e-323", 0x0000000000000008); CheckOneDouble("4.5e-323", 0x0000000000000009); CheckOneDouble("5.0e-323", 0x000000000000000a); CheckOneDouble("5.5e-323", 0x000000000000000b); CheckOneDouble("6.0e-323", 0x000000000000000c); CheckOneDouble("6.5e-323", 0x000000000000000d); CheckOneDouble("7.0e-323", 0x000000000000000e); CheckOneDouble("7.5e-323", 0x000000000000000f); CheckOneDouble("2.2250738585071935e-308", 0x000ffffffffffff0); CheckOneDouble("2.2250738585071940e-308", 0x000ffffffffffff1); CheckOneDouble("2.2250738585071945e-308", 0x000ffffffffffff2); CheckOneDouble("2.2250738585071950e-308", 0x000ffffffffffff3); CheckOneDouble("2.2250738585071955e-308", 0x000ffffffffffff4); CheckOneDouble("2.2250738585071960e-308", 0x000ffffffffffff5); CheckOneDouble("2.2250738585071964e-308", 0x000ffffffffffff6); CheckOneDouble("2.2250738585071970e-308", 0x000ffffffffffff7); CheckOneDouble("2.2250738585071974e-308", 0x000ffffffffffff8); CheckOneDouble("2.2250738585071980e-308", 0x000ffffffffffff9); CheckOneDouble("2.2250738585071984e-308", 0x000ffffffffffffa); CheckOneDouble("2.2250738585071990e-308", 0x000ffffffffffffb); CheckOneDouble("2.2250738585071994e-308", 0x000ffffffffffffc); CheckOneDouble("2.2250738585072000e-308", 0x000ffffffffffffd); CheckOneDouble("2.2250738585072004e-308", 0x000ffffffffffffe); CheckOneDouble("2.2250738585072010e-308", 0x000fffffffffffff); // Test cases from Rick Regan's article, "Incorrectly Rounded Conversions in Visual C++": // // http://www.exploringbinary.com/incorrectly-rounded-conversions-in-visual-c-plus-plus/ // // Example 1: CheckOneDouble( "9214843084008499", 0x43405e6cec57761a); // Example 2: CheckOneDouble( "0.500000000000000166533453693773481063544750213623046875", 0x3fe0000000000002); // Example 3 (2^-1 + 2^-53 + 2^-54): CheckOneDouble( "30078505129381147446200", 0x44997a3c7271b021); // Example 4: CheckOneDouble( "1777820000000000000001", 0x4458180d5bad2e3e); // Example 5 (2^-1 + 2^-53 + 2^-54 + 2^-66): CheckOneDouble( "0.500000000000000166547006220929549868969843373633921146392822265625", 0x3fe0000000000002); // Example 6 (2^-1 + 2^-53 + 2^-54 + 2^-65): CheckOneDouble( "0.50000000000000016656055874808561867439493653364479541778564453125", 0x3fe0000000000002); // Example 7: CheckOneDouble( "0.3932922657273", 0x3fd92bb352c4623a ); // The following test cases are taken from other articles on Rick Regan's // Exploring Binary blog. These are conversions that other implementations // were found to perform incorrectly. // http://www.exploringbinary.com/nondeterministic-floating-point-conversions-in-java/ // http://www.exploringbinary.com/incorrectly-rounded-subnormal-conversions-in-java/ // Example 1 (2^-1047 + 2^-1075, half-ulp above a power of two): CheckOneDouble( "6.6312368714697582767853966302759672433990999473553031442499717587" + "362866301392654396180682007880487441059604205526018528897150063763" + "256665955396033303618005191075917832333584923372080578494993608994" + "251286407188566165030934449228547591599881603044399098682919739314" + "266256986631577498362522745234853124423586512070512924530832781161" + "439325697279187097860044978723221938561502254152119972830784963194" + "121246401117772161481107528151017752957198119743384519360959074196" + "224175384736794951486324803914359317679811223967034438033355297560" + "033532098300718322306892013830155987921841729099279241763393155074" + "022348361207309147831684007154624400538175927027662135590421159867" + "638194826541287705957668068727833491469671712939495988506756821156" + "96218943412532098591327667236328125E-316", 0x0000000008000000); // Example 2 (2^-1058 - 2^-1075, half-ulp below a power of two): CheckOneDouble( "3.2378839133029012895883524125015321748630376694231080599012970495" + "523019706706765657868357425877995578606157765598382834355143910841" + "531692526891905643964595773946180389283653051434639551003566966656" + "292020173313440317300443693602052583458034314716600326995807313009" + "548483639755486900107515300188817581841745696521731104736960227499" + "346384253806233697747365600089974040609674980283891918789639685754" + "392222064169814626901133425240027243859416510512935526014211553334" + "302252372915238433223313261384314778235911424088000307751706259156" + "707286570031519536642607698224949379518458015308952384398197084033" + "899378732414634842056080000272705311068273879077914449185347715987" + "501628125488627684932015189916680282517302999531439241685457086639" + "13273994694463908672332763671875E-319", 0x0000000000010000); // Example 3 (2^-1027 + 2^-1066 + 2^-1075, half-ulp above a non-power of two): CheckOneDouble( "6.9533558078476771059728052155218916902221198171459507544162056079" + "800301315496366888061157263994418800653863998640286912755395394146" + "528315847956685600829998895513577849614468960421131982842131079351" + "102171626549398024160346762138294097205837595404767869364138165416" + "212878432484332023692099166122496760055730227032447997146221165421" + "888377703760223711720795591258533828013962195524188394697705149041" + "926576270603193728475623010741404426602378441141744972109554498963" + "891803958271916028866544881824524095839813894427833770015054620157" + "450178487545746683421617594966617660200287528887833870748507731929" + "971029979366198762266880963149896457660004790090837317365857503352" + "620998601508967187744019647968271662832256419920407478943826987518" + "09812609536720628966577351093292236328125E-310", 0x0000800000000100 ); // Example 4 (2^-1058 + 2^-1063 + 2^-1075, half-ulp below a non-power of two): CheckOneDouble( "3.3390685575711885818357137012809439119234019169985217716556569973" + "284403145596153181688491490746626090999981130094655664268081703784" + "340657229916596426194677060348844249897410807907667784563321682004" + "646515939958173717821250106683466529959122339932545844611258684816" + "333436749050742710644097630907080178565840197768788124253120088123" + "262603630354748115322368533599053346255754042160606228586332807443" + "018924703005556787346899784768703698535494132771566221702458461669" + "916553215355296238706468887866375289955928004361779017462862722733" + "744717014529914330472578638646014242520247915673681950560773208853" + "293843223323915646452641434007986196650406080775491621739636492640" + "497383622906068758834568265867109610417379088720358034812416003767" + "05491726170293986797332763671875E-319", 0x0000000000010800 ); // http://www.exploringbinary.com/gays-strtod-returns-zero-for-inputs-just-above-2-1075/ // A number between 2^-2074 and 2^-1075, just slightly larger than 2^-1075. // It has bit 1075 set (the denormal rounding bit), followed by 2506 zeroes, // followed by one bits. It should round up to 2^-1074. CheckOneDouble( "2.470328229206232720882843964341106861825299013071623822127928412503" + "37753635104375932649918180817996189898282347722858865463328355177969" + "89819938739800539093906315035659515570226392290858392449105184435931" + "80284993653615250031937045767824921936562366986365848075700158576926" + "99037063119282795585513329278343384093519780155312465972635795746227" + "66465272827220056374006485499977096599470454020828166226237857393450" + "73633900796776193057750674017632467360096895134053553745851666113422" + "37666786041621596804619144672918403005300575308490487653917113865916" + "46239524912623653881879636239373280423891018672348497668235089863388" + "58792562830275599565752445550725518931369083625477918694866799496832" + "40497058210285131854513962138377228261454376934125320985913276672363" + "28125001e-324", 0x0000000000000001); CheckOneDouble("1.0e-99999999999999999999", 0.0); CheckOneDouble("0e-99999999999999999999", 0.0); CheckOneDouble("0e99999999999999999999", 0.0); } private static void TestRoundTripDouble(ulong bits) { double d = BitConverter.Int64BitsToDouble((long)bits); if (double.IsInfinity(d) || double.IsNaN(d)) return; string s = InvariantToString(d); CheckOneDouble(s, bits); } private static string InvariantToString(object o) { return string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:G17}", o); } private static void TestRoundTripDouble(double d) { string s = InvariantToString(d); CheckOneDouble(s, d); } private static void CheckOneDouble(string s, ulong expectedBits) { CheckOneDouble(s, BitConverter.Int64BitsToDouble((long)expectedBits)); } private static void CheckOneDouble(string s, double expected) { double actual; if (!RealParser.TryParseDouble(s, out actual)) actual = 1.0 / 0.0; if (!actual.Equals(expected)) { throw new Exception($@" Error for double input ""{s}"" expected {InvariantToString(expected)} actual {InvariantToString(actual)}"); } } // ============ test some floats ============ [Fact] public static void TestSpecificFloats() { CheckOneFloat(" 0.0", 0x00000000); // Verify the smallest denormals: for (uint i = 0x00000001; i != 0x00000100; ++i) { TestRoundTripFloat(i); } // Verify the largest denormals and the smallest normals: for (uint i = 0x007fff00; i != 0x00800100; ++i) { TestRoundTripFloat(i); } // Verify the largest normals: for (uint i = 0x7f7fff00; i != 0x7f800000; ++i) { TestRoundTripFloat(i); } // Verify all representable powers of two and nearby values: for (int i = -1022; i != 1023; ++i) { float f; try { f = (float)Math.Pow(2.0, i); } catch (OverflowException) { continue; } if (f == 0) continue; uint bits = FloatToInt32Bits(f); TestRoundTripFloat(bits - 1); TestRoundTripFloat(bits); TestRoundTripFloat(bits + 1); } // Verify all representable powers of ten and nearby values: for (int i = -50; i <= 40; ++i) { float f; try { f = (float)Math.Pow(10.0, i); } catch (OverflowException) { continue; } if (f == 0) continue; uint bits = FloatToInt32Bits(f); TestRoundTripFloat(bits - 1); TestRoundTripFloat(bits); TestRoundTripFloat(bits + 1); } TestRoundTripFloat((float)int.MaxValue); TestRoundTripFloat((float)uint.MaxValue); // Verify small and large exactly representable integers: CheckOneFloat("1", 0x3f800000); CheckOneFloat("2", 0x40000000); CheckOneFloat("3", 0x40400000); CheckOneFloat("4", 0x40800000); CheckOneFloat("5", 0x40A00000); CheckOneFloat("6", 0x40C00000); CheckOneFloat("7", 0x40E00000); CheckOneFloat("8", 0x41000000); CheckOneFloat("16777208", 0x4b7ffff8); CheckOneFloat("16777209", 0x4b7ffff9); CheckOneFloat("16777210", 0x4b7ffffa); CheckOneFloat("16777211", 0x4b7ffffb); CheckOneFloat("16777212", 0x4b7ffffc); CheckOneFloat("16777213", 0x4b7ffffd); CheckOneFloat("16777214", 0x4b7ffffe); CheckOneFloat("16777215", 0x4b7fffff); // 2^24 - 1 // Verify the smallest and largest denormal values: CheckOneFloat("1.4012984643248170e-45", 0x00000001); CheckOneFloat("2.8025969286496340e-45", 0x00000002); CheckOneFloat("4.2038953929744510e-45", 0x00000003); CheckOneFloat("5.6051938572992680e-45", 0x00000004); CheckOneFloat("7.0064923216240850e-45", 0x00000005); CheckOneFloat("8.4077907859489020e-45", 0x00000006); CheckOneFloat("9.8090892502737200e-45", 0x00000007); CheckOneFloat("1.1210387714598537e-44", 0x00000008); CheckOneFloat("1.2611686178923354e-44", 0x00000009); CheckOneFloat("1.4012984643248170e-44", 0x0000000a); CheckOneFloat("1.5414283107572988e-44", 0x0000000b); CheckOneFloat("1.6815581571897805e-44", 0x0000000c); CheckOneFloat("1.8216880036222622e-44", 0x0000000d); CheckOneFloat("1.9618178500547440e-44", 0x0000000e); CheckOneFloat("2.1019476964872256e-44", 0x0000000f); CheckOneFloat("1.1754921087447446e-38", 0x007ffff0); CheckOneFloat("1.1754922488745910e-38", 0x007ffff1); CheckOneFloat("1.1754923890044375e-38", 0x007ffff2); CheckOneFloat("1.1754925291342839e-38", 0x007ffff3); CheckOneFloat("1.1754926692641303e-38", 0x007ffff4); CheckOneFloat("1.1754928093939768e-38", 0x007ffff5); CheckOneFloat("1.1754929495238232e-38", 0x007ffff6); CheckOneFloat("1.1754930896536696e-38", 0x007ffff7); CheckOneFloat("1.1754932297835160e-38", 0x007ffff8); CheckOneFloat("1.1754933699133625e-38", 0x007ffff9); CheckOneFloat("1.1754935100432089e-38", 0x007ffffa); CheckOneFloat("1.1754936501730553e-38", 0x007ffffb); CheckOneFloat("1.1754937903029018e-38", 0x007ffffc); CheckOneFloat("1.1754939304327482e-38", 0x007ffffd); CheckOneFloat("1.1754940705625946e-38", 0x007ffffe); CheckOneFloat("1.1754942106924411e-38", 0x007fffff); // This number is exactly representable and should not be rounded in any // mode: // 0.1111111111111111111111100 // ^ CheckOneFloat("0.99999988079071044921875", 0x3f7ffffe); // This number is below the halfway point between two representable values // so it should round down in nearest mode: // 0.11111111111111111111111001 // ^ CheckOneFloat("0.99999989569187164306640625", 0x3f7ffffe); // This number is exactly halfway between two representable values, so it // should round to even in nearest mode: // 0.1111111111111111111111101 // ^ CheckOneFloat("0.9999999105930328369140625", 0x3f7ffffe); // This number is above the halfway point between two representable values // so it should round up in nearest mode: // 0.11111111111111111111111011 // ^ CheckOneFloat("0.99999992549419403076171875", 0x3f7fffff); } private static void TestRoundTripFloat(uint bits) { float d = Int32BitsToFloat(bits); if (float.IsInfinity(d) || float.IsNaN(d)) return; string s = InvariantToString(d); CheckOneFloat(s, bits); } private static void TestRoundTripFloat(float d) { string s = InvariantToString(d); if (s != "NaN" && s != "Infinity") CheckOneFloat(s, d); } private static void CheckOneFloat(string s, uint expectedBits) { CheckOneFloat(s, Int32BitsToFloat(expectedBits)); } private static void CheckOneFloat(string s, float expected) { float actual; if (!RealParser.TryParseFloat(s, out actual)) actual = 1.0f / 0.0f; if (!actual.Equals(expected)) { throw new Exception($@"Error for float input ""{s}"" expected {InvariantToString(expected)} actual {InvariantToString(actual)}"); } } private static uint FloatToInt32Bits(float f) { var bits = default(FloatUnion); bits.FloatData = f; return bits.IntData; } private static float Int32BitsToFloat(uint i) { var bits = default(FloatUnion); bits.IntData = i; return bits.FloatData; } [StructLayout(LayoutKind.Explicit)] private struct FloatUnion { [FieldOffset(0)] public uint IntData; [FieldOffset(0)] public float FloatData; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class RealParserTests { /// <summary> /// Test some specific floating-point literals that have been shown to be problematic /// in some implementation. /// </summary> [Fact] public static void TestTroublesomeDoubles() { //// https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx CheckOneDouble("0.6822871999174", 0x3FE5D54BF743FD1Bul); //// Common problem numbers CheckOneDouble("2.2250738585072011e-308", 0x000FFFFFFFFFFFFFul); CheckOneDouble("2.2250738585072012e-308", 0x0010000000000000ul); //// http://www.exploringbinary.com/bigcomp-deciding-truncated-near-halfway-conversions/ CheckOneDouble("1.3694713649464322631e-11", 0x3DAE1D703BB5749Dul); CheckOneDouble("9.3170532238714134438e+16", 0x4374B021AFD9F651ul); //// https://connect.microsoft.com/VisualStudio/feedback/details/914964/double-round-trip-conversion-via-a-string-is-not-safe CheckOneDouble("0.84551240822557006", 0x3FEB0E7009B61CE0ul); // This value has a non-terminating binary fraction. It has a 0 at bit 54 // followed by 120 ones. //// http://www.exploringbinary.com/a-bug-in-the-bigcomp-function-of-david-gays-strtod/ CheckOneDouble("1.8254370818746402660437411213933955878019332885742187", 0x3FFD34FD8378EA83ul); //// http://www.exploringbinary.com/decimal-to-floating-point-needs-arbitrary-precision CheckOneDouble("7.8459735791271921e+65", 0x4D9DCD0089C1314Eul); CheckOneDouble("3.08984926168550152811e-32", 0x39640DE48676653Bul); //// other values from https://github.com/dotnet/roslyn/issues/4221 CheckOneDouble("0.6822871999174000000", 0x3FE5D54BF743FD1Bul); CheckOneDouble("0.6822871999174000001", 0x3FE5D54BF743FD1Bul); // A handful of selected values for which double.Parse has been observed to produce an incorrect result CheckOneDouble("88.7448699245e+188", 0x675fde6aee647ed2ul); CheckOneDouble("02.0500496671303857e-88", 0x2dba19a3cf32cd7ful); CheckOneDouble("1.15362842193e193", 0x68043a6fcda86331ul); CheckOneDouble("65.9925719e-190", 0x18dd672e04e96a79ul); CheckOneDouble("0.4619024460e-158", 0x1f103c1e5abd7c87ul); CheckOneDouble("61.8391820096448e147", 0x5ed35849885ad12bul); CheckOneDouble("0.2e+127", 0x5a27a2ecc414a03ful); CheckOneDouble("0.8e+127", 0x5a47a2ecc414a03ful); CheckOneDouble("35.27614496323756e-307", 0x0083d141335ce6c7ul); CheckOneDouble("3.400034617466e190", 0x677e863a216ab367ul); CheckOneDouble("0.78393577148319e-254", 0x0b2d6d5379bc932dul); CheckOneDouble("0.947231e+100", 0x54b152a10483a38ful); CheckOneDouble("4.e126", 0x5a37a2ecc414a03ful); CheckOneDouble("6.235271922748e-165", 0x1dd6faeba4fc9f91ul); CheckOneDouble("3.497444198362024e-82", 0x2f053b8036dd4203ul); CheckOneDouble("8.e+126", 0x5a47a2ecc414a03ful); CheckOneDouble("10.027247729e+91", 0x53089cc2d930ed3ful); CheckOneDouble("4.6544819e-192", 0x18353c5d35ceaaadul); CheckOneDouble("5.e+125", 0x5a07a2ecc414a03ful); CheckOneDouble("6.96768e68", 0x4e39d8352ee997f9ul); CheckOneDouble("0.73433e-145", 0x21cd57b723dc17bful); CheckOneDouble("31.076044256878e259", 0x76043627aa7248dful); CheckOneDouble("0.8089124675e-201", 0x162fb3bf98f037f7ul); CheckOneDouble("88.7453407049700914e-144", 0x227150a674c218e3ul); CheckOneDouble("32.401089401e-65", 0x32c10fa88084d643ul); CheckOneDouble("0.734277884753e-209", 0x14834fdfb6248755ul); CheckOneDouble("8.3435e+153", 0x5fe3e9c5b617dc39ul); CheckOneDouble("30.379e-129", 0x25750ec799af9efful); CheckOneDouble("78.638509299e141", 0x5d99cb8c0a72cd05ul); CheckOneDouble("30.096884930e-42", 0x3784f976b4d47d63ul); //// values from http://www.icir.org/vern/papers/testbase-report.pdf table 1 (less than half ULP - round down) CheckOneDouble("69e+267", 0x77C0B7CB60C994DAul); CheckOneDouble("999e-026", 0x3B282782AFE1869Eul); CheckOneDouble("7861e-034", 0x39AFE3544145E9D8ul); CheckOneDouble("75569e-254", 0x0C35A462D91C6AB3ul); CheckOneDouble("928609e-261", 0x0AFBE2DD66200BEFul); CheckOneDouble("9210917e+080", 0x51FDA232347E6032ul); CheckOneDouble("84863171e+114", 0x59406E98F5EC8F37ul); CheckOneDouble("653777767e+273", 0x7A720223F2B3A881ul); CheckOneDouble("5232604057e-298", 0x041465B896C24520ul); CheckOneDouble("27235667517e-109", 0x2B77D41824D64FB2ul); CheckOneDouble("653532977297e-123", 0x28D925A0AABCDC68ul); CheckOneDouble("3142213164987e-294", 0x057D3409DFBCA26Ful); CheckOneDouble("46202199371337e-072", 0x33D28F9EDFBD341Ful); CheckOneDouble("231010996856685e-073", 0x33C28F9EDFBD341Ful); CheckOneDouble("9324754620109615e+212", 0x6F43AE60753AF6CAul); CheckOneDouble("78459735791271921e+049", 0x4D9DCD0089C1314Eul); CheckOneDouble("272104041512242479e+200", 0x6D13BBB4BF05F087ul); CheckOneDouble("6802601037806061975e+198", 0x6CF3BBB4BF05F087ul); CheckOneDouble("20505426358836677347e-221", 0x161012954B6AABBAul); CheckOneDouble("836168422905420598437e-234", 0x13B20403A628A9CAul); CheckOneDouble("4891559871276714924261e+222", 0x7286ECAF7694A3C7ul); //// values from http://www.icir.org/vern/papers/testbase-report.pdf table 2 (greater than half ULP - round up) CheckOneDouble("85e-037", 0x38A698CCDC60015Aul); CheckOneDouble("623e+100", 0x554640A62F3A83DFul); CheckOneDouble("3571e+263", 0x77462644C61D41AAul); CheckOneDouble("81661e+153", 0x60B7CA8E3D68578Eul); CheckOneDouble("920657e-023", 0x3C653A9985DBDE6Cul); CheckOneDouble("4603285e-024", 0x3C553A9985DBDE6Cul); CheckOneDouble("87575437e-309", 0x016E07320602056Cul); CheckOneDouble("245540327e+122", 0x5B01B6231E18C5CBul); CheckOneDouble("6138508175e+120", 0x5AE1B6231E18C5CBul); CheckOneDouble("83356057653e+193", 0x6A4544E6DAEE2A18ul); CheckOneDouble("619534293513e+124", 0x5C210C20303FE0F1ul); CheckOneDouble("2335141086879e+218", 0x6FC340A1C932C1EEul); CheckOneDouble("36167929443327e-159", 0x21BCE77C2B3328FCul); CheckOneDouble("609610927149051e-255", 0x0E104273B18918B1ul); CheckOneDouble("3743626360493413e-165", 0x20E8823A57ADBEF9ul); CheckOneDouble("94080055902682397e-242", 0x11364981E39E66CAul); CheckOneDouble("899810892172646163e+283", 0x7E6ADF51FA055E03ul); CheckOneDouble("7120190517612959703e+120", 0x5CC3220DCD5899FDul); CheckOneDouble("25188282901709339043e-252", 0x0FA4059AF3DB2A84ul); CheckOneDouble("308984926168550152811e-052", 0x39640DE48676653Bul); CheckOneDouble("6372891218502368041059e+064", 0x51C067047DBB38FEul); // http://www.exploringbinary.com/incorrect-decimal-to-floating-point-conversion-in-sqlite/ CheckOneDouble("1e-23", 0x3B282DB34012B251ul); CheckOneDouble("8.533e+68", 0x4E3FA69165A8EEA2ul); CheckOneDouble("4.1006e-184", 0x19DBE0D1C7EA60C9ul); CheckOneDouble("9.998e+307", 0x7FE1CC0A350CA87Bul); CheckOneDouble("9.9538452227e-280", 0x0602117AE45CDE43ul); CheckOneDouble("6.47660115e-260", 0x0A1FDD9E333BADADul); CheckOneDouble("7.4e+47", 0x49E033D7ECA0ADEFul); CheckOneDouble("5.92e+48", 0x4A1033D7ECA0ADEFul); CheckOneDouble("7.35e+66", 0x4DD172B70EABABA9ul); CheckOneDouble("8.32116e+55", 0x4B8B2628393E02CDul); } /// <summary> /// Test round tripping for some specific floating-point values constructed to test the edge cases of conversion implementations. /// </summary> [Fact] public static void TestSpecificDoubles() { CheckOneDouble("0.0", 0x0000000000000000ul); // Verify the smallest denormals: for (ulong i = 0x0000000000000001ul; i != 0x0000000000000100ul; ++i) { TestRoundTripDouble(i); } // Verify the largest denormals and the smallest normals: for (ulong i = 0x000fffffffffff00ul; i != 0x0010000000000100ul; ++i) { TestRoundTripDouble(i); } // Verify the largest normals: for (ulong i = 0x7fefffffffffff00ul; i != 0x7ff0000000000000ul; ++i) { TestRoundTripDouble(i); } // Verify all representable powers of two and nearby values: for (int pow = -1022; pow <= 1023; pow++) { ulong twoToThePow = ((ulong)(pow + 1023)) << 52; TestRoundTripDouble(twoToThePow); TestRoundTripDouble(twoToThePow + 1); TestRoundTripDouble(twoToThePow - 1); } // Verify all representable powers of ten and nearby values: for (int pow = -323; pow <= 308; pow++) { var s = $"1.0e{pow}"; double value; RealParser.TryParseDouble(s, out value); var tenToThePow = (ulong)BitConverter.DoubleToInt64Bits(value); CheckOneDouble(s, value); TestRoundTripDouble(tenToThePow + 1); TestRoundTripDouble(tenToThePow - 1); } // Verify a few large integer values: TestRoundTripDouble((double)long.MaxValue); TestRoundTripDouble((double)ulong.MaxValue); // Verify small and large exactly representable integers: CheckOneDouble("1", 0x3ff0000000000000); CheckOneDouble("2", 0x4000000000000000); CheckOneDouble("3", 0x4008000000000000); CheckOneDouble("4", 0x4010000000000000); CheckOneDouble("5", 0x4014000000000000); CheckOneDouble("6", 0x4018000000000000); CheckOneDouble("7", 0x401C000000000000); CheckOneDouble("8", 0x4020000000000000); CheckOneDouble("9007199254740984", 0x433ffffffffffff8); CheckOneDouble("9007199254740985", 0x433ffffffffffff9); CheckOneDouble("9007199254740986", 0x433ffffffffffffa); CheckOneDouble("9007199254740987", 0x433ffffffffffffb); CheckOneDouble("9007199254740988", 0x433ffffffffffffc); CheckOneDouble("9007199254740989", 0x433ffffffffffffd); CheckOneDouble("9007199254740990", 0x433ffffffffffffe); CheckOneDouble("9007199254740991", 0x433fffffffffffff); // 2^53 - 1 // Verify the smallest and largest denormal values: CheckOneDouble("5.0e-324", 0x0000000000000001); CheckOneDouble("1.0e-323", 0x0000000000000002); CheckOneDouble("1.5e-323", 0x0000000000000003); CheckOneDouble("2.0e-323", 0x0000000000000004); CheckOneDouble("2.5e-323", 0x0000000000000005); CheckOneDouble("3.0e-323", 0x0000000000000006); CheckOneDouble("3.5e-323", 0x0000000000000007); CheckOneDouble("4.0e-323", 0x0000000000000008); CheckOneDouble("4.5e-323", 0x0000000000000009); CheckOneDouble("5.0e-323", 0x000000000000000a); CheckOneDouble("5.5e-323", 0x000000000000000b); CheckOneDouble("6.0e-323", 0x000000000000000c); CheckOneDouble("6.5e-323", 0x000000000000000d); CheckOneDouble("7.0e-323", 0x000000000000000e); CheckOneDouble("7.5e-323", 0x000000000000000f); CheckOneDouble("2.2250738585071935e-308", 0x000ffffffffffff0); CheckOneDouble("2.2250738585071940e-308", 0x000ffffffffffff1); CheckOneDouble("2.2250738585071945e-308", 0x000ffffffffffff2); CheckOneDouble("2.2250738585071950e-308", 0x000ffffffffffff3); CheckOneDouble("2.2250738585071955e-308", 0x000ffffffffffff4); CheckOneDouble("2.2250738585071960e-308", 0x000ffffffffffff5); CheckOneDouble("2.2250738585071964e-308", 0x000ffffffffffff6); CheckOneDouble("2.2250738585071970e-308", 0x000ffffffffffff7); CheckOneDouble("2.2250738585071974e-308", 0x000ffffffffffff8); CheckOneDouble("2.2250738585071980e-308", 0x000ffffffffffff9); CheckOneDouble("2.2250738585071984e-308", 0x000ffffffffffffa); CheckOneDouble("2.2250738585071990e-308", 0x000ffffffffffffb); CheckOneDouble("2.2250738585071994e-308", 0x000ffffffffffffc); CheckOneDouble("2.2250738585072000e-308", 0x000ffffffffffffd); CheckOneDouble("2.2250738585072004e-308", 0x000ffffffffffffe); CheckOneDouble("2.2250738585072010e-308", 0x000fffffffffffff); // Test cases from Rick Regan's article, "Incorrectly Rounded Conversions in Visual C++": // // http://www.exploringbinary.com/incorrectly-rounded-conversions-in-visual-c-plus-plus/ // // Example 1: CheckOneDouble( "9214843084008499", 0x43405e6cec57761a); // Example 2: CheckOneDouble( "0.500000000000000166533453693773481063544750213623046875", 0x3fe0000000000002); // Example 3 (2^-1 + 2^-53 + 2^-54): CheckOneDouble( "30078505129381147446200", 0x44997a3c7271b021); // Example 4: CheckOneDouble( "1777820000000000000001", 0x4458180d5bad2e3e); // Example 5 (2^-1 + 2^-53 + 2^-54 + 2^-66): CheckOneDouble( "0.500000000000000166547006220929549868969843373633921146392822265625", 0x3fe0000000000002); // Example 6 (2^-1 + 2^-53 + 2^-54 + 2^-65): CheckOneDouble( "0.50000000000000016656055874808561867439493653364479541778564453125", 0x3fe0000000000002); // Example 7: CheckOneDouble( "0.3932922657273", 0x3fd92bb352c4623a ); // The following test cases are taken from other articles on Rick Regan's // Exploring Binary blog. These are conversions that other implementations // were found to perform incorrectly. // http://www.exploringbinary.com/nondeterministic-floating-point-conversions-in-java/ // http://www.exploringbinary.com/incorrectly-rounded-subnormal-conversions-in-java/ // Example 1 (2^-1047 + 2^-1075, half-ulp above a power of two): CheckOneDouble( "6.6312368714697582767853966302759672433990999473553031442499717587" + "362866301392654396180682007880487441059604205526018528897150063763" + "256665955396033303618005191075917832333584923372080578494993608994" + "251286407188566165030934449228547591599881603044399098682919739314" + "266256986631577498362522745234853124423586512070512924530832781161" + "439325697279187097860044978723221938561502254152119972830784963194" + "121246401117772161481107528151017752957198119743384519360959074196" + "224175384736794951486324803914359317679811223967034438033355297560" + "033532098300718322306892013830155987921841729099279241763393155074" + "022348361207309147831684007154624400538175927027662135590421159867" + "638194826541287705957668068727833491469671712939495988506756821156" + "96218943412532098591327667236328125E-316", 0x0000000008000000); // Example 2 (2^-1058 - 2^-1075, half-ulp below a power of two): CheckOneDouble( "3.2378839133029012895883524125015321748630376694231080599012970495" + "523019706706765657868357425877995578606157765598382834355143910841" + "531692526891905643964595773946180389283653051434639551003566966656" + "292020173313440317300443693602052583458034314716600326995807313009" + "548483639755486900107515300188817581841745696521731104736960227499" + "346384253806233697747365600089974040609674980283891918789639685754" + "392222064169814626901133425240027243859416510512935526014211553334" + "302252372915238433223313261384314778235911424088000307751706259156" + "707286570031519536642607698224949379518458015308952384398197084033" + "899378732414634842056080000272705311068273879077914449185347715987" + "501628125488627684932015189916680282517302999531439241685457086639" + "13273994694463908672332763671875E-319", 0x0000000000010000); // Example 3 (2^-1027 + 2^-1066 + 2^-1075, half-ulp above a non-power of two): CheckOneDouble( "6.9533558078476771059728052155218916902221198171459507544162056079" + "800301315496366888061157263994418800653863998640286912755395394146" + "528315847956685600829998895513577849614468960421131982842131079351" + "102171626549398024160346762138294097205837595404767869364138165416" + "212878432484332023692099166122496760055730227032447997146221165421" + "888377703760223711720795591258533828013962195524188394697705149041" + "926576270603193728475623010741404426602378441141744972109554498963" + "891803958271916028866544881824524095839813894427833770015054620157" + "450178487545746683421617594966617660200287528887833870748507731929" + "971029979366198762266880963149896457660004790090837317365857503352" + "620998601508967187744019647968271662832256419920407478943826987518" + "09812609536720628966577351093292236328125E-310", 0x0000800000000100 ); // Example 4 (2^-1058 + 2^-1063 + 2^-1075, half-ulp below a non-power of two): CheckOneDouble( "3.3390685575711885818357137012809439119234019169985217716556569973" + "284403145596153181688491490746626090999981130094655664268081703784" + "340657229916596426194677060348844249897410807907667784563321682004" + "646515939958173717821250106683466529959122339932545844611258684816" + "333436749050742710644097630907080178565840197768788124253120088123" + "262603630354748115322368533599053346255754042160606228586332807443" + "018924703005556787346899784768703698535494132771566221702458461669" + "916553215355296238706468887866375289955928004361779017462862722733" + "744717014529914330472578638646014242520247915673681950560773208853" + "293843223323915646452641434007986196650406080775491621739636492640" + "497383622906068758834568265867109610417379088720358034812416003767" + "05491726170293986797332763671875E-319", 0x0000000000010800 ); // http://www.exploringbinary.com/gays-strtod-returns-zero-for-inputs-just-above-2-1075/ // A number between 2^-2074 and 2^-1075, just slightly larger than 2^-1075. // It has bit 1075 set (the denormal rounding bit), followed by 2506 zeroes, // followed by one bits. It should round up to 2^-1074. CheckOneDouble( "2.470328229206232720882843964341106861825299013071623822127928412503" + "37753635104375932649918180817996189898282347722858865463328355177969" + "89819938739800539093906315035659515570226392290858392449105184435931" + "80284993653615250031937045767824921936562366986365848075700158576926" + "99037063119282795585513329278343384093519780155312465972635795746227" + "66465272827220056374006485499977096599470454020828166226237857393450" + "73633900796776193057750674017632467360096895134053553745851666113422" + "37666786041621596804619144672918403005300575308490487653917113865916" + "46239524912623653881879636239373280423891018672348497668235089863388" + "58792562830275599565752445550725518931369083625477918694866799496832" + "40497058210285131854513962138377228261454376934125320985913276672363" + "28125001e-324", 0x0000000000000001); CheckOneDouble("1.0e-99999999999999999999", 0.0); CheckOneDouble("0e-99999999999999999999", 0.0); CheckOneDouble("0e99999999999999999999", 0.0); } private static void TestRoundTripDouble(ulong bits) { double d = BitConverter.Int64BitsToDouble((long)bits); if (double.IsInfinity(d) || double.IsNaN(d)) return; string s = InvariantToString(d); CheckOneDouble(s, bits); } private static string InvariantToString(object o) { return string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:G17}", o); } private static void TestRoundTripDouble(double d) { string s = InvariantToString(d); CheckOneDouble(s, d); } private static void CheckOneDouble(string s, ulong expectedBits) { CheckOneDouble(s, BitConverter.Int64BitsToDouble((long)expectedBits)); } private static void CheckOneDouble(string s, double expected) { double actual; if (!RealParser.TryParseDouble(s, out actual)) actual = 1.0 / 0.0; if (!actual.Equals(expected)) { throw new Exception($@" Error for double input ""{s}"" expected {InvariantToString(expected)} actual {InvariantToString(actual)}"); } } // ============ test some floats ============ [Fact] public static void TestSpecificFloats() { CheckOneFloat(" 0.0", 0x00000000); // Verify the smallest denormals: for (uint i = 0x00000001; i != 0x00000100; ++i) { TestRoundTripFloat(i); } // Verify the largest denormals and the smallest normals: for (uint i = 0x007fff00; i != 0x00800100; ++i) { TestRoundTripFloat(i); } // Verify the largest normals: for (uint i = 0x7f7fff00; i != 0x7f800000; ++i) { TestRoundTripFloat(i); } // Verify all representable powers of two and nearby values: for (int i = -1022; i != 1023; ++i) { float f; try { f = (float)Math.Pow(2.0, i); } catch (OverflowException) { continue; } if (f == 0) continue; uint bits = FloatToInt32Bits(f); TestRoundTripFloat(bits - 1); TestRoundTripFloat(bits); TestRoundTripFloat(bits + 1); } // Verify all representable powers of ten and nearby values: for (int i = -50; i <= 40; ++i) { float f; try { f = (float)Math.Pow(10.0, i); } catch (OverflowException) { continue; } if (f == 0) continue; uint bits = FloatToInt32Bits(f); TestRoundTripFloat(bits - 1); TestRoundTripFloat(bits); TestRoundTripFloat(bits + 1); } TestRoundTripFloat((float)int.MaxValue); TestRoundTripFloat((float)uint.MaxValue); // Verify small and large exactly representable integers: CheckOneFloat("1", 0x3f800000); CheckOneFloat("2", 0x40000000); CheckOneFloat("3", 0x40400000); CheckOneFloat("4", 0x40800000); CheckOneFloat("5", 0x40A00000); CheckOneFloat("6", 0x40C00000); CheckOneFloat("7", 0x40E00000); CheckOneFloat("8", 0x41000000); CheckOneFloat("16777208", 0x4b7ffff8); CheckOneFloat("16777209", 0x4b7ffff9); CheckOneFloat("16777210", 0x4b7ffffa); CheckOneFloat("16777211", 0x4b7ffffb); CheckOneFloat("16777212", 0x4b7ffffc); CheckOneFloat("16777213", 0x4b7ffffd); CheckOneFloat("16777214", 0x4b7ffffe); CheckOneFloat("16777215", 0x4b7fffff); // 2^24 - 1 // Verify the smallest and largest denormal values: CheckOneFloat("1.4012984643248170e-45", 0x00000001); CheckOneFloat("2.8025969286496340e-45", 0x00000002); CheckOneFloat("4.2038953929744510e-45", 0x00000003); CheckOneFloat("5.6051938572992680e-45", 0x00000004); CheckOneFloat("7.0064923216240850e-45", 0x00000005); CheckOneFloat("8.4077907859489020e-45", 0x00000006); CheckOneFloat("9.8090892502737200e-45", 0x00000007); CheckOneFloat("1.1210387714598537e-44", 0x00000008); CheckOneFloat("1.2611686178923354e-44", 0x00000009); CheckOneFloat("1.4012984643248170e-44", 0x0000000a); CheckOneFloat("1.5414283107572988e-44", 0x0000000b); CheckOneFloat("1.6815581571897805e-44", 0x0000000c); CheckOneFloat("1.8216880036222622e-44", 0x0000000d); CheckOneFloat("1.9618178500547440e-44", 0x0000000e); CheckOneFloat("2.1019476964872256e-44", 0x0000000f); CheckOneFloat("1.1754921087447446e-38", 0x007ffff0); CheckOneFloat("1.1754922488745910e-38", 0x007ffff1); CheckOneFloat("1.1754923890044375e-38", 0x007ffff2); CheckOneFloat("1.1754925291342839e-38", 0x007ffff3); CheckOneFloat("1.1754926692641303e-38", 0x007ffff4); CheckOneFloat("1.1754928093939768e-38", 0x007ffff5); CheckOneFloat("1.1754929495238232e-38", 0x007ffff6); CheckOneFloat("1.1754930896536696e-38", 0x007ffff7); CheckOneFloat("1.1754932297835160e-38", 0x007ffff8); CheckOneFloat("1.1754933699133625e-38", 0x007ffff9); CheckOneFloat("1.1754935100432089e-38", 0x007ffffa); CheckOneFloat("1.1754936501730553e-38", 0x007ffffb); CheckOneFloat("1.1754937903029018e-38", 0x007ffffc); CheckOneFloat("1.1754939304327482e-38", 0x007ffffd); CheckOneFloat("1.1754940705625946e-38", 0x007ffffe); CheckOneFloat("1.1754942106924411e-38", 0x007fffff); // This number is exactly representable and should not be rounded in any // mode: // 0.1111111111111111111111100 // ^ CheckOneFloat("0.99999988079071044921875", 0x3f7ffffe); // This number is below the halfway point between two representable values // so it should round down in nearest mode: // 0.11111111111111111111111001 // ^ CheckOneFloat("0.99999989569187164306640625", 0x3f7ffffe); // This number is exactly halfway between two representable values, so it // should round to even in nearest mode: // 0.1111111111111111111111101 // ^ CheckOneFloat("0.9999999105930328369140625", 0x3f7ffffe); // This number is above the halfway point between two representable values // so it should round up in nearest mode: // 0.11111111111111111111111011 // ^ CheckOneFloat("0.99999992549419403076171875", 0x3f7fffff); } private static void TestRoundTripFloat(uint bits) { float d = Int32BitsToFloat(bits); if (float.IsInfinity(d) || float.IsNaN(d)) return; string s = InvariantToString(d); CheckOneFloat(s, bits); } private static void TestRoundTripFloat(float d) { string s = InvariantToString(d); if (s != "NaN" && s != "Infinity") CheckOneFloat(s, d); } private static void CheckOneFloat(string s, uint expectedBits) { CheckOneFloat(s, Int32BitsToFloat(expectedBits)); } private static void CheckOneFloat(string s, float expected) { float actual; if (!RealParser.TryParseFloat(s, out actual)) actual = 1.0f / 0.0f; if (!actual.Equals(expected)) { throw new Exception($@"Error for float input ""{s}"" expected {InvariantToString(expected)} actual {InvariantToString(actual)}"); } } private static uint FloatToInt32Bits(float f) { var bits = default(FloatUnion); bits.FloatData = f; return bits.IntData; } private static float Int32BitsToFloat(uint i) { var bits = default(FloatUnion); bits.IntData = i; return bits.FloatData; } [StructLayout(LayoutKind.Explicit)] private struct FloatUnion { [FieldOffset(0)] public uint IntData; [FieldOffset(0)] public float FloatData; } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/OptionPages/ForceLowMemoryMode_Options.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Options; namespace Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages { internal sealed partial class ForceLowMemoryMode { public static readonly Option2<bool> Enabled = new(nameof(ForceLowMemoryMode), nameof(Enabled), defaultValue: false, storageLocation: new LocalUserProfileStorageLocation(@"Roslyn\ForceLowMemoryMode\Enabled")); public static readonly Option2<int> SizeInMegabytes = new(nameof(ForceLowMemoryMode), nameof(SizeInMegabytes), defaultValue: 500, storageLocation: new LocalUserProfileStorageLocation(@"Roslyn\ForceLowMemoryMode\SizeInMegabytes")); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Options; namespace Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages { internal sealed partial class ForceLowMemoryMode { public static readonly Option2<bool> Enabled = new(nameof(ForceLowMemoryMode), nameof(Enabled), defaultValue: false, storageLocation: new LocalUserProfileStorageLocation(@"Roslyn\ForceLowMemoryMode\Enabled")); public static readonly Option2<int> SizeInMegabytes = new(nameof(ForceLowMemoryMode), nameof(SizeInMegabytes), defaultValue: 500, storageLocation: new LocalUserProfileStorageLocation(@"Roslyn\ForceLowMemoryMode\SizeInMegabytes")); } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Compilers/CSharp/Portable/BoundTree/BoundInterpolatedStringArgumentPlaceholder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundInterpolatedStringArgumentPlaceholder { public const int InstanceParameter = -1; public const int TrailingConstructorValidityParameter = -2; public const int UnspecifiedParameter = -3; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundInterpolatedStringArgumentPlaceholder { public const int InstanceParameter = -1; public const int TrailingConstructorValidityParameter = -2; public const int UnspecifiedParameter = -3; } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Tools/AnalyzerRunner/AnalyzerRunner.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets" /> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFrameworks>net5.0;netcoreapp3.1;net472</TargetFrameworks> <IsShipping>false</IsShipping> <PlatformTarget>AnyCPU</PlatformTarget> <ServerGarbageCollection>true</ServerGarbageCollection> <!-- Automatically generate the necessary assembly binding redirects --> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> </PropertyGroup> <PropertyGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'"> <!-- Avoid allocation interference due to a boxing bug which was fixed for .NET 5. https://github.com/dotnet/runtime/issues/1713 --> <TieredCompilation>false</TieredCompilation> </PropertyGroup> <ItemGroup> <PackageReference Include="SQLitePCLRaw.bundle_green" Version="$(SQLitePCLRawbundle_greenVersion)" PrivateAssets="all" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildFrameworkVersion)" ExcludeAssets="Runtime" PrivateAssets="All" /> <PackageReference Include="Microsoft.Build.Locator" Version="$(MicrosoftBuildLocatorVersion)" /> <PackageReference Include="System.Buffers" Version="$(SystemBuffersVersion)" /> <PackageReference Include="System.ComponentModel.Composition" Version="$(SystemComponentModelCompositionVersion)" /> <PackageReference Include="System.Threading.Tasks.Dataflow" Version="$(SystemThreadingTasksDataflowVersion)" /> <PackageReference Include="Microsoft.Win32.Registry" Version="$(MicrosoftWin32RegistryVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> </ItemGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\MSBuild\Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj" /> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <!-- These aren't used by the build, but it allows the tool to locate dependencies of the built-in analyzers. --> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net472'"> <!-- These aren't used by the build, but it allows the tool to locate dependencies of the built-in analyzers. --> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net472'"> <!-- Install the AppDomainManager from SourceBrowser https://github.com/microsoft/MSBuildLocator/issues/16 --> <PackageReference Include="SourceBrowser" Version="$(SourceBrowserVersion)" ExcludeAssets="build;compile" PrivateAssets="all" /> <Content Include="$(NuGetPackageRoot)\sourcebrowser\$(SourceBrowserVersion)\tools\HtmlGenerator.exe" Visible="false" CopyToOutputDirectory="PreserveNewest" /> <Content Include="$(NuGetPackageRoot)\sourcebrowser\$(SourceBrowserVersion)\tools\Microsoft.SourceBrowser.Common.dll" Visible="false" CopyToOutputDirectory="PreserveNewest" /> </ItemGroup> <ItemGroup> <None Include="app.config" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets" /> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFrameworks>net5.0;netcoreapp3.1;net472</TargetFrameworks> <IsShipping>false</IsShipping> <PlatformTarget>AnyCPU</PlatformTarget> <ServerGarbageCollection>true</ServerGarbageCollection> <!-- Automatically generate the necessary assembly binding redirects --> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> </PropertyGroup> <PropertyGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'"> <!-- Avoid allocation interference due to a boxing bug which was fixed for .NET 5. https://github.com/dotnet/runtime/issues/1713 --> <TieredCompilation>false</TieredCompilation> </PropertyGroup> <ItemGroup> <PackageReference Include="SQLitePCLRaw.bundle_green" Version="$(SQLitePCLRawbundle_greenVersion)" PrivateAssets="all" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildFrameworkVersion)" ExcludeAssets="Runtime" PrivateAssets="All" /> <PackageReference Include="Microsoft.Build.Locator" Version="$(MicrosoftBuildLocatorVersion)" /> <PackageReference Include="System.Buffers" Version="$(SystemBuffersVersion)" /> <PackageReference Include="System.ComponentModel.Composition" Version="$(SystemComponentModelCompositionVersion)" /> <PackageReference Include="System.Threading.Tasks.Dataflow" Version="$(SystemThreadingTasksDataflowVersion)" /> <PackageReference Include="Microsoft.Win32.Registry" Version="$(MicrosoftWin32RegistryVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> </ItemGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\MSBuild\Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj" /> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <!-- These aren't used by the build, but it allows the tool to locate dependencies of the built-in analyzers. --> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net472'"> <!-- These aren't used by the build, but it allows the tool to locate dependencies of the built-in analyzers. --> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net472'"> <!-- Install the AppDomainManager from SourceBrowser https://github.com/microsoft/MSBuildLocator/issues/16 --> <PackageReference Include="SourceBrowser" Version="$(SourceBrowserVersion)" ExcludeAssets="build;compile" PrivateAssets="all" /> <Content Include="$(NuGetPackageRoot)\sourcebrowser\$(SourceBrowserVersion)\tools\HtmlGenerator.exe" Visible="false" CopyToOutputDirectory="PreserveNewest" /> <Content Include="$(NuGetPackageRoot)\sourcebrowser\$(SourceBrowserVersion)\tools\Microsoft.SourceBrowser.Common.dll" Visible="false" CopyToOutputDirectory="PreserveNewest" /> </ItemGroup> <ItemGroup> <None Include="app.config" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression { using Constants = ConvertSwitchStatementToExpressionConstants; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertSwitchStatementToExpression), Shared] internal sealed partial class ConvertSwitchStatementToExpressionCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ConvertSwitchStatementToExpressionCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.ConvertSwitchStatementToExpressionDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var switchLocation = context.Diagnostics.First().AdditionalLocations[0]; var switchStatement = (SwitchStatementSyntax)switchLocation.FindNode(getInnermostNodeForTie: true, context.CancellationToken); if (switchStatement.ContainsDirectives) { // Avoid providing code fixes for switch statements containing directives return Task.CompletedTask; } context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { using var spansDisposer = ArrayBuilder<TextSpan>.GetInstance(diagnostics.Length, out var spans); foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); var switchLocation = diagnostic.AdditionalLocations[0]; if (spans.Any((s, nodeSpan) => s.Contains(nodeSpan), switchLocation.SourceSpan)) { // Skip nested switch expressions in case of a fix-all operation. continue; } spans.Add(switchLocation.SourceSpan); var properties = diagnostic.Properties; var nodeToGenerate = (SyntaxKind)int.Parse(properties[Constants.NodeToGenerateKey]); var shouldRemoveNextStatement = bool.Parse(properties[Constants.ShouldRemoveNextStatementKey]); var declaratorToRemoveLocationOpt = diagnostic.AdditionalLocations.ElementAtOrDefault(1); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); SyntaxNode declaratorToRemoveNodeOpt = null; ITypeSymbol declaratorToRemoveTypeOpt = null; if (declaratorToRemoveLocationOpt != null) { declaratorToRemoveNodeOpt = declaratorToRemoveLocationOpt.FindNode(cancellationToken); declaratorToRemoveTypeOpt = semanticModel.GetDeclaredSymbol(declaratorToRemoveNodeOpt, cancellationToken).GetSymbolType(); } var switchStatement = (SwitchStatementSyntax)switchLocation.FindNode(getInnermostNodeForTie: true, cancellationToken); var switchExpression = Rewriter.Rewrite( switchStatement, semanticModel, declaratorToRemoveTypeOpt, nodeToGenerate, shouldMoveNextStatementToSwitchExpression: shouldRemoveNextStatement, generateDeclaration: declaratorToRemoveLocationOpt is object); editor.ReplaceNode(switchStatement, switchExpression.WithAdditionalAnnotations(Formatter.Annotation)); if (declaratorToRemoveLocationOpt is object) { editor.RemoveNode(declaratorToRemoveLocationOpt.FindNode(cancellationToken)); } if (shouldRemoveNextStatement) { // Already morphed into the top-level switch expression. SyntaxNode nextStatement = switchStatement.GetNextStatement(); Debug.Assert(nextStatement.IsKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement)); editor.RemoveNode(nextStatement.IsParentKind(SyntaxKind.GlobalStatement) ? nextStatement.Parent : nextStatement); } } } private sealed class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Convert_switch_statement_to_expression, createChangedDocument, nameof(CSharpAnalyzersResources.Convert_switch_statement_to_expression)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression { using Constants = ConvertSwitchStatementToExpressionConstants; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertSwitchStatementToExpression), Shared] internal sealed partial class ConvertSwitchStatementToExpressionCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ConvertSwitchStatementToExpressionCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.ConvertSwitchStatementToExpressionDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var switchLocation = context.Diagnostics.First().AdditionalLocations[0]; var switchStatement = (SwitchStatementSyntax)switchLocation.FindNode(getInnermostNodeForTie: true, context.CancellationToken); if (switchStatement.ContainsDirectives) { // Avoid providing code fixes for switch statements containing directives return Task.CompletedTask; } context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { using var spansDisposer = ArrayBuilder<TextSpan>.GetInstance(diagnostics.Length, out var spans); foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); var switchLocation = diagnostic.AdditionalLocations[0]; if (spans.Any((s, nodeSpan) => s.Contains(nodeSpan), switchLocation.SourceSpan)) { // Skip nested switch expressions in case of a fix-all operation. continue; } spans.Add(switchLocation.SourceSpan); var properties = diagnostic.Properties; var nodeToGenerate = (SyntaxKind)int.Parse(properties[Constants.NodeToGenerateKey]); var shouldRemoveNextStatement = bool.Parse(properties[Constants.ShouldRemoveNextStatementKey]); var declaratorToRemoveLocationOpt = diagnostic.AdditionalLocations.ElementAtOrDefault(1); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); SyntaxNode declaratorToRemoveNodeOpt = null; ITypeSymbol declaratorToRemoveTypeOpt = null; if (declaratorToRemoveLocationOpt != null) { declaratorToRemoveNodeOpt = declaratorToRemoveLocationOpt.FindNode(cancellationToken); declaratorToRemoveTypeOpt = semanticModel.GetDeclaredSymbol(declaratorToRemoveNodeOpt, cancellationToken).GetSymbolType(); } var switchStatement = (SwitchStatementSyntax)switchLocation.FindNode(getInnermostNodeForTie: true, cancellationToken); var switchExpression = Rewriter.Rewrite( switchStatement, semanticModel, declaratorToRemoveTypeOpt, nodeToGenerate, shouldMoveNextStatementToSwitchExpression: shouldRemoveNextStatement, generateDeclaration: declaratorToRemoveLocationOpt is object); editor.ReplaceNode(switchStatement, switchExpression.WithAdditionalAnnotations(Formatter.Annotation)); if (declaratorToRemoveLocationOpt is object) { editor.RemoveNode(declaratorToRemoveLocationOpt.FindNode(cancellationToken)); } if (shouldRemoveNextStatement) { // Already morphed into the top-level switch expression. SyntaxNode nextStatement = switchStatement.GetNextStatement(); Debug.Assert(nextStatement.IsKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement)); editor.RemoveNode(nextStatement.IsParentKind(SyntaxKind.GlobalStatement) ? nextStatement.Parent : nextStatement); } } } private sealed class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Convert_switch_statement_to_expression, createChangedDocument, nameof(CSharpAnalyzersResources.Convert_switch_statement_to_expression)) { } } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndHashWithDialogCodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.PickMembers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers { internal partial class GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider { private class GenerateEqualsAndGetHashCodeWithDialogCodeAction : CodeActionWithOptions { private readonly bool _generateEquals; private readonly bool _generateGetHashCode; private readonly GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider _service; private readonly Document _document; private readonly SyntaxNode _typeDeclaration; private readonly INamedTypeSymbol _containingType; private readonly ImmutableArray<ISymbol> _viableMembers; private readonly ImmutableArray<PickMembersOption> _pickMembersOptions; private bool? _implementIEqutableOptionValue; private bool? _generateOperatorsOptionValue; public GenerateEqualsAndGetHashCodeWithDialogCodeAction( GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider service, Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> viableMembers, ImmutableArray<PickMembersOption> pickMembersOptions, bool generateEquals = false, bool generateGetHashCode = false) { _service = service; _document = document; _typeDeclaration = typeDeclaration; _containingType = containingType; _viableMembers = viableMembers; _pickMembersOptions = pickMembersOptions; _generateEquals = generateEquals; _generateGetHashCode = generateGetHashCode; } public override string EquivalenceKey => Title; public override object GetOptions(CancellationToken cancellationToken) { var service = _service._pickMembersService_forTestingPurposes ?? _document.Project.Solution.Workspace.Services.GetRequiredService<IPickMembersService>(); return service.PickMembers(FeaturesResources.Pick_members_to_be_used_in_Equals_GetHashCode, _viableMembers, _pickMembersOptions); } protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken) { var result = (PickMembersResult)options; if (result.IsCanceled) { return SpecializedCollections.EmptyEnumerable<CodeActionOperation>(); } // If we presented the user any options, then persist whatever values // the user chose. That way we'll keep that as the default for the // next time the user opens the dialog. var workspace = _document.Project.Solution.Workspace; var implementIEqutableOption = result.Options.FirstOrDefault(o => o.Id == ImplementIEquatableId); if (implementIEqutableOption != null) { _implementIEqutableOptionValue = implementIEqutableOption.Value; } var generateOperatorsOption = result.Options.FirstOrDefault(o => o.Id == GenerateOperatorsId); if (generateOperatorsOption != null) { _generateOperatorsOptionValue = generateOperatorsOption.Value; } var implementIEquatable = (implementIEqutableOption?.Value ?? false); var generatorOperators = (generateOperatorsOption?.Value ?? false); var action = new GenerateEqualsAndGetHashCodeAction( _document, _typeDeclaration, _containingType, result.Members, _generateEquals, _generateGetHashCode, implementIEquatable, generatorOperators); return await action.GetOperationsAsync(cancellationToken).ConfigureAwait(false); } public override string Title => GenerateEqualsAndGetHashCodeAction.GetTitle(_generateEquals, _generateGetHashCode) + "..."; protected override async Task<Solution?> GetChangedSolutionAsync(CancellationToken cancellationToken) { var solution = await base.GetChangedSolutionAsync(cancellationToken).ConfigureAwait(false); if (_implementIEqutableOptionValue.HasValue) { solution = solution?.WithOptions(solution.Options.WithChangedOption( GenerateEqualsAndGetHashCodeFromMembersOptions.ImplementIEquatable, _document.Project.Language, _implementIEqutableOptionValue.Value)); } if (_generateOperatorsOptionValue.HasValue) { solution = solution?.WithOptions(solution.Options.WithChangedOption( GenerateEqualsAndGetHashCodeFromMembersOptions.GenerateOperators, _document.Project.Language, _generateOperatorsOptionValue.Value)); } return solution; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.PickMembers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers { internal partial class GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider { private class GenerateEqualsAndGetHashCodeWithDialogCodeAction : CodeActionWithOptions { private readonly bool _generateEquals; private readonly bool _generateGetHashCode; private readonly GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider _service; private readonly Document _document; private readonly SyntaxNode _typeDeclaration; private readonly INamedTypeSymbol _containingType; private readonly ImmutableArray<ISymbol> _viableMembers; private readonly ImmutableArray<PickMembersOption> _pickMembersOptions; private bool? _implementIEqutableOptionValue; private bool? _generateOperatorsOptionValue; public GenerateEqualsAndGetHashCodeWithDialogCodeAction( GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider service, Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> viableMembers, ImmutableArray<PickMembersOption> pickMembersOptions, bool generateEquals = false, bool generateGetHashCode = false) { _service = service; _document = document; _typeDeclaration = typeDeclaration; _containingType = containingType; _viableMembers = viableMembers; _pickMembersOptions = pickMembersOptions; _generateEquals = generateEquals; _generateGetHashCode = generateGetHashCode; } public override string EquivalenceKey => Title; public override object GetOptions(CancellationToken cancellationToken) { var service = _service._pickMembersService_forTestingPurposes ?? _document.Project.Solution.Workspace.Services.GetRequiredService<IPickMembersService>(); return service.PickMembers(FeaturesResources.Pick_members_to_be_used_in_Equals_GetHashCode, _viableMembers, _pickMembersOptions); } protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken) { var result = (PickMembersResult)options; if (result.IsCanceled) { return SpecializedCollections.EmptyEnumerable<CodeActionOperation>(); } // If we presented the user any options, then persist whatever values // the user chose. That way we'll keep that as the default for the // next time the user opens the dialog. var workspace = _document.Project.Solution.Workspace; var implementIEqutableOption = result.Options.FirstOrDefault(o => o.Id == ImplementIEquatableId); if (implementIEqutableOption != null) { _implementIEqutableOptionValue = implementIEqutableOption.Value; } var generateOperatorsOption = result.Options.FirstOrDefault(o => o.Id == GenerateOperatorsId); if (generateOperatorsOption != null) { _generateOperatorsOptionValue = generateOperatorsOption.Value; } var implementIEquatable = (implementIEqutableOption?.Value ?? false); var generatorOperators = (generateOperatorsOption?.Value ?? false); var action = new GenerateEqualsAndGetHashCodeAction( _document, _typeDeclaration, _containingType, result.Members, _generateEquals, _generateGetHashCode, implementIEquatable, generatorOperators); return await action.GetOperationsAsync(cancellationToken).ConfigureAwait(false); } public override string Title => GenerateEqualsAndGetHashCodeAction.GetTitle(_generateEquals, _generateGetHashCode) + "..."; protected override async Task<Solution?> GetChangedSolutionAsync(CancellationToken cancellationToken) { var solution = await base.GetChangedSolutionAsync(cancellationToken).ConfigureAwait(false); if (_implementIEqutableOptionValue.HasValue) { solution = solution?.WithOptions(solution.Options.WithChangedOption( GenerateEqualsAndGetHashCodeFromMembersOptions.ImplementIEquatable, _document.Project.Language, _implementIEqutableOptionValue.Value)); } if (_generateOperatorsOptionValue.HasValue) { solution = solution?.WithOptions(solution.Options.WithChangedOption( GenerateEqualsAndGetHashCodeFromMembersOptions.GenerateOperators, _document.Project.Language, _generateOperatorsOptionValue.Value)); } return solution; } } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/EditorFeatures/VisualBasic/LineCommit/BeforeCommitCaretMoveUndoPrimitive.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Friend Class BeforeCommitCaretMoveUndoPrimitive Inherits AbstractCommitCaretMoveUndoPrimitive Private ReadOnly _oldPosition As Integer Private ReadOnly _oldVirtualSpaces As Integer Private _active As Boolean Public Sub New(textBuffer As ITextBuffer, textBufferAssociatedViewService As ITextBufferAssociatedViewService, oldLocation As CaretPosition) MyBase.New(textBuffer, textBufferAssociatedViewService) ' Grab the old position and virtual spaces. This is cheaper than holding onto ' a VirtualSnapshotPoint as it won't hold old snapshots alive _oldPosition = oldLocation.VirtualBufferPosition.Position _oldVirtualSpaces = oldLocation.VirtualBufferPosition.VirtualSpaces End Sub Public Sub MarkAsActive() ' We must create this undo primitive and add it to the transaction before we know if our ' commit is actually going to do something. If we cancel the transaction, we still get ' called on Undo, but we don't want to actually do anything there. Thus we have flag to ' know if we're actually a live undo primitive _active = True End Sub Public Overrides Sub [Do]() ' When we are going forward, we do nothing here since the AfterCommitCaretMoveUndoPrimitive ' will take care of it End Sub Public Overrides Sub Undo() ' Sometimes we cancel the transaction, in this case don't do anything. If Not _active Then Return End If Dim view = TryGetView() If view IsNot Nothing Then view.Caret.MoveTo(New VirtualSnapshotPoint(New SnapshotPoint(view.TextSnapshot, _oldPosition), _oldVirtualSpaces)) view.Caret.EnsureVisible() End If End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Friend Class BeforeCommitCaretMoveUndoPrimitive Inherits AbstractCommitCaretMoveUndoPrimitive Private ReadOnly _oldPosition As Integer Private ReadOnly _oldVirtualSpaces As Integer Private _active As Boolean Public Sub New(textBuffer As ITextBuffer, textBufferAssociatedViewService As ITextBufferAssociatedViewService, oldLocation As CaretPosition) MyBase.New(textBuffer, textBufferAssociatedViewService) ' Grab the old position and virtual spaces. This is cheaper than holding onto ' a VirtualSnapshotPoint as it won't hold old snapshots alive _oldPosition = oldLocation.VirtualBufferPosition.Position _oldVirtualSpaces = oldLocation.VirtualBufferPosition.VirtualSpaces End Sub Public Sub MarkAsActive() ' We must create this undo primitive and add it to the transaction before we know if our ' commit is actually going to do something. If we cancel the transaction, we still get ' called on Undo, but we don't want to actually do anything there. Thus we have flag to ' know if we're actually a live undo primitive _active = True End Sub Public Overrides Sub [Do]() ' When we are going forward, we do nothing here since the AfterCommitCaretMoveUndoPrimitive ' will take care of it End Sub Public Overrides Sub Undo() ' Sometimes we cancel the transaction, in this case don't do anything. If Not _active Then Return End If Dim view = TryGetView() If view IsNot Nothing Then view.Caret.MoveTo(New VirtualSnapshotPoint(New SnapshotPoint(view.TextSnapshot, _oldPosition), _oldVirtualSpaces)) view.Caret.EnsureVisible() End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ByteKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ByteKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public ByteKeywordRecommender() : base(SyntaxKind.ByteKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsEnumBaseListContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_Byte; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ByteKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public ByteKeywordRecommender() : base(SyntaxKind.ByteKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsEnumBaseListContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_Byte; } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/Core/Portable/EditAndContinue/Remote/RemoteDebuggingSessionProxy.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable { private readonly IDisposable? _connection; private readonly DebuggingSessionId _sessionId; private readonly Workspace _workspace; public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId) { _connection = connection; _sessionId = sessionId; _workspace = workspace; } public void Dispose() { _connection?.Dispose(); } private IEditAndContinueWorkspaceService GetLocalService() => _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask BreakStateChangedAsync(IDiagnosticAnalyzerService diagnosticService, bool inBreakState, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().BreakStateChanged(_sessionId, inBreakState, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.BreakStateChangedAsync(_sessionId, inBreakState, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask EndDebuggingSessionAsync(Solution compileTimeSolution, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } var designTimeDocumentsToReanalyze = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync( compileTimeSolution, documentsToReanalyze, designTimeSolution: _workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: designTimeDocumentsToReanalyze); // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); Dispose(); } public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : true; } public async ValueTask<( ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>)> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, CancellationToken cancellationToken) { ManagedModuleUpdates moduleUpdates; ImmutableArray<DiagnosticData> diagnosticData; ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); moduleUpdates = results.ModuleUpdates; diagnosticData = results.GetDiagnosticData(solution); rudeEdits = results.RudeEdits; } else { var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (result.HasValue) { moduleUpdates = result.Value.ModuleUpdates; diagnosticData = result.Value.Diagnostics; rudeEdits = result.Value.RudeEdits; } else { moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); diagnosticData = ImmutableArray<DiagnosticData>.Empty; rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty; } } // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId)); // report emit/apply diagnostics: diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData); return (moduleUpdates, diagnosticData, rudeEdits); } public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().DiscardSolutionUpdate(_sessionId); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( (service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>( solution, (service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>( solution, (service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty; } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class RemoteDebuggingSessionProxy : IActiveStatementSpanProvider, IDisposable { private readonly IDisposable? _connection; private readonly DebuggingSessionId _sessionId; private readonly Workspace _workspace; public RemoteDebuggingSessionProxy(Workspace workspace, IDisposable? connection, DebuggingSessionId sessionId) { _connection = connection; _sessionId = sessionId; _workspace = workspace; } public void Dispose() { _connection?.Dispose(); } private IEditAndContinueWorkspaceService GetLocalService() => _workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); public async ValueTask BreakStateChangedAsync(IDiagnosticAnalyzerService diagnosticService, bool inBreakState, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().BreakStateChanged(_sessionId, inBreakState, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.BreakStateChangedAsync(_sessionId, inBreakState, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask EndDebuggingSessionAsync(Solution compileTimeSolution, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().EndDebuggingSession(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.EndDebuggingSessionAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } var designTimeDocumentsToReanalyze = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync( compileTimeSolution, documentsToReanalyze, designTimeSolution: _workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: designTimeDocumentsToReanalyze); // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); Dispose(); } public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().HasChangesAsync(_sessionId, solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.HasChangesAsync(solutionInfo, callbackId, _sessionId, sourceFilePath, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : true; } public async ValueTask<( ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>)> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, CancellationToken cancellationToken) { ManagedModuleUpdates moduleUpdates; ImmutableArray<DiagnosticData> diagnosticData; ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> rudeEdits; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { var results = await GetLocalService().EmitSolutionUpdateAsync(_sessionId, solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); moduleUpdates = results.ModuleUpdates; diagnosticData = results.GetDiagnosticData(solution); rudeEdits = results.RudeEdits; } else { var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, EmitSolutionUpdateResults.Data>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.EmitSolutionUpdateAsync(solutionInfo, callbackId, _sessionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); if (result.HasValue) { moduleUpdates = result.Value.ModuleUpdates; diagnosticData = result.Value.Diagnostics; rudeEdits = result.Value.RudeEdits; } else { moduleUpdates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); diagnosticData = ImmutableArray<DiagnosticData>.Empty; rudeEdits = ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)>.Empty; } } // clear emit/apply diagnostics reported previously: diagnosticUpdateSource.ClearDiagnostics(); // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: rudeEdits.Select(d => d.DocumentId)); // report emit/apply diagnostics: diagnosticUpdateSource.ReportDiagnostics(_workspace, solution, diagnosticData); return (moduleUpdates, diagnosticData, rudeEdits); } public async ValueTask CommitSolutionUpdateAsync(IDiagnosticAnalyzerService diagnosticService, CancellationToken cancellationToken) { ImmutableArray<DocumentId> documentsToReanalyze; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().CommitSolutionUpdate(_sessionId, out documentsToReanalyze); } else { var documentsToReanalyzeOpt = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DocumentId>>( (service, cancallationToken) => service.CommitSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); documentsToReanalyze = documentsToReanalyzeOpt.HasValue ? documentsToReanalyzeOpt.Value : ImmutableArray<DocumentId>.Empty; } // clear all reported rude edits: diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); } public async ValueTask DiscardSolutionUpdateAsync(CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { GetLocalService().DiscardSolutionUpdate(_sessionId); return; } await client.TryInvokeAsync<IRemoteEditAndContinueService>( (service, cancellationToken) => service.DiscardSolutionUpdateAsync(_sessionId, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetCurrentActiveStatementPositionAsync(_sessionId, solution, activeStatementSpanProvider, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, LinePositionSpan?>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetCurrentActiveStatementPositionAsync(solutionInfo, callbackId, _sessionId, instructionId, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace.Services, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().IsActiveStatementInExceptionRegionAsync(_sessionId, solution, instructionId, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, bool?>( solution, (service, solutionInfo, cancellationToken) => service.IsActiveStatementInExceptionRegionAsync(solutionInfo, _sessionId, instructionId, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : null; } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetBaseActiveStatementSpansAsync(_sessionId, solution, documentIds, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ImmutableArray<ActiveStatementSpan>>>( solution, (service, solutionInfo, cancellationToken) => service.GetBaseActiveStatementSpansAsync(solutionInfo, _sessionId, documentIds, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ImmutableArray<ActiveStatementSpan>>.Empty; } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); } var result = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<ActiveStatementSpan>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken), callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ActiveStatementSpan>.Empty; } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/MoveToNamespaceDialog_OutOfProc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class MoveToNamespaceDialog_OutOfProc : OutOfProcComponent { private readonly MoveToNamespaceDialog_InProc _inProc; public MoveToNamespaceDialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _inProc = CreateInProcComponent<MoveToNamespaceDialog_InProc>(visualStudioInstance); } /// <summary> /// Verifies that the Move To Namespace dialog is currently open. /// </summary> public void VerifyOpen() => _inProc.VerifyOpen(); /// <summary> /// Verifies that the Move To Namespace dialog is currently closed. /// </summary> public void VerifyClosed() => _inProc.VerifyClosed(); public bool CloseWindow() => _inProc.CloseWindow(); public void SetNamespace(string @namespace) => _inProc.SetSetNamespace(@namespace); /// <summary> /// Clicks the "OK" button and waits for the Move To Namespace operation to complete. /// </summary> public void ClickOK() => _inProc.ClickOK(); /// <summary> /// Clicks the "Cancel" button and waits for the Move To Namespace operation to complete. /// </summary> public void ClickCancel() => _inProc.ClickCancel(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class MoveToNamespaceDialog_OutOfProc : OutOfProcComponent { private readonly MoveToNamespaceDialog_InProc _inProc; public MoveToNamespaceDialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _inProc = CreateInProcComponent<MoveToNamespaceDialog_InProc>(visualStudioInstance); } /// <summary> /// Verifies that the Move To Namespace dialog is currently open. /// </summary> public void VerifyOpen() => _inProc.VerifyOpen(); /// <summary> /// Verifies that the Move To Namespace dialog is currently closed. /// </summary> public void VerifyClosed() => _inProc.VerifyClosed(); public bool CloseWindow() => _inProc.CloseWindow(); public void SetNamespace(string @namespace) => _inProc.SetSetNamespace(@namespace); /// <summary> /// Clicks the "OK" button and waits for the Move To Namespace operation to complete. /// </summary> public void ClickOK() => _inProc.ClickOK(); /// <summary> /// Clicks the "Cancel" button and waits for the Move To Namespace operation to complete. /// </summary> public void ClickCancel() => _inProc.ClickCancel(); } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Compilers/Core/CodeAnalysisTest/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Compilers/VisualBasic/Portable/Symbols/Source/SynthesizedLambdaKind.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Enum SynthesizedLambdaKind UserDefined DelegateRelaxationStub LateBoundAddressOfLambda ' query lambdas: FilterConditionQueryLambda ' where, take while, skip while conditions OrderingQueryLambda AggregationQueryLambda AggregateQueryLambda FromOrAggregateVariableQueryLambda LetVariableQueryLambda SelectQueryLambda GroupByItemsQueryLambda GroupByKeysQueryLambda JoinLeftQueryLambda JoinRightQueryLambda ' non-user code lambdas: JoinNonUserCodeQueryLambda AggregateNonUserCodeQueryLambda FromNonUserCodeQueryLambda GroupNonUserCodeQueryLambda ' group join, group by ConversionNonUserCodeQueryLambda End Enum Friend Module SynthesizedLambdaKindExtensions <Extension> Friend Function IsQueryLambda(kind As SynthesizedLambdaKind) As Boolean Return kind >= SynthesizedLambdaKind.FilterConditionQueryLambda AndAlso kind <= SynthesizedLambdaKind.ConversionNonUserCodeQueryLambda End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Enum SynthesizedLambdaKind UserDefined DelegateRelaxationStub LateBoundAddressOfLambda ' query lambdas: FilterConditionQueryLambda ' where, take while, skip while conditions OrderingQueryLambda AggregationQueryLambda AggregateQueryLambda FromOrAggregateVariableQueryLambda LetVariableQueryLambda SelectQueryLambda GroupByItemsQueryLambda GroupByKeysQueryLambda JoinLeftQueryLambda JoinRightQueryLambda ' non-user code lambdas: JoinNonUserCodeQueryLambda AggregateNonUserCodeQueryLambda FromNonUserCodeQueryLambda GroupNonUserCodeQueryLambda ' group join, group by ConversionNonUserCodeQueryLambda End Enum Friend Module SynthesizedLambdaKindExtensions <Extension> Friend Function IsQueryLambda(kind As SynthesizedLambdaKind) As Boolean Return kind >= SynthesizedLambdaKind.FilterConditionQueryLambda AndAlso kind <= SynthesizedLambdaKind.ConversionNonUserCodeQueryLambda End Function End Module End Namespace
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/CSharpProjectShim.IVsEditorFactoryNotify.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { // The native project system requires that project sites implement IVsEditorFactoryNotify, and // the project system stores an internal list of the interface pointers to them. The old editor // factory would then call each implementation from it's own IVsEditorFactoryNotify methods. // Since we now supply our own editor factory that doesn't do this, these methods will never be // called. Still, we must implement the interface or we'll never load at all. internal partial class CSharpProjectShim : IVsEditorFactoryNotify { public int NotifyDependentItemSaved(IVsHierarchy hier, uint itemidParent, string documentParentMoniker, uint itemidDpendent, string documentDependentMoniker) => throw new NotSupportedException(); public int NotifyItemAdded(uint grfEFN, IVsHierarchy hier, uint itemid, string documentId) => throw new NotSupportedException(); public int NotifyItemRenamed(IVsHierarchy hier, uint itemid, string documentOldMoniker, string documentNewMoniker) => throw new NotSupportedException(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { // The native project system requires that project sites implement IVsEditorFactoryNotify, and // the project system stores an internal list of the interface pointers to them. The old editor // factory would then call each implementation from it's own IVsEditorFactoryNotify methods. // Since we now supply our own editor factory that doesn't do this, these methods will never be // called. Still, we must implement the interface or we'll never load at all. internal partial class CSharpProjectShim : IVsEditorFactoryNotify { public int NotifyDependentItemSaved(IVsHierarchy hier, uint itemidParent, string documentParentMoniker, uint itemidDpendent, string documentDependentMoniker) => throw new NotSupportedException(); public int NotifyItemAdded(uint grfEFN, IVsHierarchy hier, uint itemid, string documentId) => throw new NotSupportedException(); public int NotifyItemRenamed(IVsHierarchy hier, uint itemid, string documentOldMoniker, string documentNewMoniker) => throw new NotSupportedException(); } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Compilers/VisualBasic/Portable/BoundTree/BoundAddressOfOperator.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundAddressOfOperator Private ReadOnly _delegateResolutionResultCache As New ConcurrentDictionary(Of TypeSymbol, Binder.DelegateResolutionResult)() ''' <summary> ''' Gets the <see>Binder.DelegateResolutionResult</see> for the given targetType. ''' </summary> ''' <remarks> ''' One needs to call <see>GetConversionClassification</see> before in order to fill the cache. ''' </remarks> ''' <param name="targetType">Type of the target.</param> ''' <returns>The <see cref="Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion ''' of the AddressOf operand to the target type ''' </returns> Friend Function GetDelegateResolutionResult(targetType As TypeSymbol, ByRef delegateResolutionResult As Binder.DelegateResolutionResult) As Boolean Return _delegateResolutionResultCache.TryGetValue(targetType, delegateResolutionResult) End Function ''' <summary> ''' Gets the conversion classification. ''' </summary> ''' <param name="targetType">The destination type to convert to.</param> Friend Function GetConversionClassification(targetType As TypeSymbol) As ConversionKind Dim delegateResolutionResult As Binder.DelegateResolutionResult = Nothing If Not _delegateResolutionResultCache.TryGetValue(targetType, delegateResolutionResult) Then delegateResolutionResult = Binder.InterpretDelegateBinding(Me, targetType, isForHandles:=False) _delegateResolutionResultCache.TryAdd(targetType, delegateResolutionResult) End If Return delegateResolutionResult.DelegateConversions End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundAddressOfOperator Private ReadOnly _delegateResolutionResultCache As New ConcurrentDictionary(Of TypeSymbol, Binder.DelegateResolutionResult)() ''' <summary> ''' Gets the <see>Binder.DelegateResolutionResult</see> for the given targetType. ''' </summary> ''' <remarks> ''' One needs to call <see>GetConversionClassification</see> before in order to fill the cache. ''' </remarks> ''' <param name="targetType">Type of the target.</param> ''' <returns>The <see cref="Binder.DelegateResolutionResult">Binder.DelegateResolutionResult</see> for the conversion ''' of the AddressOf operand to the target type ''' </returns> Friend Function GetDelegateResolutionResult(targetType As TypeSymbol, ByRef delegateResolutionResult As Binder.DelegateResolutionResult) As Boolean Return _delegateResolutionResultCache.TryGetValue(targetType, delegateResolutionResult) End Function ''' <summary> ''' Gets the conversion classification. ''' </summary> ''' <param name="targetType">The destination type to convert to.</param> Friend Function GetConversionClassification(targetType As TypeSymbol) As ConversionKind Dim delegateResolutionResult As Binder.DelegateResolutionResult = Nothing If Not _delegateResolutionResultCache.TryGetValue(targetType, delegateResolutionResult) Then delegateResolutionResult = Binder.InterpretDelegateBinding(Me, targetType, isForHandles:=False) _delegateResolutionResultCache.TryAdd(targetType, delegateResolutionResult) End If Return delegateResolutionResult.DelegateConversions End Function End Class End Namespace
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./eng/prepare-tests.sh
#!/usr/bin/env bash # Copyright (c) .NET Foundation and contributors. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for full license information. # Stop script if unbound variable found (use ${var:-} if intentional) set -u # Stop script if subcommand fails set -e source="${BASH_SOURCE[0]}" # resolve $source until the file is no longer a symlink while [[ -h "$source" ]]; do scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" source="$(readlink "$source")" # if $source was a relative symlink, we need to resolve it relative to the path where the # symlink file was located [[ $source != /* ]] && source="$scriptroot/$source" done scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" # Import Arcade functions . "$scriptroot/common/tools.sh" InitializeDotNetCli true # permissions issues make this a pain to do in PrepareTests itself. rm -rf "$repo_root/artifacts/testPayload" dotnet "$repo_root/artifacts/bin/PrepareTests/Debug/net5.0/PrepareTests.dll" --source "$repo_root" --destination "$repo_root/artifacts/testPayload" --unix
#!/usr/bin/env bash # Copyright (c) .NET Foundation and contributors. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for full license information. # Stop script if unbound variable found (use ${var:-} if intentional) set -u # Stop script if subcommand fails set -e source="${BASH_SOURCE[0]}" # resolve $source until the file is no longer a symlink while [[ -h "$source" ]]; do scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" source="$(readlink "$source")" # if $source was a relative symlink, we need to resolve it relative to the path where the # symlink file was located [[ $source != /* ]] && source="$scriptroot/$source" done scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" # Import Arcade functions . "$scriptroot/common/tools.sh" InitializeDotNetCli true # permissions issues make this a pain to do in PrepareTests itself. rm -rf "$repo_root/artifacts/testPayload" dotnet "$repo_root/artifacts/bin/PrepareTests/Debug/net5.0/PrepareTests.dll" --source "$repo_root" --destination "$repo_root/artifacts/testPayload" --unix
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Features/LanguageServer/Protocol/CustomProtocol/FindUsagesLSPContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindSymbols.Finders; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.CustomProtocol { internal class FindUsagesLSPContext : FindUsagesContext { private readonly IProgress<VSInternalReferenceItem[]> _progress; private readonly Document _document; private readonly int _position; private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; /// <summary> /// Methods in FindUsagesLSPContext can be called by multiple threads concurrently. /// We need this sempahore to ensure that we aren't making concurrent /// modifications to data such as _id and _definitionToId. /// </summary> private readonly SemaphoreSlim _semaphore = new(1); private readonly Dictionary<DefinitionItem, int> _definitionToId = new(); /// <summary> /// Keeps track of definitions that cannot be reported without references and which we have /// not yet found a reference for. /// </summary> private readonly Dictionary<int, VSInternalReferenceItem> _definitionsWithoutReference = new(); /// <summary> /// Set of the locations we've found references at. We may end up with multiple references /// being reported for the same location. For example, this can happen in multi-targetting /// scenarios when there are symbols in files linked into multiple projects. Those symbols /// may have references that themselves are in linked locations, leading to multiple references /// found at different virtual locations that the user considers at the same physical location. /// For now we filter out these duplicates to not clutter the UI. If LSP supports the ability /// to override an already reported VSReferenceItem, we could also reissue the item with the /// additional information about all the projects it is found in. /// </summary> private readonly HashSet<(string? filePath, TextSpan span)> _referenceLocations = new(); /// <summary> /// We report the results in chunks. A batch, if it contains results, is reported every 0.5s. /// </summary> private readonly AsyncBatchingWorkQueue<VSInternalReferenceItem> _workQueue; // Unique identifier given to each definition and reference. private int _id = 0; public FindUsagesLSPContext( IProgress<VSInternalReferenceItem[]> progress, Document document, int position, IMetadataAsSourceFileService metadataAsSourceFileService, IAsynchronousOperationListener asyncListener, CancellationToken cancellationToken) { _progress = progress; _document = document; _position = position; _metadataAsSourceFileService = metadataAsSourceFileService; _workQueue = new AsyncBatchingWorkQueue<VSInternalReferenceItem>( TimeSpan.FromMilliseconds(500), ReportReferencesAsync, asyncListener, cancellationToken); } // After all definitions/references have been found, wait here until all results have been reported. public override async ValueTask OnCompletedAsync(CancellationToken cancellationToken) => await _workQueue.WaitUntilCurrentBatchCompletesAsync().ConfigureAwait(false); public override async ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { using (await _semaphore.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (_definitionToId.ContainsKey(definition)) { return; } // Assigning a new id to the definition _id++; _definitionToId.Add(definition, _id); // Creating a new VSReferenceItem for the definition var definitionItem = await GenerateVSReferenceItemAsync( _id, definitionId: _id, _document, _position, definition.SourceSpans.FirstOrNull(), definition.DisplayableProperties, _metadataAsSourceFileService, definition.GetClassifiedText(), definition.Tags.GetFirstGlyph(), symbolUsageInfo: null, isWrittenTo: false, cancellationToken).ConfigureAwait(false); if (definitionItem != null) { // If a definition shouldn't be included in the results list if it doesn't have references, we // have to hold off on reporting it until later when we do find a reference. if (definition.DisplayIfNoReferences) { _workQueue.AddWork(definitionItem); } else { _definitionsWithoutReference.Add(definitionItem.Id, definitionItem); } } } } public override async ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken) { using (await _semaphore.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { // Each reference should be associated with a definition. If this somehow isn't the // case, we bail out early. if (!_definitionToId.TryGetValue(reference.Definition, out var definitionId)) return; var documentSpan = reference.SourceSpan; var document = documentSpan.Document; // If this is reference to the same physical location we've already reported, just // filter this out. it will clutter the UI to show the same places. if (!_referenceLocations.Add((document.FilePath, reference.SourceSpan.SourceSpan))) return; // If the definition hasn't been reported yet, add it to our list of references to report. if (_definitionsWithoutReference.TryGetValue(definitionId, out var definition)) { _workQueue.AddWork(definition); _definitionsWithoutReference.Remove(definitionId); } _id++; // Creating a new VSReferenceItem for the reference var referenceItem = await GenerateVSReferenceItemAsync( _id, definitionId, _document, _position, reference.SourceSpan, reference.AdditionalProperties, _metadataAsSourceFileService, definitionText: null, definitionGlyph: Glyph.None, reference.SymbolUsageInfo, reference.IsWrittenTo, cancellationToken).ConfigureAwait(false); if (referenceItem != null) { _workQueue.AddWork(referenceItem); } } } private static async Task<VSInternalReferenceItem?> GenerateVSReferenceItemAsync( int id, int? definitionId, Document document, int position, DocumentSpan? documentSpan, ImmutableDictionary<string, string> properties, IMetadataAsSourceFileService metadataAsSourceFileService, ClassifiedTextElement? definitionText, Glyph definitionGlyph, SymbolUsageInfo? symbolUsageInfo, bool isWrittenTo, CancellationToken cancellationToken) { var location = await ComputeLocationAsync(document, position, documentSpan, metadataAsSourceFileService, cancellationToken).ConfigureAwait(false); // Getting the text for the Text property. If we somehow can't compute the text, that means we're probably dealing with a metadata // reference, and those don't show up in the results list in Roslyn FAR anyway. var text = await ComputeTextAsync(id, definitionId, documentSpan, definitionText, isWrittenTo, cancellationToken).ConfigureAwait(false); if (text == null) { return null; } // TO-DO: The Origin property should be added once Rich-Nav is completed. // https://github.com/dotnet/roslyn/issues/42847 var result = new VSInternalReferenceItem { DefinitionId = definitionId, DefinitionText = definitionText, // Only definitions should have a non-null DefinitionText DefinitionIcon = definitionGlyph.GetImageElement(), DisplayPath = location?.Uri.LocalPath, Id = id, Kind = symbolUsageInfo.HasValue ? ProtocolConversions.SymbolUsageInfoToReferenceKinds(symbolUsageInfo.Value) : Array.Empty<VSInternalReferenceKind>(), ResolutionStatus = VSInternalResolutionStatusKind.ConfirmedAsReference, Text = text, }; // There are certain items that may not have locations, such as namespace definitions. if (location != null) { result.Location = location; } if (documentSpan != null) { result.DocumentName = documentSpan.Value.Document.Name; result.ProjectName = documentSpan.Value.Document.Project.Name; } if (properties.TryGetValue(AbstractReferenceFinder.ContainingMemberInfoPropertyName, out var referenceContainingMember)) result.ContainingMember = referenceContainingMember; if (properties.TryGetValue(AbstractReferenceFinder.ContainingTypeInfoPropertyName, out var referenceContainingType)) result.ContainingType = referenceContainingType; return result; // Local functions static async Task<LSP.Location?> ComputeLocationAsync( Document document, int position, DocumentSpan? documentSpan, IMetadataAsSourceFileService metadataAsSourceFileService, CancellationToken cancellationToken) { // If we have no document span, our location may be in metadata. if (documentSpan != null) { // We do have a document span, so compute location normally. return await ProtocolConversions.DocumentSpanToLocationAsync(documentSpan.Value, cancellationToken).ConfigureAwait(false); } // If we have no document span, our location may be in metadata or may be a namespace. var symbol = await SymbolFinder.FindSymbolAtPositionAsync(document, position, cancellationToken).ConfigureAwait(false); if (symbol == null || symbol.Locations.IsEmpty || symbol.Kind == SymbolKind.Namespace) { // Either: // (1) We couldn't find the location in metadata and it's not in any of our known documents. // (2) The symbol is a namespace (and therefore has no location). return null; } var declarationFile = await metadataAsSourceFileService.GetGeneratedFileAsync( document.Project, symbol, allowDecompilation: false, cancellationToken).ConfigureAwait(false); var linePosSpan = declarationFile.IdentifierLocation.GetLineSpan().Span; if (string.IsNullOrEmpty(declarationFile.FilePath)) { return null; } try { return new LSP.Location { Uri = ProtocolConversions.GetUriFromFilePath(declarationFile.FilePath), Range = ProtocolConversions.LinePositionToRange(linePosSpan), }; } catch (UriFormatException e) when (FatalError.ReportAndCatch(e)) { // We might reach this point if the file path is formatted incorrectly. return null; } } static async Task<ClassifiedTextElement?> ComputeTextAsync( int id, int? definitionId, DocumentSpan? documentSpan, ClassifiedTextElement? definitionText, bool isWrittenTo, CancellationToken cancellationToken) { // General case if (documentSpan != null) { var classifiedSpansAndHighlightSpan = await ClassifiedSpansAndHighlightSpanFactory.ClassifyAsync( documentSpan.Value, cancellationToken).ConfigureAwait(false); var classifiedSpans = classifiedSpansAndHighlightSpan.ClassifiedSpans; var docText = await documentSpan.Value.Document.GetTextAsync(cancellationToken).ConfigureAwait(false); var classifiedTextRuns = GetClassifiedTextRuns(id, definitionId, documentSpan.Value, isWrittenTo, classifiedSpans, docText); return new ClassifiedTextElement(classifiedTextRuns.ToArray()); } // Certain definitions may not have a DocumentSpan, such as namespace and metadata definitions else if (id == definitionId) { return definitionText; } return null; // Nested local functions static ClassifiedTextRun[] GetClassifiedTextRuns( int id, int? definitionId, DocumentSpan documentSpan, bool isWrittenTo, ImmutableArray<ClassifiedSpan> classifiedSpans, SourceText docText) { using var _ = ArrayBuilder<ClassifiedTextRun>.GetInstance(out var classifiedTextRuns); foreach (var span in classifiedSpans) { // Default case: Don't highlight. For example, if the user invokes FAR on 'x' in 'var x = 1', then 'var', // '=', and '1' should not be highlighted. string? markerTagType = null; // Case 1: Highlight this span of text. For example, if the user invokes FAR on 'x' in 'var x = 1', // then 'x' should be highlighted. if (span.TextSpan == documentSpan.SourceSpan) { // Case 1a: Highlight a definition if (id == definitionId) { markerTagType = DefinitionHighlightTag.TagId; } // Case 1b: Highlight a written reference else if (isWrittenTo) { markerTagType = WrittenReferenceHighlightTag.TagId; } // Case 1c: Highlight a read reference else { markerTagType = ReferenceHighlightTag.TagId; } } classifiedTextRuns.Add(new ClassifiedTextRun( span.ClassificationType, docText.ToString(span.TextSpan), ClassifiedTextRunStyle.Plain, markerTagType)); } return classifiedTextRuns.ToArray(); } } } private ValueTask ReportReferencesAsync(ImmutableArray<VSInternalReferenceItem> referencesToReport, CancellationToken cancellationToken) { // We can report outside of the lock here since _progress is thread-safe. _progress.Report(referencesToReport.ToArray()); return ValueTaskFactory.CompletedTask; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindSymbols.Finders; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.CustomProtocol { internal class FindUsagesLSPContext : FindUsagesContext { private readonly IProgress<VSInternalReferenceItem[]> _progress; private readonly Document _document; private readonly int _position; private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; /// <summary> /// Methods in FindUsagesLSPContext can be called by multiple threads concurrently. /// We need this sempahore to ensure that we aren't making concurrent /// modifications to data such as _id and _definitionToId. /// </summary> private readonly SemaphoreSlim _semaphore = new(1); private readonly Dictionary<DefinitionItem, int> _definitionToId = new(); /// <summary> /// Keeps track of definitions that cannot be reported without references and which we have /// not yet found a reference for. /// </summary> private readonly Dictionary<int, VSInternalReferenceItem> _definitionsWithoutReference = new(); /// <summary> /// Set of the locations we've found references at. We may end up with multiple references /// being reported for the same location. For example, this can happen in multi-targetting /// scenarios when there are symbols in files linked into multiple projects. Those symbols /// may have references that themselves are in linked locations, leading to multiple references /// found at different virtual locations that the user considers at the same physical location. /// For now we filter out these duplicates to not clutter the UI. If LSP supports the ability /// to override an already reported VSReferenceItem, we could also reissue the item with the /// additional information about all the projects it is found in. /// </summary> private readonly HashSet<(string? filePath, TextSpan span)> _referenceLocations = new(); /// <summary> /// We report the results in chunks. A batch, if it contains results, is reported every 0.5s. /// </summary> private readonly AsyncBatchingWorkQueue<VSInternalReferenceItem> _workQueue; // Unique identifier given to each definition and reference. private int _id = 0; public FindUsagesLSPContext( IProgress<VSInternalReferenceItem[]> progress, Document document, int position, IMetadataAsSourceFileService metadataAsSourceFileService, IAsynchronousOperationListener asyncListener, CancellationToken cancellationToken) { _progress = progress; _document = document; _position = position; _metadataAsSourceFileService = metadataAsSourceFileService; _workQueue = new AsyncBatchingWorkQueue<VSInternalReferenceItem>( TimeSpan.FromMilliseconds(500), ReportReferencesAsync, asyncListener, cancellationToken); } // After all definitions/references have been found, wait here until all results have been reported. public override async ValueTask OnCompletedAsync(CancellationToken cancellationToken) => await _workQueue.WaitUntilCurrentBatchCompletesAsync().ConfigureAwait(false); public override async ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { using (await _semaphore.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (_definitionToId.ContainsKey(definition)) { return; } // Assigning a new id to the definition _id++; _definitionToId.Add(definition, _id); // Creating a new VSReferenceItem for the definition var definitionItem = await GenerateVSReferenceItemAsync( _id, definitionId: _id, _document, _position, definition.SourceSpans.FirstOrNull(), definition.DisplayableProperties, _metadataAsSourceFileService, definition.GetClassifiedText(), definition.Tags.GetFirstGlyph(), symbolUsageInfo: null, isWrittenTo: false, cancellationToken).ConfigureAwait(false); if (definitionItem != null) { // If a definition shouldn't be included in the results list if it doesn't have references, we // have to hold off on reporting it until later when we do find a reference. if (definition.DisplayIfNoReferences) { _workQueue.AddWork(definitionItem); } else { _definitionsWithoutReference.Add(definitionItem.Id, definitionItem); } } } } public override async ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken) { using (await _semaphore.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { // Each reference should be associated with a definition. If this somehow isn't the // case, we bail out early. if (!_definitionToId.TryGetValue(reference.Definition, out var definitionId)) return; var documentSpan = reference.SourceSpan; var document = documentSpan.Document; // If this is reference to the same physical location we've already reported, just // filter this out. it will clutter the UI to show the same places. if (!_referenceLocations.Add((document.FilePath, reference.SourceSpan.SourceSpan))) return; // If the definition hasn't been reported yet, add it to our list of references to report. if (_definitionsWithoutReference.TryGetValue(definitionId, out var definition)) { _workQueue.AddWork(definition); _definitionsWithoutReference.Remove(definitionId); } _id++; // Creating a new VSReferenceItem for the reference var referenceItem = await GenerateVSReferenceItemAsync( _id, definitionId, _document, _position, reference.SourceSpan, reference.AdditionalProperties, _metadataAsSourceFileService, definitionText: null, definitionGlyph: Glyph.None, reference.SymbolUsageInfo, reference.IsWrittenTo, cancellationToken).ConfigureAwait(false); if (referenceItem != null) { _workQueue.AddWork(referenceItem); } } } private static async Task<VSInternalReferenceItem?> GenerateVSReferenceItemAsync( int id, int? definitionId, Document document, int position, DocumentSpan? documentSpan, ImmutableDictionary<string, string> properties, IMetadataAsSourceFileService metadataAsSourceFileService, ClassifiedTextElement? definitionText, Glyph definitionGlyph, SymbolUsageInfo? symbolUsageInfo, bool isWrittenTo, CancellationToken cancellationToken) { var location = await ComputeLocationAsync(document, position, documentSpan, metadataAsSourceFileService, cancellationToken).ConfigureAwait(false); // Getting the text for the Text property. If we somehow can't compute the text, that means we're probably dealing with a metadata // reference, and those don't show up in the results list in Roslyn FAR anyway. var text = await ComputeTextAsync(id, definitionId, documentSpan, definitionText, isWrittenTo, cancellationToken).ConfigureAwait(false); if (text == null) { return null; } // TO-DO: The Origin property should be added once Rich-Nav is completed. // https://github.com/dotnet/roslyn/issues/42847 var result = new VSInternalReferenceItem { DefinitionId = definitionId, DefinitionText = definitionText, // Only definitions should have a non-null DefinitionText DefinitionIcon = definitionGlyph.GetImageElement(), DisplayPath = location?.Uri.LocalPath, Id = id, Kind = symbolUsageInfo.HasValue ? ProtocolConversions.SymbolUsageInfoToReferenceKinds(symbolUsageInfo.Value) : Array.Empty<VSInternalReferenceKind>(), ResolutionStatus = VSInternalResolutionStatusKind.ConfirmedAsReference, Text = text, }; // There are certain items that may not have locations, such as namespace definitions. if (location != null) { result.Location = location; } if (documentSpan != null) { result.DocumentName = documentSpan.Value.Document.Name; result.ProjectName = documentSpan.Value.Document.Project.Name; } if (properties.TryGetValue(AbstractReferenceFinder.ContainingMemberInfoPropertyName, out var referenceContainingMember)) result.ContainingMember = referenceContainingMember; if (properties.TryGetValue(AbstractReferenceFinder.ContainingTypeInfoPropertyName, out var referenceContainingType)) result.ContainingType = referenceContainingType; return result; // Local functions static async Task<LSP.Location?> ComputeLocationAsync( Document document, int position, DocumentSpan? documentSpan, IMetadataAsSourceFileService metadataAsSourceFileService, CancellationToken cancellationToken) { // If we have no document span, our location may be in metadata. if (documentSpan != null) { // We do have a document span, so compute location normally. return await ProtocolConversions.DocumentSpanToLocationAsync(documentSpan.Value, cancellationToken).ConfigureAwait(false); } // If we have no document span, our location may be in metadata or may be a namespace. var symbol = await SymbolFinder.FindSymbolAtPositionAsync(document, position, cancellationToken).ConfigureAwait(false); if (symbol == null || symbol.Locations.IsEmpty || symbol.Kind == SymbolKind.Namespace) { // Either: // (1) We couldn't find the location in metadata and it's not in any of our known documents. // (2) The symbol is a namespace (and therefore has no location). return null; } var declarationFile = await metadataAsSourceFileService.GetGeneratedFileAsync( document.Project, symbol, allowDecompilation: false, cancellationToken).ConfigureAwait(false); var linePosSpan = declarationFile.IdentifierLocation.GetLineSpan().Span; if (string.IsNullOrEmpty(declarationFile.FilePath)) { return null; } try { return new LSP.Location { Uri = ProtocolConversions.GetUriFromFilePath(declarationFile.FilePath), Range = ProtocolConversions.LinePositionToRange(linePosSpan), }; } catch (UriFormatException e) when (FatalError.ReportAndCatch(e)) { // We might reach this point if the file path is formatted incorrectly. return null; } } static async Task<ClassifiedTextElement?> ComputeTextAsync( int id, int? definitionId, DocumentSpan? documentSpan, ClassifiedTextElement? definitionText, bool isWrittenTo, CancellationToken cancellationToken) { // General case if (documentSpan != null) { var classifiedSpansAndHighlightSpan = await ClassifiedSpansAndHighlightSpanFactory.ClassifyAsync( documentSpan.Value, cancellationToken).ConfigureAwait(false); var classifiedSpans = classifiedSpansAndHighlightSpan.ClassifiedSpans; var docText = await documentSpan.Value.Document.GetTextAsync(cancellationToken).ConfigureAwait(false); var classifiedTextRuns = GetClassifiedTextRuns(id, definitionId, documentSpan.Value, isWrittenTo, classifiedSpans, docText); return new ClassifiedTextElement(classifiedTextRuns.ToArray()); } // Certain definitions may not have a DocumentSpan, such as namespace and metadata definitions else if (id == definitionId) { return definitionText; } return null; // Nested local functions static ClassifiedTextRun[] GetClassifiedTextRuns( int id, int? definitionId, DocumentSpan documentSpan, bool isWrittenTo, ImmutableArray<ClassifiedSpan> classifiedSpans, SourceText docText) { using var _ = ArrayBuilder<ClassifiedTextRun>.GetInstance(out var classifiedTextRuns); foreach (var span in classifiedSpans) { // Default case: Don't highlight. For example, if the user invokes FAR on 'x' in 'var x = 1', then 'var', // '=', and '1' should not be highlighted. string? markerTagType = null; // Case 1: Highlight this span of text. For example, if the user invokes FAR on 'x' in 'var x = 1', // then 'x' should be highlighted. if (span.TextSpan == documentSpan.SourceSpan) { // Case 1a: Highlight a definition if (id == definitionId) { markerTagType = DefinitionHighlightTag.TagId; } // Case 1b: Highlight a written reference else if (isWrittenTo) { markerTagType = WrittenReferenceHighlightTag.TagId; } // Case 1c: Highlight a read reference else { markerTagType = ReferenceHighlightTag.TagId; } } classifiedTextRuns.Add(new ClassifiedTextRun( span.ClassificationType, docText.ToString(span.TextSpan), ClassifiedTextRunStyle.Plain, markerTagType)); } return classifiedTextRuns.ToArray(); } } } private ValueTask ReportReferencesAsync(ImmutableArray<VSInternalReferenceItem> referencesToReport, CancellationToken cancellationToken) { // We can report outside of the lock here since _progress is thread-safe. _progress.Report(referencesToReport.ToArray()); return ValueTaskFactory.CompletedTask; } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Compilers/Core/Portable/Symbols/Attributes/CommonAttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public abstract class AttributeData { protected AttributeData() { } /// <summary> /// The attribute class. /// </summary> public INamedTypeSymbol? AttributeClass { get { return CommonAttributeClass; } } protected abstract INamedTypeSymbol? CommonAttributeClass { get; } /// <summary> /// The constructor on the attribute class. /// </summary> public IMethodSymbol? AttributeConstructor { get { return CommonAttributeConstructor; } } protected abstract IMethodSymbol? CommonAttributeConstructor { get; } public SyntaxReference? ApplicationSyntaxReference { get { return CommonApplicationSyntaxReference; } } protected abstract SyntaxReference? CommonApplicationSyntaxReference { get; } /// <summary> /// Constructor arguments on the attribute. /// </summary> public ImmutableArray<TypedConstant> ConstructorArguments { get { return CommonConstructorArguments; } } protected internal abstract ImmutableArray<TypedConstant> CommonConstructorArguments { get; } /// <summary> /// Named (property value) arguments on the attribute. /// </summary> public ImmutableArray<KeyValuePair<string, TypedConstant>> NamedArguments { get { return CommonNamedArguments; } } protected internal abstract ImmutableArray<KeyValuePair<string, TypedConstant>> CommonNamedArguments { get; } /// <summary> /// Attribute is conditionally omitted if it is a source attribute and both the following are true: /// (a) It has at least one applied conditional attribute AND /// (b) None of conditional symbols are true at the attribute source location. /// </summary> internal virtual bool IsConditionallyOmitted { get { return false; } } [MemberNotNullWhen(true, nameof(AttributeClass), nameof(AttributeConstructor))] internal virtual bool HasErrors { get { return false; } } /// <summary> /// Checks if an applied attribute with the given attributeType matches the namespace name and type name of the given early attribute's description /// and the attribute description has a signature with parameter count equal to the given attributeArgCount. /// NOTE: We don't allow early decoded attributes to have optional parameters. /// </summary> internal static bool IsTargetEarlyAttribute(INamedTypeSymbolInternal attributeType, int attributeArgCount, AttributeDescription description) { if (attributeType.ContainingSymbol?.Kind != SymbolKind.Namespace) { return false; } int attributeCtorsCount = description.Signatures.Length; for (int i = 0; i < attributeCtorsCount; i++) { int parameterCount = description.GetParameterCount(signatureIndex: i); // NOTE: Below assumption disallows early decoding well-known attributes with optional parameters. if (attributeArgCount == parameterCount) { StringComparison options = description.MatchIgnoringCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; return attributeType.Name.Equals(description.Name, options) && namespaceMatch(attributeType.ContainingNamespace, description.Namespace, options); } } return false; static bool namespaceMatch(INamespaceSymbolInternal container, string namespaceName, StringComparison options) { int index = namespaceName.Length; bool expectDot = false; while (true) { if (container.IsGlobalNamespace) { return index == 0; } if (expectDot) { index--; if (index < 0 || namespaceName[index] != '.') { return false; } } else { expectDot = true; } string name = container.Name; int nameLength = name.Length; index -= nameLength; if (index < 0 || string.Compare(namespaceName, index, name, 0, nameLength, options) != 0) { return false; } container = container.ContainingNamespace; if (container is null) { return false; } } } } /// <summary> /// Returns the value of a constructor argument as type <typeparamref name="T"/>. /// Throws if no constructor argument exists or the argument cannot be converted to the type. /// </summary> internal T? GetConstructorArgument<T>(int i, SpecialType specialType) { var constructorArgs = this.CommonConstructorArguments; return constructorArgs[i].DecodeValue<T>(specialType); } /// <summary> /// Returns named attribute argument with the given <paramref name="name"/> as type <typeparamref name="T"/>. /// If there is more than one named argument with this name, it returns the last one. /// If no named argument is found then the <paramref name="defaultValue"/> is returned. /// </summary> /// <param name="name">The metadata property or field name. This name is case sensitive (both VB and C#).</param> /// <param name="specialType">SpecialType of the named argument.</param> /// <param name="defaultValue">Default value for the named argument.</param> /// <remarks> /// For user defined attributes VB allows duplicate named arguments and uses the last value. /// Dev11 reports an error for pseudo-custom attributes when emitting metadata. We don't. /// </remarks> internal T? DecodeNamedArgument<T>(string name, SpecialType specialType, T? defaultValue = default) { return DecodeNamedArgument<T>(CommonNamedArguments, name, specialType, defaultValue); } private static T? DecodeNamedArgument<T>(ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments, string name, SpecialType specialType, T? defaultValue = default) { int index = IndexOfNamedArgument(namedArguments, name); return index >= 0 ? namedArguments[index].Value.DecodeValue<T>(specialType) : defaultValue; } private static int IndexOfNamedArgument(ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments, string name) { // For user defined attributes VB allows duplicate named arguments and uses the last value. // Dev11 reports an error for pseudo-custom attributes when emitting metadata. We don't. for (int i = namedArguments.Length - 1; i >= 0; i--) { // even for VB this is case sensitive comparison: if (string.Equals(namedArguments[i].Key, name, StringComparison.Ordinal)) { return i; } } return -1; } #region Decimal and DateTime Constant Decoding internal ConstantValue DecodeDecimalConstantValue() { // There are two decimal constant attribute ctors: // (byte scale, byte sign, uint high, uint mid, uint low) and // (byte scale, byte sign, int high, int mid, int low) // The dev10 compiler only honors the first; Roslyn honours both. // We should not end up in this code path unless we know we have one of them. Debug.Assert(AttributeConstructor is object); var parameters = AttributeConstructor.Parameters; ImmutableArray<TypedConstant> args = this.CommonConstructorArguments; Debug.Assert(parameters.Length == 5); Debug.Assert(parameters[0].Type.SpecialType == SpecialType.System_Byte); Debug.Assert(parameters[1].Type.SpecialType == SpecialType.System_Byte); int low, mid, high; byte scale = args[0].DecodeValue<byte>(SpecialType.System_Byte); bool isNegative = args[1].DecodeValue<byte>(SpecialType.System_Byte) != 0; if (parameters[2].Type.SpecialType == SpecialType.System_Int32) { Debug.Assert(parameters[2].Type.SpecialType == SpecialType.System_Int32); Debug.Assert(parameters[3].Type.SpecialType == SpecialType.System_Int32); Debug.Assert(parameters[4].Type.SpecialType == SpecialType.System_Int32); high = args[2].DecodeValue<int>(SpecialType.System_Int32); mid = args[3].DecodeValue<int>(SpecialType.System_Int32); low = args[4].DecodeValue<int>(SpecialType.System_Int32); } else { Debug.Assert(parameters[2].Type.SpecialType == SpecialType.System_UInt32); Debug.Assert(parameters[3].Type.SpecialType == SpecialType.System_UInt32); Debug.Assert(parameters[4].Type.SpecialType == SpecialType.System_UInt32); high = unchecked((int)args[2].DecodeValue<uint>(SpecialType.System_UInt32)); mid = unchecked((int)args[3].DecodeValue<uint>(SpecialType.System_UInt32)); low = unchecked((int)args[4].DecodeValue<uint>(SpecialType.System_UInt32)); } return ConstantValue.Create(new decimal(low, mid, high, isNegative, scale)); } internal ConstantValue DecodeDateTimeConstantValue() { long value = this.CommonConstructorArguments[0].DecodeValue<long>(SpecialType.System_Int64); // if value is outside this range, DateTime would throw when constructed if (value < DateTime.MinValue.Ticks || value > DateTime.MaxValue.Ticks) { return ConstantValue.Bad; } return ConstantValue.Create(new DateTime(value)); } #endregion internal ObsoleteAttributeData DecodeObsoleteAttribute(ObsoleteAttributeKind kind) { switch (kind) { case ObsoleteAttributeKind.Obsolete: return DecodeObsoleteAttribute(); case ObsoleteAttributeKind.Deprecated: return DecodeDeprecatedAttribute(); case ObsoleteAttributeKind.Experimental: return DecodeExperimentalAttribute(); default: throw ExceptionUtilities.UnexpectedValue(kind); } } /// <summary> /// Decode the arguments to ObsoleteAttribute. ObsoleteAttribute can have 0, 1 or 2 arguments. /// </summary> private ObsoleteAttributeData DecodeObsoleteAttribute() { ImmutableArray<TypedConstant> args = this.CommonConstructorArguments; // ObsoleteAttribute() string? message = null; bool isError = false; if (args.Length > 0) { // ObsoleteAttribute(string) // ObsoleteAttribute(string, bool) Debug.Assert(args.Length <= 2); message = (string?)args[0].ValueInternal; if (args.Length == 2) { Debug.Assert(args[1].ValueInternal is object); isError = (bool)args[1].ValueInternal!; } } string? diagnosticId = null; string? urlFormat = null; foreach (var (name, value) in this.CommonNamedArguments) { if (diagnosticId is null && name == ObsoleteAttributeData.DiagnosticIdPropertyName && IsStringProperty(ObsoleteAttributeData.DiagnosticIdPropertyName)) { diagnosticId = value.ValueInternal as string; } else if (urlFormat is null && name == ObsoleteAttributeData.UrlFormatPropertyName && IsStringProperty(ObsoleteAttributeData.UrlFormatPropertyName)) { urlFormat = value.ValueInternal as string; } if (diagnosticId is object && urlFormat is object) { break; } } return new ObsoleteAttributeData(ObsoleteAttributeKind.Obsolete, message, isError, diagnosticId, urlFormat); } // Note: it is disallowed to declare a property and a field // with the same name in C# or VB source, even if it is allowed in IL. // // We use a virtual method and override to prevent having to realize the public symbols just to decode obsolete attributes. // Ideally we would use an abstract method, but that would require making the method visible to // public consumers who inherit from this class, which we don't want to do. // Therefore we just make it a 'private protected virtual' method instead. private protected virtual bool IsStringProperty(string memberName) => throw ExceptionUtilities.Unreachable; /// <summary> /// Decode the arguments to DeprecatedAttribute. DeprecatedAttribute can have 3 or 4 arguments. /// </summary> private ObsoleteAttributeData DecodeDeprecatedAttribute() { var args = this.CommonConstructorArguments; // DeprecatedAttribute() string? message = null; bool isError = false; if (args.Length == 3 || args.Length == 4) { // DeprecatedAttribute(String, DeprecationType, UInt32) // DeprecatedAttribute(String, DeprecationType, UInt32, Platform) // DeprecatedAttribute(String, DeprecationType, UInt32, String) Debug.Assert(args[1].ValueInternal is object); message = (string?)args[0].ValueInternal; isError = ((int)args[1].ValueInternal! == 1); } return new ObsoleteAttributeData(ObsoleteAttributeKind.Deprecated, message, isError, diagnosticId: null, urlFormat: null); } /// <summary> /// Decode the arguments to ExperimentalAttribute. ExperimentalAttribute has 0 arguments. /// </summary> private ObsoleteAttributeData DecodeExperimentalAttribute() { // ExperimentalAttribute() Debug.Assert(this.CommonConstructorArguments.Length == 0); return ObsoleteAttributeData.Experimental; } internal static void DecodeMethodImplAttribute<T, TAttributeSyntaxNode, TAttributeData, TAttributeLocation>( ref DecodeWellKnownAttributeArguments<TAttributeSyntaxNode, TAttributeData, TAttributeLocation> arguments, CommonMessageProvider messageProvider) where T : CommonMethodWellKnownAttributeData, new() where TAttributeSyntaxNode : SyntaxNode where TAttributeData : AttributeData { Debug.Assert(arguments.AttributeSyntaxOpt is object); MethodImplOptions options; var attribute = arguments.Attribute; if (attribute.CommonConstructorArguments.Length == 1) { Debug.Assert(attribute.AttributeConstructor is object); if (attribute.AttributeConstructor.Parameters[0].Type.SpecialType == SpecialType.System_Int16) { options = (MethodImplOptions)attribute.CommonConstructorArguments[0].DecodeValue<short>(SpecialType.System_Int16); } else { options = attribute.CommonConstructorArguments[0].DecodeValue<MethodImplOptions>(SpecialType.System_Enum); } // low two bits should only be set via MethodCodeType property if (((int)options & 3) != 0) { messageProvider.ReportInvalidAttributeArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, attribute); options = options & ~(MethodImplOptions)3; } } else { options = default; } MethodImplAttributes codeType = MethodImplAttributes.IL; int position = 1; foreach (var namedArg in attribute.CommonNamedArguments) { if (namedArg.Key == "MethodCodeType") { var value = (MethodImplAttributes)namedArg.Value.DecodeValue<int>(SpecialType.System_Enum); if (value < 0 || value > MethodImplAttributes.Runtime) { Debug.Assert(attribute.AttributeClass is object); messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, attribute.AttributeClass, "MethodCodeType"); } else { codeType = value; } } position++; } arguments.GetOrCreateData<T>().SetMethodImplementation(arguments.Index, (MethodImplAttributes)options | codeType); } internal static void DecodeStructLayoutAttribute<TTypeWellKnownAttributeData, TAttributeSyntaxNode, TAttributeData, TAttributeLocation>( ref DecodeWellKnownAttributeArguments<TAttributeSyntaxNode, TAttributeData, TAttributeLocation> arguments, CharSet defaultCharSet, int defaultAutoLayoutSize, CommonMessageProvider messageProvider) where TTypeWellKnownAttributeData : CommonTypeWellKnownAttributeData, new() where TAttributeSyntaxNode : SyntaxNode where TAttributeData : AttributeData { Debug.Assert(arguments.AttributeSyntaxOpt is object); var attribute = arguments.Attribute; Debug.Assert(attribute.AttributeClass is object); CharSet charSet = (defaultCharSet != Cci.Constants.CharSet_None) ? defaultCharSet : CharSet.Ansi; int? size = null; int? alignment = null; bool hasErrors = false; LayoutKind kind = attribute.CommonConstructorArguments[0].DecodeValue<LayoutKind>(SpecialType.System_Enum); switch (kind) { case LayoutKind.Auto: case LayoutKind.Explicit: case LayoutKind.Sequential: break; default: messageProvider.ReportInvalidAttributeArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, attribute); hasErrors = true; break; } int position = 1; foreach (var namedArg in attribute.CommonNamedArguments) { switch (namedArg.Key) { case "CharSet": charSet = namedArg.Value.DecodeValue<CharSet>(SpecialType.System_Enum); switch (charSet) { case Cci.Constants.CharSet_None: charSet = CharSet.Ansi; break; case CharSet.Ansi: case Cci.Constants.CharSet_Auto: case CharSet.Unicode: break; default: messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, attribute.AttributeClass, namedArg.Key); hasErrors = true; break; } break; case "Pack": alignment = namedArg.Value.DecodeValue<int>(SpecialType.System_Int32); // only powers of 2 less or equal to 128 are allowed: if (alignment > 128 || (alignment & (alignment - 1)) != 0) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; case "Size": size = namedArg.Value.DecodeValue<int>(Microsoft.CodeAnalysis.SpecialType.System_Int32); if (size < 0) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; } position++; } if (!hasErrors) { if (kind == LayoutKind.Auto && size == null && alignment != null) { // If size is unspecified // C# emits size=0 // VB emits size=1 if the type is a struct, auto-layout and has alignment specified; 0 otherwise size = defaultAutoLayoutSize; } arguments.GetOrCreateData<TTypeWellKnownAttributeData>().SetStructLayout(new TypeLayout(kind, size ?? 0, (byte)(alignment ?? 0)), charSet); } } internal AttributeUsageInfo DecodeAttributeUsageAttribute() { return DecodeAttributeUsageAttribute(this.CommonConstructorArguments[0], this.CommonNamedArguments); } internal static AttributeUsageInfo DecodeAttributeUsageAttribute(TypedConstant positionalArg, ImmutableArray<KeyValuePair<string, TypedConstant>> namedArgs) { // BREAKING CHANGE (C#): // If the well known attribute class System.AttributeUsage is overridden in source, // we will use the overriding AttributeUsage type for attribute usage validation, // i.e. we try to find a constructor in that type with signature AttributeUsage(AttributeTargets) // and public bool properties Inherited and AllowMultiple. // If we are unable to find any of these, we use their default values. // // This behavior matches the approach chosen by native VB and Roslyn VB compilers, // but breaks compatibility with native C# compiler. // Native C# compiler preloads all the well known attribute types from mscorlib prior to binding, // hence it uses the AttributeUsage type defined in mscorlib for attribute usage validation. // // See Roslyn Bug 8603: ETA crashes with InvalidOperationException on duplicate attributes for details. Debug.Assert(positionalArg.ValueInternal is object); var validOn = (AttributeTargets)positionalArg.ValueInternal; bool allowMultiple = DecodeNamedArgument(namedArgs, "AllowMultiple", SpecialType.System_Boolean, false); bool inherited = DecodeNamedArgument(namedArgs, "Inherited", SpecialType.System_Boolean, true); return new AttributeUsageInfo(validOn, allowMultiple, inherited); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public abstract class AttributeData { protected AttributeData() { } /// <summary> /// The attribute class. /// </summary> public INamedTypeSymbol? AttributeClass { get { return CommonAttributeClass; } } protected abstract INamedTypeSymbol? CommonAttributeClass { get; } /// <summary> /// The constructor on the attribute class. /// </summary> public IMethodSymbol? AttributeConstructor { get { return CommonAttributeConstructor; } } protected abstract IMethodSymbol? CommonAttributeConstructor { get; } public SyntaxReference? ApplicationSyntaxReference { get { return CommonApplicationSyntaxReference; } } protected abstract SyntaxReference? CommonApplicationSyntaxReference { get; } /// <summary> /// Constructor arguments on the attribute. /// </summary> public ImmutableArray<TypedConstant> ConstructorArguments { get { return CommonConstructorArguments; } } protected internal abstract ImmutableArray<TypedConstant> CommonConstructorArguments { get; } /// <summary> /// Named (property value) arguments on the attribute. /// </summary> public ImmutableArray<KeyValuePair<string, TypedConstant>> NamedArguments { get { return CommonNamedArguments; } } protected internal abstract ImmutableArray<KeyValuePair<string, TypedConstant>> CommonNamedArguments { get; } /// <summary> /// Attribute is conditionally omitted if it is a source attribute and both the following are true: /// (a) It has at least one applied conditional attribute AND /// (b) None of conditional symbols are true at the attribute source location. /// </summary> internal virtual bool IsConditionallyOmitted { get { return false; } } [MemberNotNullWhen(true, nameof(AttributeClass), nameof(AttributeConstructor))] internal virtual bool HasErrors { get { return false; } } /// <summary> /// Checks if an applied attribute with the given attributeType matches the namespace name and type name of the given early attribute's description /// and the attribute description has a signature with parameter count equal to the given attributeArgCount. /// NOTE: We don't allow early decoded attributes to have optional parameters. /// </summary> internal static bool IsTargetEarlyAttribute(INamedTypeSymbolInternal attributeType, int attributeArgCount, AttributeDescription description) { if (attributeType.ContainingSymbol?.Kind != SymbolKind.Namespace) { return false; } int attributeCtorsCount = description.Signatures.Length; for (int i = 0; i < attributeCtorsCount; i++) { int parameterCount = description.GetParameterCount(signatureIndex: i); // NOTE: Below assumption disallows early decoding well-known attributes with optional parameters. if (attributeArgCount == parameterCount) { StringComparison options = description.MatchIgnoringCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; return attributeType.Name.Equals(description.Name, options) && namespaceMatch(attributeType.ContainingNamespace, description.Namespace, options); } } return false; static bool namespaceMatch(INamespaceSymbolInternal container, string namespaceName, StringComparison options) { int index = namespaceName.Length; bool expectDot = false; while (true) { if (container.IsGlobalNamespace) { return index == 0; } if (expectDot) { index--; if (index < 0 || namespaceName[index] != '.') { return false; } } else { expectDot = true; } string name = container.Name; int nameLength = name.Length; index -= nameLength; if (index < 0 || string.Compare(namespaceName, index, name, 0, nameLength, options) != 0) { return false; } container = container.ContainingNamespace; if (container is null) { return false; } } } } /// <summary> /// Returns the value of a constructor argument as type <typeparamref name="T"/>. /// Throws if no constructor argument exists or the argument cannot be converted to the type. /// </summary> internal T? GetConstructorArgument<T>(int i, SpecialType specialType) { var constructorArgs = this.CommonConstructorArguments; return constructorArgs[i].DecodeValue<T>(specialType); } /// <summary> /// Returns named attribute argument with the given <paramref name="name"/> as type <typeparamref name="T"/>. /// If there is more than one named argument with this name, it returns the last one. /// If no named argument is found then the <paramref name="defaultValue"/> is returned. /// </summary> /// <param name="name">The metadata property or field name. This name is case sensitive (both VB and C#).</param> /// <param name="specialType">SpecialType of the named argument.</param> /// <param name="defaultValue">Default value for the named argument.</param> /// <remarks> /// For user defined attributes VB allows duplicate named arguments and uses the last value. /// Dev11 reports an error for pseudo-custom attributes when emitting metadata. We don't. /// </remarks> internal T? DecodeNamedArgument<T>(string name, SpecialType specialType, T? defaultValue = default) { return DecodeNamedArgument<T>(CommonNamedArguments, name, specialType, defaultValue); } private static T? DecodeNamedArgument<T>(ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments, string name, SpecialType specialType, T? defaultValue = default) { int index = IndexOfNamedArgument(namedArguments, name); return index >= 0 ? namedArguments[index].Value.DecodeValue<T>(specialType) : defaultValue; } private static int IndexOfNamedArgument(ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments, string name) { // For user defined attributes VB allows duplicate named arguments and uses the last value. // Dev11 reports an error for pseudo-custom attributes when emitting metadata. We don't. for (int i = namedArguments.Length - 1; i >= 0; i--) { // even for VB this is case sensitive comparison: if (string.Equals(namedArguments[i].Key, name, StringComparison.Ordinal)) { return i; } } return -1; } #region Decimal and DateTime Constant Decoding internal ConstantValue DecodeDecimalConstantValue() { // There are two decimal constant attribute ctors: // (byte scale, byte sign, uint high, uint mid, uint low) and // (byte scale, byte sign, int high, int mid, int low) // The dev10 compiler only honors the first; Roslyn honours both. // We should not end up in this code path unless we know we have one of them. Debug.Assert(AttributeConstructor is object); var parameters = AttributeConstructor.Parameters; ImmutableArray<TypedConstant> args = this.CommonConstructorArguments; Debug.Assert(parameters.Length == 5); Debug.Assert(parameters[0].Type.SpecialType == SpecialType.System_Byte); Debug.Assert(parameters[1].Type.SpecialType == SpecialType.System_Byte); int low, mid, high; byte scale = args[0].DecodeValue<byte>(SpecialType.System_Byte); bool isNegative = args[1].DecodeValue<byte>(SpecialType.System_Byte) != 0; if (parameters[2].Type.SpecialType == SpecialType.System_Int32) { Debug.Assert(parameters[2].Type.SpecialType == SpecialType.System_Int32); Debug.Assert(parameters[3].Type.SpecialType == SpecialType.System_Int32); Debug.Assert(parameters[4].Type.SpecialType == SpecialType.System_Int32); high = args[2].DecodeValue<int>(SpecialType.System_Int32); mid = args[3].DecodeValue<int>(SpecialType.System_Int32); low = args[4].DecodeValue<int>(SpecialType.System_Int32); } else { Debug.Assert(parameters[2].Type.SpecialType == SpecialType.System_UInt32); Debug.Assert(parameters[3].Type.SpecialType == SpecialType.System_UInt32); Debug.Assert(parameters[4].Type.SpecialType == SpecialType.System_UInt32); high = unchecked((int)args[2].DecodeValue<uint>(SpecialType.System_UInt32)); mid = unchecked((int)args[3].DecodeValue<uint>(SpecialType.System_UInt32)); low = unchecked((int)args[4].DecodeValue<uint>(SpecialType.System_UInt32)); } return ConstantValue.Create(new decimal(low, mid, high, isNegative, scale)); } internal ConstantValue DecodeDateTimeConstantValue() { long value = this.CommonConstructorArguments[0].DecodeValue<long>(SpecialType.System_Int64); // if value is outside this range, DateTime would throw when constructed if (value < DateTime.MinValue.Ticks || value > DateTime.MaxValue.Ticks) { return ConstantValue.Bad; } return ConstantValue.Create(new DateTime(value)); } #endregion internal ObsoleteAttributeData DecodeObsoleteAttribute(ObsoleteAttributeKind kind) { switch (kind) { case ObsoleteAttributeKind.Obsolete: return DecodeObsoleteAttribute(); case ObsoleteAttributeKind.Deprecated: return DecodeDeprecatedAttribute(); case ObsoleteAttributeKind.Experimental: return DecodeExperimentalAttribute(); default: throw ExceptionUtilities.UnexpectedValue(kind); } } /// <summary> /// Decode the arguments to ObsoleteAttribute. ObsoleteAttribute can have 0, 1 or 2 arguments. /// </summary> private ObsoleteAttributeData DecodeObsoleteAttribute() { ImmutableArray<TypedConstant> args = this.CommonConstructorArguments; // ObsoleteAttribute() string? message = null; bool isError = false; if (args.Length > 0) { // ObsoleteAttribute(string) // ObsoleteAttribute(string, bool) Debug.Assert(args.Length <= 2); message = (string?)args[0].ValueInternal; if (args.Length == 2) { Debug.Assert(args[1].ValueInternal is object); isError = (bool)args[1].ValueInternal!; } } string? diagnosticId = null; string? urlFormat = null; foreach (var (name, value) in this.CommonNamedArguments) { if (diagnosticId is null && name == ObsoleteAttributeData.DiagnosticIdPropertyName && IsStringProperty(ObsoleteAttributeData.DiagnosticIdPropertyName)) { diagnosticId = value.ValueInternal as string; } else if (urlFormat is null && name == ObsoleteAttributeData.UrlFormatPropertyName && IsStringProperty(ObsoleteAttributeData.UrlFormatPropertyName)) { urlFormat = value.ValueInternal as string; } if (diagnosticId is object && urlFormat is object) { break; } } return new ObsoleteAttributeData(ObsoleteAttributeKind.Obsolete, message, isError, diagnosticId, urlFormat); } // Note: it is disallowed to declare a property and a field // with the same name in C# or VB source, even if it is allowed in IL. // // We use a virtual method and override to prevent having to realize the public symbols just to decode obsolete attributes. // Ideally we would use an abstract method, but that would require making the method visible to // public consumers who inherit from this class, which we don't want to do. // Therefore we just make it a 'private protected virtual' method instead. private protected virtual bool IsStringProperty(string memberName) => throw ExceptionUtilities.Unreachable; /// <summary> /// Decode the arguments to DeprecatedAttribute. DeprecatedAttribute can have 3 or 4 arguments. /// </summary> private ObsoleteAttributeData DecodeDeprecatedAttribute() { var args = this.CommonConstructorArguments; // DeprecatedAttribute() string? message = null; bool isError = false; if (args.Length == 3 || args.Length == 4) { // DeprecatedAttribute(String, DeprecationType, UInt32) // DeprecatedAttribute(String, DeprecationType, UInt32, Platform) // DeprecatedAttribute(String, DeprecationType, UInt32, String) Debug.Assert(args[1].ValueInternal is object); message = (string?)args[0].ValueInternal; isError = ((int)args[1].ValueInternal! == 1); } return new ObsoleteAttributeData(ObsoleteAttributeKind.Deprecated, message, isError, diagnosticId: null, urlFormat: null); } /// <summary> /// Decode the arguments to ExperimentalAttribute. ExperimentalAttribute has 0 arguments. /// </summary> private ObsoleteAttributeData DecodeExperimentalAttribute() { // ExperimentalAttribute() Debug.Assert(this.CommonConstructorArguments.Length == 0); return ObsoleteAttributeData.Experimental; } internal static void DecodeMethodImplAttribute<T, TAttributeSyntaxNode, TAttributeData, TAttributeLocation>( ref DecodeWellKnownAttributeArguments<TAttributeSyntaxNode, TAttributeData, TAttributeLocation> arguments, CommonMessageProvider messageProvider) where T : CommonMethodWellKnownAttributeData, new() where TAttributeSyntaxNode : SyntaxNode where TAttributeData : AttributeData { Debug.Assert(arguments.AttributeSyntaxOpt is object); MethodImplOptions options; var attribute = arguments.Attribute; if (attribute.CommonConstructorArguments.Length == 1) { Debug.Assert(attribute.AttributeConstructor is object); if (attribute.AttributeConstructor.Parameters[0].Type.SpecialType == SpecialType.System_Int16) { options = (MethodImplOptions)attribute.CommonConstructorArguments[0].DecodeValue<short>(SpecialType.System_Int16); } else { options = attribute.CommonConstructorArguments[0].DecodeValue<MethodImplOptions>(SpecialType.System_Enum); } // low two bits should only be set via MethodCodeType property if (((int)options & 3) != 0) { messageProvider.ReportInvalidAttributeArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, attribute); options = options & ~(MethodImplOptions)3; } } else { options = default; } MethodImplAttributes codeType = MethodImplAttributes.IL; int position = 1; foreach (var namedArg in attribute.CommonNamedArguments) { if (namedArg.Key == "MethodCodeType") { var value = (MethodImplAttributes)namedArg.Value.DecodeValue<int>(SpecialType.System_Enum); if (value < 0 || value > MethodImplAttributes.Runtime) { Debug.Assert(attribute.AttributeClass is object); messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, attribute.AttributeClass, "MethodCodeType"); } else { codeType = value; } } position++; } arguments.GetOrCreateData<T>().SetMethodImplementation(arguments.Index, (MethodImplAttributes)options | codeType); } internal static void DecodeStructLayoutAttribute<TTypeWellKnownAttributeData, TAttributeSyntaxNode, TAttributeData, TAttributeLocation>( ref DecodeWellKnownAttributeArguments<TAttributeSyntaxNode, TAttributeData, TAttributeLocation> arguments, CharSet defaultCharSet, int defaultAutoLayoutSize, CommonMessageProvider messageProvider) where TTypeWellKnownAttributeData : CommonTypeWellKnownAttributeData, new() where TAttributeSyntaxNode : SyntaxNode where TAttributeData : AttributeData { Debug.Assert(arguments.AttributeSyntaxOpt is object); var attribute = arguments.Attribute; Debug.Assert(attribute.AttributeClass is object); CharSet charSet = (defaultCharSet != Cci.Constants.CharSet_None) ? defaultCharSet : CharSet.Ansi; int? size = null; int? alignment = null; bool hasErrors = false; LayoutKind kind = attribute.CommonConstructorArguments[0].DecodeValue<LayoutKind>(SpecialType.System_Enum); switch (kind) { case LayoutKind.Auto: case LayoutKind.Explicit: case LayoutKind.Sequential: break; default: messageProvider.ReportInvalidAttributeArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, attribute); hasErrors = true; break; } int position = 1; foreach (var namedArg in attribute.CommonNamedArguments) { switch (namedArg.Key) { case "CharSet": charSet = namedArg.Value.DecodeValue<CharSet>(SpecialType.System_Enum); switch (charSet) { case Cci.Constants.CharSet_None: charSet = CharSet.Ansi; break; case CharSet.Ansi: case Cci.Constants.CharSet_Auto: case CharSet.Unicode: break; default: messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, attribute.AttributeClass, namedArg.Key); hasErrors = true; break; } break; case "Pack": alignment = namedArg.Value.DecodeValue<int>(SpecialType.System_Int32); // only powers of 2 less or equal to 128 are allowed: if (alignment > 128 || (alignment & (alignment - 1)) != 0) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; case "Size": size = namedArg.Value.DecodeValue<int>(Microsoft.CodeAnalysis.SpecialType.System_Int32); if (size < 0) { messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, attribute.AttributeClass, namedArg.Key); hasErrors = true; } break; } position++; } if (!hasErrors) { if (kind == LayoutKind.Auto && size == null && alignment != null) { // If size is unspecified // C# emits size=0 // VB emits size=1 if the type is a struct, auto-layout and has alignment specified; 0 otherwise size = defaultAutoLayoutSize; } arguments.GetOrCreateData<TTypeWellKnownAttributeData>().SetStructLayout(new TypeLayout(kind, size ?? 0, (byte)(alignment ?? 0)), charSet); } } internal AttributeUsageInfo DecodeAttributeUsageAttribute() { return DecodeAttributeUsageAttribute(this.CommonConstructorArguments[0], this.CommonNamedArguments); } internal static AttributeUsageInfo DecodeAttributeUsageAttribute(TypedConstant positionalArg, ImmutableArray<KeyValuePair<string, TypedConstant>> namedArgs) { // BREAKING CHANGE (C#): // If the well known attribute class System.AttributeUsage is overridden in source, // we will use the overriding AttributeUsage type for attribute usage validation, // i.e. we try to find a constructor in that type with signature AttributeUsage(AttributeTargets) // and public bool properties Inherited and AllowMultiple. // If we are unable to find any of these, we use their default values. // // This behavior matches the approach chosen by native VB and Roslyn VB compilers, // but breaks compatibility with native C# compiler. // Native C# compiler preloads all the well known attribute types from mscorlib prior to binding, // hence it uses the AttributeUsage type defined in mscorlib for attribute usage validation. // // See Roslyn Bug 8603: ETA crashes with InvalidOperationException on duplicate attributes for details. Debug.Assert(positionalArg.ValueInternal is object); var validOn = (AttributeTargets)positionalArg.ValueInternal; bool allowMultiple = DecodeNamedArgument(namedArgs, "AllowMultiple", SpecialType.System_Boolean, false); bool inherited = DecodeNamedArgument(namedArgs, "Inherited", SpecialType.System_Boolean, true); return new AttributeUsageInfo(validOn, allowMultiple, inherited); } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Compilers/Core/Portable/CodeGen/MetadataNamedArgument.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Cci = Microsoft.Cci; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// An expression that represents a (name, value) pair and that is typically used in method calls, custom attributes and object initializers. /// </summary> internal sealed class MetadataNamedArgument : Cci.IMetadataNamedArgument { private readonly ISymbolInternal _entity; private readonly Cci.ITypeReference _type; private readonly Cci.IMetadataExpression _value; public MetadataNamedArgument(ISymbolInternal entity, Cci.ITypeReference type, Cci.IMetadataExpression value) { // entity must be one of INamedEntity or IFieldDefinition or IPropertyDefinition _entity = entity; _type = type; _value = value; } /// <summary> /// The name of the parameter or property or field that corresponds to the argument. /// </summary> string Cci.IMetadataNamedArgument.ArgumentName => _entity.Name; /// <summary> /// The value of the argument. /// </summary> Cci.IMetadataExpression Cci.IMetadataNamedArgument.ArgumentValue => _value; /// <summary> /// True if the named argument provides the value of a field. /// </summary> bool Cci.IMetadataNamedArgument.IsField => _entity.Kind == SymbolKind.Field; void Cci.IMetadataExpression.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit(this); } Cci.ITypeReference Cci.IMetadataExpression.Type => _type; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Cci = Microsoft.Cci; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// An expression that represents a (name, value) pair and that is typically used in method calls, custom attributes and object initializers. /// </summary> internal sealed class MetadataNamedArgument : Cci.IMetadataNamedArgument { private readonly ISymbolInternal _entity; private readonly Cci.ITypeReference _type; private readonly Cci.IMetadataExpression _value; public MetadataNamedArgument(ISymbolInternal entity, Cci.ITypeReference type, Cci.IMetadataExpression value) { // entity must be one of INamedEntity or IFieldDefinition or IPropertyDefinition _entity = entity; _type = type; _value = value; } /// <summary> /// The name of the parameter or property or field that corresponds to the argument. /// </summary> string Cci.IMetadataNamedArgument.ArgumentName => _entity.Name; /// <summary> /// The value of the argument. /// </summary> Cci.IMetadataExpression Cci.IMetadataNamedArgument.ArgumentValue => _value; /// <summary> /// True if the named argument provides the value of a field. /// </summary> bool Cci.IMetadataNamedArgument.IsField => _entity.Kind == SymbolKind.Field; void Cci.IMetadataExpression.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit(this); } Cci.ITypeReference Cci.IMetadataExpression.Type => _type; } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Dependencies/Collections/ImmutableSegmentedDictionary`2+Enumerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Collections { internal readonly partial struct ImmutableSegmentedDictionary<TKey, TValue> { public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private readonly SegmentedDictionary<TKey, TValue> _dictionary; private readonly ReturnType _returnType; private SegmentedDictionary<TKey, TValue>.Enumerator _enumerator; internal Enumerator(SegmentedDictionary<TKey, TValue> dictionary, ReturnType returnType) { _dictionary = dictionary; _returnType = returnType; _enumerator = dictionary.GetEnumerator(); } internal enum ReturnType { /// <summary> /// The return value from the implementation of <see cref="IEnumerable.GetEnumerator"/> is /// <see cref="KeyValuePair{TKey, TValue}"/>. This is the return value for most instances of this /// enumerator. /// </summary> KeyValuePair, /// <summary> /// The return value from the implementation of <see cref="IEnumerable.GetEnumerator"/> is /// <see cref="System.Collections.DictionaryEntry"/>. This is the return value for instances of this /// enumerator created by the <see cref="IDictionary.GetEnumerator"/> implementation in /// <see cref="ImmutableSegmentedDictionary{TKey, TValue}"/>. /// </summary> DictionaryEntry, } public KeyValuePair<TKey, TValue> Current => _enumerator.Current; object IEnumerator.Current => _returnType == ReturnType.DictionaryEntry ? (object)((IDictionaryEnumerator)this).Entry : Current; DictionaryEntry IDictionaryEnumerator.Entry => new(Current.Key, Current.Value); object IDictionaryEnumerator.Key => Current.Key; object? IDictionaryEnumerator.Value => Current.Value; public void Dispose() => _enumerator.Dispose(); public bool MoveNext() => _enumerator.MoveNext(); public void Reset() { _enumerator = _dictionary.GetEnumerator(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Collections { internal readonly partial struct ImmutableSegmentedDictionary<TKey, TValue> { public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private readonly SegmentedDictionary<TKey, TValue> _dictionary; private readonly ReturnType _returnType; private SegmentedDictionary<TKey, TValue>.Enumerator _enumerator; internal Enumerator(SegmentedDictionary<TKey, TValue> dictionary, ReturnType returnType) { _dictionary = dictionary; _returnType = returnType; _enumerator = dictionary.GetEnumerator(); } internal enum ReturnType { /// <summary> /// The return value from the implementation of <see cref="IEnumerable.GetEnumerator"/> is /// <see cref="KeyValuePair{TKey, TValue}"/>. This is the return value for most instances of this /// enumerator. /// </summary> KeyValuePair, /// <summary> /// The return value from the implementation of <see cref="IEnumerable.GetEnumerator"/> is /// <see cref="System.Collections.DictionaryEntry"/>. This is the return value for instances of this /// enumerator created by the <see cref="IDictionary.GetEnumerator"/> implementation in /// <see cref="ImmutableSegmentedDictionary{TKey, TValue}"/>. /// </summary> DictionaryEntry, } public KeyValuePair<TKey, TValue> Current => _enumerator.Current; object IEnumerator.Current => _returnType == ReturnType.DictionaryEntry ? (object)((IDictionaryEnumerator)this).Entry : Current; DictionaryEntry IDictionaryEnumerator.Entry => new(Current.Key, Current.Value); object IDictionaryEnumerator.Key => Current.Key; object? IDictionaryEnumerator.Value => Current.Value; public void Dispose() => _enumerator.Dispose(); public bool MoveNext() => _enumerator.MoveNext(); public void Reset() { _enumerator = _dictionary.GetEnumerator(); } } } }
-1
dotnet/roslyn
55,910
Freeze semantics for all branches when asked
We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
jasonmalinowski
2021-08-26T01:30:34Z
2021-08-28T02:11:31Z
4b957187b2fda9545981021533ea01bff3f03062
53ba85783fa120bf13cc95ab765369639540d9af
Freeze semantics for all branches when asked. We had logic in Document.WithFrozenPartialSemantics which meant we would only freeze semantics if the Soluion in question was the "primary" branch, that is the actual instance from some Workspace.CurrentSolution. This seems terribly unwise: features like completion call GetOpenDocumentInCurrentContextWithChanges when doing things like computing entries or committing; if the text snapshots were out of sync then that would always be forking. In that case Freeze did nothing at all -- it would return the original Solution instance, so asking for semantics would build the full compilation like before. This is even worse with source generators, since we weren't freezing the generator state either and would rerun generators when later asked. The comment before the code to me isn't really explaining why this behavior is desirable: it's correct that if you have a forked Solution there is no background compiler pulling it forward. But it'll still have the state that was computed when it was forked, which should be enough for anybody opting into partial semantics in the first place. While writing a test, I also discovered our existing tests around frozen partial semantics and generators weren't actually testing anything, since the workspace didn't have partial semantics on in the first place. Worse off, they still didn't work unless we also remove the BranchId check.
./src/Analyzers/Core/Analyzers/UseCollectionInitializer/ObjectCreationExpressionAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.UseCollectionInitializer { internal class ObjectCreationExpressionAnalyzer< TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TInvocationExpressionSyntax, TExpressionStatementSyntax, TVariableDeclaratorSyntax> : AbstractObjectCreationExpressionAnalyzer< TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TVariableDeclaratorSyntax, TExpressionStatementSyntax> where TExpressionSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TObjectCreationExpressionSyntax : TExpressionSyntax where TMemberAccessExpressionSyntax : TExpressionSyntax where TInvocationExpressionSyntax : TExpressionSyntax where TExpressionStatementSyntax : TStatementSyntax where TVariableDeclaratorSyntax : SyntaxNode { private static readonly ObjectPool<ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TInvocationExpressionSyntax, TExpressionStatementSyntax, TVariableDeclaratorSyntax>> s_pool = SharedPools.Default<ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TInvocationExpressionSyntax, TExpressionStatementSyntax, TVariableDeclaratorSyntax>>(); public static ImmutableArray<TExpressionStatementSyntax>? Analyze( SemanticModel semanticModel, ISyntaxFacts syntaxFacts, TObjectCreationExpressionSyntax objectCreationExpression, CancellationToken cancellationToken) { var analyzer = s_pool.Allocate(); analyzer.Initialize(semanticModel, syntaxFacts, objectCreationExpression, cancellationToken); try { return analyzer.AnalyzeWorker(); } finally { analyzer.Clear(); s_pool.Free(analyzer); } } protected override void AddMatches(ArrayBuilder<TExpressionStatementSyntax> matches) { var containingBlock = _containingStatement.Parent; var foundStatement = false; var seenInvocation = false; var seenIndexAssignment = false; foreach (var child in containingBlock.ChildNodesAndTokens()) { if (!foundStatement) { if (child == _containingStatement) { foundStatement = true; } continue; } if (child.IsToken) { return; } if (child.AsNode() is not TExpressionStatementSyntax statement) { return; } SyntaxNode instance = null; if (!seenIndexAssignment) { if (TryAnalyzeAddInvocation(statement, out instance)) { seenInvocation = true; } } if (!seenInvocation) { if (TryAnalyzeIndexAssignment(statement, out instance)) { seenIndexAssignment = true; } } if (instance == null) { return; } if (!ValuePatternMatches((TExpressionSyntax)instance)) { return; } matches.Add(statement); } } protected override bool ShouldAnalyze() { var type = _semanticModel.GetTypeInfo(_objectCreationExpression, _cancellationToken).Type; if (type == null) { return false; } var addMethods = _semanticModel.LookupSymbols( _objectCreationExpression.SpanStart, container: type, name: WellKnownMemberNames.CollectionInitializerAddMethodName, includeReducedExtensionMethods: true); return addMethods.Any(m => m is IMethodSymbol methodSymbol && methodSymbol.Parameters.Any()); } private bool TryAnalyzeIndexAssignment( TExpressionStatementSyntax statement, out SyntaxNode instance) { instance = null; if (!_syntaxFacts.SupportsIndexingInitializer(statement.SyntaxTree.Options)) { return false; } if (!_syntaxFacts.IsSimpleAssignmentStatement(statement)) { return false; } _syntaxFacts.GetPartsOfAssignmentStatement(statement, out var left, out var right); if (!_syntaxFacts.IsElementAccessExpression(left)) { return false; } // If we're initializing a variable, then we can't reference that variable on the right // side of the initialization. Rewriting this into a collection initializer would lead // to a definite-assignment error. if (ExpressionContainsValuePatternOrReferencesInitializedSymbol(right)) { return false; } instance = _syntaxFacts.GetExpressionOfElementAccessExpression(left); return true; } private bool TryAnalyzeAddInvocation( TExpressionStatementSyntax statement, out SyntaxNode instance) { instance = null; if (_syntaxFacts.GetExpressionOfExpressionStatement(statement) is not TInvocationExpressionSyntax invocationExpression) { return false; } var arguments = _syntaxFacts.GetArgumentsOfInvocationExpression(invocationExpression); if (arguments.Count < 1) { return false; } foreach (var argument in arguments) { if (!_syntaxFacts.IsSimpleArgument(argument)) { return false; } var argumentExpression = _syntaxFacts.GetExpressionOfArgument(argument); if (ExpressionContainsValuePatternOrReferencesInitializedSymbol(argumentExpression)) { return false; } } if (_syntaxFacts.GetExpressionOfInvocationExpression(invocationExpression) is not TMemberAccessExpressionSyntax memberAccess) { return false; } if (!_syntaxFacts.IsSimpleMemberAccessExpression(memberAccess)) { return false; } _syntaxFacts.GetPartsOfMemberAccessExpression(memberAccess, out var localInstance, out var memberName); _syntaxFacts.GetNameAndArityOfSimpleName(memberName, out var name, out var arity); if (arity != 0 || !name.Equals(WellKnownMemberNames.CollectionInitializerAddMethodName)) { return false; } instance = localInstance; return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.UseCollectionInitializer { internal class ObjectCreationExpressionAnalyzer< TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TInvocationExpressionSyntax, TExpressionStatementSyntax, TVariableDeclaratorSyntax> : AbstractObjectCreationExpressionAnalyzer< TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TVariableDeclaratorSyntax, TExpressionStatementSyntax> where TExpressionSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TObjectCreationExpressionSyntax : TExpressionSyntax where TMemberAccessExpressionSyntax : TExpressionSyntax where TInvocationExpressionSyntax : TExpressionSyntax where TExpressionStatementSyntax : TStatementSyntax where TVariableDeclaratorSyntax : SyntaxNode { private static readonly ObjectPool<ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TInvocationExpressionSyntax, TExpressionStatementSyntax, TVariableDeclaratorSyntax>> s_pool = SharedPools.Default<ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TInvocationExpressionSyntax, TExpressionStatementSyntax, TVariableDeclaratorSyntax>>(); public static ImmutableArray<TExpressionStatementSyntax>? Analyze( SemanticModel semanticModel, ISyntaxFacts syntaxFacts, TObjectCreationExpressionSyntax objectCreationExpression, CancellationToken cancellationToken) { var analyzer = s_pool.Allocate(); analyzer.Initialize(semanticModel, syntaxFacts, objectCreationExpression, cancellationToken); try { return analyzer.AnalyzeWorker(); } finally { analyzer.Clear(); s_pool.Free(analyzer); } } protected override void AddMatches(ArrayBuilder<TExpressionStatementSyntax> matches) { var containingBlock = _containingStatement.Parent; var foundStatement = false; var seenInvocation = false; var seenIndexAssignment = false; foreach (var child in containingBlock.ChildNodesAndTokens()) { if (!foundStatement) { if (child == _containingStatement) { foundStatement = true; } continue; } if (child.IsToken) { return; } if (child.AsNode() is not TExpressionStatementSyntax statement) { return; } SyntaxNode instance = null; if (!seenIndexAssignment) { if (TryAnalyzeAddInvocation(statement, out instance)) { seenInvocation = true; } } if (!seenInvocation) { if (TryAnalyzeIndexAssignment(statement, out instance)) { seenIndexAssignment = true; } } if (instance == null) { return; } if (!ValuePatternMatches((TExpressionSyntax)instance)) { return; } matches.Add(statement); } } protected override bool ShouldAnalyze() { var type = _semanticModel.GetTypeInfo(_objectCreationExpression, _cancellationToken).Type; if (type == null) { return false; } var addMethods = _semanticModel.LookupSymbols( _objectCreationExpression.SpanStart, container: type, name: WellKnownMemberNames.CollectionInitializerAddMethodName, includeReducedExtensionMethods: true); return addMethods.Any(m => m is IMethodSymbol methodSymbol && methodSymbol.Parameters.Any()); } private bool TryAnalyzeIndexAssignment( TExpressionStatementSyntax statement, out SyntaxNode instance) { instance = null; if (!_syntaxFacts.SupportsIndexingInitializer(statement.SyntaxTree.Options)) { return false; } if (!_syntaxFacts.IsSimpleAssignmentStatement(statement)) { return false; } _syntaxFacts.GetPartsOfAssignmentStatement(statement, out var left, out var right); if (!_syntaxFacts.IsElementAccessExpression(left)) { return false; } // If we're initializing a variable, then we can't reference that variable on the right // side of the initialization. Rewriting this into a collection initializer would lead // to a definite-assignment error. if (ExpressionContainsValuePatternOrReferencesInitializedSymbol(right)) { return false; } instance = _syntaxFacts.GetExpressionOfElementAccessExpression(left); return true; } private bool TryAnalyzeAddInvocation( TExpressionStatementSyntax statement, out SyntaxNode instance) { instance = null; if (_syntaxFacts.GetExpressionOfExpressionStatement(statement) is not TInvocationExpressionSyntax invocationExpression) { return false; } var arguments = _syntaxFacts.GetArgumentsOfInvocationExpression(invocationExpression); if (arguments.Count < 1) { return false; } foreach (var argument in arguments) { if (!_syntaxFacts.IsSimpleArgument(argument)) { return false; } var argumentExpression = _syntaxFacts.GetExpressionOfArgument(argument); if (ExpressionContainsValuePatternOrReferencesInitializedSymbol(argumentExpression)) { return false; } } if (_syntaxFacts.GetExpressionOfInvocationExpression(invocationExpression) is not TMemberAccessExpressionSyntax memberAccess) { return false; } if (!_syntaxFacts.IsSimpleMemberAccessExpression(memberAccess)) { return false; } _syntaxFacts.GetPartsOfMemberAccessExpression(memberAccess, out var localInstance, out var memberName); _syntaxFacts.GetNameAndArityOfSimpleName(memberName, out var name, out var arity); if (arity != 0 || !name.Equals(WellKnownMemberNames.CollectionInitializerAddMethodName)) { return false; } instance = localInstance; return true; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Portable/SourceGeneration/CSharpGeneratorDriver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using System.Linq; using System.ComponentModel; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A <see cref="GeneratorDriver"/> implementation for the CSharp language. /// </summary> public sealed class CSharpGeneratorDriver : GeneratorDriver { /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> /// </summary> /// <param name="parseOptions">The <see cref="CSharpParseOptions"/> that should be used when parsing generated files.</param> /// <param name="generators">The generators that will run as part of this driver.</param> /// <param name="optionsProvider">An <see cref="AnalyzerConfigOptionsProvider"/> that can be used to retrieve analyzer config values by the generators in this driver.</param> /// <param name="additionalTexts">A list of <see cref="AdditionalText"/>s available to generators in this driver.</param> internal CSharpGeneratorDriver(CSharpParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, GeneratorDriverOptions driverOptions) : base(parseOptions, generators, optionsProvider, additionalTexts, driverOptions) { } private CSharpGeneratorDriver(GeneratorDriverState state) : base(state) { } /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and default options /// </summary> /// <param name="generators">The generators to create this driver with</param> /// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns> public static CSharpGeneratorDriver Create(params ISourceGenerator[] generators) => Create(generators, additionalTexts: null); /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="IIncrementalGenerator"/>s and default options /// </summary> /// <param name="incrementalGenerators">The incremental generators to create this driver with</param> /// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns> public static CSharpGeneratorDriver Create(params IIncrementalGenerator[] incrementalGenerators) => Create(incrementalGenerators.Select(GeneratorExtensions.AsSourceGenerator), additionalTexts: null); /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and the provided options or default. /// </summary> /// <param name="generators">The generators to create this driver with</param> /// <param name="additionalTexts">A list of <see cref="AdditionalText"/>s available to generators in this driver, or <c>null</c> if there are none.</param> /// <param name="parseOptions">The <see cref="CSharpParseOptions"/> that should be used when parsing generated files, or <c>null</c> to use <see cref="CSharpParseOptions.Default"/></param> /// <param name="optionsProvider">An <see cref="AnalyzerConfigOptionsProvider"/> that can be used to retrieve analyzer config values by the generators in this driver, or <c>null</c> if there are none.</param> /// <param name="driverOptions">A <see cref="GeneratorDriverOptions"/> that controls the behavior of the created driver.</param> /// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns> public static CSharpGeneratorDriver Create(IEnumerable<ISourceGenerator> generators, IEnumerable<AdditionalText>? additionalTexts = null, CSharpParseOptions? parseOptions = null, AnalyzerConfigOptionsProvider? optionsProvider = null, GeneratorDriverOptions driverOptions = default) => new CSharpGeneratorDriver(parseOptions ?? CSharpParseOptions.Default, generators.ToImmutableArray(), optionsProvider ?? CompilerAnalyzerConfigOptionsProvider.Empty, additionalTexts.AsImmutableOrEmpty(), driverOptions); // 3.11 BACKCOMPAT OVERLOAD -- DO NOT TOUCH [EditorBrowsable(EditorBrowsableState.Never)] public static CSharpGeneratorDriver Create(IEnumerable<ISourceGenerator> generators, IEnumerable<AdditionalText>? additionalTexts, CSharpParseOptions? parseOptions, AnalyzerConfigOptionsProvider? optionsProvider) => Create(generators, additionalTexts, parseOptions, optionsProvider, driverOptions: default); internal override SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken) => CSharpSyntaxTree.ParseTextLazy(input.Text, (CSharpParseOptions)_state.ParseOptions, fileName); internal override GeneratorDriver FromState(GeneratorDriverState state) => new CSharpGeneratorDriver(state); internal override CommonMessageProvider MessageProvider => CSharp.MessageProvider.Instance; internal override AdditionalSourcesCollection CreateSourcesCollection() => new AdditionalSourcesCollection(".cs"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using System.Linq; using System.ComponentModel; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A <see cref="GeneratorDriver"/> implementation for the CSharp language. /// </summary> public sealed class CSharpGeneratorDriver : GeneratorDriver { /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> /// </summary> /// <param name="parseOptions">The <see cref="CSharpParseOptions"/> that should be used when parsing generated files.</param> /// <param name="generators">The generators that will run as part of this driver.</param> /// <param name="optionsProvider">An <see cref="AnalyzerConfigOptionsProvider"/> that can be used to retrieve analyzer config values by the generators in this driver.</param> /// <param name="additionalTexts">A list of <see cref="AdditionalText"/>s available to generators in this driver.</param> internal CSharpGeneratorDriver(CSharpParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, GeneratorDriverOptions driverOptions) : base(parseOptions, generators, optionsProvider, additionalTexts, driverOptions) { } private CSharpGeneratorDriver(GeneratorDriverState state) : base(state) { } /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and default options /// </summary> /// <param name="generators">The generators to create this driver with</param> /// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns> public static CSharpGeneratorDriver Create(params ISourceGenerator[] generators) => Create(generators, additionalTexts: null); /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="IIncrementalGenerator"/>s and default options /// </summary> /// <param name="incrementalGenerators">The incremental generators to create this driver with</param> /// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns> public static CSharpGeneratorDriver Create(params IIncrementalGenerator[] incrementalGenerators) => Create(incrementalGenerators.Select(GeneratorExtensions.AsSourceGenerator), additionalTexts: null); /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and the provided options or default. /// </summary> /// <param name="generators">The generators to create this driver with</param> /// <param name="additionalTexts">A list of <see cref="AdditionalText"/>s available to generators in this driver, or <c>null</c> if there are none.</param> /// <param name="parseOptions">The <see cref="CSharpParseOptions"/> that should be used when parsing generated files, or <c>null</c> to use <see cref="CSharpParseOptions.Default"/></param> /// <param name="optionsProvider">An <see cref="AnalyzerConfigOptionsProvider"/> that can be used to retrieve analyzer config values by the generators in this driver, or <c>null</c> if there are none.</param> /// <param name="driverOptions">A <see cref="GeneratorDriverOptions"/> that controls the behavior of the created driver.</param> /// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns> public static CSharpGeneratorDriver Create(IEnumerable<ISourceGenerator> generators, IEnumerable<AdditionalText>? additionalTexts = null, CSharpParseOptions? parseOptions = null, AnalyzerConfigOptionsProvider? optionsProvider = null, GeneratorDriverOptions driverOptions = default) => new CSharpGeneratorDriver(parseOptions ?? CSharpParseOptions.Default, generators.ToImmutableArray(), optionsProvider ?? CompilerAnalyzerConfigOptionsProvider.Empty, additionalTexts.AsImmutableOrEmpty(), driverOptions); // 3.11 BACKCOMPAT OVERLOAD -- DO NOT TOUCH [EditorBrowsable(EditorBrowsableState.Never)] public static CSharpGeneratorDriver Create(IEnumerable<ISourceGenerator> generators, IEnumerable<AdditionalText>? additionalTexts, CSharpParseOptions? parseOptions, AnalyzerConfigOptionsProvider? optionsProvider) => Create(generators, additionalTexts, parseOptions, optionsProvider, driverOptions: default); internal override SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken) => CSharpSyntaxTree.ParseTextLazy(input.Text, (CSharpParseOptions)_state.ParseOptions, fileName); internal override GeneratorDriver FromState(GeneratorDriverState state) => new CSharpGeneratorDriver(state); internal override CommonMessageProvider MessageProvider => CSharp.MessageProvider.Instance; internal override string SourceExtension => ".cs"; } }
1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Test/Semantic/SourceGeneration/AdditionalSourcesCollectionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class AdditionalSourcesCollectionTests : CSharpTestBase { [Theory] [InlineData("abc")] // abc.cs [InlineData("abc.cs")] //abc.cs [InlineData("abc.vb")] // abc.vb.cs [InlineData("abc.generated.cs")] [InlineData("abc_-_")] [InlineData("abc - generated.cs")] [InlineData("abc\u0064.cs")] //acbd.cs [InlineData("abc(1).cs")] [InlineData("abc[1].cs")] [InlineData("abc{1}.cs")] public void HintName_ValidValues(string hintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8)); Assert.True(asc.Contains(hintName)); var sources = asc.ToImmutableAndFree(); Assert.Single(sources); Assert.True(sources[0].HintName.EndsWith(".cs")); } [Theory] [InlineData("abc")] // abc.vb [InlineData("abc.cs")] //abc.cs.vb [InlineData("abc.vb")] // abc.vb public void HintName_WithExtension(string hintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".vb"); asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8)); Assert.True(asc.Contains(hintName)); var sources = asc.ToImmutableAndFree(); Assert.Single(sources); Assert.True(sources[0].HintName.EndsWith(".vb")); } [Theory] [InlineData("/abc/def.cs")] [InlineData("\\")] [InlineData(":")] [InlineData("*")] [InlineData("?")] [InlineData("\"")] [InlineData("<")] [InlineData(">")] [InlineData("|")] [InlineData("\0")] [InlineData("abc\u00A0.cs")] // unicode non-breaking space public void HintName_InvalidValues(string hintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); var exception = Assert.Throws<ArgumentException>(nameof(hintName), () => asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8))); Assert.Contains(hintName, exception.Message); } [Fact] public void AddedSources_Are_Deterministic() { // a few manual simple ones AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add("file3.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file1.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file2.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file5.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file4.cs", SourceText.From("", Encoding.UTF8)); var sources = asc.ToImmutableAndFree(); var hintNames = sources.Select(s => s.HintName).ToArray(); Assert.Equal(new[] { "file3.cs", "file1.cs", "file2.cs", "file5.cs", "file4.cs" }, hintNames); // generate a long random list, remembering the order we added them Random r = new Random(); string[] names = new string[1000]; asc = new AdditionalSourcesCollection(".cs"); for (int i = 0; i < 1000; i++) { names[i] = CSharpTestBase.GetUniqueName() + ".cs"; asc.Add(names[i], SourceText.From("", Encoding.UTF8)); } sources = asc.ToImmutableAndFree(); hintNames = sources.Select(s => s.HintName).ToArray(); Assert.Equal(names, hintNames); } [Theory] [InlineData("file.cs", "file.cs")] [InlineData("file", "file")] [InlineData("file", "file.cs")] [InlineData("file.cs", "file")] [InlineData("file.cs", "file.CS")] [InlineData("file.CS", "file.cs")] [InlineData("file", "file.CS")] [InlineData("file.CS", "file")] [InlineData("File", "file")] [InlineData("file", "File")] public void Hint_Name_Must_Be_Unique(string hintName1, string hintName2) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(hintName1, SourceText.From("", Encoding.UTF8)); var exception = Assert.Throws<ArgumentException>("hintName", () => asc.Add(hintName2, SourceText.From("", Encoding.UTF8))); Assert.Contains(hintName2, exception.Message); } [Theory] [InlineData("file.cs", "file.cs")] [InlineData("file", "file")] [InlineData("file", "file.cs")] [InlineData("file.cs", "file")] [InlineData("file.CS", "file")] [InlineData("file", "file.CS")] [InlineData("File", "file.cs")] [InlineData("File.cs", "file")] [InlineData("File.cs", "file.CS")] public void Contains(string addHintName, string checkHintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(addHintName, SourceText.From("", Encoding.UTF8)); Assert.True(asc.Contains(checkHintName)); } [Theory] [InlineData("file.cs", "file.cs")] [InlineData("file", "file")] [InlineData("file", "file.cs")] [InlineData("file.cs", "file")] public void Remove(string addHintName, string removeHintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(addHintName, SourceText.From("", Encoding.UTF8)); asc.RemoveSource(removeHintName); var sources = asc.ToImmutableAndFree(); Assert.Empty(sources); } [Fact] public void SourceTextRequiresEncoding() { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); // fine asc.Add("file1.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file2.cs", SourceText.From("", Encoding.UTF32)); asc.Add("file3.cs", SourceText.From("", Encoding.Unicode)); // no encoding Assert.Throws<ArgumentException>(() => asc.Add("file4.cs", SourceText.From(""))); // explicit null encoding Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null))); var exception = Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null))); // check the exception contains the expected hintName Assert.Contains("file5.cs", exception.Message); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class AdditionalSourcesCollectionTests : CSharpTestBase { [Theory] [InlineData("abc")] // abc.cs [InlineData("abc.cs")] //abc.cs [InlineData("abc.vb")] // abc.vb.cs [InlineData("abc.generated.cs")] [InlineData("abc_-_")] [InlineData("abc - generated.cs")] [InlineData("abc\u0064.cs")] //acbd.cs [InlineData("abc(1).cs")] [InlineData("abc[1].cs")] [InlineData("abc{1}.cs")] public void HintName_ValidValues(string hintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8)); Assert.True(asc.Contains(hintName)); var sources = asc.ToImmutableAndFree(); Assert.Single(sources); Assert.True(sources[0].HintName.EndsWith(".cs")); } [Theory] [InlineData("abc")] // abc.vb [InlineData("abc.cs")] //abc.cs.vb [InlineData("abc.vb")] // abc.vb public void HintName_WithExtension(string hintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".vb"); asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8)); Assert.True(asc.Contains(hintName)); var sources = asc.ToImmutableAndFree(); Assert.Single(sources); Assert.True(sources[0].HintName.EndsWith(".vb")); } [Theory] [InlineData("/abc/def.cs")] [InlineData("\\")] [InlineData(":")] [InlineData("*")] [InlineData("?")] [InlineData("\"")] [InlineData("<")] [InlineData(">")] [InlineData("|")] [InlineData("\0")] [InlineData("abc\u00A0.cs")] // unicode non-breaking space public void HintName_InvalidValues(string hintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); var exception = Assert.Throws<ArgumentException>(nameof(hintName), () => asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8))); Assert.Contains(hintName, exception.Message); } [Fact] public void AddedSources_Are_Deterministic() { // a few manual simple ones AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add("file3.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file1.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file2.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file5.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file4.cs", SourceText.From("", Encoding.UTF8)); var sources = asc.ToImmutableAndFree(); var hintNames = sources.Select(s => s.HintName).ToArray(); Assert.Equal(new[] { "file3.cs", "file1.cs", "file2.cs", "file5.cs", "file4.cs" }, hintNames); // generate a long random list, remembering the order we added them Random r = new Random(); string[] names = new string[1000]; asc = new AdditionalSourcesCollection(".cs"); for (int i = 0; i < 1000; i++) { names[i] = CSharpTestBase.GetUniqueName() + ".cs"; asc.Add(names[i], SourceText.From("", Encoding.UTF8)); } sources = asc.ToImmutableAndFree(); hintNames = sources.Select(s => s.HintName).ToArray(); Assert.Equal(names, hintNames); } [Theory] [InlineData("file.cs", "file.cs")] [InlineData("file", "file")] [InlineData("file", "file.cs")] [InlineData("file.cs", "file")] [InlineData("file.cs", "file.CS")] [InlineData("file.CS", "file.cs")] [InlineData("file", "file.CS")] [InlineData("file.CS", "file")] [InlineData("File", "file")] [InlineData("file", "File")] public void Hint_Name_Must_Be_Unique(string hintName1, string hintName2) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(hintName1, SourceText.From("", Encoding.UTF8)); var exception = Assert.Throws<ArgumentException>("hintName", () => asc.Add(hintName2, SourceText.From("", Encoding.UTF8))); Assert.Contains(hintName2, exception.Message); } [Fact] public void Hint_Name_Must_Be_Unique_When_Combining_Soruces() { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add("hintName1", SourceText.From("", Encoding.UTF8)); asc.Add("hintName2", SourceText.From("", Encoding.UTF8)); AdditionalSourcesCollection asc2 = new AdditionalSourcesCollection(".cs"); asc2.Add("hintName3", SourceText.From("", Encoding.UTF8)); asc2.Add("hintName1", SourceText.From("", Encoding.UTF8)); var exception = Assert.Throws<ArgumentException>("hintName", () => asc.CopyTo(asc2)); Assert.Contains("hintName1", exception.Message); } [Theory] [InlineData("file.cs", "file.cs")] [InlineData("file", "file")] [InlineData("file", "file.cs")] [InlineData("file.cs", "file")] [InlineData("file.CS", "file")] [InlineData("file", "file.CS")] [InlineData("File", "file.cs")] [InlineData("File.cs", "file")] [InlineData("File.cs", "file.CS")] public void Contains(string addHintName, string checkHintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(addHintName, SourceText.From("", Encoding.UTF8)); Assert.True(asc.Contains(checkHintName)); } [Theory] [InlineData("file.cs", "file.cs")] [InlineData("file", "file")] [InlineData("file", "file.cs")] [InlineData("file.cs", "file")] public void Remove(string addHintName, string removeHintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(addHintName, SourceText.From("", Encoding.UTF8)); asc.RemoveSource(removeHintName); var sources = asc.ToImmutableAndFree(); Assert.Empty(sources); } [Fact] public void SourceTextRequiresEncoding() { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); // fine asc.Add("file1.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file2.cs", SourceText.From("", Encoding.UTF32)); asc.Add("file3.cs", SourceText.From("", Encoding.Unicode)); // no encoding Assert.Throws<ArgumentException>(() => asc.Add("file4.cs", SourceText.From(""))); // explicit null encoding Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null))); var exception = Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null))); // check the exception contains the expected hintName Assert.Contains("file5.cs", exception.Message); } } }
1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class GeneratorDriverTests : CSharpTestBase { [Fact] public void Running_With_No_Changes_Is_NoOp() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Empty(diagnostics); Assert.Single(outputCompilation.SyntaxTrees); Assert.Equal(compilation, outputCompilation); } [Fact] public void Generator_Is_Initialized_Before_Running() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Equal(1, initCount); Assert.Equal(1, executeCount); } [Fact] public void Generator_Is_Not_Initialized_If_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); Assert.Equal(0, initCount); Assert.Equal(0, executeCount); } [Fact] public void Generator_Is_Only_Initialized_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++, source: "public class C { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); driver = driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); Assert.Equal(1, initCount); Assert.Equal(3, executeCount); } [Fact] public void Single_File_Is_Added() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation); var generatedClass = outputCompilation.GlobalNamespace.GetTypeMembers("GeneratedClass").Single(); Assert.True(generatedClass.Locations.Single().IsInSource); } [Fact] public void Analyzer_Is_Run() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; var analyzer = new Analyzer_Is_Run_Analyzer(); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); compilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.GeneratedClassCount); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.GeneratedClassCount); } private class Analyzer_Is_Run_Analyzer : DiagnosticAnalyzer { public int GeneratedClassCount; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "GeneratedClass": Interlocked.Increment(ref GeneratedClassCount); break; case "C": case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void Single_File_Is_Added_OnlyOnce_For_Multiple_Calls() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation1, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation2, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation3, out _); Assert.Equal(2, outputCompilation1.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation2.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation3.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation1); Assert.NotEqual(compilation, outputCompilation2); Assert.NotEqual(compilation, outputCompilation3); } [Fact] public void User_Source_Can_Depend_On_Generated_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); } [Fact] public void Error_During_Initialization_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_Generator_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }, source: "class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Single(outputCompilation.SyntaxTrees); } [Fact] public void Error_During_Generation_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Does_Not_Affect_Other_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { }, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_With_Dependent_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Has_Exception_In_Description() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); // Since translated description strings can have punctuation that differs based on locale, simply ensure the // exception message is contains in the diagnostic description. Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString()); } [Fact] public void Generator_Can_Report_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => sgc.ReportDiagnostic(diagnostic)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( Diagnostic("TG001").WithLocation(1, 1) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54185: the addition happens later so the exceptions don't occur directly at add-time. we should decide if this subtle behavior change is acceptable")] public void Generator_HintName_MustBe_Unique() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); // the assert should swallow the exception, so we'll actually successfully generate Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8))); // also throws for <name> vs <name>.cs Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8))); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [Fact] public void Generator_HintName_Is_Appended_With_GeneratorName() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); var generator2 = new SingleFileTestGenerator2("public class E {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(3, outputCompilation.SyntaxTrees.Count()); var filePaths = outputCompilation.SyntaxTrees.Skip(1).Select(t => t.FilePath).ToArray(); Assert.Equal(new[] { Path.Combine(generator.GetType().Assembly.GetName().Name!, generator.GetType().FullName!, "source.cs"), Path.Combine(generator2.GetType().Assembly.GetName().Name!, generator2.GetType().FullName!, "source.cs") }, filePaths); } [Fact] public void RunResults_Are_Empty_Before_Generation() { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: TestOptions.Regular); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Empty(results.Diagnostics); Assert.Empty(results.Results); } [Fact] public void RunResults_Are_Available_After_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.GeneratedTrees); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results.Single(); Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Single(result.GeneratedSources); Assert.Equal(results.GeneratedTrees.Single(), result.GeneratedSources.Single().SyntaxTree); } [Fact] public void RunResults_Combine_SyntaxTrees() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); sgc.AddSource("test2", SourceText.From("public class E {}", Encoding.UTF8)); }); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void RunResults_Combine_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(2, results.Results.Length); Assert.Equal(3, results.Diagnostics.Length); Assert.Empty(results.GeneratedTrees); var result1 = results.Results[0]; var result2 = results.Results[1]; Assert.Null(result1.Exception); Assert.Equal(2, result1.Diagnostics.Length); Assert.Empty(result1.GeneratedSources); Assert.Equal(results.Diagnostics[0], result1.Diagnostics[0]); Assert.Equal(results.Diagnostics[1], result1.Diagnostics[1]); Assert.Null(result2.Exception); Assert.Single(result2.Diagnostics); Assert.Empty(result2.GeneratedSources); Assert.Equal(results.Diagnostics[2], result2.Diagnostics[0]); } [Fact] public void FullGeneration_Diagnostics_AreSame_As_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var fullDiagnostics); var results = driver.GetRunResult(); Assert.Equal(3, results.Diagnostics.Length); Assert.Equal(3, fullDiagnostics.Length); AssertEx.Equal(results.Diagnostics, fullDiagnostics); } [Fact] public void Cancellation_During_Execution_Doesnt_Report_As_Generator_Error() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { cts.Cancel(); } ); // test generator cancels the token. Check that the call to this generator doesn't make it look like it errored. var testGenerator2 = new CallbackGenerator2( onInit: (i) => { }, onExecute: (e) => { e.AddSource("a", SourceText.From("public class E {}", Encoding.UTF8)); e.CancellationToken.ThrowIfCancellationRequested(); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions); var oldDriver = driver; Assert.Throws<OperationCanceledException>(() => driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics, cts.Token) ); Assert.Same(oldDriver, driver); } [ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")] public void Adding_A_Source_Text_Without_Encoding_Fails_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("a", SourceText.From("")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var outputDiagnostics); Assert.Single(outputDiagnostics); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "ArgumentException", "The SourceText with hintName 'a.cs' must have an explicit encoding set. (Parameter 'source')").WithLocation(1, 1) ); } [Fact] public void ParseOptions_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ParseOptions? passedOptions = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { passedOptions = e.ParseOptions; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Same(parseOptions, passedOptions); } [Fact] public void AdditionalFiles_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var texts = ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a", "abc"), new InMemoryAdditionalText("b", "def")); ImmutableArray<AdditionalText> passedIn = default; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => passedIn = e.AdditionalFiles ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, additionalTexts: texts); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Equal(2, passedIn.Length); Assert.Equal<AdditionalText>(texts, passedIn); } [Fact] public void AnalyzerConfigOptions_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var options = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("a", "abc").Add("b", "def"))); AnalyzerConfigOptionsProvider? passedIn = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => passedIn = e.AnalyzerConfigOptions ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, optionsProvider: options); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(passedIn); Assert.True(passedIn!.GlobalOptions.TryGetValue("a", out var item1)); Assert.Equal("abc", item1); Assert.True(passedIn!.GlobalOptions.TryGetValue("b", out var item2)); Assert.Equal("def", item2); } [Fact] public void Generator_Can_Provide_Source_In_PostInit() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [Fact] public void PostInit_Source_Is_Available_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Source_Is_Available_To_Other_Generators_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Is_Only_Called_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int postInitCount = 0; int executeCount = 0; void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); postInitCount++; } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => executeCount++, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(1, postInitCount); Assert.Equal(3, executeCount); } [Fact] public void Error_During_PostInit_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); throw new InvalidOperationException("post init error"); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'post init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "post init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_PostInit_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void init(GeneratorInitializationContext context) { context.RegisterForPostInitialization(postInit); throw new InvalidOperationException("init error"); } static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); Assert.True(false, "Should not execute"); } var generator = new CallbackGenerator(init, (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void PostInit_SyntaxTrees_Are_Available_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results[0]; Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Equal(2, result.GeneratedSources.Length); } [Fact] public void PostInit_SyntaxTrees_Are_Combined_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void SyntaxTrees_Are_Lazy() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); var tree = Assert.Single(results.GeneratedTrees); Assert.False(tree.TryGetRoot(out _)); var rootFromGetRoot = tree.GetRoot(); Assert.NotNull(rootFromGetRoot); Assert.True(tree.TryGetRoot(out var rootFromTryGetRoot)); Assert.Same(rootFromGetRoot, rootFromTryGetRoot); } [Fact] public void Diagnostics_Respect_Suppression() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { c.ReportDiagnostic(CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2)); c.ReportDiagnostic(CSDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 3)); }); var options = ((CSharpCompilationOptions)compilation.Options); // generator driver diagnostics are reported separately from the compilation verifyDiagnosticsWithOptions(options, Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be individually suppressed verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Suppress), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Suppress), Diagnostic("GEN001").WithLocation(1, 1)); // warning level is respected verifyDiagnosticsWithOptions(options.WithWarningLevel(0)); verifyDiagnosticsWithOptions(options.WithWarningLevel(2), Diagnostic("GEN001").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithWarningLevel(3), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be upgraded to errors verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(true), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(true)); void verifyDiagnosticsWithOptions(CompilationOptions options, params DiagnosticDescription[] expected) { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); var updatedCompilation = compilation.WithOptions(options); driver.RunGeneratorsAndUpdateCompilation(updatedCompilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } [Fact] public void Diagnostics_Respect_Pragma_Suppression() { var gen001 = CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2); // reported diagnostics can have a location in source verifyDiagnosticsWithSource("//comment", new[] { (gen001, TextSpan.FromBounds(2, 5)) }, Diagnostic("GEN001", "com").WithLocation(1, 3)); // diagnostics are suppressed via #pragma verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, TextSpan.FromBounds(27, 30)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // but not when they don't have a source location verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, new TextSpan(0, 0)) }, Diagnostic("GEN001").WithLocation(1, 1)); // can be suppressed explicitly verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment", new[] { (gen001, TextSpan.FromBounds(34, 37)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // suppress + restore verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment #pragma warning restore GEN001 //another", new[] { (gen001, TextSpan.FromBounds(34, 37)), (gen001, TextSpan.FromBounds(77, 80)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3), Diagnostic("GEN001", "ano").WithLocation(4, 3)); void verifyDiagnosticsWithSource(string source, (Diagnostic, TextSpan)[] reportDiagnostics, params DiagnosticDescription[] expected) { var parseOptions = TestOptions.Regular; source = source.Replace(Environment.NewLine, "\r\n"); Compilation compilation = CreateCompilation(source, sourceFileName: "sourcefile.cs", options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { foreach ((var d, var l) in reportDiagnostics) { if (l.IsEmpty) { c.ReportDiagnostic(d); } else { c.ReportDiagnostic(d.WithLocation(Location.Create(c.Compilation.SyntaxTrees.First(), l))); } } }); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } [Fact] public void GeneratorDriver_Prefers_Incremental_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); int incrementalInitCount = 0; var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++)); int dualInitCount = 0, dualExecuteCount = 0, dualIncrementalInitCount = 0; var generator3 = new IncrementalAndSourceCallbackGenerator((ic) => dualInitCount++, (sgc) => dualExecuteCount++, (ic) => dualIncrementalInitCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver.RunGenerators(compilation); // ran individual incremental and source generators Assert.Equal(1, initCount); Assert.Equal(1, executeCount); Assert.Equal(1, incrementalInitCount); // ran the combined generator only as an IIncrementalGenerator Assert.Equal(0, dualInitCount); Assert.Equal(0, dualExecuteCount); Assert.Equal(1, dualIncrementalInitCount); } [Fact] public void GeneratorDriver_Initializes_Incremental_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int incrementalInitCount = 0; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver.RunGenerators(compilation); // ran the incremental generator Assert.Equal(1, incrementalInitCount); } [Fact] public void Incremental_Generators_Exception_During_Initialization() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => throw e)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e))); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution_Doesnt_Produce_AnySource() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", "")); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution_Doesnt_Stop_Other_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e); })); var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator2((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Equal(2, runResults.Results.Length); Assert.Single(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void IncrementalGenerator_With_No_Pipeline_Callback_Is_Valid() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => { })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); Assert.Empty(diagnostics); } [Fact] public void IncrementalGenerator_Can_Add_PostInit_Source() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => ic.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}")))); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); Assert.Empty(diagnostics); } [Fact] public void User_WrappedFunc_Throw_Exceptions() { Func<int, CancellationToken, int> func = (input, _) => input; Func<int, CancellationToken, int> throwsFunc = (input, _) => throw new InvalidOperationException("user code exception"); Func<int, CancellationToken, int> timeoutFunc = (input, ct) => { ct.ThrowIfCancellationRequested(); return input; }; Func<int, CancellationToken, int> otherTimeoutFunc = (input, _) => throw new OperationCanceledException(); var userFunc = func.WrapUserFunction(); var userThrowsFunc = throwsFunc.WrapUserFunction(); var userTimeoutFunc = timeoutFunc.WrapUserFunction(); var userOtherTimeoutFunc = otherTimeoutFunc.WrapUserFunction(); // user functions return same values when wrapped var result = userFunc(10, CancellationToken.None); var userResult = userFunc(10, CancellationToken.None); Assert.Equal(10, result); Assert.Equal(result, userResult); // exceptions thrown in user code are wrapped Assert.Throws<InvalidOperationException>(() => throwsFunc(20, CancellationToken.None)); Assert.Throws<UserFunctionException>(() => userThrowsFunc(20, CancellationToken.None)); try { userThrowsFunc(20, CancellationToken.None); } catch (UserFunctionException e) { Assert.IsType<InvalidOperationException>(e.InnerException); } // cancellation is not wrapped, and is bubbled up Assert.Throws<OperationCanceledException>(() => timeoutFunc(30, new CancellationToken(true))); Assert.Throws<OperationCanceledException>(() => userTimeoutFunc(30, new CancellationToken(true))); // unless it wasn't *our* cancellation token, in which case it still gets wrapped Assert.Throws<OperationCanceledException>(() => otherTimeoutFunc(30, CancellationToken.None)); Assert.Throws<UserFunctionException>(() => userOtherTimeoutFunc(30, CancellationToken.None)); } [Fact] public void IncrementalGenerator_Doesnt_Run_For_Same_Input() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var filePaths = ctx.CompilationProvider.SelectMany((c, _) => c.SyntaxTrees).Select((tree, _) => tree.FilePath); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); // run the same compilation through again, and confirm the output wasn't called driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_Runs_Only_For_Changed_Inputs() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var text1 = new InMemoryAdditionalText("Text1", "content1"); var text2 = new InMemoryAdditionalText("Text2", "content2"); List<Compilation> compilationsCalledFor = new List<Compilation>(); List<AdditionalText> textsCalledFor = new List<AdditionalText>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); }); ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, c) => { textsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, additionalTexts: new[] { text1 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); Assert.Equal(1, textsCalledFor.Count); Assert.Equal(text1, textsCalledFor[0]); // clear the results, add an additional text, but keep the compilation the same compilationsCalledFor.Clear(); textsCalledFor.Clear(); driver = driver.AddAdditionalTexts(ImmutableArray.Create<AdditionalText>(text2)); driver = driver.RunGenerators(compilation); Assert.Equal(0, compilationsCalledFor.Count); Assert.Equal(1, textsCalledFor.Count); Assert.Equal(text2, textsCalledFor[0]); // now edit the compilation compilationsCalledFor.Clear(); textsCalledFor.Clear(); var newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newComp")); driver = driver.RunGenerators(newCompilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(newCompilation, compilationsCalledFor[0]); Assert.Equal(0, textsCalledFor.Count); // re run without changing anything compilationsCalledFor.Clear(); textsCalledFor.Clear(); driver = driver.RunGenerators(newCompilation); Assert.Equal(0, compilationsCalledFor.Count); Assert.Equal(0, textsCalledFor.Count); } [Fact] public void IncrementalGenerator_Can_Add_Comparer_To_Input_Node() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var compilationSource = ctx.CompilationProvider.WithComparer(new LambdaComparer<Compilation>((c1, c2) => true, 0)); ctx.RegisterSourceOutput(compilationSource, (spc, c) => { compilationsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); // now edit the compilation, run the generator, and confirm that the output was not called again this time Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation")); driver = driver.RunGenerators(newCompilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_Can_Add_Comparer_To_Combine_Node() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<AdditionalText> texts = new List<AdditionalText>() { new InMemoryAdditionalText("abc", "") }; List<(Compilation, ImmutableArray<AdditionalText>)> calledFor = new List<(Compilation, ImmutableArray<AdditionalText>)>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var compilationSource = ctx.CompilationProvider.Combine(ctx.AdditionalTextsProvider.Collect()) // comparer that ignores the LHS (additional texts) .WithComparer(new LambdaComparer<(Compilation, ImmutableArray<AdditionalText>)>((c1, c2) => c1.Item1 == c2.Item1, 0)); ctx.RegisterSourceOutput(compilationSource, (spc, c) => { calledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation + additional texts GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: texts); driver = driver.RunGenerators(compilation); Assert.Equal(1, calledFor.Count); Assert.Equal(compilation, calledFor[0].Item1); Assert.Equal(texts[0], calledFor[0].Item2.Single()); // edit the additional texts, and verify that the output was *not* called again on the next run driver = driver.RemoveAdditionalTexts(texts.ToImmutableArray()); driver = driver.RunGenerators(compilation); Assert.Equal(1, calledFor.Count); // now edit the compilation, run the generator, and confirm that the output *was* called again this time with the new compilation and no additional texts Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation")); driver = driver.RunGenerators(newCompilation); Assert.Equal(2, calledFor.Count); Assert.Equal(newCompilation, calledFor[1].Item1); Assert.Empty(calledFor[1].Item2); } [Fact] public void IncrementalGenerator_Register_End_Node_Only_Once_Through_Combines() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var source = ctx.CompilationProvider; var source2 = ctx.CompilationProvider.Combine(source); var source3 = ctx.CompilationProvider.Combine(source2); var source4 = ctx.CompilationProvider.Combine(source3); var source5 = ctx.CompilationProvider.Combine(source4); ctx.RegisterSourceOutput(source5, (spc, c) => { compilationsCalledFor.Add(c.Item1); }); })); // run the generator and check that we didn't multiple register the generate source node through the combine GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_PostInit_Source_Is_Cached() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<ClassDeclarationSyntax> classes = new List<ClassDeclarationSyntax>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}")); ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider(static (n, _) => n is ClassDeclarationSyntax, (gsc, _) => (ClassDeclarationSyntax)gsc.Node), (spc, node) => classes.Add(node)); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(2, classes.Count); Assert.Equal("C", classes[0].Identifier.ValueText); Assert.Equal("D", classes[1].Identifier.ValueText); // clear classes, re-run classes.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(classes); // modify the original tree, see that the post init is still cached var c2 = compilation.ReplaceSyntaxTree(compilation.SyntaxTrees.First(), CSharpSyntaxTree.ParseText("class E{}", parseOptions)); classes.Clear(); driver = driver.RunGenerators(c2); Assert.Single(classes); Assert.Equal("E", classes[0].Identifier.ValueText); } [Fact] public void Incremental_Generators_Can_Be_Cancelled() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); bool generatorCancelled = false; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { var step1 = ctx.CompilationProvider.Select((c, ct) => { generatorCancelled = true; cts.Cancel(); return c; }); var step2 = step1.Select((c, ct) => { ct.ThrowIfCancellationRequested(); return c; }); ctx.RegisterSourceOutput(step2, (spc, c) => spc.AddSource("a", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token)); Assert.True(generatorCancelled); } [Fact] public void ParseOptions_Can_Be_Updated() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<ParseOptions> parseOptionsCalledFor = new List<ParseOptions>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, p) => { parseOptionsCalledFor.Add(p); }); })); // run the generator once, and check it was passed the parse options GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, parseOptionsCalledFor.Count); Assert.Equal(parseOptions, parseOptionsCalledFor[0]); // clear the results, and re-run parseOptionsCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(parseOptionsCalledFor); // now update the parse options parseOptionsCalledFor.Clear(); var newParseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose); driver = driver.WithUpdatedParseOptions(newParseOptions); // check we ran driver = driver.RunGenerators(compilation); Assert.Equal(1, parseOptionsCalledFor.Count); Assert.Equal(newParseOptions, parseOptionsCalledFor[0]); // clear the results, and re-run parseOptionsCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(parseOptionsCalledFor); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedParseOptions(null!)); } [Fact] public void AnalyzerConfig_Can_Be_Updated() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string? analyzerOptionsValue = string.Empty; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider, (spc, p) => p.GlobalOptions.TryGetValue("test", out analyzerOptionsValue)); })); var builder = ImmutableDictionary<string, string>.Empty.ToBuilder(); builder.Add("test", "value1"); var optionsProvider = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(builder.ToImmutable())); // run the generator once, and check it was passed the configs GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, optionsProvider: optionsProvider); driver = driver.RunGenerators(compilation); Assert.Equal("value1", analyzerOptionsValue); // clear the results, and re-run analyzerOptionsValue = null; driver = driver.RunGenerators(compilation); Assert.Null(analyzerOptionsValue); // now update the config analyzerOptionsValue = null; builder.Clear(); builder.Add("test", "value2"); var newOptionsProvider = optionsProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(builder.ToImmutable())); driver = driver.WithUpdatedAnalyzerConfigOptions(newOptionsProvider); // check we ran driver = driver.RunGenerators(compilation); Assert.Equal("value2", analyzerOptionsValue); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedAnalyzerConfigOptions(null!)); } [Fact] public void AdditionalText_Can_Be_Replaced() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); InMemoryAdditionalText additionalText1 = new InMemoryAdditionalText("path1.txt", ""); InMemoryAdditionalText additionalText2 = new InMemoryAdditionalText("path2.txt", ""); InMemoryAdditionalText additionalText3 = new InMemoryAdditionalText("path3.txt", ""); List<string?> additionalTextPaths = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider.Select((t, _) => t.Path), (spc, p) => { additionalTextPaths.Add(p); }); })); // run the generator once and check we saw the additional file GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText1, additionalText2, additionalText3 }); driver = driver.RunGenerators(compilation); Assert.Equal(3, additionalTextPaths.Count); Assert.Equal("path1.txt", additionalTextPaths[0]); Assert.Equal("path2.txt", additionalTextPaths[1]); Assert.Equal("path3.txt", additionalTextPaths[2]); // re-run and check nothing else got added additionalTextPaths.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(additionalTextPaths); // now, update the additional text, but keep the path the same additionalTextPaths.Clear(); driver = driver.ReplaceAdditionalText(additionalText2, new InMemoryAdditionalText("path4.txt", "")); // run, and check that only the replaced file was invoked driver = driver.RunGenerators(compilation); Assert.Single(additionalTextPaths); Assert.Equal("path4.txt", additionalTextPaths[0]); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.ReplaceAdditionalText(additionalText1, null!)); } [Fact] public void Replaced_Input_Is_Treated_As_Modified() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); InMemoryAdditionalText additionalText = new InMemoryAdditionalText("path.txt", "abc"); List<string?> additionalTextPaths = new List<string?>(); List<string?> additionalTextsContents = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var texts = ctx.AdditionalTextsProvider; var paths = texts.Select((t, _) => t?.Path); var contents = texts.Select((t, _) => t?.GetText()?.ToString()); ctx.RegisterSourceOutput(paths, (spc, p) => { additionalTextPaths.Add(p); }); ctx.RegisterSourceOutput(contents, (spc, p) => { additionalTextsContents.Add(p); }); })); // run the generator once and check we saw the additional file GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText }); driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal("path.txt", additionalTextPaths[0]); Assert.Equal(1, additionalTextsContents.Count); Assert.Equal("abc", additionalTextsContents[0]); // re-run and check nothing else got added driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal(1, additionalTextsContents.Count); // now, update the additional text, but keep the path the same additionalTextPaths.Clear(); additionalTextsContents.Clear(); var secondText = new InMemoryAdditionalText("path.txt", "def"); driver = driver.ReplaceAdditionalText(additionalText, secondText); // run, and check that only the contents got re-run driver = driver.RunGenerators(compilation); Assert.Empty(additionalTextPaths); Assert.Equal(1, additionalTextsContents.Count); Assert.Equal("def", additionalTextsContents[0]); // now replace the text with a different path, but the same text additionalTextPaths.Clear(); additionalTextsContents.Clear(); var thirdText = new InMemoryAdditionalText("path2.txt", "def"); driver = driver.ReplaceAdditionalText(secondText, thirdText); // run, and check that only the paths got re-run driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal("path2.txt", additionalTextPaths[0]); Assert.Empty(additionalTextsContents); } [Theory] [CombinatorialData] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation)] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.PostInit)] [InlineData(IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)] public void Generator_Output_Kinds_Can_Be_Disabled(IncrementalGeneratorOutputKind disabledOutput) { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new PipelineCallbackGenerator(ctx => { ctx.RegisterPostInitializationOutput((context) => context.AddSource("PostInit", "")); ctx.RegisterSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Source", "")); ctx.RegisterImplementationSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Implementation", "")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, driverOptions: new GeneratorDriverOptions(disabledOutput), parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var result = driver.GetRunResult(); Assert.Single(result.Results); Assert.Empty(result.Results[0].Diagnostics); // verify the expected outputs were generated // NOTE: adding new output types will cause this test to fail. Update above as needed. foreach (IncrementalGeneratorOutputKind kind in Enum.GetValues(typeof(IncrementalGeneratorOutputKind))) { if (kind == IncrementalGeneratorOutputKind.None) continue; if (disabledOutput.HasFlag((IncrementalGeneratorOutputKind)kind)) { Assert.DoesNotContain(result.Results[0].GeneratedSources, isTextForKind); } else { Assert.Contains(result.Results[0].GeneratedSources, isTextForKind); } bool isTextForKind(GeneratedSourceResult s) => s.HintName == Enum.GetName(typeof(IncrementalGeneratorOutputKind), kind) + ".cs"; } } [Fact] public void Metadata_References_Provider() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; var metadataRefs = new[] { MetadataReference.CreateFromAssemblyInternal(this.GetType().Assembly), MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly) }; Compilation compilation = CreateEmptyCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions, references: metadataRefs); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<string?> referenceList = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.MetadataReferencesProvider, (spc, r) => { referenceList.Add(r.Display); }); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(referenceList[0], metadataRefs[0].Display); Assert.Equal(referenceList[1], metadataRefs[1].Display); // re-run and check we didn't see anything new referenceList.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(referenceList); // Modify the reference var modifiedRef = metadataRefs[0].WithAliases(new[] { "Alias " }); metadataRefs[0] = modifiedRef; compilation = compilation.WithReferences(metadataRefs); driver = driver.RunGenerators(compilation); Assert.Single(referenceList, modifiedRef.Display); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class GeneratorDriverTests : CSharpTestBase { [Fact] public void Running_With_No_Changes_Is_NoOp() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Empty(diagnostics); Assert.Single(outputCompilation.SyntaxTrees); Assert.Equal(compilation, outputCompilation); } [Fact] public void Generator_Is_Initialized_Before_Running() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Equal(1, initCount); Assert.Equal(1, executeCount); } [Fact] public void Generator_Is_Not_Initialized_If_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); Assert.Equal(0, initCount); Assert.Equal(0, executeCount); } [Fact] public void Generator_Is_Only_Initialized_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++, source: "public class C { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); driver = driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); Assert.Equal(1, initCount); Assert.Equal(3, executeCount); } [Fact] public void Single_File_Is_Added() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation); var generatedClass = outputCompilation.GlobalNamespace.GetTypeMembers("GeneratedClass").Single(); Assert.True(generatedClass.Locations.Single().IsInSource); } [Fact] public void Analyzer_Is_Run() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; var analyzer = new Analyzer_Is_Run_Analyzer(); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); compilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.GeneratedClassCount); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.GeneratedClassCount); } private class Analyzer_Is_Run_Analyzer : DiagnosticAnalyzer { public int GeneratedClassCount; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "GeneratedClass": Interlocked.Increment(ref GeneratedClassCount); break; case "C": case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void Single_File_Is_Added_OnlyOnce_For_Multiple_Calls() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation1, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation2, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation3, out _); Assert.Equal(2, outputCompilation1.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation2.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation3.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation1); Assert.NotEqual(compilation, outputCompilation2); Assert.NotEqual(compilation, outputCompilation3); } [Fact] public void User_Source_Can_Depend_On_Generated_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); } [Fact] public void Error_During_Initialization_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_Generator_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }, source: "class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Single(outputCompilation.SyntaxTrees); } [Fact] public void Error_During_Generation_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Does_Not_Affect_Other_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { }, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_With_Dependent_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Has_Exception_In_Description() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); // Since translated description strings can have punctuation that differs based on locale, simply ensure the // exception message is contains in the diagnostic description. Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString()); } [Fact] public void Generator_Can_Report_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => sgc.ReportDiagnostic(diagnostic)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( Diagnostic("TG001").WithLocation(1, 1) ); } [Fact] public void Generator_HintName_MustBe_Unique() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); // the assert should swallow the exception, so we'll actually successfully generate Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8))); // also throws for <name> vs <name>.cs Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8))); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")] public void Generator_HintName_MustBe_Unique_Across_Outputs() { var source = @" class C { } "; var parseOptions = TestOptions.Regular.WithLanguageVersion(LanguageVersion.Preview); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); // throws immediately, because we're within the same output node Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8))); // throws for .cs too Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8))); }); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { // will not throw at this point, because we have no way of knowing what the other outputs added // we *will* throw later in the driver when we combine them however (this is a change for V2, but not visible from V1) spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( Diagnostic("CS8785").WithArguments("PipelineCallbackGenerator", "ArgumentException", "The hintName 'test.cs' of the added source file must be unique within a generator. (Parameter 'hintName')").WithLocation(1, 1) ); Assert.Equal(1, outputCompilation.SyntaxTrees.Count()); } [Fact] public void Generator_HintName_Is_Appended_With_GeneratorName() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); var generator2 = new SingleFileTestGenerator2("public class E {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(3, outputCompilation.SyntaxTrees.Count()); var filePaths = outputCompilation.SyntaxTrees.Skip(1).Select(t => t.FilePath).ToArray(); Assert.Equal(new[] { Path.Combine(generator.GetType().Assembly.GetName().Name!, generator.GetType().FullName!, "source.cs"), Path.Combine(generator2.GetType().Assembly.GetName().Name!, generator2.GetType().FullName!, "source.cs") }, filePaths); } [Fact] public void RunResults_Are_Empty_Before_Generation() { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: TestOptions.Regular); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Empty(results.Diagnostics); Assert.Empty(results.Results); } [Fact] public void RunResults_Are_Available_After_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.GeneratedTrees); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results.Single(); Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Single(result.GeneratedSources); Assert.Equal(results.GeneratedTrees.Single(), result.GeneratedSources.Single().SyntaxTree); } [Fact] public void RunResults_Combine_SyntaxTrees() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); sgc.AddSource("test2", SourceText.From("public class E {}", Encoding.UTF8)); }); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void RunResults_Combine_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(2, results.Results.Length); Assert.Equal(3, results.Diagnostics.Length); Assert.Empty(results.GeneratedTrees); var result1 = results.Results[0]; var result2 = results.Results[1]; Assert.Null(result1.Exception); Assert.Equal(2, result1.Diagnostics.Length); Assert.Empty(result1.GeneratedSources); Assert.Equal(results.Diagnostics[0], result1.Diagnostics[0]); Assert.Equal(results.Diagnostics[1], result1.Diagnostics[1]); Assert.Null(result2.Exception); Assert.Single(result2.Diagnostics); Assert.Empty(result2.GeneratedSources); Assert.Equal(results.Diagnostics[2], result2.Diagnostics[0]); } [Fact] public void FullGeneration_Diagnostics_AreSame_As_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var fullDiagnostics); var results = driver.GetRunResult(); Assert.Equal(3, results.Diagnostics.Length); Assert.Equal(3, fullDiagnostics.Length); AssertEx.Equal(results.Diagnostics, fullDiagnostics); } [Fact] public void Cancellation_During_Execution_Doesnt_Report_As_Generator_Error() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { cts.Cancel(); } ); // test generator cancels the token. Check that the call to this generator doesn't make it look like it errored. var testGenerator2 = new CallbackGenerator2( onInit: (i) => { }, onExecute: (e) => { e.AddSource("a", SourceText.From("public class E {}", Encoding.UTF8)); e.CancellationToken.ThrowIfCancellationRequested(); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions); var oldDriver = driver; Assert.Throws<OperationCanceledException>(() => driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics, cts.Token) ); Assert.Same(oldDriver, driver); } [ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")] public void Adding_A_Source_Text_Without_Encoding_Fails_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("a", SourceText.From("")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var outputDiagnostics); Assert.Single(outputDiagnostics); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "ArgumentException", "The SourceText with hintName 'a.cs' must have an explicit encoding set. (Parameter 'source')").WithLocation(1, 1) ); } [Fact] public void ParseOptions_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ParseOptions? passedOptions = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { passedOptions = e.ParseOptions; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Same(parseOptions, passedOptions); } [Fact] public void AdditionalFiles_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var texts = ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a", "abc"), new InMemoryAdditionalText("b", "def")); ImmutableArray<AdditionalText> passedIn = default; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => passedIn = e.AdditionalFiles ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, additionalTexts: texts); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Equal(2, passedIn.Length); Assert.Equal<AdditionalText>(texts, passedIn); } [Fact] public void AnalyzerConfigOptions_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var options = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("a", "abc").Add("b", "def"))); AnalyzerConfigOptionsProvider? passedIn = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => passedIn = e.AnalyzerConfigOptions ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, optionsProvider: options); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(passedIn); Assert.True(passedIn!.GlobalOptions.TryGetValue("a", out var item1)); Assert.Equal("abc", item1); Assert.True(passedIn!.GlobalOptions.TryGetValue("b", out var item2)); Assert.Equal("def", item2); } [Fact] public void Generator_Can_Provide_Source_In_PostInit() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [Fact] public void PostInit_Source_Is_Available_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Source_Is_Available_To_Other_Generators_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Is_Only_Called_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int postInitCount = 0; int executeCount = 0; void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); postInitCount++; } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => executeCount++, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(1, postInitCount); Assert.Equal(3, executeCount); } [Fact] public void Error_During_PostInit_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); throw new InvalidOperationException("post init error"); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'post init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "post init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_PostInit_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void init(GeneratorInitializationContext context) { context.RegisterForPostInitialization(postInit); throw new InvalidOperationException("init error"); } static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); Assert.True(false, "Should not execute"); } var generator = new CallbackGenerator(init, (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void PostInit_SyntaxTrees_Are_Available_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results[0]; Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Equal(2, result.GeneratedSources.Length); } [Fact] public void PostInit_SyntaxTrees_Are_Combined_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void SyntaxTrees_Are_Lazy() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); var tree = Assert.Single(results.GeneratedTrees); Assert.False(tree.TryGetRoot(out _)); var rootFromGetRoot = tree.GetRoot(); Assert.NotNull(rootFromGetRoot); Assert.True(tree.TryGetRoot(out var rootFromTryGetRoot)); Assert.Same(rootFromGetRoot, rootFromTryGetRoot); } [Fact] public void Diagnostics_Respect_Suppression() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { c.ReportDiagnostic(CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2)); c.ReportDiagnostic(CSDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 3)); }); var options = ((CSharpCompilationOptions)compilation.Options); // generator driver diagnostics are reported separately from the compilation verifyDiagnosticsWithOptions(options, Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be individually suppressed verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Suppress), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Suppress), Diagnostic("GEN001").WithLocation(1, 1)); // warning level is respected verifyDiagnosticsWithOptions(options.WithWarningLevel(0)); verifyDiagnosticsWithOptions(options.WithWarningLevel(2), Diagnostic("GEN001").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithWarningLevel(3), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be upgraded to errors verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(true), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(true)); void verifyDiagnosticsWithOptions(CompilationOptions options, params DiagnosticDescription[] expected) { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); var updatedCompilation = compilation.WithOptions(options); driver.RunGeneratorsAndUpdateCompilation(updatedCompilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } [Fact] public void Diagnostics_Respect_Pragma_Suppression() { var gen001 = CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2); // reported diagnostics can have a location in source verifyDiagnosticsWithSource("//comment", new[] { (gen001, TextSpan.FromBounds(2, 5)) }, Diagnostic("GEN001", "com").WithLocation(1, 3)); // diagnostics are suppressed via #pragma verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, TextSpan.FromBounds(27, 30)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // but not when they don't have a source location verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, new TextSpan(0, 0)) }, Diagnostic("GEN001").WithLocation(1, 1)); // can be suppressed explicitly verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment", new[] { (gen001, TextSpan.FromBounds(34, 37)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // suppress + restore verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment #pragma warning restore GEN001 //another", new[] { (gen001, TextSpan.FromBounds(34, 37)), (gen001, TextSpan.FromBounds(77, 80)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3), Diagnostic("GEN001", "ano").WithLocation(4, 3)); void verifyDiagnosticsWithSource(string source, (Diagnostic, TextSpan)[] reportDiagnostics, params DiagnosticDescription[] expected) { var parseOptions = TestOptions.Regular; source = source.Replace(Environment.NewLine, "\r\n"); Compilation compilation = CreateCompilation(source, sourceFileName: "sourcefile.cs", options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { foreach ((var d, var l) in reportDiagnostics) { if (l.IsEmpty) { c.ReportDiagnostic(d); } else { c.ReportDiagnostic(d.WithLocation(Location.Create(c.Compilation.SyntaxTrees.First(), l))); } } }); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } [Fact] public void GeneratorDriver_Prefers_Incremental_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); int incrementalInitCount = 0; var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++)); int dualInitCount = 0, dualExecuteCount = 0, dualIncrementalInitCount = 0; var generator3 = new IncrementalAndSourceCallbackGenerator((ic) => dualInitCount++, (sgc) => dualExecuteCount++, (ic) => dualIncrementalInitCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver.RunGenerators(compilation); // ran individual incremental and source generators Assert.Equal(1, initCount); Assert.Equal(1, executeCount); Assert.Equal(1, incrementalInitCount); // ran the combined generator only as an IIncrementalGenerator Assert.Equal(0, dualInitCount); Assert.Equal(0, dualExecuteCount); Assert.Equal(1, dualIncrementalInitCount); } [Fact] public void GeneratorDriver_Initializes_Incremental_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int incrementalInitCount = 0; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver.RunGenerators(compilation); // ran the incremental generator Assert.Equal(1, incrementalInitCount); } [Fact] public void Incremental_Generators_Exception_During_Initialization() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => throw e)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e))); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution_Doesnt_Produce_AnySource() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", "")); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution_Doesnt_Stop_Other_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e); })); var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator2((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Equal(2, runResults.Results.Length); Assert.Single(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void IncrementalGenerator_With_No_Pipeline_Callback_Is_Valid() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => { })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); Assert.Empty(diagnostics); } [Fact] public void IncrementalGenerator_Can_Add_PostInit_Source() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => ic.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}")))); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); Assert.Empty(diagnostics); } [Fact] public void User_WrappedFunc_Throw_Exceptions() { Func<int, CancellationToken, int> func = (input, _) => input; Func<int, CancellationToken, int> throwsFunc = (input, _) => throw new InvalidOperationException("user code exception"); Func<int, CancellationToken, int> timeoutFunc = (input, ct) => { ct.ThrowIfCancellationRequested(); return input; }; Func<int, CancellationToken, int> otherTimeoutFunc = (input, _) => throw new OperationCanceledException(); var userFunc = func.WrapUserFunction(); var userThrowsFunc = throwsFunc.WrapUserFunction(); var userTimeoutFunc = timeoutFunc.WrapUserFunction(); var userOtherTimeoutFunc = otherTimeoutFunc.WrapUserFunction(); // user functions return same values when wrapped var result = userFunc(10, CancellationToken.None); var userResult = userFunc(10, CancellationToken.None); Assert.Equal(10, result); Assert.Equal(result, userResult); // exceptions thrown in user code are wrapped Assert.Throws<InvalidOperationException>(() => throwsFunc(20, CancellationToken.None)); Assert.Throws<UserFunctionException>(() => userThrowsFunc(20, CancellationToken.None)); try { userThrowsFunc(20, CancellationToken.None); } catch (UserFunctionException e) { Assert.IsType<InvalidOperationException>(e.InnerException); } // cancellation is not wrapped, and is bubbled up Assert.Throws<OperationCanceledException>(() => timeoutFunc(30, new CancellationToken(true))); Assert.Throws<OperationCanceledException>(() => userTimeoutFunc(30, new CancellationToken(true))); // unless it wasn't *our* cancellation token, in which case it still gets wrapped Assert.Throws<OperationCanceledException>(() => otherTimeoutFunc(30, CancellationToken.None)); Assert.Throws<UserFunctionException>(() => userOtherTimeoutFunc(30, CancellationToken.None)); } [Fact] public void IncrementalGenerator_Doesnt_Run_For_Same_Input() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var filePaths = ctx.CompilationProvider.SelectMany((c, _) => c.SyntaxTrees).Select((tree, _) => tree.FilePath); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); // run the same compilation through again, and confirm the output wasn't called driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_Runs_Only_For_Changed_Inputs() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var text1 = new InMemoryAdditionalText("Text1", "content1"); var text2 = new InMemoryAdditionalText("Text2", "content2"); List<Compilation> compilationsCalledFor = new List<Compilation>(); List<AdditionalText> textsCalledFor = new List<AdditionalText>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); }); ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, c) => { textsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, additionalTexts: new[] { text1 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); Assert.Equal(1, textsCalledFor.Count); Assert.Equal(text1, textsCalledFor[0]); // clear the results, add an additional text, but keep the compilation the same compilationsCalledFor.Clear(); textsCalledFor.Clear(); driver = driver.AddAdditionalTexts(ImmutableArray.Create<AdditionalText>(text2)); driver = driver.RunGenerators(compilation); Assert.Equal(0, compilationsCalledFor.Count); Assert.Equal(1, textsCalledFor.Count); Assert.Equal(text2, textsCalledFor[0]); // now edit the compilation compilationsCalledFor.Clear(); textsCalledFor.Clear(); var newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newComp")); driver = driver.RunGenerators(newCompilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(newCompilation, compilationsCalledFor[0]); Assert.Equal(0, textsCalledFor.Count); // re run without changing anything compilationsCalledFor.Clear(); textsCalledFor.Clear(); driver = driver.RunGenerators(newCompilation); Assert.Equal(0, compilationsCalledFor.Count); Assert.Equal(0, textsCalledFor.Count); } [Fact] public void IncrementalGenerator_Can_Add_Comparer_To_Input_Node() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var compilationSource = ctx.CompilationProvider.WithComparer(new LambdaComparer<Compilation>((c1, c2) => true, 0)); ctx.RegisterSourceOutput(compilationSource, (spc, c) => { compilationsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); // now edit the compilation, run the generator, and confirm that the output was not called again this time Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation")); driver = driver.RunGenerators(newCompilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_Can_Add_Comparer_To_Combine_Node() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<AdditionalText> texts = new List<AdditionalText>() { new InMemoryAdditionalText("abc", "") }; List<(Compilation, ImmutableArray<AdditionalText>)> calledFor = new List<(Compilation, ImmutableArray<AdditionalText>)>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var compilationSource = ctx.CompilationProvider.Combine(ctx.AdditionalTextsProvider.Collect()) // comparer that ignores the LHS (additional texts) .WithComparer(new LambdaComparer<(Compilation, ImmutableArray<AdditionalText>)>((c1, c2) => c1.Item1 == c2.Item1, 0)); ctx.RegisterSourceOutput(compilationSource, (spc, c) => { calledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation + additional texts GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: texts); driver = driver.RunGenerators(compilation); Assert.Equal(1, calledFor.Count); Assert.Equal(compilation, calledFor[0].Item1); Assert.Equal(texts[0], calledFor[0].Item2.Single()); // edit the additional texts, and verify that the output was *not* called again on the next run driver = driver.RemoveAdditionalTexts(texts.ToImmutableArray()); driver = driver.RunGenerators(compilation); Assert.Equal(1, calledFor.Count); // now edit the compilation, run the generator, and confirm that the output *was* called again this time with the new compilation and no additional texts Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation")); driver = driver.RunGenerators(newCompilation); Assert.Equal(2, calledFor.Count); Assert.Equal(newCompilation, calledFor[1].Item1); Assert.Empty(calledFor[1].Item2); } [Fact] public void IncrementalGenerator_Register_End_Node_Only_Once_Through_Combines() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var source = ctx.CompilationProvider; var source2 = ctx.CompilationProvider.Combine(source); var source3 = ctx.CompilationProvider.Combine(source2); var source4 = ctx.CompilationProvider.Combine(source3); var source5 = ctx.CompilationProvider.Combine(source4); ctx.RegisterSourceOutput(source5, (spc, c) => { compilationsCalledFor.Add(c.Item1); }); })); // run the generator and check that we didn't multiple register the generate source node through the combine GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_PostInit_Source_Is_Cached() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<ClassDeclarationSyntax> classes = new List<ClassDeclarationSyntax>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}")); ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider(static (n, _) => n is ClassDeclarationSyntax, (gsc, _) => (ClassDeclarationSyntax)gsc.Node), (spc, node) => classes.Add(node)); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(2, classes.Count); Assert.Equal("C", classes[0].Identifier.ValueText); Assert.Equal("D", classes[1].Identifier.ValueText); // clear classes, re-run classes.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(classes); // modify the original tree, see that the post init is still cached var c2 = compilation.ReplaceSyntaxTree(compilation.SyntaxTrees.First(), CSharpSyntaxTree.ParseText("class E{}", parseOptions)); classes.Clear(); driver = driver.RunGenerators(c2); Assert.Single(classes); Assert.Equal("E", classes[0].Identifier.ValueText); } [Fact] public void Incremental_Generators_Can_Be_Cancelled() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); bool generatorCancelled = false; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { var step1 = ctx.CompilationProvider.Select((c, ct) => { generatorCancelled = true; cts.Cancel(); return c; }); var step2 = step1.Select((c, ct) => { ct.ThrowIfCancellationRequested(); return c; }); ctx.RegisterSourceOutput(step2, (spc, c) => spc.AddSource("a", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token)); Assert.True(generatorCancelled); } [Fact] public void ParseOptions_Can_Be_Updated() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<ParseOptions> parseOptionsCalledFor = new List<ParseOptions>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, p) => { parseOptionsCalledFor.Add(p); }); })); // run the generator once, and check it was passed the parse options GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, parseOptionsCalledFor.Count); Assert.Equal(parseOptions, parseOptionsCalledFor[0]); // clear the results, and re-run parseOptionsCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(parseOptionsCalledFor); // now update the parse options parseOptionsCalledFor.Clear(); var newParseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose); driver = driver.WithUpdatedParseOptions(newParseOptions); // check we ran driver = driver.RunGenerators(compilation); Assert.Equal(1, parseOptionsCalledFor.Count); Assert.Equal(newParseOptions, parseOptionsCalledFor[0]); // clear the results, and re-run parseOptionsCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(parseOptionsCalledFor); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedParseOptions(null!)); } [Fact] public void AnalyzerConfig_Can_Be_Updated() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string? analyzerOptionsValue = string.Empty; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider, (spc, p) => p.GlobalOptions.TryGetValue("test", out analyzerOptionsValue)); })); var builder = ImmutableDictionary<string, string>.Empty.ToBuilder(); builder.Add("test", "value1"); var optionsProvider = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(builder.ToImmutable())); // run the generator once, and check it was passed the configs GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, optionsProvider: optionsProvider); driver = driver.RunGenerators(compilation); Assert.Equal("value1", analyzerOptionsValue); // clear the results, and re-run analyzerOptionsValue = null; driver = driver.RunGenerators(compilation); Assert.Null(analyzerOptionsValue); // now update the config analyzerOptionsValue = null; builder.Clear(); builder.Add("test", "value2"); var newOptionsProvider = optionsProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(builder.ToImmutable())); driver = driver.WithUpdatedAnalyzerConfigOptions(newOptionsProvider); // check we ran driver = driver.RunGenerators(compilation); Assert.Equal("value2", analyzerOptionsValue); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedAnalyzerConfigOptions(null!)); } [Fact] public void AdditionalText_Can_Be_Replaced() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); InMemoryAdditionalText additionalText1 = new InMemoryAdditionalText("path1.txt", ""); InMemoryAdditionalText additionalText2 = new InMemoryAdditionalText("path2.txt", ""); InMemoryAdditionalText additionalText3 = new InMemoryAdditionalText("path3.txt", ""); List<string?> additionalTextPaths = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider.Select((t, _) => t.Path), (spc, p) => { additionalTextPaths.Add(p); }); })); // run the generator once and check we saw the additional file GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText1, additionalText2, additionalText3 }); driver = driver.RunGenerators(compilation); Assert.Equal(3, additionalTextPaths.Count); Assert.Equal("path1.txt", additionalTextPaths[0]); Assert.Equal("path2.txt", additionalTextPaths[1]); Assert.Equal("path3.txt", additionalTextPaths[2]); // re-run and check nothing else got added additionalTextPaths.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(additionalTextPaths); // now, update the additional text, but keep the path the same additionalTextPaths.Clear(); driver = driver.ReplaceAdditionalText(additionalText2, new InMemoryAdditionalText("path4.txt", "")); // run, and check that only the replaced file was invoked driver = driver.RunGenerators(compilation); Assert.Single(additionalTextPaths); Assert.Equal("path4.txt", additionalTextPaths[0]); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.ReplaceAdditionalText(additionalText1, null!)); } [Fact] public void Replaced_Input_Is_Treated_As_Modified() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); InMemoryAdditionalText additionalText = new InMemoryAdditionalText("path.txt", "abc"); List<string?> additionalTextPaths = new List<string?>(); List<string?> additionalTextsContents = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var texts = ctx.AdditionalTextsProvider; var paths = texts.Select((t, _) => t?.Path); var contents = texts.Select((t, _) => t?.GetText()?.ToString()); ctx.RegisterSourceOutput(paths, (spc, p) => { additionalTextPaths.Add(p); }); ctx.RegisterSourceOutput(contents, (spc, p) => { additionalTextsContents.Add(p); }); })); // run the generator once and check we saw the additional file GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText }); driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal("path.txt", additionalTextPaths[0]); Assert.Equal(1, additionalTextsContents.Count); Assert.Equal("abc", additionalTextsContents[0]); // re-run and check nothing else got added driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal(1, additionalTextsContents.Count); // now, update the additional text, but keep the path the same additionalTextPaths.Clear(); additionalTextsContents.Clear(); var secondText = new InMemoryAdditionalText("path.txt", "def"); driver = driver.ReplaceAdditionalText(additionalText, secondText); // run, and check that only the contents got re-run driver = driver.RunGenerators(compilation); Assert.Empty(additionalTextPaths); Assert.Equal(1, additionalTextsContents.Count); Assert.Equal("def", additionalTextsContents[0]); // now replace the text with a different path, but the same text additionalTextPaths.Clear(); additionalTextsContents.Clear(); var thirdText = new InMemoryAdditionalText("path2.txt", "def"); driver = driver.ReplaceAdditionalText(secondText, thirdText); // run, and check that only the paths got re-run driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal("path2.txt", additionalTextPaths[0]); Assert.Empty(additionalTextsContents); } [Theory] [CombinatorialData] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation)] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.PostInit)] [InlineData(IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)] public void Generator_Output_Kinds_Can_Be_Disabled(IncrementalGeneratorOutputKind disabledOutput) { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new PipelineCallbackGenerator(ctx => { ctx.RegisterPostInitializationOutput((context) => context.AddSource("PostInit", "")); ctx.RegisterSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Source", "")); ctx.RegisterImplementationSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Implementation", "")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, driverOptions: new GeneratorDriverOptions(disabledOutput), parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var result = driver.GetRunResult(); Assert.Single(result.Results); Assert.Empty(result.Results[0].Diagnostics); // verify the expected outputs were generated // NOTE: adding new output types will cause this test to fail. Update above as needed. foreach (IncrementalGeneratorOutputKind kind in Enum.GetValues(typeof(IncrementalGeneratorOutputKind))) { if (kind == IncrementalGeneratorOutputKind.None) continue; if (disabledOutput.HasFlag((IncrementalGeneratorOutputKind)kind)) { Assert.DoesNotContain(result.Results[0].GeneratedSources, isTextForKind); } else { Assert.Contains(result.Results[0].GeneratedSources, isTextForKind); } bool isTextForKind(GeneratedSourceResult s) => s.HintName == Enum.GetName(typeof(IncrementalGeneratorOutputKind), kind) + ".cs"; } } [Fact] public void Metadata_References_Provider() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; var metadataRefs = new[] { MetadataReference.CreateFromAssemblyInternal(this.GetType().Assembly), MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly) }; Compilation compilation = CreateEmptyCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions, references: metadataRefs); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<string?> referenceList = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.MetadataReferencesProvider, (spc, r) => { referenceList.Add(r.Display); }); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(referenceList[0], metadataRefs[0].Display); Assert.Equal(referenceList[1], metadataRefs[1].Display); // re-run and check we didn't see anything new referenceList.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(referenceList); // Modify the reference var modifiedRef = metadataRefs[0].WithAliases(new[] { "Alias " }); metadataRefs[0] = modifiedRef; compilation = compilation.WithReferences(metadataRefs); driver = driver.RunGenerators(compilation); Assert.Single(referenceList, modifiedRef.Display); } } }
1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/SourceGeneration/AdditionalSourcesCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class AdditionalSourcesCollection { private readonly ArrayBuilder<GeneratedSourceText> _sourcesAdded; private readonly string _fileExtension; private const StringComparison _hintNameComparison = StringComparison.OrdinalIgnoreCase; private static readonly StringComparer s_hintNameComparer = StringComparer.OrdinalIgnoreCase; internal AdditionalSourcesCollection(string fileExtension) { Debug.Assert(fileExtension.Length > 0 && fileExtension[0] == '.'); _sourcesAdded = ArrayBuilder<GeneratedSourceText>.GetInstance(); _fileExtension = fileExtension; } public void Add(string hintName, SourceText source) { if (string.IsNullOrWhiteSpace(hintName)) { throw new ArgumentNullException(nameof(hintName)); } // allow any identifier character or [.,-_ ()[]{}] for (int i = 0; i < hintName.Length; i++) { char c = hintName[i]; if (!UnicodeCharacterUtilities.IsIdentifierPartCharacter(c) && c != '.' && c != ',' && c != '-' && c != '_' && c != ' ' && c != '(' && c != ')' && c != '[' && c != ']' && c != '{' && c != '}') { throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameInvalidChar, hintName, c, i), nameof(hintName)); } } hintName = AppendExtensionIfRequired(hintName); if (this.Contains(hintName)) { throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameUniquePerGenerator, hintName), nameof(hintName)); } if (source.Encoding is null) { throw new ArgumentException(string.Format(CodeAnalysisResources.SourceTextRequiresEncoding, hintName), nameof(source)); } _sourcesAdded.Add(new GeneratedSourceText(hintName, source)); } public void RemoveSource(string hintName) { hintName = AppendExtensionIfRequired(hintName); for (int i = 0; i < _sourcesAdded.Count; i++) { if (s_hintNameComparer.Equals(_sourcesAdded[i].HintName, hintName)) { _sourcesAdded.RemoveAt(i); return; } } } public bool Contains(string hintName) { hintName = AppendExtensionIfRequired(hintName); for (int i = 0; i < _sourcesAdded.Count; i++) { if (s_hintNameComparer.Equals(_sourcesAdded[i].HintName, hintName)) { return true; } } return false; } internal ImmutableArray<GeneratedSourceText> ToImmutableAndFree() => _sourcesAdded.ToImmutableAndFree(); internal ImmutableArray<GeneratedSourceText> ToImmutable() => _sourcesAdded.ToImmutable(); internal void Free() => _sourcesAdded.Free(); private string AppendExtensionIfRequired(string hintName) { if (!hintName.EndsWith(_fileExtension, _hintNameComparison)) { hintName = string.Concat(hintName, _fileExtension); } return hintName; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class AdditionalSourcesCollection { private readonly ArrayBuilder<GeneratedSourceText> _sourcesAdded; private readonly string _fileExtension; private const StringComparison _hintNameComparison = StringComparison.OrdinalIgnoreCase; private static readonly StringComparer s_hintNameComparer = StringComparer.OrdinalIgnoreCase; internal AdditionalSourcesCollection(string fileExtension) { Debug.Assert(fileExtension.Length > 0 && fileExtension[0] == '.'); _sourcesAdded = ArrayBuilder<GeneratedSourceText>.GetInstance(); _fileExtension = fileExtension; } public void Add(string hintName, SourceText source) { if (string.IsNullOrWhiteSpace(hintName)) { throw new ArgumentNullException(nameof(hintName)); } // allow any identifier character or [.,-_ ()[]{}] for (int i = 0; i < hintName.Length; i++) { char c = hintName[i]; if (!UnicodeCharacterUtilities.IsIdentifierPartCharacter(c) && c != '.' && c != ',' && c != '-' && c != '_' && c != ' ' && c != '(' && c != ')' && c != '[' && c != ']' && c != '{' && c != '}') { throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameInvalidChar, hintName, c, i), nameof(hintName)); } } hintName = AppendExtensionIfRequired(hintName); if (this.Contains(hintName)) { throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameUniquePerGenerator, hintName), nameof(hintName)); } if (source.Encoding is null) { throw new ArgumentException(string.Format(CodeAnalysisResources.SourceTextRequiresEncoding, hintName), nameof(source)); } _sourcesAdded.Add(new GeneratedSourceText(hintName, source)); } public void RemoveSource(string hintName) { hintName = AppendExtensionIfRequired(hintName); for (int i = 0; i < _sourcesAdded.Count; i++) { if (s_hintNameComparer.Equals(_sourcesAdded[i].HintName, hintName)) { _sourcesAdded.RemoveAt(i); return; } } } public bool Contains(string hintName) { hintName = AppendExtensionIfRequired(hintName); for (int i = 0; i < _sourcesAdded.Count; i++) { if (s_hintNameComparer.Equals(_sourcesAdded[i].HintName, hintName)) { return true; } } return false; } public void CopyTo(AdditionalSourcesCollection asc) { // we know the individual hint names are valid, but we do need to check that they // don't collide with any we already have if (asc._sourcesAdded.Count == 0) { asc._sourcesAdded.AddRange(this._sourcesAdded); } else { foreach (var source in this._sourcesAdded) { if (asc.Contains(source.HintName)) { throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameUniquePerGenerator, source.HintName), "hintName"); } asc._sourcesAdded.Add(source); } } } internal ImmutableArray<GeneratedSourceText> ToImmutableAndFree() => _sourcesAdded.ToImmutableAndFree(); internal ImmutableArray<GeneratedSourceText> ToImmutable() => _sourcesAdded.ToImmutable(); internal void Free() => _sourcesAdded.Free(); private string AppendExtensionIfRequired(string hintName) { if (!hintName.EndsWith(_fileExtension, _hintNameComparison)) { hintName = string.Concat(hintName, _fileExtension); } return hintName; } } }
1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/SourceGeneration/GeneratorAdaptor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Adapts an ISourceGenerator to an incremental generator that /// by providing an execution environment that matches the old one /// </summary> internal sealed class SourceGeneratorAdaptor : IIncrementalGenerator { internal ISourceGenerator SourceGenerator { get; } public SourceGeneratorAdaptor(ISourceGenerator generator) { SourceGenerator = generator; } public void Initialize(IncrementalGeneratorInitializationContext context) { GeneratorInitializationContext generatorInitContext = new GeneratorInitializationContext(CancellationToken.None); SourceGenerator.Initialize(generatorInitContext); if (generatorInitContext.InfoBuilder.PostInitCallback is object) { context.RegisterPostInitializationOutput(generatorInitContext.InfoBuilder.PostInitCallback); } var contextBuilderSource = context.CompilationProvider .Select((c, _) => new GeneratorContextBuilder(c)) .Combine(context.ParseOptionsProvider).Select((p, _) => p.Item1 with { ParseOptions = p.Item2 }) .Combine(context.AnalyzerConfigOptionsProvider).Select((p, _) => p.Item1 with { ConfigOptions = p.Item2 }) .Combine(context.AdditionalTextsProvider.Collect()).Select((p, _) => p.Item1 with { AdditionalTexts = p.Item2 }); var syntaxContextReceiverCreator = generatorInitContext.InfoBuilder.SyntaxContextReceiverCreator; if (syntaxContextReceiverCreator is object) { contextBuilderSource = contextBuilderSource .Combine(context.SyntaxProvider.CreateSyntaxReceiverProvider(syntaxContextReceiverCreator)) .Select((p, _) => p.Item1 with { Receiver = p.Item2 }); } context.RegisterSourceOutput(contextBuilderSource, (productionContext, contextBuilder) => { var generatorExecutionContext = contextBuilder.ToExecutionContext(productionContext.CancellationToken); SourceGenerator.Execute(generatorExecutionContext); // copy the contents of the old context to the new generatorExecutionContext.CopyToProductionContext(productionContext); generatorExecutionContext.Free(); }); } internal record GeneratorContextBuilder(Compilation Compilation) { public ParseOptions? ParseOptions; public ImmutableArray<AdditionalText> AdditionalTexts; public Diagnostics.AnalyzerConfigOptionsProvider? ConfigOptions; public ISyntaxContextReceiver? Receiver; public GeneratorExecutionContext ToExecutionContext(CancellationToken cancellationToken) { Debug.Assert(ParseOptions is object && ConfigOptions is object); return new GeneratorExecutionContext(Compilation, ParseOptions, AdditionalTexts, ConfigOptions, Receiver, cancellationToken); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Adapts an ISourceGenerator to an incremental generator that /// by providing an execution environment that matches the old one /// </summary> internal sealed class SourceGeneratorAdaptor : IIncrementalGenerator { private readonly string _sourceExtension; internal ISourceGenerator SourceGenerator { get; } public SourceGeneratorAdaptor(ISourceGenerator generator, string sourceExtension) { SourceGenerator = generator; _sourceExtension = sourceExtension; } public void Initialize(IncrementalGeneratorInitializationContext context) { GeneratorInitializationContext generatorInitContext = new GeneratorInitializationContext(CancellationToken.None); SourceGenerator.Initialize(generatorInitContext); if (generatorInitContext.InfoBuilder.PostInitCallback is object) { context.RegisterPostInitializationOutput(generatorInitContext.InfoBuilder.PostInitCallback); } var contextBuilderSource = context.CompilationProvider .Select((c, _) => new GeneratorContextBuilder(c)) .Combine(context.ParseOptionsProvider).Select((p, _) => p.Item1 with { ParseOptions = p.Item2 }) .Combine(context.AnalyzerConfigOptionsProvider).Select((p, _) => p.Item1 with { ConfigOptions = p.Item2 }) .Combine(context.AdditionalTextsProvider.Collect()).Select((p, _) => p.Item1 with { AdditionalTexts = p.Item2 }); var syntaxContextReceiverCreator = generatorInitContext.InfoBuilder.SyntaxContextReceiverCreator; if (syntaxContextReceiverCreator is object) { contextBuilderSource = contextBuilderSource .Combine(context.SyntaxProvider.CreateSyntaxReceiverProvider(syntaxContextReceiverCreator)) .Select((p, _) => p.Item1 with { Receiver = p.Item2 }); } context.RegisterSourceOutput(contextBuilderSource, (productionContext, contextBuilder) => { var generatorExecutionContext = contextBuilder.ToExecutionContext(_sourceExtension, productionContext.CancellationToken); SourceGenerator.Execute(generatorExecutionContext); // copy the contents of the old context to the new generatorExecutionContext.CopyToProductionContext(productionContext); generatorExecutionContext.Free(); }); } internal record GeneratorContextBuilder(Compilation Compilation) { public ParseOptions? ParseOptions; public ImmutableArray<AdditionalText> AdditionalTexts; public Diagnostics.AnalyzerConfigOptionsProvider? ConfigOptions; public ISyntaxContextReceiver? Receiver; public GeneratorExecutionContext ToExecutionContext(string sourceExtension, CancellationToken cancellationToken) { Debug.Assert(ParseOptions is object && ConfigOptions is object); return new GeneratorExecutionContext(Compilation, ParseOptions, AdditionalTexts, ConfigOptions, Receiver, sourceExtension, cancellationToken); } } } }
1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/SourceGeneration/GeneratorContexts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Context passed to a source generator when <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> is called /// </summary> public readonly struct GeneratorExecutionContext { private readonly DiagnosticBag _diagnostics; private readonly ArrayBuilder<GeneratedSourceText> _additionalSources; internal GeneratorExecutionContext(Compilation compilation, ParseOptions parseOptions, ImmutableArray<AdditionalText> additionalTexts, AnalyzerConfigOptionsProvider optionsProvider, ISyntaxContextReceiver? syntaxReceiver, CancellationToken cancellationToken = default) { Compilation = compilation; ParseOptions = parseOptions; AdditionalFiles = additionalTexts; AnalyzerConfigOptions = optionsProvider; SyntaxReceiver = (syntaxReceiver as SyntaxContextReceiverAdaptor)?.Receiver; SyntaxContextReceiver = (syntaxReceiver is SyntaxContextReceiverAdaptor) ? null : syntaxReceiver; CancellationToken = cancellationToken; _additionalSources = ArrayBuilder<GeneratedSourceText>.GetInstance(); _diagnostics = new DiagnosticBag(); } /// <summary> /// Get the current <see cref="CodeAnalysis.Compilation"/> at the time of execution. /// </summary> /// <remarks> /// This compilation contains only the user supplied code; other generated code is not /// available. As user code can depend on the results of generation, it is possible that /// this compilation will contain errors. /// </remarks> public Compilation Compilation { get; } /// <summary> /// Get the <see cref="CodeAnalysis.ParseOptions"/> that will be used to parse any added sources. /// </summary> public ParseOptions ParseOptions { get; } /// <summary> /// A set of additional non-code text files that can be used by generators. /// </summary> public ImmutableArray<AdditionalText> AdditionalFiles { get; } /// <summary> /// Allows access to options provided by an analyzer config /// </summary> public AnalyzerConfigOptionsProvider AnalyzerConfigOptions { get; } /// <summary> /// If the generator registered an <see cref="ISyntaxReceiver"/> during initialization, this will be the instance created for this generation pass. /// </summary> public ISyntaxReceiver? SyntaxReceiver { get; } /// <summary> /// If the generator registered an <see cref="ISyntaxContextReceiver"/> during initialization, this will be the instance created for this generation pass. /// </summary> public ISyntaxContextReceiver? SyntaxContextReceiver { get; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the generation should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation. /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(new GeneratedSourceText(hintName, sourceText)); /// <summary> /// Adds a <see cref="Diagnostic"/> to the users compilation /// </summary> /// <param name="diagnostic">The diagnostic that should be added to the compilation</param> /// <remarks> /// The severity of the diagnostic may cause the compilation to fail, depending on the <see cref="Compilation"/> settings. /// </remarks> public void ReportDiagnostic(Diagnostic diagnostic) => _diagnostics.Add(diagnostic); internal (ImmutableArray<GeneratedSourceText> sources, ImmutableArray<Diagnostic> diagnostics) ToImmutableAndFree() => (_additionalSources.ToImmutableAndFree(), _diagnostics.ToReadOnlyAndFree()); internal void Free() { _additionalSources.Free(); _diagnostics.Free(); } internal void CopyToProductionContext(SourceProductionContext ctx) { ctx.Sources.AddRange(_additionalSources); ctx.Diagnostics.AddRange(_diagnostics); } } /// <summary> /// Context passed to a source generator when <see cref="ISourceGenerator.Initialize(GeneratorInitializationContext)"/> is called /// </summary> public struct GeneratorInitializationContext { internal GeneratorInitializationContext(CancellationToken cancellationToken = default) { CancellationToken = cancellationToken; InfoBuilder = new GeneratorInfo.Builder(); } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the initialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } internal GeneratorInfo.Builder InfoBuilder { get; } /// <summary> /// Register a <see cref="SyntaxReceiverCreator"/> for this generator, which can be used to create an instance of an <see cref="ISyntaxReceiver"/>. /// </summary> /// <remarks> /// This method allows generators to be 'syntax aware'. Before each generation the <paramref name="receiverCreator"/> will be invoked to create /// an instance of <see cref="ISyntaxReceiver"/>. This receiver will have its <see cref="ISyntaxReceiver.OnVisitSyntaxNode(SyntaxNode)"/> /// invoked for each syntax node in the compilation, allowing the receiver to build up information about the compilation before generation occurs. /// /// During <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> the generator can obtain the <see cref="ISyntaxReceiver"/> instance that was /// created by accessing the <see cref="GeneratorExecutionContext.SyntaxReceiver"/> property. Any information that was collected by the receiver can be /// used to generate the final output. /// /// A new instance of <see cref="ISyntaxReceiver"/> is created per-generation, meaning there is no need to manage the lifetime of the /// receiver or its contents. /// </remarks> /// <param name="receiverCreator">A <see cref="SyntaxReceiverCreator"/> that can be invoked to create an instance of <see cref="ISyntaxReceiver"/></param> public void RegisterForSyntaxNotifications(SyntaxReceiverCreator receiverCreator) { CheckIsEmpty(InfoBuilder.SyntaxContextReceiverCreator, $"{nameof(SyntaxReceiverCreator)} / {nameof(SyntaxContextReceiverCreator)}"); InfoBuilder.SyntaxContextReceiverCreator = SyntaxContextReceiverAdaptor.Create(receiverCreator); } /// <summary> /// Register a <see cref="SyntaxContextReceiverCreator"/> for this generator, which can be used to create an instance of an <see cref="ISyntaxContextReceiver"/>. /// </summary> /// <remarks> /// This method allows generators to be 'syntax aware'. Before each generation the <paramref name="receiverCreator"/> will be invoked to create /// an instance of <see cref="ISyntaxContextReceiver"/>. This receiver will have its <see cref="ISyntaxContextReceiver.OnVisitSyntaxNode(GeneratorSyntaxContext)"/> /// invoked for each syntax node in the compilation, allowing the receiver to build up information about the compilation before generation occurs. /// /// During <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> the generator can obtain the <see cref="ISyntaxContextReceiver"/> instance that was /// created by accessing the <see cref="GeneratorExecutionContext.SyntaxContextReceiver"/> property. Any information that was collected by the receiver can be /// used to generate the final output. /// /// A new instance of <see cref="ISyntaxContextReceiver"/> is created prior to every call to <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/>, /// meaning there is no need to manage the lifetime of the receiver or its contents. /// </remarks> /// <param name="receiverCreator">A <see cref="SyntaxContextReceiverCreator"/> that can be invoked to create an instance of <see cref="ISyntaxContextReceiver"/></param> public void RegisterForSyntaxNotifications(SyntaxContextReceiverCreator receiverCreator) { CheckIsEmpty(InfoBuilder.SyntaxContextReceiverCreator, $"{nameof(SyntaxReceiverCreator)} / {nameof(SyntaxContextReceiverCreator)}"); InfoBuilder.SyntaxContextReceiverCreator = receiverCreator; } /// <summary> /// Register a callback that is invoked after initialization. /// </summary> /// <remarks> /// This method allows a generator to opt-in to an extra phase in the generator lifecycle called PostInitialization. After being initialized /// any generators that have opted in will have their provided callback invoked with a <see cref="GeneratorPostInitializationContext"/> instance /// that can be used to alter the compilation that is provided to subsequent generator phases. /// /// For example a generator may choose to add sources during PostInitialization. These will be added to the compilation before execution and /// will be visited by a registered <see cref="ISyntaxReceiver"/> and available for semantic analysis as part of the <see cref="GeneratorExecutionContext.Compilation"/> /// /// Note that any sources added during PostInitialization <i>will</i> be visible to the later phases of other generators operating on the compilation. /// </remarks> /// <param name="callback">An <see cref="Action{T}"/> that accepts a <see cref="GeneratorPostInitializationContext"/> that will be invoked after initialization.</param> public void RegisterForPostInitialization(Action<GeneratorPostInitializationContext> callback) { CheckIsEmpty(InfoBuilder.PostInitCallback); InfoBuilder.PostInitCallback = (context) => callback(new GeneratorPostInitializationContext(context.AdditionalSources, context.CancellationToken)); } private static void CheckIsEmpty<T>(T x, string? typeName = null) where T : class? { if (x is object) { throw new InvalidOperationException(string.Format(CodeAnalysisResources.Single_type_per_generator_0, typeName ?? typeof(T).Name)); } } } /// <summary> /// Context passed to an <see cref="ISyntaxContextReceiver"/> when <see cref="ISyntaxContextReceiver.OnVisitSyntaxNode(GeneratorSyntaxContext)"/> is called /// </summary> public readonly struct GeneratorSyntaxContext { internal GeneratorSyntaxContext(SyntaxNode node, SemanticModel semanticModel) { Node = node; SemanticModel = semanticModel; } /// <summary> /// The <see cref="SyntaxNode"/> currently being visited /// </summary> public SyntaxNode Node { get; } /// <summary> /// The <see cref="CodeAnalysis.SemanticModel" /> that can be queried to obtain information about <see cref="Node"/>. /// </summary> public SemanticModel SemanticModel { get; } } /// <summary> /// Context passed to a source generator when it has opted-in to PostInitialization via <see cref="GeneratorInitializationContext.RegisterForPostInitialization(Action{GeneratorPostInitializationContext})"/> /// </summary> public readonly struct GeneratorPostInitializationContext { private readonly AdditionalSourcesCollection _additionalSources; internal GeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) { _additionalSources = additionalSources; CancellationToken = cancellationToken; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the PostInitialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(hintName, sourceText); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Context passed to a source generator when <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> is called /// </summary> public readonly struct GeneratorExecutionContext { private readonly DiagnosticBag _diagnostics; private readonly AdditionalSourcesCollection _additionalSources; internal GeneratorExecutionContext(Compilation compilation, ParseOptions parseOptions, ImmutableArray<AdditionalText> additionalTexts, AnalyzerConfigOptionsProvider optionsProvider, ISyntaxContextReceiver? syntaxReceiver, string sourceExtension, CancellationToken cancellationToken = default) { Compilation = compilation; ParseOptions = parseOptions; AdditionalFiles = additionalTexts; AnalyzerConfigOptions = optionsProvider; SyntaxReceiver = (syntaxReceiver as SyntaxContextReceiverAdaptor)?.Receiver; SyntaxContextReceiver = (syntaxReceiver is SyntaxContextReceiverAdaptor) ? null : syntaxReceiver; CancellationToken = cancellationToken; _additionalSources = new AdditionalSourcesCollection(sourceExtension); _diagnostics = new DiagnosticBag(); } /// <summary> /// Get the current <see cref="CodeAnalysis.Compilation"/> at the time of execution. /// </summary> /// <remarks> /// This compilation contains only the user supplied code; other generated code is not /// available. As user code can depend on the results of generation, it is possible that /// this compilation will contain errors. /// </remarks> public Compilation Compilation { get; } /// <summary> /// Get the <see cref="CodeAnalysis.ParseOptions"/> that will be used to parse any added sources. /// </summary> public ParseOptions ParseOptions { get; } /// <summary> /// A set of additional non-code text files that can be used by generators. /// </summary> public ImmutableArray<AdditionalText> AdditionalFiles { get; } /// <summary> /// Allows access to options provided by an analyzer config /// </summary> public AnalyzerConfigOptionsProvider AnalyzerConfigOptions { get; } /// <summary> /// If the generator registered an <see cref="ISyntaxReceiver"/> during initialization, this will be the instance created for this generation pass. /// </summary> public ISyntaxReceiver? SyntaxReceiver { get; } /// <summary> /// If the generator registered an <see cref="ISyntaxContextReceiver"/> during initialization, this will be the instance created for this generation pass. /// </summary> public ISyntaxContextReceiver? SyntaxContextReceiver { get; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the generation should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation. /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(hintName, sourceText); /// <summary> /// Adds a <see cref="Diagnostic"/> to the users compilation /// </summary> /// <param name="diagnostic">The diagnostic that should be added to the compilation</param> /// <remarks> /// The severity of the diagnostic may cause the compilation to fail, depending on the <see cref="Compilation"/> settings. /// </remarks> public void ReportDiagnostic(Diagnostic diagnostic) => _diagnostics.Add(diagnostic); internal (ImmutableArray<GeneratedSourceText> sources, ImmutableArray<Diagnostic> diagnostics) ToImmutableAndFree() => (_additionalSources.ToImmutableAndFree(), _diagnostics.ToReadOnlyAndFree()); internal void Free() { _additionalSources.Free(); _diagnostics.Free(); } internal void CopyToProductionContext(SourceProductionContext ctx) { _additionalSources.CopyTo(ctx.Sources); ctx.Diagnostics.AddRange(_diagnostics); } } /// <summary> /// Context passed to a source generator when <see cref="ISourceGenerator.Initialize(GeneratorInitializationContext)"/> is called /// </summary> public struct GeneratorInitializationContext { internal GeneratorInitializationContext(CancellationToken cancellationToken = default) { CancellationToken = cancellationToken; InfoBuilder = new GeneratorInfo.Builder(); } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the initialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } internal GeneratorInfo.Builder InfoBuilder { get; } /// <summary> /// Register a <see cref="SyntaxReceiverCreator"/> for this generator, which can be used to create an instance of an <see cref="ISyntaxReceiver"/>. /// </summary> /// <remarks> /// This method allows generators to be 'syntax aware'. Before each generation the <paramref name="receiverCreator"/> will be invoked to create /// an instance of <see cref="ISyntaxReceiver"/>. This receiver will have its <see cref="ISyntaxReceiver.OnVisitSyntaxNode(SyntaxNode)"/> /// invoked for each syntax node in the compilation, allowing the receiver to build up information about the compilation before generation occurs. /// /// During <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> the generator can obtain the <see cref="ISyntaxReceiver"/> instance that was /// created by accessing the <see cref="GeneratorExecutionContext.SyntaxReceiver"/> property. Any information that was collected by the receiver can be /// used to generate the final output. /// /// A new instance of <see cref="ISyntaxReceiver"/> is created per-generation, meaning there is no need to manage the lifetime of the /// receiver or its contents. /// </remarks> /// <param name="receiverCreator">A <see cref="SyntaxReceiverCreator"/> that can be invoked to create an instance of <see cref="ISyntaxReceiver"/></param> public void RegisterForSyntaxNotifications(SyntaxReceiverCreator receiverCreator) { CheckIsEmpty(InfoBuilder.SyntaxContextReceiverCreator, $"{nameof(SyntaxReceiverCreator)} / {nameof(SyntaxContextReceiverCreator)}"); InfoBuilder.SyntaxContextReceiverCreator = SyntaxContextReceiverAdaptor.Create(receiverCreator); } /// <summary> /// Register a <see cref="SyntaxContextReceiverCreator"/> for this generator, which can be used to create an instance of an <see cref="ISyntaxContextReceiver"/>. /// </summary> /// <remarks> /// This method allows generators to be 'syntax aware'. Before each generation the <paramref name="receiverCreator"/> will be invoked to create /// an instance of <see cref="ISyntaxContextReceiver"/>. This receiver will have its <see cref="ISyntaxContextReceiver.OnVisitSyntaxNode(GeneratorSyntaxContext)"/> /// invoked for each syntax node in the compilation, allowing the receiver to build up information about the compilation before generation occurs. /// /// During <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> the generator can obtain the <see cref="ISyntaxContextReceiver"/> instance that was /// created by accessing the <see cref="GeneratorExecutionContext.SyntaxContextReceiver"/> property. Any information that was collected by the receiver can be /// used to generate the final output. /// /// A new instance of <see cref="ISyntaxContextReceiver"/> is created prior to every call to <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/>, /// meaning there is no need to manage the lifetime of the receiver or its contents. /// </remarks> /// <param name="receiverCreator">A <see cref="SyntaxContextReceiverCreator"/> that can be invoked to create an instance of <see cref="ISyntaxContextReceiver"/></param> public void RegisterForSyntaxNotifications(SyntaxContextReceiverCreator receiverCreator) { CheckIsEmpty(InfoBuilder.SyntaxContextReceiverCreator, $"{nameof(SyntaxReceiverCreator)} / {nameof(SyntaxContextReceiverCreator)}"); InfoBuilder.SyntaxContextReceiverCreator = receiverCreator; } /// <summary> /// Register a callback that is invoked after initialization. /// </summary> /// <remarks> /// This method allows a generator to opt-in to an extra phase in the generator lifecycle called PostInitialization. After being initialized /// any generators that have opted in will have their provided callback invoked with a <see cref="GeneratorPostInitializationContext"/> instance /// that can be used to alter the compilation that is provided to subsequent generator phases. /// /// For example a generator may choose to add sources during PostInitialization. These will be added to the compilation before execution and /// will be visited by a registered <see cref="ISyntaxReceiver"/> and available for semantic analysis as part of the <see cref="GeneratorExecutionContext.Compilation"/> /// /// Note that any sources added during PostInitialization <i>will</i> be visible to the later phases of other generators operating on the compilation. /// </remarks> /// <param name="callback">An <see cref="Action{T}"/> that accepts a <see cref="GeneratorPostInitializationContext"/> that will be invoked after initialization.</param> public void RegisterForPostInitialization(Action<GeneratorPostInitializationContext> callback) { CheckIsEmpty(InfoBuilder.PostInitCallback); InfoBuilder.PostInitCallback = (context) => callback(new GeneratorPostInitializationContext(context.AdditionalSources, context.CancellationToken)); } private static void CheckIsEmpty<T>(T x, string? typeName = null) where T : class? { if (x is object) { throw new InvalidOperationException(string.Format(CodeAnalysisResources.Single_type_per_generator_0, typeName ?? typeof(T).Name)); } } } /// <summary> /// Context passed to an <see cref="ISyntaxContextReceiver"/> when <see cref="ISyntaxContextReceiver.OnVisitSyntaxNode(GeneratorSyntaxContext)"/> is called /// </summary> public readonly struct GeneratorSyntaxContext { internal GeneratorSyntaxContext(SyntaxNode node, SemanticModel semanticModel) { Node = node; SemanticModel = semanticModel; } /// <summary> /// The <see cref="SyntaxNode"/> currently being visited /// </summary> public SyntaxNode Node { get; } /// <summary> /// The <see cref="CodeAnalysis.SemanticModel" /> that can be queried to obtain information about <see cref="Node"/>. /// </summary> public SemanticModel SemanticModel { get; } } /// <summary> /// Context passed to a source generator when it has opted-in to PostInitialization via <see cref="GeneratorInitializationContext.RegisterForPostInitialization(Action{GeneratorPostInitializationContext})"/> /// </summary> public readonly struct GeneratorPostInitializationContext { private readonly AdditionalSourcesCollection _additionalSources; internal GeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) { _additionalSources = additionalSources; CancellationToken = cancellationToken; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the PostInitialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(hintName, sourceText); } }
1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/SourceGeneration/GeneratorDriver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Responsible for orchestrating a source generation pass /// </summary> /// <remarks> /// GeneratorDriver is an immutable class that can be manipulated by returning a mutated copy of itself. /// In the compiler we only ever create a single instance and ignore the mutated copy. The IDE may perform /// multiple edits, or generation passes of the same driver, re-using the state as needed. /// </remarks> public abstract class GeneratorDriver { internal readonly GeneratorDriverState _state; internal GeneratorDriver(GeneratorDriverState state) { Debug.Assert(state.Generators.GroupBy(s => s.GetGeneratorType()).Count() == state.Generators.Length); // ensure we don't have duplicate generator types _state = state; } internal GeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, GeneratorDriverOptions driverOptions) { (var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators); _state = new GeneratorDriverState(parseOptions, optionsProvider, filteredGenerators, incrementalGenerators, additionalTexts, ImmutableArray.Create(new GeneratorState[filteredGenerators.Length]), DriverStateTable.Empty, driverOptions.DisabledOutputs); } public GeneratorDriver RunGenerators(Compilation compilation, CancellationToken cancellationToken = default) { var state = RunGeneratorsCore(compilation, diagnosticsBag: null, cancellationToken); //don't directly collect diagnostics on this path return FromState(state); } public GeneratorDriver RunGeneratorsAndUpdateCompilation(Compilation compilation, out Compilation outputCompilation, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken = default) { var diagnosticsBag = DiagnosticBag.GetInstance(); var state = RunGeneratorsCore(compilation, diagnosticsBag, cancellationToken); // build the output compilation diagnostics = diagnosticsBag.ToReadOnlyAndFree(); ArrayBuilder<SyntaxTree> trees = ArrayBuilder<SyntaxTree>.GetInstance(); foreach (var generatorState in state.GeneratorStates) { trees.AddRange(generatorState.PostInitTrees.Select(t => t.Tree)); trees.AddRange(generatorState.GeneratedTrees.Select(t => t.Tree)); } outputCompilation = compilation.AddSyntaxTrees(trees); trees.Free(); return FromState(state); } public GeneratorDriver AddGenerators(ImmutableArray<ISourceGenerator> generators) { (var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators); var newState = _state.With(sourceGenerators: _state.Generators.AddRange(filteredGenerators), incrementalGenerators: _state.IncrementalGenerators.AddRange(incrementalGenerators), generatorStates: _state.GeneratorStates.AddRange(new GeneratorState[filteredGenerators.Length])); return FromState(newState); } public GeneratorDriver RemoveGenerators(ImmutableArray<ISourceGenerator> generators) { var newGenerators = _state.Generators; var newStates = _state.GeneratorStates; var newIncrementalGenerators = _state.IncrementalGenerators; for (int i = 0; i < newGenerators.Length; i++) { if (generators.Contains(newGenerators[i])) { newGenerators = newGenerators.RemoveAt(i); newStates = newStates.RemoveAt(i); newIncrementalGenerators = newIncrementalGenerators.RemoveAt(i); i--; } } return FromState(_state.With(sourceGenerators: newGenerators, incrementalGenerators: newIncrementalGenerators, generatorStates: newStates)); } public GeneratorDriver AddAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts) { var newState = _state.With(additionalTexts: _state.AdditionalTexts.AddRange(additionalTexts)); return FromState(newState); } public GeneratorDriver RemoveAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts) { var newState = _state.With(additionalTexts: _state.AdditionalTexts.RemoveRange(additionalTexts)); return FromState(newState); } public GeneratorDriver ReplaceAdditionalText(AdditionalText oldText, AdditionalText newText) { if (oldText is null) { throw new ArgumentNullException(nameof(oldText)); } if (newText is null) { throw new ArgumentNullException(nameof(newText)); } var newState = _state.With(additionalTexts: _state.AdditionalTexts.Replace(oldText, newText)); return FromState(newState); } public GeneratorDriver WithUpdatedParseOptions(ParseOptions newOptions) => newOptions is object ? FromState(_state.With(parseOptions: newOptions)) : throw new ArgumentNullException(nameof(newOptions)); public GeneratorDriver WithUpdatedAnalyzerConfigOptions(AnalyzerConfigOptionsProvider newOptions) => newOptions is object ? FromState(_state.With(optionsProvider: newOptions)) : throw new ArgumentNullException(nameof(newOptions)); public GeneratorDriverRunResult GetRunResult() { var results = _state.Generators.ZipAsArray( _state.GeneratorStates, (generator, generatorState) => new GeneratorRunResult(generator, diagnostics: generatorState.Diagnostics, exception: generatorState.Exception, generatedSources: getGeneratorSources(generatorState))); return new GeneratorDriverRunResult(results); static ImmutableArray<GeneratedSourceResult> getGeneratorSources(GeneratorState generatorState) { ArrayBuilder<GeneratedSourceResult> sources = ArrayBuilder<GeneratedSourceResult>.GetInstance(generatorState.PostInitTrees.Length + generatorState.GeneratedTrees.Length); foreach (var tree in generatorState.PostInitTrees) { sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName)); } foreach (var tree in generatorState.GeneratedTrees) { sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName)); } return sources.ToImmutableAndFree(); } } internal GeneratorDriverState RunGeneratorsCore(Compilation compilation, DiagnosticBag? diagnosticsBag, CancellationToken cancellationToken = default) { // with no generators, there is no work to do if (_state.Generators.IsEmpty) { return _state.With(stateTable: DriverStateTable.Empty); } // run the actual generation var state = _state; var stateBuilder = ArrayBuilder<GeneratorState>.GetInstance(state.Generators.Length); var constantSourcesBuilder = ArrayBuilder<SyntaxTree>.GetInstance(); var syntaxInputNodes = ArrayBuilder<ISyntaxInputNode>.GetInstance(); for (int i = 0; i < state.IncrementalGenerators.Length; i++) { var generator = state.IncrementalGenerators[i]; var generatorState = state.GeneratorStates[i]; var sourceGenerator = state.Generators[i]; // initialize the generator if needed if (!generatorState.Initialized) { var outputBuilder = ArrayBuilder<IIncrementalGeneratorOutputNode>.GetInstance(); var inputBuilder = ArrayBuilder<ISyntaxInputNode>.GetInstance(); var postInitSources = ImmutableArray<GeneratedSyntaxTree>.Empty; var pipelineContext = new IncrementalGeneratorInitializationContext(inputBuilder, outputBuilder); Exception? ex = null; try { generator.Initialize(pipelineContext); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { ex = e; } var outputNodes = outputBuilder.ToImmutableAndFree(); var inputNodes = inputBuilder.ToImmutableAndFree(); // run post init if (ex is null) { try { IncrementalExecutionContext context = UpdateOutputs(outputNodes, IncrementalGeneratorOutputKind.PostInit, cancellationToken); postInitSources = ParseAdditionalSources(sourceGenerator, context.ToImmutableAndFree().sources, cancellationToken); } catch (UserFunctionException e) { ex = e.InnerException; } } generatorState = ex is null ? new GeneratorState(generatorState.Info, postInitSources, inputNodes, outputNodes) : SetGeneratorException(MessageProvider, generatorState, sourceGenerator, ex, diagnosticsBag, isInit: true); } // if the pipeline registered any syntax input nodes, record them if (!generatorState.InputNodes.IsEmpty) { syntaxInputNodes.AddRange(generatorState.InputNodes); } // record any constant sources if (generatorState.Exception is null && generatorState.PostInitTrees.Length > 0) { constantSourcesBuilder.AddRange(generatorState.PostInitTrees.Select(t => t.Tree)); } stateBuilder.Add(generatorState); } // update the compilation with any constant sources if (constantSourcesBuilder.Count > 0) { compilation = compilation.AddSyntaxTrees(constantSourcesBuilder); } constantSourcesBuilder.Free(); var driverStateBuilder = new DriverStateTable.Builder(compilation, _state, syntaxInputNodes.ToImmutableAndFree(), cancellationToken); for (int i = 0; i < state.IncrementalGenerators.Length; i++) { var generatorState = stateBuilder[i]; if (generatorState.Exception is object) { continue; } try { var context = UpdateOutputs(generatorState.OutputNodes, IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation, cancellationToken, driverStateBuilder); (var sources, var generatorDiagnostics) = context.ToImmutableAndFree(); generatorDiagnostics = FilterDiagnostics(compilation, generatorDiagnostics, driverDiagnostics: diagnosticsBag, cancellationToken); stateBuilder[i] = new GeneratorState(generatorState.Info, generatorState.PostInitTrees, generatorState.InputNodes, generatorState.OutputNodes, ParseAdditionalSources(state.Generators[i], sources, cancellationToken), generatorDiagnostics); } catch (UserFunctionException ufe) { stateBuilder[i] = SetGeneratorException(MessageProvider, stateBuilder[i], state.Generators[i], ufe.InnerException, diagnosticsBag); } } state = state.With(stateTable: driverStateBuilder.ToImmutable(), generatorStates: stateBuilder.ToImmutableAndFree()); return state; } private IncrementalExecutionContext UpdateOutputs(ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, IncrementalGeneratorOutputKind outputKind, CancellationToken cancellationToken, DriverStateTable.Builder? driverStateBuilder = null) { Debug.Assert(outputKind != IncrementalGeneratorOutputKind.None); IncrementalExecutionContext context = new IncrementalExecutionContext(driverStateBuilder, CreateSourcesCollection()); foreach (var outputNode in outputNodes) { // if we're looking for this output kind, and it has not been explicitly disabled if (outputKind.HasFlag(outputNode.Kind) && !_state.DisabledOutputs.HasFlag(outputNode.Kind)) { outputNode.AppendOutputs(context, cancellationToken); } } return context; } private ImmutableArray<GeneratedSyntaxTree> ParseAdditionalSources(ISourceGenerator generator, ImmutableArray<GeneratedSourceText> generatedSources, CancellationToken cancellationToken) { var trees = ArrayBuilder<GeneratedSyntaxTree>.GetInstance(generatedSources.Length); var type = generator.GetGeneratorType(); var prefix = GetFilePathPrefixForGenerator(generator); foreach (var source in generatedSources) { var tree = ParseGeneratedSourceText(source, Path.Combine(prefix, source.HintName), cancellationToken); trees.Add(new GeneratedSyntaxTree(source.HintName, source.Text, tree)); } return trees.ToImmutableAndFree(); } private static GeneratorState SetGeneratorException(CommonMessageProvider provider, GeneratorState generatorState, ISourceGenerator generator, Exception e, DiagnosticBag? diagnosticBag, bool isInit = false) { var errorCode = isInit ? provider.WRN_GeneratorFailedDuringInitialization : provider.WRN_GeneratorFailedDuringGeneration; // ISSUE: Diagnostics don't currently allow descriptions with arguments, so we have to manually create the diagnostic description // ISSUE: Exceptions also don't support IFormattable, so will always be in the current UI Culture. // ISSUE: See https://github.com/dotnet/roslyn/issues/46939 var description = string.Format(provider.GetDescription(errorCode).ToString(CultureInfo.CurrentUICulture), e); var descriptor = new DiagnosticDescriptor( provider.GetIdForErrorCode(errorCode), provider.GetTitle(errorCode), provider.GetMessageFormat(errorCode), description: description, category: "Compiler", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.AnalyzerException); var diagnostic = Diagnostic.Create(descriptor, Location.None, generator.GetGeneratorType().Name, e.GetType().Name, e.Message); diagnosticBag?.Add(diagnostic); return new GeneratorState(generatorState.Info, e, diagnostic); } private static ImmutableArray<Diagnostic> FilterDiagnostics(Compilation compilation, ImmutableArray<Diagnostic> generatorDiagnostics, DiagnosticBag? driverDiagnostics, CancellationToken cancellationToken) { ArrayBuilder<Diagnostic> filteredDiagnostics = ArrayBuilder<Diagnostic>.GetInstance(); foreach (var diag in generatorDiagnostics) { var filtered = compilation.Options.FilterDiagnostic(diag, cancellationToken); if (filtered is object) { filteredDiagnostics.Add(filtered); driverDiagnostics?.Add(filtered); } } return filteredDiagnostics.ToImmutableAndFree(); } internal static string GetFilePathPrefixForGenerator(ISourceGenerator generator) { var type = generator.GetGeneratorType(); return Path.Combine(type.Assembly.GetName().Name ?? string.Empty, type.FullName!); } private static (ImmutableArray<ISourceGenerator>, ImmutableArray<IIncrementalGenerator>) GetIncrementalGenerators(ImmutableArray<ISourceGenerator> generators) { return (generators, generators.SelectAsArray(g => g switch { IncrementalGeneratorWrapper igw => igw.Generator, IIncrementalGenerator ig => ig, _ => new SourceGeneratorAdaptor(g) })); } internal abstract CommonMessageProvider MessageProvider { get; } internal abstract GeneratorDriver FromState(GeneratorDriverState state); internal abstract SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken); internal abstract AdditionalSourcesCollection CreateSourcesCollection(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Responsible for orchestrating a source generation pass /// </summary> /// <remarks> /// GeneratorDriver is an immutable class that can be manipulated by returning a mutated copy of itself. /// In the compiler we only ever create a single instance and ignore the mutated copy. The IDE may perform /// multiple edits, or generation passes of the same driver, re-using the state as needed. /// </remarks> public abstract class GeneratorDriver { internal readonly GeneratorDriverState _state; internal GeneratorDriver(GeneratorDriverState state) { Debug.Assert(state.Generators.GroupBy(s => s.GetGeneratorType()).Count() == state.Generators.Length); // ensure we don't have duplicate generator types _state = state; } internal GeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, GeneratorDriverOptions driverOptions) { (var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators, SourceExtension); _state = new GeneratorDriverState(parseOptions, optionsProvider, filteredGenerators, incrementalGenerators, additionalTexts, ImmutableArray.Create(new GeneratorState[filteredGenerators.Length]), DriverStateTable.Empty, driverOptions.DisabledOutputs); } public GeneratorDriver RunGenerators(Compilation compilation, CancellationToken cancellationToken = default) { var state = RunGeneratorsCore(compilation, diagnosticsBag: null, cancellationToken); //don't directly collect diagnostics on this path return FromState(state); } public GeneratorDriver RunGeneratorsAndUpdateCompilation(Compilation compilation, out Compilation outputCompilation, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken = default) { var diagnosticsBag = DiagnosticBag.GetInstance(); var state = RunGeneratorsCore(compilation, diagnosticsBag, cancellationToken); // build the output compilation diagnostics = diagnosticsBag.ToReadOnlyAndFree(); ArrayBuilder<SyntaxTree> trees = ArrayBuilder<SyntaxTree>.GetInstance(); foreach (var generatorState in state.GeneratorStates) { trees.AddRange(generatorState.PostInitTrees.Select(t => t.Tree)); trees.AddRange(generatorState.GeneratedTrees.Select(t => t.Tree)); } outputCompilation = compilation.AddSyntaxTrees(trees); trees.Free(); return FromState(state); } public GeneratorDriver AddGenerators(ImmutableArray<ISourceGenerator> generators) { (var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators, SourceExtension); var newState = _state.With(sourceGenerators: _state.Generators.AddRange(filteredGenerators), incrementalGenerators: _state.IncrementalGenerators.AddRange(incrementalGenerators), generatorStates: _state.GeneratorStates.AddRange(new GeneratorState[filteredGenerators.Length])); return FromState(newState); } public GeneratorDriver RemoveGenerators(ImmutableArray<ISourceGenerator> generators) { var newGenerators = _state.Generators; var newStates = _state.GeneratorStates; var newIncrementalGenerators = _state.IncrementalGenerators; for (int i = 0; i < newGenerators.Length; i++) { if (generators.Contains(newGenerators[i])) { newGenerators = newGenerators.RemoveAt(i); newStates = newStates.RemoveAt(i); newIncrementalGenerators = newIncrementalGenerators.RemoveAt(i); i--; } } return FromState(_state.With(sourceGenerators: newGenerators, incrementalGenerators: newIncrementalGenerators, generatorStates: newStates)); } public GeneratorDriver AddAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts) { var newState = _state.With(additionalTexts: _state.AdditionalTexts.AddRange(additionalTexts)); return FromState(newState); } public GeneratorDriver RemoveAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts) { var newState = _state.With(additionalTexts: _state.AdditionalTexts.RemoveRange(additionalTexts)); return FromState(newState); } public GeneratorDriver ReplaceAdditionalText(AdditionalText oldText, AdditionalText newText) { if (oldText is null) { throw new ArgumentNullException(nameof(oldText)); } if (newText is null) { throw new ArgumentNullException(nameof(newText)); } var newState = _state.With(additionalTexts: _state.AdditionalTexts.Replace(oldText, newText)); return FromState(newState); } public GeneratorDriver WithUpdatedParseOptions(ParseOptions newOptions) => newOptions is object ? FromState(_state.With(parseOptions: newOptions)) : throw new ArgumentNullException(nameof(newOptions)); public GeneratorDriver WithUpdatedAnalyzerConfigOptions(AnalyzerConfigOptionsProvider newOptions) => newOptions is object ? FromState(_state.With(optionsProvider: newOptions)) : throw new ArgumentNullException(nameof(newOptions)); public GeneratorDriverRunResult GetRunResult() { var results = _state.Generators.ZipAsArray( _state.GeneratorStates, (generator, generatorState) => new GeneratorRunResult(generator, diagnostics: generatorState.Diagnostics, exception: generatorState.Exception, generatedSources: getGeneratorSources(generatorState))); return new GeneratorDriverRunResult(results); static ImmutableArray<GeneratedSourceResult> getGeneratorSources(GeneratorState generatorState) { ArrayBuilder<GeneratedSourceResult> sources = ArrayBuilder<GeneratedSourceResult>.GetInstance(generatorState.PostInitTrees.Length + generatorState.GeneratedTrees.Length); foreach (var tree in generatorState.PostInitTrees) { sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName)); } foreach (var tree in generatorState.GeneratedTrees) { sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName)); } return sources.ToImmutableAndFree(); } } internal GeneratorDriverState RunGeneratorsCore(Compilation compilation, DiagnosticBag? diagnosticsBag, CancellationToken cancellationToken = default) { // with no generators, there is no work to do if (_state.Generators.IsEmpty) { return _state.With(stateTable: DriverStateTable.Empty); } // run the actual generation var state = _state; var stateBuilder = ArrayBuilder<GeneratorState>.GetInstance(state.Generators.Length); var constantSourcesBuilder = ArrayBuilder<SyntaxTree>.GetInstance(); var syntaxInputNodes = ArrayBuilder<ISyntaxInputNode>.GetInstance(); for (int i = 0; i < state.IncrementalGenerators.Length; i++) { var generator = state.IncrementalGenerators[i]; var generatorState = state.GeneratorStates[i]; var sourceGenerator = state.Generators[i]; // initialize the generator if needed if (!generatorState.Initialized) { var outputBuilder = ArrayBuilder<IIncrementalGeneratorOutputNode>.GetInstance(); var inputBuilder = ArrayBuilder<ISyntaxInputNode>.GetInstance(); var postInitSources = ImmutableArray<GeneratedSyntaxTree>.Empty; var pipelineContext = new IncrementalGeneratorInitializationContext(inputBuilder, outputBuilder, SourceExtension); Exception? ex = null; try { generator.Initialize(pipelineContext); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { ex = e; } var outputNodes = outputBuilder.ToImmutableAndFree(); var inputNodes = inputBuilder.ToImmutableAndFree(); // run post init if (ex is null) { try { IncrementalExecutionContext context = UpdateOutputs(outputNodes, IncrementalGeneratorOutputKind.PostInit, cancellationToken); postInitSources = ParseAdditionalSources(sourceGenerator, context.ToImmutableAndFree().sources, cancellationToken); } catch (UserFunctionException e) { ex = e.InnerException; } } generatorState = ex is null ? new GeneratorState(generatorState.Info, postInitSources, inputNodes, outputNodes) : SetGeneratorException(MessageProvider, generatorState, sourceGenerator, ex, diagnosticsBag, isInit: true); } // if the pipeline registered any syntax input nodes, record them if (!generatorState.InputNodes.IsEmpty) { syntaxInputNodes.AddRange(generatorState.InputNodes); } // record any constant sources if (generatorState.Exception is null && generatorState.PostInitTrees.Length > 0) { constantSourcesBuilder.AddRange(generatorState.PostInitTrees.Select(t => t.Tree)); } stateBuilder.Add(generatorState); } // update the compilation with any constant sources if (constantSourcesBuilder.Count > 0) { compilation = compilation.AddSyntaxTrees(constantSourcesBuilder); } constantSourcesBuilder.Free(); var driverStateBuilder = new DriverStateTable.Builder(compilation, _state, syntaxInputNodes.ToImmutableAndFree(), cancellationToken); for (int i = 0; i < state.IncrementalGenerators.Length; i++) { var generatorState = stateBuilder[i]; if (generatorState.Exception is object) { continue; } try { var context = UpdateOutputs(generatorState.OutputNodes, IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation, cancellationToken, driverStateBuilder); (var sources, var generatorDiagnostics) = context.ToImmutableAndFree(); generatorDiagnostics = FilterDiagnostics(compilation, generatorDiagnostics, driverDiagnostics: diagnosticsBag, cancellationToken); stateBuilder[i] = new GeneratorState(generatorState.Info, generatorState.PostInitTrees, generatorState.InputNodes, generatorState.OutputNodes, ParseAdditionalSources(state.Generators[i], sources, cancellationToken), generatorDiagnostics); } catch (UserFunctionException ufe) { stateBuilder[i] = SetGeneratorException(MessageProvider, stateBuilder[i], state.Generators[i], ufe.InnerException, diagnosticsBag); } } state = state.With(stateTable: driverStateBuilder.ToImmutable(), generatorStates: stateBuilder.ToImmutableAndFree()); return state; } private IncrementalExecutionContext UpdateOutputs(ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, IncrementalGeneratorOutputKind outputKind, CancellationToken cancellationToken, DriverStateTable.Builder? driverStateBuilder = null) { Debug.Assert(outputKind != IncrementalGeneratorOutputKind.None); IncrementalExecutionContext context = new IncrementalExecutionContext(driverStateBuilder, new AdditionalSourcesCollection(SourceExtension)); foreach (var outputNode in outputNodes) { // if we're looking for this output kind, and it has not been explicitly disabled if (outputKind.HasFlag(outputNode.Kind) && !_state.DisabledOutputs.HasFlag(outputNode.Kind)) { outputNode.AppendOutputs(context, cancellationToken); } } return context; } private ImmutableArray<GeneratedSyntaxTree> ParseAdditionalSources(ISourceGenerator generator, ImmutableArray<GeneratedSourceText> generatedSources, CancellationToken cancellationToken) { var trees = ArrayBuilder<GeneratedSyntaxTree>.GetInstance(generatedSources.Length); var type = generator.GetGeneratorType(); var prefix = GetFilePathPrefixForGenerator(generator); foreach (var source in generatedSources) { var tree = ParseGeneratedSourceText(source, Path.Combine(prefix, source.HintName), cancellationToken); trees.Add(new GeneratedSyntaxTree(source.HintName, source.Text, tree)); } return trees.ToImmutableAndFree(); } private static GeneratorState SetGeneratorException(CommonMessageProvider provider, GeneratorState generatorState, ISourceGenerator generator, Exception e, DiagnosticBag? diagnosticBag, bool isInit = false) { var errorCode = isInit ? provider.WRN_GeneratorFailedDuringInitialization : provider.WRN_GeneratorFailedDuringGeneration; // ISSUE: Diagnostics don't currently allow descriptions with arguments, so we have to manually create the diagnostic description // ISSUE: Exceptions also don't support IFormattable, so will always be in the current UI Culture. // ISSUE: See https://github.com/dotnet/roslyn/issues/46939 var description = string.Format(provider.GetDescription(errorCode).ToString(CultureInfo.CurrentUICulture), e); var descriptor = new DiagnosticDescriptor( provider.GetIdForErrorCode(errorCode), provider.GetTitle(errorCode), provider.GetMessageFormat(errorCode), description: description, category: "Compiler", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.AnalyzerException); var diagnostic = Diagnostic.Create(descriptor, Location.None, generator.GetGeneratorType().Name, e.GetType().Name, e.Message); diagnosticBag?.Add(diagnostic); return new GeneratorState(generatorState.Info, e, diagnostic); } private static ImmutableArray<Diagnostic> FilterDiagnostics(Compilation compilation, ImmutableArray<Diagnostic> generatorDiagnostics, DiagnosticBag? driverDiagnostics, CancellationToken cancellationToken) { ArrayBuilder<Diagnostic> filteredDiagnostics = ArrayBuilder<Diagnostic>.GetInstance(); foreach (var diag in generatorDiagnostics) { var filtered = compilation.Options.FilterDiagnostic(diag, cancellationToken); if (filtered is object) { filteredDiagnostics.Add(filtered); driverDiagnostics?.Add(filtered); } } return filteredDiagnostics.ToImmutableAndFree(); } internal static string GetFilePathPrefixForGenerator(ISourceGenerator generator) { var type = generator.GetGeneratorType(); return Path.Combine(type.Assembly.GetName().Name ?? string.Empty, type.FullName!); } private static (ImmutableArray<ISourceGenerator>, ImmutableArray<IIncrementalGenerator>) GetIncrementalGenerators(ImmutableArray<ISourceGenerator> generators, string sourceExtension) { return (generators, generators.SelectAsArray(g => g switch { IncrementalGeneratorWrapper igw => igw.Generator, IIncrementalGenerator ig => ig, _ => new SourceGeneratorAdaptor(g, sourceExtension) })); } internal abstract CommonMessageProvider MessageProvider { get; } internal abstract GeneratorDriver FromState(GeneratorDriverState state); internal abstract SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken); internal abstract string SourceExtension { get; } } }
1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/SourceGeneration/IncrementalContexts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Context passed to an incremental generator when <see cref="IIncrementalGenerator.Initialize(IncrementalGeneratorInitializationContext)"/> is called /// </summary> public readonly struct IncrementalGeneratorInitializationContext { private readonly ArrayBuilder<ISyntaxInputNode> _syntaxInputBuilder; private readonly ArrayBuilder<IIncrementalGeneratorOutputNode> _outputNodes; internal IncrementalGeneratorInitializationContext(ArrayBuilder<ISyntaxInputNode> syntaxInputBuilder, ArrayBuilder<IIncrementalGeneratorOutputNode> outputNodes) { _syntaxInputBuilder = syntaxInputBuilder; _outputNodes = outputNodes; } public SyntaxValueProvider SyntaxProvider => new SyntaxValueProvider(_syntaxInputBuilder, RegisterOutput); public IncrementalValueProvider<Compilation> CompilationProvider => new IncrementalValueProvider<Compilation>(SharedInputNodes.Compilation.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<ParseOptions> ParseOptionsProvider => new IncrementalValueProvider<ParseOptions>(SharedInputNodes.ParseOptions.WithRegisterOutput(RegisterOutput)); public IncrementalValuesProvider<AdditionalText> AdditionalTextsProvider => new IncrementalValuesProvider<AdditionalText>(SharedInputNodes.AdditionalTexts.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<AnalyzerConfigOptionsProvider> AnalyzerConfigOptionsProvider => new IncrementalValueProvider<AnalyzerConfigOptionsProvider>(SharedInputNodes.AnalyzerConfigOptions.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<MetadataReference> MetadataReferencesProvider => new IncrementalValueProvider<MetadataReference>(SharedInputNodes.MetadataReferences.WithRegisterOutput(RegisterOutput)); public void RegisterSourceOutput<TSource>(IncrementalValueProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source); public void RegisterSourceOutput<TSource>(IncrementalValuesProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source); public void RegisterImplementationSourceOutput<TSource>(IncrementalValueProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation); public void RegisterImplementationSourceOutput<TSource>(IncrementalValuesProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation); public void RegisterPostInitializationOutput(Action<IncrementalGeneratorPostInitializationContext> callback) => _outputNodes.Add(new PostInitOutputNode(callback.WrapUserAction())); private void RegisterOutput(IIncrementalGeneratorOutputNode outputNode) { if (!_outputNodes.Contains(outputNode)) { _outputNodes.Add(outputNode); } } private static void RegisterSourceOutput<TSource>(IIncrementalGeneratorNode<TSource> node, Action<SourceProductionContext, TSource> action, IncrementalGeneratorOutputKind kind) { node.RegisterOutput(new SourceOutputNode<TSource>(node, action.WrapUserAction(), kind)); } } /// <summary> /// Context passed to an incremental generator when it has registered an output via <see cref="IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(Action{IncrementalGeneratorPostInitializationContext})"/> /// </summary> public readonly struct IncrementalGeneratorPostInitializationContext { internal readonly AdditionalSourcesCollection AdditionalSources; internal IncrementalGeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) { AdditionalSources = additionalSources; CancellationToken = cancellationToken; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the PostInitialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => AdditionalSources.Add(hintName, sourceText); } /// <summary> /// Context passed to an incremental generator when it has registered an output via <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> public readonly struct SourceProductionContext { internal readonly ArrayBuilder<GeneratedSourceText> Sources; internal readonly DiagnosticBag Diagnostics; internal SourceProductionContext(ArrayBuilder<GeneratedSourceText> sources, DiagnosticBag diagnostics, CancellationToken cancellationToken) { CancellationToken = cancellationToken; Sources = sources; Diagnostics = diagnostics; } public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation. /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => Sources.Add(new GeneratedSourceText(hintName, sourceText)); /// <summary> /// Adds a <see cref="Diagnostic"/> to the users compilation /// </summary> /// <param name="diagnostic">The diagnostic that should be added to the compilation</param> /// <remarks> /// The severity of the diagnostic may cause the compilation to fail, depending on the <see cref="Compilation"/> settings. /// </remarks> public void ReportDiagnostic(Diagnostic diagnostic) => Diagnostics.Add(diagnostic); } // https://github.com/dotnet/roslyn/issues/53608 right now we only support generating source + diagnostics, but actively want to support generation of other things internal readonly struct IncrementalExecutionContext { internal readonly DiagnosticBag Diagnostics; internal readonly AdditionalSourcesCollection Sources; internal readonly DriverStateTable.Builder? TableBuilder; public IncrementalExecutionContext(DriverStateTable.Builder? tableBuilder, AdditionalSourcesCollection sources) { TableBuilder = tableBuilder; Sources = sources; Diagnostics = DiagnosticBag.GetInstance(); } internal (ImmutableArray<GeneratedSourceText> sources, ImmutableArray<Diagnostic> diagnostics) ToImmutableAndFree() => (Sources.ToImmutableAndFree(), Diagnostics.ToReadOnlyAndFree()); internal void Free() { Sources.Free(); Diagnostics.Free(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Context passed to an incremental generator when <see cref="IIncrementalGenerator.Initialize(IncrementalGeneratorInitializationContext)"/> is called /// </summary> public readonly struct IncrementalGeneratorInitializationContext { private readonly ArrayBuilder<ISyntaxInputNode> _syntaxInputBuilder; private readonly ArrayBuilder<IIncrementalGeneratorOutputNode> _outputNodes; private readonly string _sourceExtension; internal IncrementalGeneratorInitializationContext(ArrayBuilder<ISyntaxInputNode> syntaxInputBuilder, ArrayBuilder<IIncrementalGeneratorOutputNode> outputNodes, string sourceExtension) { _syntaxInputBuilder = syntaxInputBuilder; _outputNodes = outputNodes; _sourceExtension = sourceExtension; } public SyntaxValueProvider SyntaxProvider => new SyntaxValueProvider(_syntaxInputBuilder, RegisterOutput); public IncrementalValueProvider<Compilation> CompilationProvider => new IncrementalValueProvider<Compilation>(SharedInputNodes.Compilation.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<ParseOptions> ParseOptionsProvider => new IncrementalValueProvider<ParseOptions>(SharedInputNodes.ParseOptions.WithRegisterOutput(RegisterOutput)); public IncrementalValuesProvider<AdditionalText> AdditionalTextsProvider => new IncrementalValuesProvider<AdditionalText>(SharedInputNodes.AdditionalTexts.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<AnalyzerConfigOptionsProvider> AnalyzerConfigOptionsProvider => new IncrementalValueProvider<AnalyzerConfigOptionsProvider>(SharedInputNodes.AnalyzerConfigOptions.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<MetadataReference> MetadataReferencesProvider => new IncrementalValueProvider<MetadataReference>(SharedInputNodes.MetadataReferences.WithRegisterOutput(RegisterOutput)); public void RegisterSourceOutput<TSource>(IncrementalValueProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source, _sourceExtension); public void RegisterSourceOutput<TSource>(IncrementalValuesProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source, _sourceExtension); public void RegisterImplementationSourceOutput<TSource>(IncrementalValueProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation, _sourceExtension); public void RegisterImplementationSourceOutput<TSource>(IncrementalValuesProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation, _sourceExtension); public void RegisterPostInitializationOutput(Action<IncrementalGeneratorPostInitializationContext> callback) => _outputNodes.Add(new PostInitOutputNode(callback.WrapUserAction())); private void RegisterOutput(IIncrementalGeneratorOutputNode outputNode) { if (!_outputNodes.Contains(outputNode)) { _outputNodes.Add(outputNode); } } private static void RegisterSourceOutput<TSource>(IIncrementalGeneratorNode<TSource> node, Action<SourceProductionContext, TSource> action, IncrementalGeneratorOutputKind kind, string sourceExt) { node.RegisterOutput(new SourceOutputNode<TSource>(node, action.WrapUserAction(), kind, sourceExt)); } } /// <summary> /// Context passed to an incremental generator when it has registered an output via <see cref="IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(Action{IncrementalGeneratorPostInitializationContext})"/> /// </summary> public readonly struct IncrementalGeneratorPostInitializationContext { internal readonly AdditionalSourcesCollection AdditionalSources; internal IncrementalGeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) { AdditionalSources = additionalSources; CancellationToken = cancellationToken; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the PostInitialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => AdditionalSources.Add(hintName, sourceText); } /// <summary> /// Context passed to an incremental generator when it has registered an output via <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> public readonly struct SourceProductionContext { internal readonly AdditionalSourcesCollection Sources; internal readonly DiagnosticBag Diagnostics; internal SourceProductionContext(AdditionalSourcesCollection sources, DiagnosticBag diagnostics, CancellationToken cancellationToken) { CancellationToken = cancellationToken; Sources = sources; Diagnostics = diagnostics; } public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation. /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => Sources.Add(hintName, sourceText); /// <summary> /// Adds a <see cref="Diagnostic"/> to the users compilation /// </summary> /// <param name="diagnostic">The diagnostic that should be added to the compilation</param> /// <remarks> /// The severity of the diagnostic may cause the compilation to fail, depending on the <see cref="Compilation"/> settings. /// </remarks> public void ReportDiagnostic(Diagnostic diagnostic) => Diagnostics.Add(diagnostic); } // https://github.com/dotnet/roslyn/issues/53608 right now we only support generating source + diagnostics, but actively want to support generation of other things internal readonly struct IncrementalExecutionContext { internal readonly DiagnosticBag Diagnostics; internal readonly AdditionalSourcesCollection Sources; internal readonly DriverStateTable.Builder? TableBuilder; public IncrementalExecutionContext(DriverStateTable.Builder? tableBuilder, AdditionalSourcesCollection sources) { TableBuilder = tableBuilder; Sources = sources; Diagnostics = DiagnosticBag.GetInstance(); } internal (ImmutableArray<GeneratedSourceText> sources, ImmutableArray<Diagnostic> diagnostics) ToImmutableAndFree() => (Sources.ToImmutableAndFree(), Diagnostics.ToReadOnlyAndFree()); internal void Free() { Sources.Free(); Diagnostics.Free(); } } }
1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/SourceOutputNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using TOutput = System.ValueTuple<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.GeneratedSourceText>, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic>>; namespace Microsoft.CodeAnalysis { internal sealed class SourceOutputNode<TInput> : IIncrementalGeneratorOutputNode, IIncrementalGeneratorNode<TOutput> { private readonly IIncrementalGeneratorNode<TInput> _source; private readonly Action<SourceProductionContext, TInput> _action; private readonly IncrementalGeneratorOutputKind _outputKind; public SourceOutputNode(IIncrementalGeneratorNode<TInput> source, Action<SourceProductionContext, TInput> action, IncrementalGeneratorOutputKind outputKind) { _source = source; _action = action; Debug.Assert(outputKind == IncrementalGeneratorOutputKind.Source || outputKind == IncrementalGeneratorOutputKind.Implementation); _outputKind = outputKind; } public IncrementalGeneratorOutputKind Kind => _outputKind; public NodeStateTable<TOutput> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<TOutput> previousTable, CancellationToken cancellationToken) { var sourceTable = graphState.GetLatestStateTableForNode(_source); if (sourceTable.IsCached) { return previousTable; } var nodeTable = previousTable.ToBuilder(); foreach (var entry in sourceTable) { if (entry.state == EntryState.Removed) { nodeTable.RemoveEntries(); } else if (entry.state != EntryState.Cached || !nodeTable.TryUseCachedEntries()) { // we don't currently handle modified any differently than added at the output // we just run the action and mark the new source as added. In theory we could compare // the diagnostics and sources produced and compare them, to see if they are any different // than before. var sourcesBuilder = ArrayBuilder<GeneratedSourceText>.GetInstance(); var diagnostics = DiagnosticBag.GetInstance(); SourceProductionContext context = new SourceProductionContext(sourcesBuilder, diagnostics, cancellationToken); try { _action(context, entry.item); nodeTable.AddEntry((sourcesBuilder.ToImmutable(), diagnostics.ToReadOnly()), EntryState.Added); } finally { sourcesBuilder.Free(); diagnostics.Free(); } } } return nodeTable.ToImmutableAndFree(); } IIncrementalGeneratorNode<TOutput> IIncrementalGeneratorNode<TOutput>.WithComparer(IEqualityComparer<TOutput> comparer) => throw ExceptionUtilities.Unreachable; void IIncrementalGeneratorNode<TOutput>.RegisterOutput(IIncrementalGeneratorOutputNode output) => throw ExceptionUtilities.Unreachable; public void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken) { // get our own state table Debug.Assert(context.TableBuilder is object); var table = context.TableBuilder.GetLatestStateTableForNode(this); // add each non-removed entry to the context foreach (var ((sources, diagnostics), state) in table) { if (state != EntryState.Removed) { foreach (var text in sources) { try { context.Sources.Add(text.HintName, text.Text); } catch (ArgumentException e) { throw new UserFunctionException(e); } } context.Diagnostics.AddRange(diagnostics); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using TOutput = System.ValueTuple<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.GeneratedSourceText>, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic>>; namespace Microsoft.CodeAnalysis { internal sealed class SourceOutputNode<TInput> : IIncrementalGeneratorOutputNode, IIncrementalGeneratorNode<TOutput> { private readonly IIncrementalGeneratorNode<TInput> _source; private readonly Action<SourceProductionContext, TInput> _action; private readonly IncrementalGeneratorOutputKind _outputKind; private readonly string _sourceExtension; public SourceOutputNode(IIncrementalGeneratorNode<TInput> source, Action<SourceProductionContext, TInput> action, IncrementalGeneratorOutputKind outputKind, string sourceExtension) { _source = source; _action = action; Debug.Assert(outputKind == IncrementalGeneratorOutputKind.Source || outputKind == IncrementalGeneratorOutputKind.Implementation); _outputKind = outputKind; _sourceExtension = sourceExtension; } public IncrementalGeneratorOutputKind Kind => _outputKind; public NodeStateTable<TOutput> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<TOutput> previousTable, CancellationToken cancellationToken) { var sourceTable = graphState.GetLatestStateTableForNode(_source); if (sourceTable.IsCached) { return previousTable; } var nodeTable = previousTable.ToBuilder(); foreach (var entry in sourceTable) { if (entry.state == EntryState.Removed) { nodeTable.RemoveEntries(); } else if (entry.state != EntryState.Cached || !nodeTable.TryUseCachedEntries()) { // we don't currently handle modified any differently than added at the output // we just run the action and mark the new source as added. In theory we could compare // the diagnostics and sources produced and compare them, to see if they are any different // than before. var sourcesBuilder = new AdditionalSourcesCollection(_sourceExtension); var diagnostics = DiagnosticBag.GetInstance(); SourceProductionContext context = new SourceProductionContext(sourcesBuilder, diagnostics, cancellationToken); try { _action(context, entry.item); nodeTable.AddEntry((sourcesBuilder.ToImmutable(), diagnostics.ToReadOnly()), EntryState.Added); } finally { sourcesBuilder.Free(); diagnostics.Free(); } } } return nodeTable.ToImmutableAndFree(); } IIncrementalGeneratorNode<TOutput> IIncrementalGeneratorNode<TOutput>.WithComparer(IEqualityComparer<TOutput> comparer) => throw ExceptionUtilities.Unreachable; void IIncrementalGeneratorNode<TOutput>.RegisterOutput(IIncrementalGeneratorOutputNode output) => throw ExceptionUtilities.Unreachable; public void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken) { // get our own state table Debug.Assert(context.TableBuilder is object); var table = context.TableBuilder.GetLatestStateTableForNode(this); // add each non-removed entry to the context foreach (var ((sources, diagnostics), state) in table) { if (state != EntryState.Removed) { foreach (var text in sources) { try { context.Sources.Add(text.HintName, text.Text); } catch (ArgumentException e) { throw new UserFunctionException(e); } } context.Diagnostics.AddRange(diagnostics); } } } } }
1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/VisualBasic/Portable/SourceGeneration/VisualBasicGeneratorDriver.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.ComponentModel Imports System.Threading Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.VisualBasic Public Class VisualBasicGeneratorDriver Inherits GeneratorDriver Private Sub New(state As GeneratorDriverState) MyBase.New(state) End Sub Friend Sub New(parseOptions As VisualBasicParseOptions, generators As ImmutableArray(Of ISourceGenerator), optionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), driverOptions As GeneratorDriverOptions) MyBase.New(parseOptions, generators, optionsProvider, additionalTexts, driverOptions) End Sub Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider Get Return VisualBasic.MessageProvider.Instance End Get End Property Friend Overrides Function FromState(state As GeneratorDriverState) As GeneratorDriver Return New VisualBasicGeneratorDriver(state) End Function Friend Overrides Function ParseGeneratedSourceText(input As GeneratedSourceText, fileName As String, cancellationToken As CancellationToken) As SyntaxTree Return VisualBasicSyntaxTree.ParseTextLazy(input.Text, CType(_state.ParseOptions, VisualBasicParseOptions), fileName) End Function Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), Optional additionalTexts As ImmutableArray(Of AdditionalText) = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider = Nothing, Optional driverOptions As GeneratorDriverOptions = Nothing) As VisualBasicGeneratorDriver Return New VisualBasicGeneratorDriver(parseOptions, generators, If(analyzerConfigOptionsProvider, CompilerAnalyzerConfigOptionsProvider.Empty), additionalTexts.NullToEmpty(), driverOptions) End Function ' 3.11 BACK COMPAT OVERLOAD -- DO NOT TOUCH <EditorBrowsable(EditorBrowsableState.Never)> Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), additionalTexts As ImmutableArray(Of AdditionalText), parseOptions As VisualBasicParseOptions, analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider) As VisualBasicGeneratorDriver Return Create(generators, additionalTexts, parseOptions, analyzerConfigOptionsProvider, driverOptions:=Nothing) End Function Friend Overrides Function CreateSourcesCollection() As AdditionalSourcesCollection Return New AdditionalSourcesCollection(".vb") End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.ComponentModel Imports System.Threading Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.VisualBasic Public Class VisualBasicGeneratorDriver Inherits GeneratorDriver Private Sub New(state As GeneratorDriverState) MyBase.New(state) End Sub Friend Sub New(parseOptions As VisualBasicParseOptions, generators As ImmutableArray(Of ISourceGenerator), optionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), driverOptions As GeneratorDriverOptions) MyBase.New(parseOptions, generators, optionsProvider, additionalTexts, driverOptions) End Sub Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider Get Return VisualBasic.MessageProvider.Instance End Get End Property Friend Overrides Function FromState(state As GeneratorDriverState) As GeneratorDriver Return New VisualBasicGeneratorDriver(state) End Function Friend Overrides Function ParseGeneratedSourceText(input As GeneratedSourceText, fileName As String, cancellationToken As CancellationToken) As SyntaxTree Return VisualBasicSyntaxTree.ParseTextLazy(input.Text, CType(_state.ParseOptions, VisualBasicParseOptions), fileName) End Function Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), Optional additionalTexts As ImmutableArray(Of AdditionalText) = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider = Nothing, Optional driverOptions As GeneratorDriverOptions = Nothing) As VisualBasicGeneratorDriver Return New VisualBasicGeneratorDriver(parseOptions, generators, If(analyzerConfigOptionsProvider, CompilerAnalyzerConfigOptionsProvider.Empty), additionalTexts.NullToEmpty(), driverOptions) End Function ' 3.11 BACK COMPAT OVERLOAD -- DO NOT TOUCH <EditorBrowsable(EditorBrowsableState.Never)> Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), additionalTexts As ImmutableArray(Of AdditionalText), parseOptions As VisualBasicParseOptions, analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider) As VisualBasicGeneratorDriver Return Create(generators, additionalTexts, parseOptions, analyzerConfigOptionsProvider, driverOptions:=Nothing) End Function Friend Overrides ReadOnly Property SourceExtension As String Get Return ".vb" End Get End Property End Class End Namespace
1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAutomaticBraceCompletion.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.Log; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpAutomaticBraceCompletion : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpAutomaticBraceCompletion(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpAutomaticBraceCompletion)) { } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_InsertionAndTabCompleting(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void Goo() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("if (true) {"); VisualStudio.Editor.Verify.CurrentLineText("if (true) { $$}", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("if (true) { }$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_Overtyping(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void Goo() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("if (true) {"); VisualStudio.Editor.Verify.CurrentLineText("if (true) { $$}", assertCaretPosition: true); VisualStudio.Editor.SendKeys("}"); VisualStudio.Editor.Verify.CurrentLineText("if (true) { }$$", assertCaretPosition: true); } /// <summary> /// This is a muscle-memory test for users who rely on the following sequence: /// <list type="number"> /// <item><description><c>Enter</c></description></item> /// <item><description><c>{</c></description></item> /// <item><description><c>Enter</c></description></item> /// <item><description><c>}</c></description></item> /// </list> /// </summary> [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_Overtyping_Method() { SetUpEditor(@" class C { $$ }"); VisualStudio.Editor.SendKeys("public void A()"); VisualStudio.Editor.SendKeys(VirtualKey.Enter, '{', VirtualKey.Enter, '}'); VisualStudio.Editor.Verify.CurrentLineText("}$$", assertCaretPosition: true); } /// <summary> /// This is a muscle-memory test for users who rely on the following sequence: /// <list type="number"> /// <item><description><c>Enter</c></description></item> /// <item><description><c>{</c></description></item> /// <item><description><c>Enter</c></description></item> /// <item><description><c>}</c></description></item> /// </list> /// </summary> [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_Overtyping_Property() { SetUpEditor(@" class C { $$ }"); VisualStudio.Editor.SendKeys("public int X"); VisualStudio.Editor.SendKeys(VirtualKey.Enter, '{', VirtualKey.Enter, '}'); VisualStudio.Editor.Verify.CurrentLineText("}$$", assertCaretPosition: true); } /// <summary> /// This is a muscle-memory test for users who rely on the following sequence: /// <list type="number"> /// <item><description><c>Enter</c></description></item> /// <item><description><c>{</c></description></item> /// <item><description><c>Enter</c></description></item> /// <item><description><c>}</c></description></item> /// </list> /// </summary> [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_Overtyping_CollectionInitializer() { SetUpEditor(@" using System.Collections.Generic; class C { void Method() { $$ } }"); VisualStudio.Editor.SendKeys("var x = new List<string>()"); VisualStudio.Editor.SendKeys(VirtualKey.Enter, '{', VirtualKey.Enter, '}'); VisualStudio.Editor.Verify.CurrentLineText("}$$", assertCaretPosition: true); } /// <summary> /// This is a muscle-memory test for users who rely on the following sequence: /// <list type="number"> /// <item><description><c>Enter</c></description></item> /// <item><description><c>{</c></description></item> /// <item><description><c>Enter</c></description></item> /// <item><description><c>}</c></description></item> /// </list> /// </summary> [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_Overtyping_ObjectInitializer() { SetUpEditor(@" class C { void Method() { $$ } }"); VisualStudio.Editor.SendKeys("var x = new object()"); VisualStudio.Editor.SendKeys(VirtualKey.Enter, '{', VirtualKey.Enter, '}'); VisualStudio.Editor.Verify.CurrentLineText("}$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_OnReturnNoFormattingOnlyIndentationBeforeCloseBrace(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void Goo() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys( "if (true) {", VirtualKey.Enter, "var a = 1;"); VisualStudio.Editor.Verify.TextContains(@" class C { void Goo() { if (true) { var a = 1;$$ } } }", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_OnReturnOvertypingTheClosingBrace(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void Goo() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys( "if (true) {", VirtualKey.Enter, "var a = 1;", '}'); VisualStudio.Editor.Verify.TextContains(@" class C { void Goo() { if (true) { var a = 1; }$$ } }", assertCaretPosition: true); } [WorkItem(653540, "DevDiv")] [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_OnReturnWithNonWhitespaceSpanInside(bool showCompletionInArgumentLists) { VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys( "class A { int i;", VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@"class A { int i; $$}", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Paren_InsertionAndTabCompleting(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("void Goo("); VisualStudio.Editor.Verify.CurrentLineText("void Goo($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys("int x", VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("void Goo(int x)$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Paren_Overtyping(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys( "void Goo(", VirtualKey.Escape, ")"); VisualStudio.Editor.Verify.CurrentLineText("void Goo()$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void SquareBracket_Insertion(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("int ["); VisualStudio.Editor.Verify.CurrentLineText("int [$$]", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void SquareBracket_Overtyping(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("int [", ']'); VisualStudio.Editor.Verify.CurrentLineText("int []$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void DoubleQuote_InsertionAndTabCompletion(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("string str = \"", VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("string str = \"\"$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void DoubleQuote_InsertionAndOvertyping(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("string str = \"Hi Roslyn!", '"'); VisualStudio.Editor.Verify.CurrentLineText("string str = \"Hi Roslyn!\"$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void DoubleQuote_FixedInterpolatedVerbatimString(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void M() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("var v = @$\""); VisualStudio.Editor.Verify.CurrentLineText("var v = $@\"$$\"", assertCaretPosition: true); // Backspace removes quotes VisualStudio.Editor.SendKeys(VirtualKey.Backspace); VisualStudio.Editor.Verify.CurrentLineText("var v = $@$$", assertCaretPosition: true); // Undo puts them back VisualStudio.Editor.Undo(); // Incorrect assertion: https://github.com/dotnet/roslyn/issues/33672 VisualStudio.Editor.Verify.CurrentLineText("var v = $@\"\"$$", assertCaretPosition: true); // First, the FixInterpolatedVerbatimString action is undone (@$ reordering) VisualStudio.Editor.Undo(); // Incorrect assertion: https://github.com/dotnet/roslyn/issues/33672 VisualStudio.Editor.Verify.CurrentLineText("var v = @$\"\"$$", assertCaretPosition: true); // Then the automatic quote completion is undone VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("var v = @$\"$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void AngleBracket_PossibleGenerics_InsertionAndCompletion(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { //field $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("System.Action<", VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("System.Action<>$$", assertCaretPosition: true); SetUpEditor(@" class C { //method decl $$ }"); VisualStudio.Editor.SendKeys("void GenericMethod<", VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("void GenericMethod<>$$", assertCaretPosition: true); SetUpEditor(@" class C { //delegate $$ }"); VisualStudio.Editor.SendKeys("delegate void Del<"); VisualStudio.Editor.Verify.CurrentLineText("delegate void Del<$$>", assertCaretPosition: true); SetUpEditor(@" //using directive $$ "); VisualStudio.Editor.SendKeys("using ActionOfT = System.Action<"); VisualStudio.Editor.Verify.CurrentLineText("using ActionOfT = System.Action<$$>", assertCaretPosition: true); SetUpEditor(@" //class $$ "); VisualStudio.Editor.SendKeys("class GenericClass<", '>'); VisualStudio.Editor.Verify.CurrentLineText("class GenericClass<>$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void SingleQuote_InsertionAndCompletion(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("char c = '"); VisualStudio.Editor.Verify.CurrentLineText("char c = '$$'", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Delete, VirtualKey.Backspace); VisualStudio.Editor.SendKeys("'\u6666", "'"); VisualStudio.Editor.Verify.CurrentLineText("char c = '\u6666'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Nested_AllKinds(bool showCompletionInArgumentLists) { SetUpEditor(@" class Bar<U> { T Goo<T>(T t) { return t; } void M() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys( "var arr=new object[,]{{Goo(0"); if (showCompletionInArgumentLists) { Assert.False(VisualStudio.Editor.IsCompletionActive()); } VisualStudio.Editor.SendKeys( VirtualKey.Tab, VirtualKey.Tab, ",{Goo(Goo(\"hello", VirtualKey.Tab, VirtualKey.Tab, VirtualKey.Tab, VirtualKey.Tab, VirtualKey.Tab, ';'); VisualStudio.Editor.Verify.CurrentLineText("var arr = new object[,] { { Goo(0) }, { Goo(Goo(\"hello\")) } };$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionInSingleLineComments(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { // $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("{([\"'"); VisualStudio.Editor.Verify.CurrentLineText("// {([\"'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionInMultiLineComments(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { /* $$ */ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("{([\"'"); VisualStudio.Editor.Verify.CurrentLineText("{([\"'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionStringVerbatimStringOrCharLiterals(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("string s = \"{([<'"); VisualStudio.Editor.Verify.CurrentLineText("string s = \"{([<'$$\"", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.End, ';', VirtualKey.Enter); VisualStudio.Editor.SendKeys("string y = @\"{([<'"); VisualStudio.Editor.Verify.CurrentLineText("string y = @\"{([<'$$\"", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.End, ';', VirtualKey.Enter); VisualStudio.Editor.SendKeys("char ch = '{([<\""); VisualStudio.Editor.Verify.CurrentLineText("char ch = '{([<\"$$'", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionInXmlDocComments(bool showCompletionInArgumentLists) { SetUpEditor(@" $$ class C { }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys( "///", "{([<\"'"); VisualStudio.Editor.Verify.CurrentLineText("/// {([<\"'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionInDisabledPreprocesser(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { #if false $$ #endif }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("void Goo("); VisualStudio.Editor.Verify.CurrentLineText("void Goo($$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionAfterRegionPreprocesser(bool showCompletionInArgumentLists) { SetUpEditor(@" #region $$ #endregion "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("{([<\"'"); VisualStudio.Editor.Verify.CurrentLineText("#region {([<\"'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionAfterEndregionPreprocesser(bool showCompletionInArgumentLists) { SetUpEditor(@" #region #endregion $$ "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("{([<\"'"); VisualStudio.Editor.Verify.CurrentLineText("#endregion {([<\"'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionAfterIfPreprocesser(bool showCompletionInArgumentLists) { SetUpEditor(@" #if $$ "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("{([<\"'"); VisualStudio.Editor.Verify.CurrentLineText("#if {([<\"'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionAfterPragmaPreprocesser(bool showCompletionInArgumentLists) { SetUpEditor(@" #pragma $$ "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("{([<\"'"); VisualStudio.Editor.Verify.CurrentLineText("#pragma {([<\"'$$", assertCaretPosition: true); } [WorkItem(651954, "DevDiv")] [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void InteractionWithOverrideStubGeneration(bool showCompletionInArgumentLists) { SetUpEditor(@" class A { public virtual void Goo() { } } class B : A { // type ""override Goo("" $$ } "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("override "); Assert.True(VisualStudio.Editor.IsCompletionActive()); VisualStudio.Editor.SendKeys("Goo("); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" class B : A { // type ""override Goo("" public override void Goo() { base.Goo(); } }", actualText); } [WorkItem(531107, "DevDiv")] [WpfTheory, CombinatorialData] [Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void InteractionWithCompletionList(bool showCompletionInArgumentLists) { SetUpEditor(@" using System.Collections.Generic; class C { void M() { List<int> li = $$ } } "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("new Li"); Assert.True(VisualStudio.Editor.IsCompletionActive()); if (showCompletionInArgumentLists) { VisualStudio.Editor.SendKeys("(", ")"); } else { VisualStudio.Editor.SendKeys("(", VirtualKey.Tab); } VisualStudio.Editor.Verify.CurrentLineText("List<int> li = new List<int>()$$", assertCaretPosition: true); } [WorkItem(823958, "DevDiv")] [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void AutoBraceCompleteDoesNotFormatBracePairInInitializers(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void M() { var x = $$ } } "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("new int[]{"); VisualStudio.Editor.Verify.CurrentLineText("var x = new int[] {$$}", assertCaretPosition: true); } [WorkItem(823958, "DevDiv")] [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void AutoBraceCompleteDoesNotFormatBracePairInObjectCreationExpression(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void M() { var x = $$ } } "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("new {"); VisualStudio.Editor.Verify.CurrentLineText("var x = new {$$}", assertCaretPosition: true); } [WorkItem(823958, "DevDiv")] [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void AutoBraceCompleteFormatsBracePairInClassDeclarationAndAutoProperty(bool showCompletionInArgumentLists) { SetUpEditor(@" class $$ "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("C{"); VisualStudio.Editor.Verify.CurrentLineText("class C { $$}", assertCaretPosition: true); VisualStudio.Editor.SendKeys( VirtualKey.Enter, "int Prop {"); VisualStudio.Editor.Verify.TextContains(@" class C { int Prop { $$} }", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] [Trait(Traits.Feature, Traits.Features.CompleteStatement)] [WorkItem(18104, "https://github.com/dotnet/roslyn/issues/18104")] public void CompleteStatementTriggersCompletion(bool showCompletionInArgumentLists) { SetUpEditor(@" class Program { static void Main(string[] args) { Main$$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("(ar"); VisualStudio.Editor.Verify.CurrentLineText("Main(ar$$)", assertCaretPosition: true); if (showCompletionInArgumentLists) { Assert.True(VisualStudio.Editor.IsCompletionActive()); } VisualStudio.Editor.SendKeys(";"); VisualStudio.Editor.Verify.CurrentLineText("Main(args);$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_InsertionOnNewLine(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void Goo() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("if (true)", VirtualKey.Enter, "{"); VisualStudio.Editor.Verify.CurrentLineText("{ $$}", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@" class C { void Goo() { if (true) { } } }"); VisualStudio.Editor.SendKeys("}"); VisualStudio.Editor.Verify.TextContains(@" class C { void Goo() { if (true) { }$$ } }", assertCaretPosition: true); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.Log; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpAutomaticBraceCompletion : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpAutomaticBraceCompletion(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpAutomaticBraceCompletion)) { } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_InsertionAndTabCompleting(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void Goo() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("if (true) {"); VisualStudio.Editor.Verify.CurrentLineText("if (true) { $$}", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("if (true) { }$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_Overtyping(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void Goo() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("if (true) {"); VisualStudio.Editor.Verify.CurrentLineText("if (true) { $$}", assertCaretPosition: true); VisualStudio.Editor.SendKeys("}"); VisualStudio.Editor.Verify.CurrentLineText("if (true) { }$$", assertCaretPosition: true); } /// <summary> /// This is a muscle-memory test for users who rely on the following sequence: /// <list type="number"> /// <item><description><c>Enter</c></description></item> /// <item><description><c>{</c></description></item> /// <item><description><c>Enter</c></description></item> /// <item><description><c>}</c></description></item> /// </list> /// </summary> [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_Overtyping_Method() { SetUpEditor(@" class C { $$ }"); VisualStudio.Editor.SendKeys("public void A()"); VisualStudio.Editor.SendKeys(VirtualKey.Enter, '{', VirtualKey.Enter, '}'); VisualStudio.Editor.Verify.CurrentLineText("}$$", assertCaretPosition: true); } /// <summary> /// This is a muscle-memory test for users who rely on the following sequence: /// <list type="number"> /// <item><description><c>Enter</c></description></item> /// <item><description><c>{</c></description></item> /// <item><description><c>Enter</c></description></item> /// <item><description><c>}</c></description></item> /// </list> /// </summary> [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_Overtyping_Property() { SetUpEditor(@" class C { $$ }"); VisualStudio.Editor.SendKeys("public int X"); VisualStudio.Editor.SendKeys(VirtualKey.Enter, '{', VirtualKey.Enter, '}'); VisualStudio.Editor.Verify.CurrentLineText("}$$", assertCaretPosition: true); } /// <summary> /// This is a muscle-memory test for users who rely on the following sequence: /// <list type="number"> /// <item><description><c>Enter</c></description></item> /// <item><description><c>{</c></description></item> /// <item><description><c>Enter</c></description></item> /// <item><description><c>}</c></description></item> /// </list> /// </summary> [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_Overtyping_CollectionInitializer() { SetUpEditor(@" using System.Collections.Generic; class C { void Method() { $$ } }"); VisualStudio.Editor.SendKeys("var x = new List<string>()"); VisualStudio.Editor.SendKeys(VirtualKey.Enter, '{', VirtualKey.Enter, '}'); VisualStudio.Editor.Verify.CurrentLineText("}$$", assertCaretPosition: true); } /// <summary> /// This is a muscle-memory test for users who rely on the following sequence: /// <list type="number"> /// <item><description><c>Enter</c></description></item> /// <item><description><c>{</c></description></item> /// <item><description><c>Enter</c></description></item> /// <item><description><c>}</c></description></item> /// </list> /// </summary> [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_Overtyping_ObjectInitializer() { SetUpEditor(@" class C { void Method() { $$ } }"); VisualStudio.Editor.SendKeys("var x = new object()"); VisualStudio.Editor.SendKeys(VirtualKey.Enter, '{', VirtualKey.Enter, '}'); VisualStudio.Editor.Verify.CurrentLineText("}$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_OnReturnNoFormattingOnlyIndentationBeforeCloseBrace(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void Goo() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys( "if (true) {", VirtualKey.Enter, "var a = 1;"); VisualStudio.Editor.Verify.TextContains(@" class C { void Goo() { if (true) { var a = 1;$$ } } }", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_OnReturnOvertypingTheClosingBrace(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void Goo() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys( "if (true) {", VirtualKey.Enter, "var a = 1;", '}'); VisualStudio.Editor.Verify.TextContains(@" class C { void Goo() { if (true) { var a = 1; }$$ } }", assertCaretPosition: true); } [WorkItem(653540, "DevDiv")] [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_OnReturnWithNonWhitespaceSpanInside(bool showCompletionInArgumentLists) { VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys( "class A { int i;", VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@"class A { int i; $$}", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Paren_InsertionAndTabCompleting(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("void Goo("); VisualStudio.Editor.Verify.CurrentLineText("void Goo($$)", assertCaretPosition: true); VisualStudio.Editor.SendKeys("int x", VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("void Goo(int x)$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Paren_Overtyping(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys( "void Goo(", VirtualKey.Escape, ")"); VisualStudio.Editor.Verify.CurrentLineText("void Goo()$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void SquareBracket_Insertion(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("int ["); VisualStudio.Editor.Verify.CurrentLineText("int [$$]", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void SquareBracket_Overtyping(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("int [", ']'); VisualStudio.Editor.Verify.CurrentLineText("int []$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void DoubleQuote_InsertionAndTabCompletion(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("string str = \"", VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("string str = \"\"$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void DoubleQuote_InsertionAndOvertyping(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("string str = \"Hi Roslyn!", '"'); VisualStudio.Editor.Verify.CurrentLineText("string str = \"Hi Roslyn!\"$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void DoubleQuote_FixedInterpolatedVerbatimString(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void M() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("var v = @$\""); VisualStudio.Editor.Verify.CurrentLineText("var v = $@\"$$\"", assertCaretPosition: true); // Backspace removes quotes VisualStudio.Editor.SendKeys(VirtualKey.Backspace); VisualStudio.Editor.Verify.CurrentLineText("var v = $@$$", assertCaretPosition: true); // Undo puts them back VisualStudio.Editor.Undo(); // Incorrect assertion: https://github.com/dotnet/roslyn/issues/33672 VisualStudio.Editor.Verify.CurrentLineText("var v = $@\"\"$$", assertCaretPosition: true); // First, the FixInterpolatedVerbatimString action is undone (@$ reordering) VisualStudio.Editor.Undo(); // Incorrect assertion: https://github.com/dotnet/roslyn/issues/33672 VisualStudio.Editor.Verify.CurrentLineText("var v = @$\"\"$$", assertCaretPosition: true); // Then the automatic quote completion is undone VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("var v = @$\"$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void AngleBracket_PossibleGenerics_InsertionAndCompletion(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { //field $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("System.Action<", VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("System.Action<>$$", assertCaretPosition: true); SetUpEditor(@" class C { //method decl $$ }"); VisualStudio.Editor.SendKeys("void GenericMethod<", VirtualKey.Tab); VisualStudio.Editor.Verify.CurrentLineText("void GenericMethod<>$$", assertCaretPosition: true); SetUpEditor(@" class C { //delegate $$ }"); VisualStudio.Editor.SendKeys("delegate void Del<"); VisualStudio.Editor.Verify.CurrentLineText("delegate void Del<$$>", assertCaretPosition: true); SetUpEditor(@" //using directive $$ "); VisualStudio.Editor.SendKeys("using ActionOfT = System.Action<"); VisualStudio.Editor.Verify.CurrentLineText("using ActionOfT = System.Action<$$>", assertCaretPosition: true); SetUpEditor(@" //class $$ "); VisualStudio.Editor.SendKeys("class GenericClass<", '>'); VisualStudio.Editor.Verify.CurrentLineText("class GenericClass<>$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void SingleQuote_InsertionAndCompletion(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("char c = '"); VisualStudio.Editor.Verify.CurrentLineText("char c = '$$'", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Delete, VirtualKey.Backspace); VisualStudio.Editor.SendKeys("'\u6666", "'"); VisualStudio.Editor.Verify.CurrentLineText("char c = '\u6666'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Nested_AllKinds(bool showCompletionInArgumentLists) { SetUpEditor(@" class Bar<U> { T Goo<T>(T t) { return t; } void M() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys( "var arr=new object[,]{{Goo(0"); if (showCompletionInArgumentLists) { Assert.False(VisualStudio.Editor.IsCompletionActive()); } VisualStudio.Editor.SendKeys( VirtualKey.Tab, VirtualKey.Tab, ",{Goo(Goo(\"hello", VirtualKey.Tab, VirtualKey.Tab, VirtualKey.Tab, VirtualKey.Tab, VirtualKey.Tab, ';'); VisualStudio.Editor.Verify.CurrentLineText("var arr = new object[,] { { Goo(0) }, { Goo(Goo(\"hello\")) } };$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionInSingleLineComments(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { // $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("{([\"'"); VisualStudio.Editor.Verify.CurrentLineText("// {([\"'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionInMultiLineComments(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { /* $$ */ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("{([\"'"); VisualStudio.Editor.Verify.CurrentLineText("{([\"'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionStringVerbatimStringOrCharLiterals(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { $$ }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("string s = \"{([<'"); VisualStudio.Editor.Verify.CurrentLineText("string s = \"{([<'$$\"", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.End, ';', VirtualKey.Enter); VisualStudio.Editor.SendKeys("string y = @\"{([<'"); VisualStudio.Editor.Verify.CurrentLineText("string y = @\"{([<'$$\"", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.End, ';', VirtualKey.Enter); VisualStudio.Editor.SendKeys("char ch = '{([<\""); VisualStudio.Editor.Verify.CurrentLineText("char ch = '{([<\"$$'", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionInXmlDocComments(bool showCompletionInArgumentLists) { SetUpEditor(@" $$ class C { }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys( "///", "{([<\"'"); VisualStudio.Editor.Verify.CurrentLineText("/// {([<\"'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionInDisabledPreprocesser(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { #if false $$ #endif }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("void Goo("); VisualStudio.Editor.Verify.CurrentLineText("void Goo($$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionAfterRegionPreprocesser(bool showCompletionInArgumentLists) { SetUpEditor(@" #region $$ #endregion "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("{([<\"'"); VisualStudio.Editor.Verify.CurrentLineText("#region {([<\"'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionAfterEndregionPreprocesser(bool showCompletionInArgumentLists) { SetUpEditor(@" #region #endregion $$ "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("{([<\"'"); VisualStudio.Editor.Verify.CurrentLineText("#endregion {([<\"'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionAfterIfPreprocesser(bool showCompletionInArgumentLists) { SetUpEditor(@" #if $$ "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("{([<\"'"); VisualStudio.Editor.Verify.CurrentLineText("#if {([<\"'$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Negative_NoCompletionAfterPragmaPreprocesser(bool showCompletionInArgumentLists) { SetUpEditor(@" #pragma $$ "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("{([<\"'"); VisualStudio.Editor.Verify.CurrentLineText("#pragma {([<\"'$$", assertCaretPosition: true); } [WorkItem(651954, "DevDiv")] [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void InteractionWithOverrideStubGeneration(bool showCompletionInArgumentLists) { SetUpEditor(@" class A { public virtual void Goo() { } } class B : A { // type ""override Goo("" $$ } "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("override "); Assert.True(VisualStudio.Editor.IsCompletionActive()); VisualStudio.Editor.SendKeys("Goo("); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@" class B : A { // type ""override Goo("" public override void Goo() { base.Goo(); } }", actualText); } [WorkItem(531107, "DevDiv")] [WpfTheory, CombinatorialData] [Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void InteractionWithCompletionList(bool showCompletionInArgumentLists) { SetUpEditor(@" using System.Collections.Generic; class C { void M() { List<int> li = $$ } } "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("new Li"); Assert.True(VisualStudio.Editor.IsCompletionActive()); if (showCompletionInArgumentLists) { VisualStudio.Editor.SendKeys("(", ")"); } else { VisualStudio.Editor.SendKeys("(", VirtualKey.Tab); } VisualStudio.Editor.Verify.CurrentLineText("List<int> li = new List<int>()$$", assertCaretPosition: true); } [WorkItem(823958, "DevDiv")] [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void AutoBraceCompleteDoesNotFormatBracePairInInitializers(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void M() { var x = $$ } } "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("new int[]{"); VisualStudio.Editor.Verify.CurrentLineText("var x = new int[] {$$}", assertCaretPosition: true); } [WorkItem(823958, "DevDiv")] [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void AutoBraceCompleteDoesNotFormatBracePairInObjectCreationExpression(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void M() { var x = $$ } } "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("new {"); VisualStudio.Editor.Verify.CurrentLineText("var x = new {$$}", assertCaretPosition: true); } [WorkItem(823958, "DevDiv")] [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void AutoBraceCompleteFormatsBracePairInClassDeclarationAndAutoProperty(bool showCompletionInArgumentLists) { SetUpEditor(@" class $$ "); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("C{"); VisualStudio.Editor.Verify.CurrentLineText("class C { $$}", assertCaretPosition: true); VisualStudio.Editor.SendKeys( VirtualKey.Enter, "int Prop {"); VisualStudio.Editor.Verify.TextContains(@" class C { int Prop { $$} }", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] [Trait(Traits.Feature, Traits.Features.CompleteStatement)] [WorkItem(18104, "https://github.com/dotnet/roslyn/issues/18104")] public void CompleteStatementTriggersCompletion(bool showCompletionInArgumentLists) { SetUpEditor(@" class Program { static void Main(string[] args) { Main$$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("(ar"); VisualStudio.Editor.Verify.CurrentLineText("Main(ar$$)", assertCaretPosition: true); if (showCompletionInArgumentLists) { Assert.True(VisualStudio.Editor.IsCompletionActive()); } VisualStudio.Editor.SendKeys(";"); VisualStudio.Editor.Verify.CurrentLineText("Main(args);$$", assertCaretPosition: true); } [WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void Braces_InsertionOnNewLine(bool showCompletionInArgumentLists) { SetUpEditor(@" class C { void Goo() { $$ } }"); VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(showCompletionInArgumentLists); VisualStudio.Editor.SendKeys("if (true)", VirtualKey.Enter, "{"); VisualStudio.Editor.Verify.CurrentLineText("{ $$}", assertCaretPosition: true); VisualStudio.Editor.SendKeys(VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@" class C { void Goo() { if (true) { } } }"); VisualStudio.Editor.SendKeys("}"); VisualStudio.Editor.Verify.TextContains(@" class C { void Goo() { if (true) { }$$ } }", assertCaretPosition: true); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/Helpers/TestTypeExtensions.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.ComponentInterfaces Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Friend Module TestTypeExtensions <Extension> Public Function GetTypeName(type As System.Type, Optional typeInfo As DkmClrCustomTypeInfo = Nothing, Optional escapeKeywordIdentifiers As Boolean = False, Optional inspectionContext As DkmInspectionContext = Nothing) As String Dim formatter = New VisualBasicFormatter() Dim clrType = New DkmClrType(New TypeImpl(type)) If inspectionContext Is Nothing Then Dim inspectionSession = New DkmInspectionSession(ImmutableArray.Create(Of IDkmClrFormatter)(New VisualBasicFormatter()), ImmutableArray.Create(Of IDkmClrResultProvider)(New VisualBasicResultProvider())) inspectionContext = New DkmInspectionContext(inspectionSession, DkmEvaluationFlags.None, radix:=10, runtimeInstance:=Nothing) End If Return If(escapeKeywordIdentifiers, DirectCast(formatter, IDkmClrFullNameProvider).GetClrTypeName(inspectionContext, clrType, typeInfo), DirectCast(formatter, IDkmClrFormatter).GetTypeName(inspectionContext, clrType, typeInfo, Microsoft.CodeAnalysis.ExpressionEvaluator.Formatter.NoFormatSpecifiers)) End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.ComponentInterfaces Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Friend Module TestTypeExtensions <Extension> Public Function GetTypeName(type As System.Type, Optional typeInfo As DkmClrCustomTypeInfo = Nothing, Optional escapeKeywordIdentifiers As Boolean = False, Optional inspectionContext As DkmInspectionContext = Nothing) As String Dim formatter = New VisualBasicFormatter() Dim clrType = New DkmClrType(New TypeImpl(type)) If inspectionContext Is Nothing Then Dim inspectionSession = New DkmInspectionSession(ImmutableArray.Create(Of IDkmClrFormatter)(New VisualBasicFormatter()), ImmutableArray.Create(Of IDkmClrResultProvider)(New VisualBasicResultProvider())) inspectionContext = New DkmInspectionContext(inspectionSession, DkmEvaluationFlags.None, radix:=10, runtimeInstance:=Nothing) End If Return If(escapeKeywordIdentifiers, DirectCast(formatter, IDkmClrFullNameProvider).GetClrTypeName(inspectionContext, clrType, typeInfo), DirectCast(formatter, IDkmClrFormatter).GetTypeName(inspectionContext, clrType, typeInfo, Microsoft.CodeAnalysis.ExpressionEvaluator.Formatter.NoFormatSpecifiers)) End Function End Module End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/VisualBasic/Portable/Binding/TypesOfImportedNamespacesMembersBinder.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Provides lookup in types of imported namespaces, either at file level or project level. ''' </summary> Friend Class TypesOfImportedNamespacesMembersBinder Inherits Binder Private ReadOnly _importedSymbols As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) Public Sub New(containingBinder As Binder, importedSymbols As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition)) MyBase.New(containingBinder) _importedSymbols = importedSymbols End Sub Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult, name As String, arity As Integer, options As LookupOptions, originalBinder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) ' Lookup in modules of imported namespaces. For Each importedSym In _importedSymbols If importedSym.NamespaceOrType.IsNamespace Then Dim currentResult = LookupResult.GetInstance() originalBinder.LookupMemberInModules(currentResult, DirectCast(importedSym.NamespaceOrType, NamespaceSymbol), name, arity, options, useSiteInfo) If currentResult.IsGood AndAlso Not originalBinder.IsSemanticModelBinder Then Me.Compilation.MarkImportDirectiveAsUsed(Me.SyntaxTree, importedSym.ImportsClausePosition) End If lookupResult.MergeAmbiguous(currentResult, ImportedTypesAndNamespacesMembersBinder.GenerateAmbiguityError) currentResult.Free() End If Next End Sub ''' <summary> ''' Collect extension methods with the given name that are in scope in this binder. ''' The passed in ArrayBuilder must be empty. Extension methods from the same containing type ''' must be grouped together. ''' </summary> Protected Overrides Sub CollectProbableExtensionMethodsInSingleBinder(name As String, methods As ArrayBuilder(Of MethodSymbol), originalBinder As Binder) Debug.Assert(methods.Count = 0) For Each importedSym In _importedSymbols If importedSym.NamespaceOrType.IsNamespace Then Dim count = methods.Count DirectCast(importedSym.NamespaceOrType, NamespaceSymbol).AppendProbableExtensionMethods(name, methods) If methods.Count <> count AndAlso Not originalBinder.IsSemanticModelBinder Then Me.Compilation.MarkImportDirectiveAsUsed(Me.SyntaxTree, importedSym.ImportsClausePosition) End If End If Next End Sub Protected Overrides Sub AddExtensionMethodLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) For Each importedSym In _importedSymbols If importedSym.NamespaceOrType.IsNamespace Then DirectCast(importedSym.NamespaceOrType, NamespaceSymbol).AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder) End If Next End Sub Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) options = options Or LookupOptions.IgnoreExtensionMethods For Each importedSym In _importedSymbols If importedSym.NamespaceOrType.IsNamespace Then For Each containedModule As NamedTypeSymbol In DirectCast(importedSym.NamespaceOrType, NamespaceSymbol).GetModuleMembers() originalBinder.AddMemberLookupSymbolsInfo(nameSet, containedModule, options) Next End If Next End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Provides lookup in types of imported namespaces, either at file level or project level. ''' </summary> Friend Class TypesOfImportedNamespacesMembersBinder Inherits Binder Private ReadOnly _importedSymbols As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) Public Sub New(containingBinder As Binder, importedSymbols As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition)) MyBase.New(containingBinder) _importedSymbols = importedSymbols End Sub Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult, name As String, arity As Integer, options As LookupOptions, originalBinder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) ' Lookup in modules of imported namespaces. For Each importedSym In _importedSymbols If importedSym.NamespaceOrType.IsNamespace Then Dim currentResult = LookupResult.GetInstance() originalBinder.LookupMemberInModules(currentResult, DirectCast(importedSym.NamespaceOrType, NamespaceSymbol), name, arity, options, useSiteInfo) If currentResult.IsGood AndAlso Not originalBinder.IsSemanticModelBinder Then Me.Compilation.MarkImportDirectiveAsUsed(Me.SyntaxTree, importedSym.ImportsClausePosition) End If lookupResult.MergeAmbiguous(currentResult, ImportedTypesAndNamespacesMembersBinder.GenerateAmbiguityError) currentResult.Free() End If Next End Sub ''' <summary> ''' Collect extension methods with the given name that are in scope in this binder. ''' The passed in ArrayBuilder must be empty. Extension methods from the same containing type ''' must be grouped together. ''' </summary> Protected Overrides Sub CollectProbableExtensionMethodsInSingleBinder(name As String, methods As ArrayBuilder(Of MethodSymbol), originalBinder As Binder) Debug.Assert(methods.Count = 0) For Each importedSym In _importedSymbols If importedSym.NamespaceOrType.IsNamespace Then Dim count = methods.Count DirectCast(importedSym.NamespaceOrType, NamespaceSymbol).AppendProbableExtensionMethods(name, methods) If methods.Count <> count AndAlso Not originalBinder.IsSemanticModelBinder Then Me.Compilation.MarkImportDirectiveAsUsed(Me.SyntaxTree, importedSym.ImportsClausePosition) End If End If Next End Sub Protected Overrides Sub AddExtensionMethodLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) For Each importedSym In _importedSymbols If importedSym.NamespaceOrType.IsNamespace Then DirectCast(importedSym.NamespaceOrType, NamespaceSymbol).AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder) End If Next End Sub Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) options = options Or LookupOptions.IgnoreExtensionMethods For Each importedSym In _importedSymbols If importedSym.NamespaceOrType.IsNamespace Then For Each containedModule As NamedTypeSymbol In DirectCast(importedSym.NamespaceOrType, NamespaceSymbol).GetModuleMembers() originalBinder.AddMemberLookupSymbolsInfo(nameSet, containedModule, options) Next End If Next End Sub End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/Core/Portable/Workspace/Solution/MetadataOnlyReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal class MetadataOnlyReference { // version based cache private static readonly ConditionalWeakTable<BranchId, ConditionalWeakTable<ProjectId, MetadataOnlyReferenceSet>> s_cache = new(); // snapshot based cache private static readonly ConditionalWeakTable<Compilation, MetadataOnlyReferenceSet> s_snapshotCache = new(); private static readonly ConditionalWeakTable<BranchId, ConditionalWeakTable<ProjectId, MetadataOnlyReferenceSet>>.CreateValueCallback s_createReferenceSetMap = _ => new ConditionalWeakTable<ProjectId, MetadataOnlyReferenceSet>(); internal static MetadataReference GetOrBuildReference( SolutionState solution, ProjectReference projectReference, Compilation finalCompilation, VersionStamp version, CancellationToken cancellationToken) { solution.Workspace.LogTestMessage($"Looking to see if we already have a skeleton assembly for {projectReference.ProjectId} before we build one..."); if (TryGetReference(solution, projectReference, finalCompilation, version, out var reference)) { solution.Workspace.LogTestMessage($"A reference was found {projectReference.ProjectId} so we're skipping the build."); return reference; } // okay, we don't have one. so create one now. // first, prepare image // * NOTE * image is cancellable, do not create it inside of conditional weak table. var service = solution.Workspace.Services.GetService<ITemporaryStorageService>(); var image = MetadataOnlyImage.Create(solution.Workspace, service, finalCompilation, cancellationToken); if (image.IsEmpty) { // unfortunately, we couldn't create one. do best effort if (TryGetReference(solution, projectReference, finalCompilation, VersionStamp.Default, out reference)) { solution.Workspace.LogTestMessage($"We failed to create metadata so we're using the one we just found from an earlier version."); // we have one from previous compilation!!, it might be out-of-date big time, but better than nothing. // re-use it return reference; } } // okay, proceed with whatever image we have // now, remove existing set var mapFromBranch = s_cache.GetValue(solution.BranchId, s_createReferenceSetMap); mapFromBranch.Remove(projectReference.ProjectId); // create new one var newReferenceSet = new MetadataOnlyReferenceSet(version, image); var referenceSet = s_snapshotCache.GetValue(finalCompilation, _ => newReferenceSet); if (newReferenceSet != referenceSet) { // someone else has beaten us. // let image go eagerly. otherwise, finalizer in temporary storage will take care of it image.Cleanup(); // return new reference return referenceSet.GetMetadataReference(finalCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes); } else { solution.Workspace.LogTestMessage($"Successfully stored the metadata generated for {projectReference.ProjectId}"); } // record it to version based cache as well. snapshot cache always has a higher priority. we don't need to check returned set here // since snapshot based cache will take care of same compilation for us. mapFromBranch.GetValue(projectReference.ProjectId, _ => referenceSet); // return new reference return referenceSet.GetMetadataReference(finalCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes); } internal static bool TryGetReference( SolutionState solution, ProjectReference projectReference, Compilation finalOrDeclarationCompilation, VersionStamp version, out MetadataReference reference) { // if we have one from snapshot cache, use it. it will make sure same compilation will get same metadata reference always. if (s_snapshotCache.TryGetValue(finalOrDeclarationCompilation, out var referenceSet)) { solution.Workspace.LogTestMessage($"Found already cached metadata in {nameof(s_snapshotCache)} for the exact compilation"); reference = referenceSet.GetMetadataReference(finalOrDeclarationCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes); return true; } // okay, now use version based cache that can live multiple compilation as long as there is no semantic changes. // get one for the branch if (TryGetReferenceFromBranch(solution.BranchId, projectReference, finalOrDeclarationCompilation, version, out reference)) { solution.Workspace.LogTestMessage($"Found already cached metadata for the branch and version {version}"); return true; } // see whether we can use primary branch one var primaryBranchId = solution.Workspace.PrimaryBranchId; if (solution.BranchId != primaryBranchId && TryGetReferenceFromBranch(primaryBranchId, projectReference, finalOrDeclarationCompilation, version, out reference)) { solution.Workspace.LogTestMessage($"Found already cached metadata for the primary branch and version {version}"); return true; } // noop, we don't have any reference = null; return false; } private static bool TryGetReferenceFromBranch( BranchId branchId, ProjectReference projectReference, Compilation finalOrDeclarationCompilation, VersionStamp version, out MetadataReference reference) { // get map for the branch var mapFromBranch = s_cache.GetValue(branchId, s_createReferenceSetMap); // if we have one, return it if (mapFromBranch.TryGetValue(projectReference.ProjectId, out var referenceSet) && (version == VersionStamp.Default || referenceSet.Version == version)) { // record it to snapshot based cache. var newReferenceSet = s_snapshotCache.GetValue(finalOrDeclarationCompilation, _ => referenceSet); reference = newReferenceSet.GetMetadataReference(finalOrDeclarationCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes); return true; } reference = null; return false; } private class MetadataOnlyReferenceSet { // use WeakReference so we don't keep MetadataReference's alive if they are not being consumed private readonly NonReentrantLock _gate = new(useThisInstanceForSynchronization: true); // here, there is a very small chance of leaking Tuple and WeakReference, but it is so small chance, // I don't believe it will actually happen in real life situation. basically, for leak to happen, // every image creation except the first one has to fail so that we end up re-use old reference set. // and the user creates many different metadata references with multiple combination of the key (tuple). private readonly Dictionary<MetadataReferenceProperties, WeakReference<MetadataReference>> _metadataReferences = new(); private readonly VersionStamp _version; private readonly MetadataOnlyImage _image; public MetadataOnlyReferenceSet(VersionStamp version, MetadataOnlyImage image) { _version = version; _image = image; } public VersionStamp Version => _version; public MetadataReference GetMetadataReference(Compilation compilation, ImmutableArray<string> aliases, bool embedInteropTypes) { var key = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); using (_gate.DisposableWait()) { if (!_metadataReferences.TryGetValue(key, out var weakMetadata) || !weakMetadata.TryGetTarget(out var metadataReference)) { // here we give out strong reference to compilation. so there is possibility that we end up making 2 compilations for same project alive. // one for final compilation and one for declaration only compilation. but the final compilation will be eventually kicked out from compilation cache // if there is no activity on the project. or the declaration compilation will go away if the project that depends on the reference doesn't have any // activity when it is kicked out from compilation cache. if there is an activity, then both will updated as activity happens. // so simply put, things will go away when compilations are kicked out from the cache or due to user activity. // // there is one case where we could have 2 compilations for same project alive. if a user opens a file that requires a skeleton assembly when the skeleton // assembly project didn't reach the final stage yet and then the user opens another document that is part of the skeleton assembly project // and then never change it. declaration compilation will be alive by skeleton assembly and final compilation will be alive by background compiler. metadataReference = _image.CreateReference(aliases, embedInteropTypes, new DeferredDocumentationProvider(compilation)); weakMetadata = new WeakReference<MetadataReference>(metadataReference); _metadataReferences[key] = weakMetadata; } return metadataReference; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal class MetadataOnlyReference { // version based cache private static readonly ConditionalWeakTable<BranchId, ConditionalWeakTable<ProjectId, MetadataOnlyReferenceSet>> s_cache = new(); // snapshot based cache private static readonly ConditionalWeakTable<Compilation, MetadataOnlyReferenceSet> s_snapshotCache = new(); private static readonly ConditionalWeakTable<BranchId, ConditionalWeakTable<ProjectId, MetadataOnlyReferenceSet>>.CreateValueCallback s_createReferenceSetMap = _ => new ConditionalWeakTable<ProjectId, MetadataOnlyReferenceSet>(); internal static MetadataReference GetOrBuildReference( SolutionState solution, ProjectReference projectReference, Compilation finalCompilation, VersionStamp version, CancellationToken cancellationToken) { solution.Workspace.LogTestMessage($"Looking to see if we already have a skeleton assembly for {projectReference.ProjectId} before we build one..."); if (TryGetReference(solution, projectReference, finalCompilation, version, out var reference)) { solution.Workspace.LogTestMessage($"A reference was found {projectReference.ProjectId} so we're skipping the build."); return reference; } // okay, we don't have one. so create one now. // first, prepare image // * NOTE * image is cancellable, do not create it inside of conditional weak table. var service = solution.Workspace.Services.GetService<ITemporaryStorageService>(); var image = MetadataOnlyImage.Create(solution.Workspace, service, finalCompilation, cancellationToken); if (image.IsEmpty) { // unfortunately, we couldn't create one. do best effort if (TryGetReference(solution, projectReference, finalCompilation, VersionStamp.Default, out reference)) { solution.Workspace.LogTestMessage($"We failed to create metadata so we're using the one we just found from an earlier version."); // we have one from previous compilation!!, it might be out-of-date big time, but better than nothing. // re-use it return reference; } } // okay, proceed with whatever image we have // now, remove existing set var mapFromBranch = s_cache.GetValue(solution.BranchId, s_createReferenceSetMap); mapFromBranch.Remove(projectReference.ProjectId); // create new one var newReferenceSet = new MetadataOnlyReferenceSet(version, image); var referenceSet = s_snapshotCache.GetValue(finalCompilation, _ => newReferenceSet); if (newReferenceSet != referenceSet) { // someone else has beaten us. // let image go eagerly. otherwise, finalizer in temporary storage will take care of it image.Cleanup(); // return new reference return referenceSet.GetMetadataReference(finalCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes); } else { solution.Workspace.LogTestMessage($"Successfully stored the metadata generated for {projectReference.ProjectId}"); } // record it to version based cache as well. snapshot cache always has a higher priority. we don't need to check returned set here // since snapshot based cache will take care of same compilation for us. mapFromBranch.GetValue(projectReference.ProjectId, _ => referenceSet); // return new reference return referenceSet.GetMetadataReference(finalCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes); } internal static bool TryGetReference( SolutionState solution, ProjectReference projectReference, Compilation finalOrDeclarationCompilation, VersionStamp version, out MetadataReference reference) { // if we have one from snapshot cache, use it. it will make sure same compilation will get same metadata reference always. if (s_snapshotCache.TryGetValue(finalOrDeclarationCompilation, out var referenceSet)) { solution.Workspace.LogTestMessage($"Found already cached metadata in {nameof(s_snapshotCache)} for the exact compilation"); reference = referenceSet.GetMetadataReference(finalOrDeclarationCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes); return true; } // okay, now use version based cache that can live multiple compilation as long as there is no semantic changes. // get one for the branch if (TryGetReferenceFromBranch(solution.BranchId, projectReference, finalOrDeclarationCompilation, version, out reference)) { solution.Workspace.LogTestMessage($"Found already cached metadata for the branch and version {version}"); return true; } // see whether we can use primary branch one var primaryBranchId = solution.Workspace.PrimaryBranchId; if (solution.BranchId != primaryBranchId && TryGetReferenceFromBranch(primaryBranchId, projectReference, finalOrDeclarationCompilation, version, out reference)) { solution.Workspace.LogTestMessage($"Found already cached metadata for the primary branch and version {version}"); return true; } // noop, we don't have any reference = null; return false; } private static bool TryGetReferenceFromBranch( BranchId branchId, ProjectReference projectReference, Compilation finalOrDeclarationCompilation, VersionStamp version, out MetadataReference reference) { // get map for the branch var mapFromBranch = s_cache.GetValue(branchId, s_createReferenceSetMap); // if we have one, return it if (mapFromBranch.TryGetValue(projectReference.ProjectId, out var referenceSet) && (version == VersionStamp.Default || referenceSet.Version == version)) { // record it to snapshot based cache. var newReferenceSet = s_snapshotCache.GetValue(finalOrDeclarationCompilation, _ => referenceSet); reference = newReferenceSet.GetMetadataReference(finalOrDeclarationCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes); return true; } reference = null; return false; } private class MetadataOnlyReferenceSet { // use WeakReference so we don't keep MetadataReference's alive if they are not being consumed private readonly NonReentrantLock _gate = new(useThisInstanceForSynchronization: true); // here, there is a very small chance of leaking Tuple and WeakReference, but it is so small chance, // I don't believe it will actually happen in real life situation. basically, for leak to happen, // every image creation except the first one has to fail so that we end up re-use old reference set. // and the user creates many different metadata references with multiple combination of the key (tuple). private readonly Dictionary<MetadataReferenceProperties, WeakReference<MetadataReference>> _metadataReferences = new(); private readonly VersionStamp _version; private readonly MetadataOnlyImage _image; public MetadataOnlyReferenceSet(VersionStamp version, MetadataOnlyImage image) { _version = version; _image = image; } public VersionStamp Version => _version; public MetadataReference GetMetadataReference(Compilation compilation, ImmutableArray<string> aliases, bool embedInteropTypes) { var key = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); using (_gate.DisposableWait()) { if (!_metadataReferences.TryGetValue(key, out var weakMetadata) || !weakMetadata.TryGetTarget(out var metadataReference)) { // here we give out strong reference to compilation. so there is possibility that we end up making 2 compilations for same project alive. // one for final compilation and one for declaration only compilation. but the final compilation will be eventually kicked out from compilation cache // if there is no activity on the project. or the declaration compilation will go away if the project that depends on the reference doesn't have any // activity when it is kicked out from compilation cache. if there is an activity, then both will updated as activity happens. // so simply put, things will go away when compilations are kicked out from the cache or due to user activity. // // there is one case where we could have 2 compilations for same project alive. if a user opens a file that requires a skeleton assembly when the skeleton // assembly project didn't reach the final stage yet and then the user opens another document that is part of the skeleton assembly project // and then never change it. declaration compilation will be alive by skeleton assembly and final compilation will be alive by background compiler. metadataReference = _image.CreateReference(aliases, embedInteropTypes, new DeferredDocumentationProvider(compilation)); weakMetadata = new WeakReference<MetadataReference>(metadataReference); _metadataReferences[key] = weakMetadata; } return metadataReference; } } } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/VisualStudio/Core/Def/Implementation/Options/RoamingVisualStudioProfileOptionPersister.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Xml.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Setup; using Microsoft.VisualStudio.Settings; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// Serializes settings marked with <see cref="RoamingProfileStorageLocation"/> to and from the user's roaming profile. /// </summary> internal sealed class RoamingVisualStudioProfileOptionPersister : ForegroundThreadAffinitizedObject, IOptionPersister { // NOTE: This service is not public or intended for use by teams/individuals outside of Microsoft. Any data stored is subject to deletion without warning. [Guid("9B164E40-C3A2-4363-9BC5-EB4039DEF653")] private class SVsSettingsPersistenceManager { }; private readonly ISettingsManager? _settingManager; private readonly IGlobalOptionService _globalOptionService; /// <summary> /// The list of options that have been been fetched from <see cref="_settingManager"/>, by key. We track this so /// if a later change happens, we know to refresh that value. This is synchronized with monitor locks on /// <see cref="_optionsToMonitorForChangesGate" />. /// </summary> private readonly Dictionary<string, List<OptionKey>> _optionsToMonitorForChanges = new(); private readonly object _optionsToMonitorForChangesGate = new(); /// <remarks> /// We make sure this code is from the UI by asking for all <see cref="IOptionPersister"/> in <see cref="RoslynPackage.InitializeAsync"/> /// </remarks> public RoamingVisualStudioProfileOptionPersister(IThreadingContext threadingContext, IGlobalOptionService globalOptionService, ISettingsManager? settingsManager) : base(threadingContext, assertIsForeground: true) { Contract.ThrowIfNull(globalOptionService); _settingManager = settingsManager; _globalOptionService = globalOptionService; // While the settings persistence service should be available in all SKUs it is possible an ISO shell author has undefined the // contributing package. In that case persistence of settings won't work (we don't bother with a backup solution for persistence // as the scenario seems exceedingly unlikely), but we shouldn't crash the IDE. if (_settingManager != null) { var settingsSubset = _settingManager.GetSubset("*"); settingsSubset.SettingChangedAsync += OnSettingChangedAsync; } } private System.Threading.Tasks.Task OnSettingChangedAsync(object sender, PropertyChangedEventArgs args) { List<OptionKey>? optionsToRefresh = null; lock (_optionsToMonitorForChangesGate) { if (_optionsToMonitorForChanges.TryGetValue(args.PropertyName, out var optionsToRefreshInsideLock)) { // Make a copy of the list so we aren't using something that might mutate underneath us. optionsToRefresh = optionsToRefreshInsideLock.ToList(); } } if (optionsToRefresh != null) { // Refresh the actual options outside of our _optionsToMonitorForChangesGate so we avoid any deadlocks by calling back // into the global option service under our lock. There isn't some race here where if we were fetching an option for the first time // while the setting was changed we might not refresh it. Why? We call RecordObservedValueToWatchForChanges before we fetch the value // and since this event is raised after the setting is modified, any new setting would have already been observed in GetFirstOrDefaultValue. // And if it wasn't, this event will then refresh it. foreach (var optionToRefresh in optionsToRefresh) { if (TryFetch(optionToRefresh, out var optionValue)) { _globalOptionService.RefreshOption(optionToRefresh, optionValue); } } } return System.Threading.Tasks.Task.CompletedTask; } private object? GetFirstOrDefaultValue(OptionKey optionKey, IEnumerable<RoamingProfileStorageLocation> roamingSerializations) { Contract.ThrowIfNull(_settingManager); // There can be more than 1 roaming location in the order of their priority. // When fetching a value, we iterate all of them until we find the first one that exists. // When persisting a value, we always use the first location. // This functionality exists for breaking changes to persistence of some options. In such a case, there // will be a new location added to the beginning with a new name. When fetching a value, we might find the old // location (and can upgrade the value accordingly) but we only write to the new location so that // we don't interfere with older versions. This will essentially "fork" the user's options at the time of upgrade. foreach (var roamingSerialization in roamingSerializations) { var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); if (_settingManager.TryGetValue(storageKey, out object value) == GetValueResult.Success) { return value; } } return optionKey.Option.DefaultValue; } public bool TryFetch(OptionKey optionKey, out object? value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); value = null; return false; } // Do we roam this at all? var roamingSerializations = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>(); if (!roamingSerializations.Any()) { value = null; return false; } value = GetFirstOrDefaultValue(optionKey, roamingSerializations); // VS's ISettingsManager has some quirks around storing enums. Specifically, // it *can* persist and retrieve enums, but only if you properly call // GetValueOrDefault<EnumType>. This is because it actually stores enums just // as ints and depends on the type parameter passed in to convert the integral // value back to an enum value. Unfortunately, we call GetValueOrDefault<object> // and so we get the value back as boxed integer. // // Because of that, manually convert the integer to an enum here so we don't // crash later trying to cast a boxed integer to an enum value. if (optionKey.Option.Type.IsEnum) { if (value != null) { value = Enum.ToObject(optionKey.Option.Type, value); } } else if (typeof(ICodeStyleOption).IsAssignableFrom(optionKey.Option.Type)) { return DeserializeCodeStyleOption(ref value, optionKey.Option.Type); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so deserialize if (value is string serializedValue) { try { value = NamingStylePreferences.FromXElement(XElement.Parse(serializedValue)); } catch (Exception) { value = null; return false; } } else { value = null; return false; } } else if (optionKey.Option.Type == typeof(bool) && value is int intValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = intValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool) && value is long longValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = longValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool?)) { // code uses object to hold onto any value which will use boxing on value types. // see boxing on nullable types - https://msdn.microsoft.com/en-us/library/ms228597.aspx return (value is bool) || (value == null); } else if (value != null && optionKey.Option.Type != value.GetType()) { // We got something back different than we expected, so fail to deserialize value = null; return false; } return true; } private bool DeserializeCodeStyleOption(ref object? value, Type type) { if (value is string serializedValue) { try { var fromXElement = type.GetMethod(nameof(CodeStyleOption<object>.FromXElement), BindingFlags.Public | BindingFlags.Static); value = fromXElement.Invoke(null, new object[] { XElement.Parse(serializedValue) }); return true; } catch (Exception) { } } value = null; return false; } private void RecordObservedValueToWatchForChanges(OptionKey optionKey, string storageKey) { // We're about to fetch the value, so make sure that if it changes we'll know about it lock (_optionsToMonitorForChangesGate) { var optionKeysToMonitor = _optionsToMonitorForChanges.GetOrAdd(storageKey, _ => new List<OptionKey>()); if (!optionKeysToMonitor.Contains(optionKey)) { optionKeysToMonitor.Add(optionKey); } } } public bool TryPersist(OptionKey optionKey, object? value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } // Do we roam this at all? var roamingSerialization = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>().FirstOrDefault(); if (roamingSerialization == null) { return false; } var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); if (value is ICodeStyleOption codeStyleOption) { // We store these as strings, so serialize value = codeStyleOption.ToXElement().ToString(); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so serialize if (value is NamingStylePreferences valueToSerialize) { value = valueToSerialize.CreateXElement().ToString(); } } _settingManager.SetValueAsync(storageKey, value, isMachineLocal: false); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Xml.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Setup; using Microsoft.VisualStudio.Settings; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// Serializes settings marked with <see cref="RoamingProfileStorageLocation"/> to and from the user's roaming profile. /// </summary> internal sealed class RoamingVisualStudioProfileOptionPersister : ForegroundThreadAffinitizedObject, IOptionPersister { // NOTE: This service is not public or intended for use by teams/individuals outside of Microsoft. Any data stored is subject to deletion without warning. [Guid("9B164E40-C3A2-4363-9BC5-EB4039DEF653")] private class SVsSettingsPersistenceManager { }; private readonly ISettingsManager? _settingManager; private readonly IGlobalOptionService _globalOptionService; /// <summary> /// The list of options that have been been fetched from <see cref="_settingManager"/>, by key. We track this so /// if a later change happens, we know to refresh that value. This is synchronized with monitor locks on /// <see cref="_optionsToMonitorForChangesGate" />. /// </summary> private readonly Dictionary<string, List<OptionKey>> _optionsToMonitorForChanges = new(); private readonly object _optionsToMonitorForChangesGate = new(); /// <remarks> /// We make sure this code is from the UI by asking for all <see cref="IOptionPersister"/> in <see cref="RoslynPackage.InitializeAsync"/> /// </remarks> public RoamingVisualStudioProfileOptionPersister(IThreadingContext threadingContext, IGlobalOptionService globalOptionService, ISettingsManager? settingsManager) : base(threadingContext, assertIsForeground: true) { Contract.ThrowIfNull(globalOptionService); _settingManager = settingsManager; _globalOptionService = globalOptionService; // While the settings persistence service should be available in all SKUs it is possible an ISO shell author has undefined the // contributing package. In that case persistence of settings won't work (we don't bother with a backup solution for persistence // as the scenario seems exceedingly unlikely), but we shouldn't crash the IDE. if (_settingManager != null) { var settingsSubset = _settingManager.GetSubset("*"); settingsSubset.SettingChangedAsync += OnSettingChangedAsync; } } private System.Threading.Tasks.Task OnSettingChangedAsync(object sender, PropertyChangedEventArgs args) { List<OptionKey>? optionsToRefresh = null; lock (_optionsToMonitorForChangesGate) { if (_optionsToMonitorForChanges.TryGetValue(args.PropertyName, out var optionsToRefreshInsideLock)) { // Make a copy of the list so we aren't using something that might mutate underneath us. optionsToRefresh = optionsToRefreshInsideLock.ToList(); } } if (optionsToRefresh != null) { // Refresh the actual options outside of our _optionsToMonitorForChangesGate so we avoid any deadlocks by calling back // into the global option service under our lock. There isn't some race here where if we were fetching an option for the first time // while the setting was changed we might not refresh it. Why? We call RecordObservedValueToWatchForChanges before we fetch the value // and since this event is raised after the setting is modified, any new setting would have already been observed in GetFirstOrDefaultValue. // And if it wasn't, this event will then refresh it. foreach (var optionToRefresh in optionsToRefresh) { if (TryFetch(optionToRefresh, out var optionValue)) { _globalOptionService.RefreshOption(optionToRefresh, optionValue); } } } return System.Threading.Tasks.Task.CompletedTask; } private object? GetFirstOrDefaultValue(OptionKey optionKey, IEnumerable<RoamingProfileStorageLocation> roamingSerializations) { Contract.ThrowIfNull(_settingManager); // There can be more than 1 roaming location in the order of their priority. // When fetching a value, we iterate all of them until we find the first one that exists. // When persisting a value, we always use the first location. // This functionality exists for breaking changes to persistence of some options. In such a case, there // will be a new location added to the beginning with a new name. When fetching a value, we might find the old // location (and can upgrade the value accordingly) but we only write to the new location so that // we don't interfere with older versions. This will essentially "fork" the user's options at the time of upgrade. foreach (var roamingSerialization in roamingSerializations) { var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); if (_settingManager.TryGetValue(storageKey, out object value) == GetValueResult.Success) { return value; } } return optionKey.Option.DefaultValue; } public bool TryFetch(OptionKey optionKey, out object? value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); value = null; return false; } // Do we roam this at all? var roamingSerializations = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>(); if (!roamingSerializations.Any()) { value = null; return false; } value = GetFirstOrDefaultValue(optionKey, roamingSerializations); // VS's ISettingsManager has some quirks around storing enums. Specifically, // it *can* persist and retrieve enums, but only if you properly call // GetValueOrDefault<EnumType>. This is because it actually stores enums just // as ints and depends on the type parameter passed in to convert the integral // value back to an enum value. Unfortunately, we call GetValueOrDefault<object> // and so we get the value back as boxed integer. // // Because of that, manually convert the integer to an enum here so we don't // crash later trying to cast a boxed integer to an enum value. if (optionKey.Option.Type.IsEnum) { if (value != null) { value = Enum.ToObject(optionKey.Option.Type, value); } } else if (typeof(ICodeStyleOption).IsAssignableFrom(optionKey.Option.Type)) { return DeserializeCodeStyleOption(ref value, optionKey.Option.Type); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so deserialize if (value is string serializedValue) { try { value = NamingStylePreferences.FromXElement(XElement.Parse(serializedValue)); } catch (Exception) { value = null; return false; } } else { value = null; return false; } } else if (optionKey.Option.Type == typeof(bool) && value is int intValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = intValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool) && value is long longValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = longValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool?)) { // code uses object to hold onto any value which will use boxing on value types. // see boxing on nullable types - https://msdn.microsoft.com/en-us/library/ms228597.aspx return (value is bool) || (value == null); } else if (value != null && optionKey.Option.Type != value.GetType()) { // We got something back different than we expected, so fail to deserialize value = null; return false; } return true; } private bool DeserializeCodeStyleOption(ref object? value, Type type) { if (value is string serializedValue) { try { var fromXElement = type.GetMethod(nameof(CodeStyleOption<object>.FromXElement), BindingFlags.Public | BindingFlags.Static); value = fromXElement.Invoke(null, new object[] { XElement.Parse(serializedValue) }); return true; } catch (Exception) { } } value = null; return false; } private void RecordObservedValueToWatchForChanges(OptionKey optionKey, string storageKey) { // We're about to fetch the value, so make sure that if it changes we'll know about it lock (_optionsToMonitorForChangesGate) { var optionKeysToMonitor = _optionsToMonitorForChanges.GetOrAdd(storageKey, _ => new List<OptionKey>()); if (!optionKeysToMonitor.Contains(optionKey)) { optionKeysToMonitor.Add(optionKey); } } } public bool TryPersist(OptionKey optionKey, object? value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } // Do we roam this at all? var roamingSerialization = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>().FirstOrDefault(); if (roamingSerialization == null) { return false; } var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); if (value is ICodeStyleOption codeStyleOption) { // We store these as strings, so serialize value = codeStyleOption.ToXElement().ToString(); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so serialize if (value is NamingStylePreferences valueToSerialize) { value = valueToSerialize.CreateXElement().ToString(); } } _settingManager.SetValueAsync(storageKey, value, isMachineLocal: false); return true; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/MetadataTypeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MetadataTypeTests : CSharpTestBase { [Fact] public void MetadataNamespaceSymbol01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns = ns2.GetMembers("Serialization").Single() as NamespaceSymbol; Assert.Equal(mscorNS, ns.ContainingAssembly); Assert.Equal(ns2, ns.ContainingSymbol); Assert.Equal(ns2, ns.ContainingNamespace); Assert.True(ns.IsDefinition); // ? Assert.True(ns.IsNamespace); Assert.False(ns.IsType); Assert.Equal(SymbolKind.Namespace, ns.Kind); // bug 1995 Assert.Equal(Accessibility.Public, ns.DeclaredAccessibility); Assert.True(ns.IsStatic); Assert.False(ns.IsAbstract); Assert.False(ns.IsSealed); Assert.False(ns.IsVirtual); Assert.False(ns.IsOverride); // 47 types, 1 namespace (Formatters); Assert.Equal(48, ns.GetMembers().Length); Assert.Equal(47, ns.GetTypeMembers().Length); var fullName = "System.Runtime.Serialization"; Assert.Equal(fullName, ns.ToTestDisplayString()); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolClass01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns3.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; // internal static class Assert.Equal(0, class1.Arity); Assert.Equal(mscorNS, class1.ContainingAssembly); Assert.Equal(ns3, class1.ContainingSymbol); Assert.Equal(ns3, class1.ContainingNamespace); Assert.True(class1.IsDefinition); Assert.False(class1.IsNamespace); Assert.True(class1.IsType); Assert.True(class1.IsReferenceType); Assert.False(class1.IsValueType); Assert.Equal(SymbolKind.NamedType, class1.Kind); Assert.Equal(TypeKind.Class, class1.TypeKind); Assert.Equal(Accessibility.Internal, class1.DeclaredAccessibility); Assert.True(class1.IsStatic); Assert.False(class1.IsAbstract); Assert.False(class1.IsAbstract); Assert.False(class1.IsExtern); Assert.False(class1.IsSealed); Assert.False(class1.IsVirtual); Assert.False(class1.IsOverride); // 18 members Assert.Equal(18, class1.GetMembers().Length); Assert.Equal(0, class1.GetTypeMembers().Length); Assert.Equal(0, class1.Interfaces().Length); var fullName = "Microsoft.Runtime.Hosting.StrongNameHelpers"; // Internal: Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, class1.ToTestDisplayString()); Assert.Equal(0, class1.TypeArguments().Length); Assert.Equal(0, class1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolGenClass02() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("Dictionary").First() as NamedTypeSymbol; // public generic class Assert.Equal(2, type1.Arity); Assert.Equal(mscorNS, type1.ContainingAssembly); Assert.Equal(ns2, type1.ContainingSymbol); Assert.Equal(ns2, type1.ContainingNamespace); Assert.True(type1.IsDefinition); Assert.False(type1.IsNamespace); Assert.True(type1.IsType); Assert.True(type1.IsReferenceType); Assert.False(type1.IsValueType); Assert.Equal(SymbolKind.NamedType, type1.Kind); Assert.Equal(TypeKind.Class, type1.TypeKind); Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.False(type1.IsStatic); Assert.False(type1.IsAbstract); Assert.False(type1.IsSealed); Assert.False(type1.IsVirtual); Assert.False(type1.IsOverride); // 4 nested types, 67 members overall Assert.Equal(67, type1.GetMembers().Length); Assert.Equal(3, type1.GetTypeMembers().Length); // IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, // IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback Assert.Equal(10, type1.Interfaces().Length); var fullName = "System.Collections.Generic.Dictionary<TKey, TValue>"; // Internal Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, type1.ToTestDisplayString()); Assert.Equal(2, type1.TypeArguments().Length); Assert.Equal(2, type1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolGenInterface01() { var text = "public class A {}"; var compilation = CreateCompilation(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IList").First() as NamedTypeSymbol; // public generic interface Assert.Equal(1, type1.Arity); Assert.Equal(mscorNS, type1.ContainingAssembly); Assert.Equal(ns2, type1.ContainingSymbol); Assert.Equal(ns2, type1.ContainingNamespace); Assert.True(type1.IsDefinition); Assert.False(type1.IsNamespace); Assert.True(type1.IsType); Assert.True(type1.IsReferenceType); Assert.False(type1.IsValueType); Assert.Equal(SymbolKind.NamedType, type1.Kind); Assert.Equal(TypeKind.Interface, type1.TypeKind); Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.False(type1.IsStatic); Assert.True(type1.IsAbstract); Assert.False(type1.IsSealed); Assert.False(type1.IsVirtual); Assert.False(type1.IsOverride); Assert.False(type1.IsExtern); // 3 method, 2 get|set_<Prop> method, 1 Properties Assert.Equal(6, type1.GetMembers().Length); Assert.Equal(0, type1.GetTypeMembers().Length); // ICollection<T>, IEnumerable<T>, IEnumerable Assert.Equal(3, type1.Interfaces().Length); var fullName = "System.Collections.Generic.IList<T>"; // Internal Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, type1.ToTestDisplayString()); Assert.Equal(1, type1.TypeArguments().Length); Assert.Equal(1, type1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolStruct01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); var ns1 = mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Serialization").Single() as NamespaceSymbol; var type1 = ns3.GetTypeMembers("StreamingContext").First() as NamedTypeSymbol; Assert.Equal(mscorNS, type1.ContainingAssembly); Assert.Equal(ns3, type1.ContainingSymbol); Assert.Equal(ns3, type1.ContainingNamespace); Assert.True(type1.IsDefinition); Assert.False(type1.IsNamespace); Assert.True(type1.IsType); Assert.False(type1.IsReferenceType); Assert.True(type1.IsValueType); Assert.Equal(SymbolKind.NamedType, type1.Kind); Assert.Equal(TypeKind.Struct, type1.TypeKind); Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.False(type1.IsStatic); Assert.False(type1.IsAbstract); Assert.True(type1.IsSealed); Assert.False(type1.IsVirtual); Assert.False(type1.IsOverride); // 4 method + 1 synthesized ctor, 2 get_<Prop> method, 2 Properties, 2 fields Assert.Equal(11, type1.GetMembers().Length); Assert.Equal(0, type1.GetTypeMembers().Length); Assert.Equal(0, type1.Interfaces().Length); var fullName = "System.Runtime.Serialization.StreamingContext"; // Internal Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, type1.ToTestDisplayString()); Assert.Equal(0, type1.TypeArguments().Length); Assert.Equal(0, type1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataArrayTypeSymbol01() { // This is a copy of the EventProviderBase type which existed in a beta of .NET framework // 4.5. Replicating the structure of the type to maintain the test validation. var source1 = @" namespace System.Diagnostics.Eventing { internal class EventProviderBase { internal struct EventData { } internal EventData[] m_eventData = null; protected void WriteTransferEventHelper(int eventId, Guid relatedActivityId, params object[] args) { } } } "; var compilation1 = CreateEmptyCompilation(source1, new[] { TestMetadata.Net40.mscorlib, TestMetadata.Net40.SystemCore }); compilation1.VerifyDiagnostics(); var source2 = "public class A {}"; var compilation2 = CreateEmptyCompilation(source2, new MetadataReference[] { TestMetadata.Net40.mscorlib, TestMetadata.Net40.SystemCore, compilation1.EmitToImageReference() }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var compilation1Lib = compilation2.ExternalReferences[2]; var systemCoreNS = compilation2.GetReferencedAssemblySymbol(compilation1Lib); var ns1 = systemCoreNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Diagnostics").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Eventing").Single() as NamespaceSymbol; var type1 = ns3.GetTypeMembers("EventProviderBase").Single() as NamedTypeSymbol; // EventData[] var type2 = (type1.GetMembers("m_eventData").Single() as FieldSymbol).Type as ArrayTypeSymbol; var member2 = type1.GetMembers("WriteTransferEventHelper").Single() as MethodSymbol; Assert.Equal(3, member2.Parameters.Length); // params object[] var type3 = (member2.Parameters[2] as ParameterSymbol).Type as ArrayTypeSymbol; Assert.Equal(SymbolKind.ArrayType, type2.Kind); Assert.Equal(SymbolKind.ArrayType, type3.Kind); Assert.Equal(Accessibility.NotApplicable, type2.DeclaredAccessibility); Assert.Equal(Accessibility.NotApplicable, type3.DeclaredAccessibility); Assert.True(type2.IsSZArray); Assert.True(type3.IsSZArray); Assert.Equal(TypeKind.Array, type2.TypeKind); Assert.Equal(TypeKind.Array, type3.TypeKind); Assert.Equal("EventData", type2.ElementType.Name); Assert.Equal("Array", type2.BaseType().Name); Assert.Equal("Object", type3.ElementType.Name); Assert.Equal("System.Diagnostics.Eventing.EventProviderBase.EventData[]", type2.ToTestDisplayString()); Assert.Equal("System.Object[]", type3.ToTestDisplayString()); Assert.Equal(1, type2.Interfaces().Length); Assert.Equal(1, type3.Interfaces().Length); // bug // Assert.False(type2.IsDefinition); Assert.False(type2.IsNamespace); Assert.True(type3.IsType); Assert.True(type2.IsReferenceType); Assert.True(type2.ElementType.IsValueType); Assert.True(type3.IsReferenceType); Assert.False(type3.IsValueType); Assert.False(type2.IsStatic); Assert.False(type2.IsAbstract); Assert.False(type2.IsSealed); Assert.False(type3.IsVirtual); Assert.False(type3.IsOverride); Assert.Equal(0, type2.GetMembers().Length); Assert.Equal(0, type3.GetMembers(String.Empty).Length); Assert.Equal(0, type3.GetTypeMembers().Length); Assert.Equal(0, type2.GetTypeMembers(String.Empty).Length); Assert.Equal(0, type3.GetTypeMembers(String.Empty, 0).Length); Assert.Empty(compilation2.GetDeclarationDiagnostics()); } [Fact, WorkItem(531619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531619"), WorkItem(531619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531619")] public void InheritFromNetModuleMetadata01() { var modRef = TestReferences.MetadataTests.NetModule01.ModuleCS00; var text1 = @" class Test : StaticModClass {"; var text2 = @" public static int Main() { r"; var tree = SyntaxFactory.ParseSyntaxTree(String.Empty); var comp = CreateCompilation(source: tree, references: new[] { modRef }); var currComp = comp; var oldTree = comp.SyntaxTrees.First(); var oldIText = oldTree.GetText(); var span = new TextSpan(oldIText.Length, 0); var change = new TextChange(span, text1); var newIText = oldIText.WithChanges(change); var newTree = oldTree.WithChangedText(newIText); currComp = currComp.ReplaceSyntaxTree(oldTree, newTree); var model = currComp.GetSemanticModel(newTree); var id = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(s => s.ToString() == "StaticModClass").First(); // NRE is thrown later but this one has to be called first var symInfo = model.GetSymbolInfo(id); Assert.NotNull(symInfo.Symbol); oldTree = newTree; oldIText = oldTree.GetText(); span = new TextSpan(oldIText.Length, 0); change = new TextChange(span, text2); newIText = oldIText.WithChanges(change); newTree = oldTree.WithChangedText(newIText); currComp = currComp.ReplaceSyntaxTree(oldTree, newTree); model = currComp.GetSemanticModel(newTree); id = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(s => s.ToString() == "StaticModClass").First(); symInfo = model.GetSymbolInfo(id); Assert.NotNull(symInfo.Symbol); } [WorkItem(1066489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066489")] [Fact] public void InstanceIterator_ExplicitInterfaceImplementation_OldName() { var ilSource = @" .class interface public abstract auto ansi I`1<T> { .method public hidebysig newslot abstract virtual instance class [mscorlib]System.Collections.IEnumerable F() cil managed { } // end of method I`1::F } // end of class I`1 .class public auto ansi beforefieldinit C extends [mscorlib]System.Object implements class I`1<int32> { .class auto ansi sealed nested private beforefieldinit '<I<System.Int32>'.'F>d__0' extends [mscorlib]System.Object implements class [mscorlib]System.Collections.Generic.IEnumerable`1<object>, [mscorlib]System.Collections.IEnumerable, class [mscorlib]System.Collections.Generic.IEnumerator`1<object>, [mscorlib]System.Collections.IEnumerator, [mscorlib]System.IDisposable { .field private object '<>2__current' .field private int32 '<>1__state' .field private int32 '<>l__initialThreadId' .field public class C '<>4__this' .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.Generic.IEnumerator`1<object> 'System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator'() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance bool MoveNext() cil managed { ldnull throw } .method private hidebysig newslot specialname virtual final instance object 'System.Collections.Generic.IEnumerator<System.Object>.get_Current'() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance void System.Collections.IEnumerator.Reset() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance void System.IDisposable.Dispose() cil managed { ldnull throw } .method private hidebysig newslot specialname virtual final instance object System.Collections.IEnumerator.get_Current() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor(int32 '<>1__state') cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance object 'System.Collections.Generic.IEnumerator<System.Object>.Current'() { .get instance object C/'<I<System.Int32>'.'F>d__0'::'System.Collections.Generic.IEnumerator<System.Object>.get_Current'() } .property instance object System.Collections.IEnumerator.Current() { .get instance object C/'<I<System.Int32>'.'F>d__0'::System.Collections.IEnumerator.get_Current() } } // end of class '<I<System.Int32>'.'F>d__0' .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.IEnumerable 'I<System.Int32>.F'() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class C "; var comp = CreateCompilationWithILAndMscorlib40("", ilSource); var stateMachineClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<NamedTypeSymbol>().Single(); Assert.Equal("<I<System.Int32>.F>d__0", stateMachineClass.Name); // The name has been reconstructed correctly. Assert.Equal("C.<I<System.Int32>.F>d__0", stateMachineClass.ToTestDisplayString()); // SymbolDisplay works. Assert.Equal(stateMachineClass, comp.GetTypeByMetadataName("C+<I<System.Int32>.F>d__0")); // GetTypeByMetadataName works. } [ConditionalFact(typeof(ClrOnly))] [WorkItem(23761, "https://github.com/dotnet/roslyn/issues/23761")] // reason for skipping mono public void EmptyNamespaceNames() { var ilSource = @".class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } .namespace '.N' { .class public B { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace '.' { .class public C { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace '..' { .class public D { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace '..N' { .class public E { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace N.M { .class public F { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace 'N.M.' { .class public G { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace 'N.M..' { .class public H { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } }"; var comp = CreateCompilationWithILAndMscorlib40("", ilSource); comp.VerifyDiagnostics(); var builder = ArrayBuilder<string>.GetInstance(); var module = comp.GetMember<NamedTypeSymbol>("A").ContainingModule; GetAllNamespaceNames(builder, module.GlobalNamespace); Assert.Equal(new[] { "<global namespace>", "", ".", "..N", ".N", "N", "N.M", "N.M." }, builder); builder.Free(); } private static void GetAllNamespaceNames(ArrayBuilder<string> builder, NamespaceSymbol @namespace) { builder.Add(@namespace.ToTestDisplayString()); foreach (var member in @namespace.GetMembers()) { if (member.Kind != SymbolKind.Namespace) { continue; } GetAllNamespaceNames(builder, (NamespaceSymbol)member); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MetadataTypeTests : CSharpTestBase { [Fact] public void MetadataNamespaceSymbol01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns = ns2.GetMembers("Serialization").Single() as NamespaceSymbol; Assert.Equal(mscorNS, ns.ContainingAssembly); Assert.Equal(ns2, ns.ContainingSymbol); Assert.Equal(ns2, ns.ContainingNamespace); Assert.True(ns.IsDefinition); // ? Assert.True(ns.IsNamespace); Assert.False(ns.IsType); Assert.Equal(SymbolKind.Namespace, ns.Kind); // bug 1995 Assert.Equal(Accessibility.Public, ns.DeclaredAccessibility); Assert.True(ns.IsStatic); Assert.False(ns.IsAbstract); Assert.False(ns.IsSealed); Assert.False(ns.IsVirtual); Assert.False(ns.IsOverride); // 47 types, 1 namespace (Formatters); Assert.Equal(48, ns.GetMembers().Length); Assert.Equal(47, ns.GetTypeMembers().Length); var fullName = "System.Runtime.Serialization"; Assert.Equal(fullName, ns.ToTestDisplayString()); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolClass01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns3.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; // internal static class Assert.Equal(0, class1.Arity); Assert.Equal(mscorNS, class1.ContainingAssembly); Assert.Equal(ns3, class1.ContainingSymbol); Assert.Equal(ns3, class1.ContainingNamespace); Assert.True(class1.IsDefinition); Assert.False(class1.IsNamespace); Assert.True(class1.IsType); Assert.True(class1.IsReferenceType); Assert.False(class1.IsValueType); Assert.Equal(SymbolKind.NamedType, class1.Kind); Assert.Equal(TypeKind.Class, class1.TypeKind); Assert.Equal(Accessibility.Internal, class1.DeclaredAccessibility); Assert.True(class1.IsStatic); Assert.False(class1.IsAbstract); Assert.False(class1.IsAbstract); Assert.False(class1.IsExtern); Assert.False(class1.IsSealed); Assert.False(class1.IsVirtual); Assert.False(class1.IsOverride); // 18 members Assert.Equal(18, class1.GetMembers().Length); Assert.Equal(0, class1.GetTypeMembers().Length); Assert.Equal(0, class1.Interfaces().Length); var fullName = "Microsoft.Runtime.Hosting.StrongNameHelpers"; // Internal: Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, class1.ToTestDisplayString()); Assert.Equal(0, class1.TypeArguments().Length); Assert.Equal(0, class1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolGenClass02() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("Dictionary").First() as NamedTypeSymbol; // public generic class Assert.Equal(2, type1.Arity); Assert.Equal(mscorNS, type1.ContainingAssembly); Assert.Equal(ns2, type1.ContainingSymbol); Assert.Equal(ns2, type1.ContainingNamespace); Assert.True(type1.IsDefinition); Assert.False(type1.IsNamespace); Assert.True(type1.IsType); Assert.True(type1.IsReferenceType); Assert.False(type1.IsValueType); Assert.Equal(SymbolKind.NamedType, type1.Kind); Assert.Equal(TypeKind.Class, type1.TypeKind); Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.False(type1.IsStatic); Assert.False(type1.IsAbstract); Assert.False(type1.IsSealed); Assert.False(type1.IsVirtual); Assert.False(type1.IsOverride); // 4 nested types, 67 members overall Assert.Equal(67, type1.GetMembers().Length); Assert.Equal(3, type1.GetTypeMembers().Length); // IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, // IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback Assert.Equal(10, type1.Interfaces().Length); var fullName = "System.Collections.Generic.Dictionary<TKey, TValue>"; // Internal Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, type1.ToTestDisplayString()); Assert.Equal(2, type1.TypeArguments().Length); Assert.Equal(2, type1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolGenInterface01() { var text = "public class A {}"; var compilation = CreateCompilation(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IList").First() as NamedTypeSymbol; // public generic interface Assert.Equal(1, type1.Arity); Assert.Equal(mscorNS, type1.ContainingAssembly); Assert.Equal(ns2, type1.ContainingSymbol); Assert.Equal(ns2, type1.ContainingNamespace); Assert.True(type1.IsDefinition); Assert.False(type1.IsNamespace); Assert.True(type1.IsType); Assert.True(type1.IsReferenceType); Assert.False(type1.IsValueType); Assert.Equal(SymbolKind.NamedType, type1.Kind); Assert.Equal(TypeKind.Interface, type1.TypeKind); Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.False(type1.IsStatic); Assert.True(type1.IsAbstract); Assert.False(type1.IsSealed); Assert.False(type1.IsVirtual); Assert.False(type1.IsOverride); Assert.False(type1.IsExtern); // 3 method, 2 get|set_<Prop> method, 1 Properties Assert.Equal(6, type1.GetMembers().Length); Assert.Equal(0, type1.GetTypeMembers().Length); // ICollection<T>, IEnumerable<T>, IEnumerable Assert.Equal(3, type1.Interfaces().Length); var fullName = "System.Collections.Generic.IList<T>"; // Internal Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, type1.ToTestDisplayString()); Assert.Equal(1, type1.TypeArguments().Length); Assert.Equal(1, type1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolStruct01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); var ns1 = mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Serialization").Single() as NamespaceSymbol; var type1 = ns3.GetTypeMembers("StreamingContext").First() as NamedTypeSymbol; Assert.Equal(mscorNS, type1.ContainingAssembly); Assert.Equal(ns3, type1.ContainingSymbol); Assert.Equal(ns3, type1.ContainingNamespace); Assert.True(type1.IsDefinition); Assert.False(type1.IsNamespace); Assert.True(type1.IsType); Assert.False(type1.IsReferenceType); Assert.True(type1.IsValueType); Assert.Equal(SymbolKind.NamedType, type1.Kind); Assert.Equal(TypeKind.Struct, type1.TypeKind); Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.False(type1.IsStatic); Assert.False(type1.IsAbstract); Assert.True(type1.IsSealed); Assert.False(type1.IsVirtual); Assert.False(type1.IsOverride); // 4 method + 1 synthesized ctor, 2 get_<Prop> method, 2 Properties, 2 fields Assert.Equal(11, type1.GetMembers().Length); Assert.Equal(0, type1.GetTypeMembers().Length); Assert.Equal(0, type1.Interfaces().Length); var fullName = "System.Runtime.Serialization.StreamingContext"; // Internal Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, type1.ToTestDisplayString()); Assert.Equal(0, type1.TypeArguments().Length); Assert.Equal(0, type1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataArrayTypeSymbol01() { // This is a copy of the EventProviderBase type which existed in a beta of .NET framework // 4.5. Replicating the structure of the type to maintain the test validation. var source1 = @" namespace System.Diagnostics.Eventing { internal class EventProviderBase { internal struct EventData { } internal EventData[] m_eventData = null; protected void WriteTransferEventHelper(int eventId, Guid relatedActivityId, params object[] args) { } } } "; var compilation1 = CreateEmptyCompilation(source1, new[] { TestMetadata.Net40.mscorlib, TestMetadata.Net40.SystemCore }); compilation1.VerifyDiagnostics(); var source2 = "public class A {}"; var compilation2 = CreateEmptyCompilation(source2, new MetadataReference[] { TestMetadata.Net40.mscorlib, TestMetadata.Net40.SystemCore, compilation1.EmitToImageReference() }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var compilation1Lib = compilation2.ExternalReferences[2]; var systemCoreNS = compilation2.GetReferencedAssemblySymbol(compilation1Lib); var ns1 = systemCoreNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Diagnostics").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Eventing").Single() as NamespaceSymbol; var type1 = ns3.GetTypeMembers("EventProviderBase").Single() as NamedTypeSymbol; // EventData[] var type2 = (type1.GetMembers("m_eventData").Single() as FieldSymbol).Type as ArrayTypeSymbol; var member2 = type1.GetMembers("WriteTransferEventHelper").Single() as MethodSymbol; Assert.Equal(3, member2.Parameters.Length); // params object[] var type3 = (member2.Parameters[2] as ParameterSymbol).Type as ArrayTypeSymbol; Assert.Equal(SymbolKind.ArrayType, type2.Kind); Assert.Equal(SymbolKind.ArrayType, type3.Kind); Assert.Equal(Accessibility.NotApplicable, type2.DeclaredAccessibility); Assert.Equal(Accessibility.NotApplicable, type3.DeclaredAccessibility); Assert.True(type2.IsSZArray); Assert.True(type3.IsSZArray); Assert.Equal(TypeKind.Array, type2.TypeKind); Assert.Equal(TypeKind.Array, type3.TypeKind); Assert.Equal("EventData", type2.ElementType.Name); Assert.Equal("Array", type2.BaseType().Name); Assert.Equal("Object", type3.ElementType.Name); Assert.Equal("System.Diagnostics.Eventing.EventProviderBase.EventData[]", type2.ToTestDisplayString()); Assert.Equal("System.Object[]", type3.ToTestDisplayString()); Assert.Equal(1, type2.Interfaces().Length); Assert.Equal(1, type3.Interfaces().Length); // bug // Assert.False(type2.IsDefinition); Assert.False(type2.IsNamespace); Assert.True(type3.IsType); Assert.True(type2.IsReferenceType); Assert.True(type2.ElementType.IsValueType); Assert.True(type3.IsReferenceType); Assert.False(type3.IsValueType); Assert.False(type2.IsStatic); Assert.False(type2.IsAbstract); Assert.False(type2.IsSealed); Assert.False(type3.IsVirtual); Assert.False(type3.IsOverride); Assert.Equal(0, type2.GetMembers().Length); Assert.Equal(0, type3.GetMembers(String.Empty).Length); Assert.Equal(0, type3.GetTypeMembers().Length); Assert.Equal(0, type2.GetTypeMembers(String.Empty).Length); Assert.Equal(0, type3.GetTypeMembers(String.Empty, 0).Length); Assert.Empty(compilation2.GetDeclarationDiagnostics()); } [Fact, WorkItem(531619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531619"), WorkItem(531619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531619")] public void InheritFromNetModuleMetadata01() { var modRef = TestReferences.MetadataTests.NetModule01.ModuleCS00; var text1 = @" class Test : StaticModClass {"; var text2 = @" public static int Main() { r"; var tree = SyntaxFactory.ParseSyntaxTree(String.Empty); var comp = CreateCompilation(source: tree, references: new[] { modRef }); var currComp = comp; var oldTree = comp.SyntaxTrees.First(); var oldIText = oldTree.GetText(); var span = new TextSpan(oldIText.Length, 0); var change = new TextChange(span, text1); var newIText = oldIText.WithChanges(change); var newTree = oldTree.WithChangedText(newIText); currComp = currComp.ReplaceSyntaxTree(oldTree, newTree); var model = currComp.GetSemanticModel(newTree); var id = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(s => s.ToString() == "StaticModClass").First(); // NRE is thrown later but this one has to be called first var symInfo = model.GetSymbolInfo(id); Assert.NotNull(symInfo.Symbol); oldTree = newTree; oldIText = oldTree.GetText(); span = new TextSpan(oldIText.Length, 0); change = new TextChange(span, text2); newIText = oldIText.WithChanges(change); newTree = oldTree.WithChangedText(newIText); currComp = currComp.ReplaceSyntaxTree(oldTree, newTree); model = currComp.GetSemanticModel(newTree); id = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(s => s.ToString() == "StaticModClass").First(); symInfo = model.GetSymbolInfo(id); Assert.NotNull(symInfo.Symbol); } [WorkItem(1066489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066489")] [Fact] public void InstanceIterator_ExplicitInterfaceImplementation_OldName() { var ilSource = @" .class interface public abstract auto ansi I`1<T> { .method public hidebysig newslot abstract virtual instance class [mscorlib]System.Collections.IEnumerable F() cil managed { } // end of method I`1::F } // end of class I`1 .class public auto ansi beforefieldinit C extends [mscorlib]System.Object implements class I`1<int32> { .class auto ansi sealed nested private beforefieldinit '<I<System.Int32>'.'F>d__0' extends [mscorlib]System.Object implements class [mscorlib]System.Collections.Generic.IEnumerable`1<object>, [mscorlib]System.Collections.IEnumerable, class [mscorlib]System.Collections.Generic.IEnumerator`1<object>, [mscorlib]System.Collections.IEnumerator, [mscorlib]System.IDisposable { .field private object '<>2__current' .field private int32 '<>1__state' .field private int32 '<>l__initialThreadId' .field public class C '<>4__this' .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.Generic.IEnumerator`1<object> 'System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator'() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance bool MoveNext() cil managed { ldnull throw } .method private hidebysig newslot specialname virtual final instance object 'System.Collections.Generic.IEnumerator<System.Object>.get_Current'() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance void System.Collections.IEnumerator.Reset() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance void System.IDisposable.Dispose() cil managed { ldnull throw } .method private hidebysig newslot specialname virtual final instance object System.Collections.IEnumerator.get_Current() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor(int32 '<>1__state') cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance object 'System.Collections.Generic.IEnumerator<System.Object>.Current'() { .get instance object C/'<I<System.Int32>'.'F>d__0'::'System.Collections.Generic.IEnumerator<System.Object>.get_Current'() } .property instance object System.Collections.IEnumerator.Current() { .get instance object C/'<I<System.Int32>'.'F>d__0'::System.Collections.IEnumerator.get_Current() } } // end of class '<I<System.Int32>'.'F>d__0' .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.IEnumerable 'I<System.Int32>.F'() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class C "; var comp = CreateCompilationWithILAndMscorlib40("", ilSource); var stateMachineClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<NamedTypeSymbol>().Single(); Assert.Equal("<I<System.Int32>.F>d__0", stateMachineClass.Name); // The name has been reconstructed correctly. Assert.Equal("C.<I<System.Int32>.F>d__0", stateMachineClass.ToTestDisplayString()); // SymbolDisplay works. Assert.Equal(stateMachineClass, comp.GetTypeByMetadataName("C+<I<System.Int32>.F>d__0")); // GetTypeByMetadataName works. } [ConditionalFact(typeof(ClrOnly))] [WorkItem(23761, "https://github.com/dotnet/roslyn/issues/23761")] // reason for skipping mono public void EmptyNamespaceNames() { var ilSource = @".class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } .namespace '.N' { .class public B { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace '.' { .class public C { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace '..' { .class public D { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace '..N' { .class public E { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace N.M { .class public F { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace 'N.M.' { .class public G { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace 'N.M..' { .class public H { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } }"; var comp = CreateCompilationWithILAndMscorlib40("", ilSource); comp.VerifyDiagnostics(); var builder = ArrayBuilder<string>.GetInstance(); var module = comp.GetMember<NamedTypeSymbol>("A").ContainingModule; GetAllNamespaceNames(builder, module.GlobalNamespace); Assert.Equal(new[] { "<global namespace>", "", ".", "..N", ".N", "N", "N.M", "N.M." }, builder); builder.Free(); } private static void GetAllNamespaceNames(ArrayBuilder<string> builder, NamespaceSymbol @namespace) { builder.Add(@namespace.ToTestDisplayString()); foreach (var member in @namespace.GetMembers()) { if (member.Kind != SymbolKind.Namespace) { continue; } GetAllNamespaceNames(builder, (NamespaceSymbol)member); } } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/EditorFeatures/Test/Diagnostics/IDEDiagnosticIDUniquenessTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public class IDEDiagnosticIDUniquenessTest { [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)] public void UniqueIDEDiagnosticIds() { var type = typeof(IDEDiagnosticIds); var listOfIDEDiagnosticIds = type.GetFields().Select(x => x.GetValue(null).ToString()).ToList(); Assert.Equal(listOfIDEDiagnosticIds.Count, listOfIDEDiagnosticIds.Distinct().Count()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public class IDEDiagnosticIDUniquenessTest { [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)] public void UniqueIDEDiagnosticIds() { var type = typeof(IDEDiagnosticIds); var listOfIDEDiagnosticIds = type.GetFields().Select(x => x.GetValue(null).ToString()).ToList(); Assert.Equal(listOfIDEDiagnosticIds.Count, listOfIDEDiagnosticIds.Distinct().Count()); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerFileReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Represents analyzers stored in an analyzer assembly file. /// </summary> /// <remarks> /// Analyzer are read from the file, owned by the reference, and doesn't change /// since the reference is accessed until the reference object is garbage collected. /// /// If you need to manage the lifetime of the analyzer reference (and the file stream) explicitly use <see cref="AnalyzerImageReference"/>. /// </remarks> public sealed class AnalyzerFileReference : AnalyzerReference, IEquatable<AnalyzerReference> { private delegate IEnumerable<string> AttributeLanguagesFunc(PEModule module, CustomAttributeHandle attribute); public override string FullPath { get; } private readonly IAnalyzerAssemblyLoader _assemblyLoader; private readonly Extensions<DiagnosticAnalyzer> _diagnosticAnalyzers; private readonly Extensions<ISourceGenerator> _generators; private string? _lazyDisplay; private object? _lazyIdentity; private Assembly? _lazyAssembly; public event EventHandler<AnalyzerLoadFailureEventArgs>? AnalyzerLoadFailed; /// <summary> /// Creates an AnalyzerFileReference with the given <paramref name="fullPath"/> and <paramref name="assemblyLoader"/>. /// </summary> /// <param name="fullPath">Full path of the analyzer assembly.</param> /// <param name="assemblyLoader">Loader for obtaining the <see cref="Assembly"/> from the <paramref name="fullPath"/></param> public AnalyzerFileReference(string fullPath, IAnalyzerAssemblyLoader assemblyLoader) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); FullPath = fullPath; _assemblyLoader = assemblyLoader ?? throw new ArgumentNullException(nameof(assemblyLoader)); _diagnosticAnalyzers = new(this, typeof(DiagnosticAnalyzerAttribute), GetDiagnosticsAnalyzerSupportedLanguages, allowNetFramework: true); _generators = new(this, typeof(GeneratorAttribute), GetGeneratorSupportedLanguages, allowNetFramework: false, coerceFunction: CoerceGeneratorType); // Note this analyzer full path as a dependency location, so that the analyzer loader // can correctly load analyzer dependencies. assemblyLoader.AddDependencyLocation(fullPath); } public IAnalyzerAssemblyLoader AssemblyLoader => _assemblyLoader; public override bool Equals(object? obj) => Equals(obj as AnalyzerFileReference); public bool Equals(AnalyzerFileReference? other) { if (ReferenceEquals(this, other)) { return true; } return other is object && ReferenceEquals(_assemblyLoader, other._assemblyLoader) && FullPath == other.FullPath; } // legacy, for backwards compat: public bool Equals(AnalyzerReference? other) { if (ReferenceEquals(this, other)) { return true; } if (other is null) { return false; } if (other is AnalyzerFileReference fileReference) { return Equals(fileReference); } return FullPath == other.FullPath; } public override int GetHashCode() => Hash.Combine(RuntimeHelpers.GetHashCode(_assemblyLoader), FullPath.GetHashCode()); public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages() { // This API returns duplicates of analyzers that support multiple languages. // We explicitly retain this behaviour to ensure back compat return _diagnosticAnalyzers.GetExtensionsForAllLanguages(includeDuplicates: true); } public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language) { return _diagnosticAnalyzers.GetExtensions(language); } public override ImmutableArray<ISourceGenerator> GetGeneratorsForAllLanguages() { return _generators.GetExtensionsForAllLanguages(includeDuplicates: false); } [Obsolete("Use GetGenerators(string language) or GetGeneratorsForAllLanguages()")] public override ImmutableArray<ISourceGenerator> GetGenerators() { return _generators.GetExtensions(LanguageNames.CSharp); } public override ImmutableArray<ISourceGenerator> GetGenerators(string language) { return _generators.GetExtensions(language); } public override string Display { get { if (_lazyDisplay == null) { InitializeDisplayAndId(); } return _lazyDisplay; } } public override object Id { get { if (_lazyIdentity == null) { InitializeDisplayAndId(); } return _lazyIdentity; } } [MemberNotNull(nameof(_lazyIdentity), nameof(_lazyDisplay))] private void InitializeDisplayAndId() { try { // AssemblyName.GetAssemblyName(path) is not available on CoreCLR. // Use our metadata reader to do the equivalent thing. using var reader = new PEReader(FileUtilities.OpenRead(FullPath)); var metadataReader = reader.GetMetadataReader(); var assemblyIdentity = metadataReader.ReadAssemblyIdentityOrThrow(); _lazyDisplay = assemblyIdentity.Name; _lazyIdentity = assemblyIdentity; } catch { _lazyDisplay = FileNameUtilities.GetFileName(FullPath, includeExtension: false); _lazyIdentity = _lazyDisplay; } } /// <summary> /// Adds the <see cref="ImmutableArray{T}"/> of <see cref="DiagnosticAnalyzer"/> defined in this assembly reference of given <paramref name="language"/>. /// </summary> internal void AddAnalyzers(ImmutableArray<DiagnosticAnalyzer>.Builder builder, string language) { _diagnosticAnalyzers.AddExtensions(builder, language); } /// <summary> /// Adds the <see cref="ImmutableArray{T}"/> of <see cref="ISourceGenerator"/> defined in this assembly reference of given <paramref name="language"/>. /// </summary> internal void AddGenerators(ImmutableArray<ISourceGenerator>.Builder builder, string language) { _generators.AddExtensions(builder, language); } private static AnalyzerLoadFailureEventArgs CreateAnalyzerFailedArgs(Exception e, string? typeName = null) { // unwrap: e = (e as TargetInvocationException) ?? e; // remove all line breaks from the exception message string message = e.Message.Replace("\r", "").Replace("\n", ""); var errorCode = (typeName != null) ? AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer : AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer; return new AnalyzerLoadFailureEventArgs(errorCode, message, e, typeName); } internal ImmutableSortedDictionary<string, ImmutableSortedSet<string>> GetAnalyzerTypeNameMap() { return _diagnosticAnalyzers.GetExtensionTypeNameMap(); } /// <summary> /// Opens the analyzer dll with the metadata reader and builds a map of language -> analyzer type names. /// </summary> /// <exception cref="BadImageFormatException">The PE image format is invalid.</exception> /// <exception cref="IOException">IO error reading the metadata.</exception> [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30449")] private static ImmutableSortedDictionary<string, ImmutableSortedSet<string>> GetAnalyzerTypeNameMap(string fullPath, Type attributeType, AttributeLanguagesFunc languagesFunc) { using var assembly = AssemblyMetadata.CreateFromFile(fullPath); // This is longer than strictly necessary to avoid thrashing the GC with string allocations // in the call to GetFullyQualifiedTypeNames. Specifically, this checks for the presence of // supported languages prior to creating the type names. var typeNameMap = from module in assembly.GetModules() from typeDefHandle in module.MetadataReader.TypeDefinitions let typeDef = module.MetadataReader.GetTypeDefinition(typeDefHandle) let supportedLanguages = GetSupportedLanguages(typeDef, module.Module, attributeType, languagesFunc) where supportedLanguages.Any() let typeName = GetFullyQualifiedTypeName(typeDef, module.Module) from supportedLanguage in supportedLanguages group typeName by supportedLanguage; return typeNameMap.ToImmutableSortedDictionary(g => g.Key, g => g.ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase); } private static IEnumerable<string> GetSupportedLanguages(TypeDefinition typeDef, PEModule peModule, Type attributeType, AttributeLanguagesFunc languagesFunc) { IEnumerable<string>? result = null; foreach (CustomAttributeHandle customAttrHandle in typeDef.GetCustomAttributes()) { if (peModule.IsTargetAttribute(customAttrHandle, attributeType.Namespace!, attributeType.Name, ctor: out _)) { if (languagesFunc(peModule, customAttrHandle) is { } attributeSupportedLanguages) { if (result is null) { result = attributeSupportedLanguages; } else { // This is a slow path, but only occurs if a single type has multiple // DiagnosticAnalyzerAttribute instances applied to it. result = result.Concat(attributeSupportedLanguages); } } } } return result ?? SpecializedCollections.EmptyEnumerable<string>(); } private static IEnumerable<string> GetDiagnosticsAnalyzerSupportedLanguages(PEModule peModule, CustomAttributeHandle customAttrHandle) { // The DiagnosticAnalyzerAttribute has one constructor, which has a string parameter for the // first supported language and an array parameter for additional supported languages. // Parse the argument blob to extract the languages. BlobReader argsReader = peModule.GetMemoryReaderOrThrow(peModule.GetCustomAttributeValueOrThrow(customAttrHandle)); return ReadLanguagesFromAttribute(ref argsReader); } private static IEnumerable<string> GetGeneratorSupportedLanguages(PEModule peModule, CustomAttributeHandle customAttrHandle) { // The GeneratorAttribute has two constructors: one default, and one with a string parameter for the // first supported language and an array parameter for additional supported languages. BlobReader argsReader = peModule.GetMemoryReaderOrThrow(peModule.GetCustomAttributeValueOrThrow(customAttrHandle)); if (argsReader.Length == 4) { // default ctor return ImmutableArray.Create(LanguageNames.CSharp); } else { // Parse the argument blob to extract the languages. return ReadLanguagesFromAttribute(ref argsReader); } } // https://github.com/dotnet/roslyn/issues/53994 tracks re-enabling nullable and fixing this method #nullable disable private static IEnumerable<string> ReadLanguagesFromAttribute(ref BlobReader argsReader) { if (argsReader.Length > 4) { // Arguments are present--check prologue. if (argsReader.ReadByte() == 1 && argsReader.ReadByte() == 0) { string firstLanguageName; if (!PEModule.CrackStringInAttributeValue(out firstLanguageName, ref argsReader)) { return SpecializedCollections.EmptyEnumerable<string>(); } ImmutableArray<string> additionalLanguageNames; if (PEModule.CrackStringArrayInAttributeValue(out additionalLanguageNames, ref argsReader)) { if (additionalLanguageNames.Length == 0) { return SpecializedCollections.SingletonEnumerable(firstLanguageName); } return additionalLanguageNames.Insert(0, firstLanguageName); } } } return SpecializedCollections.EmptyEnumerable<string>(); } #nullable enable private static ISourceGenerator? CoerceGeneratorType(object? generator) { if (generator is IIncrementalGenerator incrementalGenerator) { return new IncrementalGeneratorWrapper(incrementalGenerator); } return null; } private static string GetFullyQualifiedTypeName(TypeDefinition typeDef, PEModule peModule) { var declaringType = typeDef.GetDeclaringType(); // Non nested type - simply get the full name if (declaringType.IsNil) { return peModule.GetFullNameOrThrow(typeDef.Namespace, typeDef.Name); } else { var declaringTypeDef = peModule.MetadataReader.GetTypeDefinition(declaringType); return GetFullyQualifiedTypeName(declaringTypeDef, peModule) + "+" + peModule.MetadataReader.GetString(typeDef.Name); } } private sealed class Extensions<TExtension> where TExtension : class { private readonly AnalyzerFileReference _reference; private readonly Type _attributeType; private readonly AttributeLanguagesFunc _languagesFunc; private readonly bool _allowNetFramework; private readonly Func<object?, TExtension?>? _coerceFunction; private ImmutableArray<TExtension> _lazyAllExtensions; private ImmutableDictionary<string, ImmutableArray<TExtension>> _lazyExtensionsPerLanguage; private ImmutableSortedDictionary<string, ImmutableSortedSet<string>>? _lazyExtensionTypeNameMap; internal Extensions(AnalyzerFileReference reference, Type attributeType, AttributeLanguagesFunc languagesFunc, bool allowNetFramework, Func<object?, TExtension?>? coerceFunction = null) { _reference = reference; _attributeType = attributeType; _languagesFunc = languagesFunc; _allowNetFramework = allowNetFramework; _coerceFunction = coerceFunction; _lazyAllExtensions = default; _lazyExtensionsPerLanguage = ImmutableDictionary<string, ImmutableArray<TExtension>>.Empty; } internal ImmutableArray<TExtension> GetExtensionsForAllLanguages(bool includeDuplicates) { if (_lazyAllExtensions.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyAllExtensions, CreateExtensionsForAllLanguages(this, includeDuplicates)); } return _lazyAllExtensions; } private static ImmutableArray<TExtension> CreateExtensionsForAllLanguages(Extensions<TExtension> extensions, bool includeDuplicates) { // Get all analyzers in the assembly. var map = ImmutableSortedDictionary.CreateBuilder<string, ImmutableArray<TExtension>>(StringComparer.OrdinalIgnoreCase); extensions.AddExtensions(map); var builder = ImmutableArray.CreateBuilder<TExtension>(); foreach (var analyzers in map.Values) { foreach (var analyzer in analyzers) { builder.Add(analyzer); } } if (includeDuplicates) { return builder.ToImmutable(); } else { return builder.Distinct(ExtTypeComparer.Instance).ToImmutableArray(); } } private class ExtTypeComparer : IEqualityComparer<TExtension> { public static readonly ExtTypeComparer Instance = new(); public bool Equals(TExtension? x, TExtension? y) => object.Equals(x?.GetType(), y?.GetType()); public int GetHashCode(TExtension obj) => obj.GetType().GetHashCode(); } internal ImmutableArray<TExtension> GetExtensions(string language) { if (string.IsNullOrEmpty(language)) { throw new ArgumentException("language"); } return ImmutableInterlocked.GetOrAdd(ref _lazyExtensionsPerLanguage, language, CreateLanguageSpecificExtensions, this); } private static ImmutableArray<TExtension> CreateLanguageSpecificExtensions(string language, Extensions<TExtension> extensions) { // Get all analyzers in the assembly for the given language. var builder = ImmutableArray.CreateBuilder<TExtension>(); extensions.AddExtensions(builder, language); return builder.ToImmutable(); } internal ImmutableSortedDictionary<string, ImmutableSortedSet<string>> GetExtensionTypeNameMap() { if (_lazyExtensionTypeNameMap == null) { var analyzerTypeNameMap = GetAnalyzerTypeNameMap(_reference.FullPath, _attributeType, _languagesFunc); Interlocked.CompareExchange(ref _lazyExtensionTypeNameMap, analyzerTypeNameMap, null); } return _lazyExtensionTypeNameMap; } internal void AddExtensions(ImmutableSortedDictionary<string, ImmutableArray<TExtension>>.Builder builder) { ImmutableSortedDictionary<string, ImmutableSortedSet<string>> analyzerTypeNameMap; Assembly analyzerAssembly; try { analyzerTypeNameMap = GetExtensionTypeNameMap(); if (analyzerTypeNameMap.Count == 0) { return; } analyzerAssembly = _reference.GetAssembly(); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e)); return; } var initialCount = builder.Count; var reportedError = false; // Add language specific analyzers. foreach (var (language, _) in analyzerTypeNameMap) { if (language == null) { continue; } var analyzers = GetLanguageSpecificAnalyzers(analyzerAssembly, analyzerTypeNameMap, language, ref reportedError); builder.Add(language, analyzers); } // If there were types with the attribute but weren't an analyzer, generate a diagnostic. // If we've reported errors already while trying to instantiate types, don't complain that there are no analyzers. if (builder.Count == initialCount && !reportedError) { _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, CodeAnalysisResources.NoAnalyzersFound)); } } internal void AddExtensions(ImmutableArray<TExtension>.Builder builder, string language) { ImmutableSortedDictionary<string, ImmutableSortedSet<string>> analyzerTypeNameMap; Assembly analyzerAssembly; try { analyzerTypeNameMap = GetExtensionTypeNameMap(); // If there are no analyzers, don't load the assembly at all. if (!analyzerTypeNameMap.ContainsKey(language)) { return; } analyzerAssembly = _reference.GetAssembly(); if (analyzerAssembly == null) { // This can be null if NoOpAnalyzerAssemblyLoader is used. return; } } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e)); return; } var initialCount = builder.Count; var reportedError = false; // Add language specific analyzers. var analyzers = GetLanguageSpecificAnalyzers(analyzerAssembly, analyzerTypeNameMap, language, ref reportedError); builder.AddRange(analyzers); // If there were types with the attribute but weren't an analyzer, generate a diagnostic. // If we've reported errors already while trying to instantiate types, don't complain that there are no analyzers. if (builder.Count == initialCount && !reportedError) { _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, CodeAnalysisResources.NoAnalyzersFound)); } } private ImmutableArray<TExtension> GetLanguageSpecificAnalyzers(Assembly analyzerAssembly, ImmutableSortedDictionary<string, ImmutableSortedSet<string>> analyzerTypeNameMap, string language, ref bool reportedError) { ImmutableSortedSet<string>? languageSpecificAnalyzerTypeNames; if (!analyzerTypeNameMap.TryGetValue(language, out languageSpecificAnalyzerTypeNames)) { return ImmutableArray<TExtension>.Empty; } return this.GetAnalyzersForTypeNames(analyzerAssembly, languageSpecificAnalyzerTypeNames, ref reportedError); } private ImmutableArray<TExtension> GetAnalyzersForTypeNames(Assembly analyzerAssembly, IEnumerable<string> analyzerTypeNames, ref bool reportedError) { var analyzers = ImmutableArray.CreateBuilder<TExtension>(); // Given the type names, get the actual System.Type and try to create an instance of the type through reflection. foreach (var typeName in analyzerTypeNames) { Type? type; try { type = analyzerAssembly.GetType(typeName, throwOnError: true, ignoreCase: false); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e, typeName)); reportedError = true; continue; } Debug.Assert(type != null); // check if this references net framework, and issue a diagnostic that this isn't supported if (!_allowNetFramework) { var targetFrameworkAttribute = analyzerAssembly.GetCustomAttribute<TargetFrameworkAttribute>(); if (targetFrameworkAttribute is object && targetFrameworkAttribute.FrameworkName.StartsWith(".NETFramework", StringComparison.OrdinalIgnoreCase)) { _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs( AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework, string.Format(CodeAnalysisResources.AssemblyReferencesNetFramework, typeName), typeNameOpt: typeName)); continue; } } object? typeInstance; try { typeInstance = Activator.CreateInstance(type); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e, typeName)); reportedError = true; continue; } TExtension? analyzer = typeInstance as TExtension ?? _coerceFunction?.Invoke(typeInstance); if (analyzer != null) { analyzers.Add(analyzer); } } return analyzers.ToImmutable(); } } public Assembly GetAssembly() { if (_lazyAssembly == null) { _lazyAssembly = _assemblyLoader.LoadFromPath(FullPath); } return _lazyAssembly; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Represents analyzers stored in an analyzer assembly file. /// </summary> /// <remarks> /// Analyzer are read from the file, owned by the reference, and doesn't change /// since the reference is accessed until the reference object is garbage collected. /// /// If you need to manage the lifetime of the analyzer reference (and the file stream) explicitly use <see cref="AnalyzerImageReference"/>. /// </remarks> public sealed class AnalyzerFileReference : AnalyzerReference, IEquatable<AnalyzerReference> { private delegate IEnumerable<string> AttributeLanguagesFunc(PEModule module, CustomAttributeHandle attribute); public override string FullPath { get; } private readonly IAnalyzerAssemblyLoader _assemblyLoader; private readonly Extensions<DiagnosticAnalyzer> _diagnosticAnalyzers; private readonly Extensions<ISourceGenerator> _generators; private string? _lazyDisplay; private object? _lazyIdentity; private Assembly? _lazyAssembly; public event EventHandler<AnalyzerLoadFailureEventArgs>? AnalyzerLoadFailed; /// <summary> /// Creates an AnalyzerFileReference with the given <paramref name="fullPath"/> and <paramref name="assemblyLoader"/>. /// </summary> /// <param name="fullPath">Full path of the analyzer assembly.</param> /// <param name="assemblyLoader">Loader for obtaining the <see cref="Assembly"/> from the <paramref name="fullPath"/></param> public AnalyzerFileReference(string fullPath, IAnalyzerAssemblyLoader assemblyLoader) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); FullPath = fullPath; _assemblyLoader = assemblyLoader ?? throw new ArgumentNullException(nameof(assemblyLoader)); _diagnosticAnalyzers = new(this, typeof(DiagnosticAnalyzerAttribute), GetDiagnosticsAnalyzerSupportedLanguages, allowNetFramework: true); _generators = new(this, typeof(GeneratorAttribute), GetGeneratorSupportedLanguages, allowNetFramework: false, coerceFunction: CoerceGeneratorType); // Note this analyzer full path as a dependency location, so that the analyzer loader // can correctly load analyzer dependencies. assemblyLoader.AddDependencyLocation(fullPath); } public IAnalyzerAssemblyLoader AssemblyLoader => _assemblyLoader; public override bool Equals(object? obj) => Equals(obj as AnalyzerFileReference); public bool Equals(AnalyzerFileReference? other) { if (ReferenceEquals(this, other)) { return true; } return other is object && ReferenceEquals(_assemblyLoader, other._assemblyLoader) && FullPath == other.FullPath; } // legacy, for backwards compat: public bool Equals(AnalyzerReference? other) { if (ReferenceEquals(this, other)) { return true; } if (other is null) { return false; } if (other is AnalyzerFileReference fileReference) { return Equals(fileReference); } return FullPath == other.FullPath; } public override int GetHashCode() => Hash.Combine(RuntimeHelpers.GetHashCode(_assemblyLoader), FullPath.GetHashCode()); public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages() { // This API returns duplicates of analyzers that support multiple languages. // We explicitly retain this behaviour to ensure back compat return _diagnosticAnalyzers.GetExtensionsForAllLanguages(includeDuplicates: true); } public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language) { return _diagnosticAnalyzers.GetExtensions(language); } public override ImmutableArray<ISourceGenerator> GetGeneratorsForAllLanguages() { return _generators.GetExtensionsForAllLanguages(includeDuplicates: false); } [Obsolete("Use GetGenerators(string language) or GetGeneratorsForAllLanguages()")] public override ImmutableArray<ISourceGenerator> GetGenerators() { return _generators.GetExtensions(LanguageNames.CSharp); } public override ImmutableArray<ISourceGenerator> GetGenerators(string language) { return _generators.GetExtensions(language); } public override string Display { get { if (_lazyDisplay == null) { InitializeDisplayAndId(); } return _lazyDisplay; } } public override object Id { get { if (_lazyIdentity == null) { InitializeDisplayAndId(); } return _lazyIdentity; } } [MemberNotNull(nameof(_lazyIdentity), nameof(_lazyDisplay))] private void InitializeDisplayAndId() { try { // AssemblyName.GetAssemblyName(path) is not available on CoreCLR. // Use our metadata reader to do the equivalent thing. using var reader = new PEReader(FileUtilities.OpenRead(FullPath)); var metadataReader = reader.GetMetadataReader(); var assemblyIdentity = metadataReader.ReadAssemblyIdentityOrThrow(); _lazyDisplay = assemblyIdentity.Name; _lazyIdentity = assemblyIdentity; } catch { _lazyDisplay = FileNameUtilities.GetFileName(FullPath, includeExtension: false); _lazyIdentity = _lazyDisplay; } } /// <summary> /// Adds the <see cref="ImmutableArray{T}"/> of <see cref="DiagnosticAnalyzer"/> defined in this assembly reference of given <paramref name="language"/>. /// </summary> internal void AddAnalyzers(ImmutableArray<DiagnosticAnalyzer>.Builder builder, string language) { _diagnosticAnalyzers.AddExtensions(builder, language); } /// <summary> /// Adds the <see cref="ImmutableArray{T}"/> of <see cref="ISourceGenerator"/> defined in this assembly reference of given <paramref name="language"/>. /// </summary> internal void AddGenerators(ImmutableArray<ISourceGenerator>.Builder builder, string language) { _generators.AddExtensions(builder, language); } private static AnalyzerLoadFailureEventArgs CreateAnalyzerFailedArgs(Exception e, string? typeName = null) { // unwrap: e = (e as TargetInvocationException) ?? e; // remove all line breaks from the exception message string message = e.Message.Replace("\r", "").Replace("\n", ""); var errorCode = (typeName != null) ? AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer : AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer; return new AnalyzerLoadFailureEventArgs(errorCode, message, e, typeName); } internal ImmutableSortedDictionary<string, ImmutableSortedSet<string>> GetAnalyzerTypeNameMap() { return _diagnosticAnalyzers.GetExtensionTypeNameMap(); } /// <summary> /// Opens the analyzer dll with the metadata reader and builds a map of language -> analyzer type names. /// </summary> /// <exception cref="BadImageFormatException">The PE image format is invalid.</exception> /// <exception cref="IOException">IO error reading the metadata.</exception> [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30449")] private static ImmutableSortedDictionary<string, ImmutableSortedSet<string>> GetAnalyzerTypeNameMap(string fullPath, Type attributeType, AttributeLanguagesFunc languagesFunc) { using var assembly = AssemblyMetadata.CreateFromFile(fullPath); // This is longer than strictly necessary to avoid thrashing the GC with string allocations // in the call to GetFullyQualifiedTypeNames. Specifically, this checks for the presence of // supported languages prior to creating the type names. var typeNameMap = from module in assembly.GetModules() from typeDefHandle in module.MetadataReader.TypeDefinitions let typeDef = module.MetadataReader.GetTypeDefinition(typeDefHandle) let supportedLanguages = GetSupportedLanguages(typeDef, module.Module, attributeType, languagesFunc) where supportedLanguages.Any() let typeName = GetFullyQualifiedTypeName(typeDef, module.Module) from supportedLanguage in supportedLanguages group typeName by supportedLanguage; return typeNameMap.ToImmutableSortedDictionary(g => g.Key, g => g.ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase); } private static IEnumerable<string> GetSupportedLanguages(TypeDefinition typeDef, PEModule peModule, Type attributeType, AttributeLanguagesFunc languagesFunc) { IEnumerable<string>? result = null; foreach (CustomAttributeHandle customAttrHandle in typeDef.GetCustomAttributes()) { if (peModule.IsTargetAttribute(customAttrHandle, attributeType.Namespace!, attributeType.Name, ctor: out _)) { if (languagesFunc(peModule, customAttrHandle) is { } attributeSupportedLanguages) { if (result is null) { result = attributeSupportedLanguages; } else { // This is a slow path, but only occurs if a single type has multiple // DiagnosticAnalyzerAttribute instances applied to it. result = result.Concat(attributeSupportedLanguages); } } } } return result ?? SpecializedCollections.EmptyEnumerable<string>(); } private static IEnumerable<string> GetDiagnosticsAnalyzerSupportedLanguages(PEModule peModule, CustomAttributeHandle customAttrHandle) { // The DiagnosticAnalyzerAttribute has one constructor, which has a string parameter for the // first supported language and an array parameter for additional supported languages. // Parse the argument blob to extract the languages. BlobReader argsReader = peModule.GetMemoryReaderOrThrow(peModule.GetCustomAttributeValueOrThrow(customAttrHandle)); return ReadLanguagesFromAttribute(ref argsReader); } private static IEnumerable<string> GetGeneratorSupportedLanguages(PEModule peModule, CustomAttributeHandle customAttrHandle) { // The GeneratorAttribute has two constructors: one default, and one with a string parameter for the // first supported language and an array parameter for additional supported languages. BlobReader argsReader = peModule.GetMemoryReaderOrThrow(peModule.GetCustomAttributeValueOrThrow(customAttrHandle)); if (argsReader.Length == 4) { // default ctor return ImmutableArray.Create(LanguageNames.CSharp); } else { // Parse the argument blob to extract the languages. return ReadLanguagesFromAttribute(ref argsReader); } } // https://github.com/dotnet/roslyn/issues/53994 tracks re-enabling nullable and fixing this method #nullable disable private static IEnumerable<string> ReadLanguagesFromAttribute(ref BlobReader argsReader) { if (argsReader.Length > 4) { // Arguments are present--check prologue. if (argsReader.ReadByte() == 1 && argsReader.ReadByte() == 0) { string firstLanguageName; if (!PEModule.CrackStringInAttributeValue(out firstLanguageName, ref argsReader)) { return SpecializedCollections.EmptyEnumerable<string>(); } ImmutableArray<string> additionalLanguageNames; if (PEModule.CrackStringArrayInAttributeValue(out additionalLanguageNames, ref argsReader)) { if (additionalLanguageNames.Length == 0) { return SpecializedCollections.SingletonEnumerable(firstLanguageName); } return additionalLanguageNames.Insert(0, firstLanguageName); } } } return SpecializedCollections.EmptyEnumerable<string>(); } #nullable enable private static ISourceGenerator? CoerceGeneratorType(object? generator) { if (generator is IIncrementalGenerator incrementalGenerator) { return new IncrementalGeneratorWrapper(incrementalGenerator); } return null; } private static string GetFullyQualifiedTypeName(TypeDefinition typeDef, PEModule peModule) { var declaringType = typeDef.GetDeclaringType(); // Non nested type - simply get the full name if (declaringType.IsNil) { return peModule.GetFullNameOrThrow(typeDef.Namespace, typeDef.Name); } else { var declaringTypeDef = peModule.MetadataReader.GetTypeDefinition(declaringType); return GetFullyQualifiedTypeName(declaringTypeDef, peModule) + "+" + peModule.MetadataReader.GetString(typeDef.Name); } } private sealed class Extensions<TExtension> where TExtension : class { private readonly AnalyzerFileReference _reference; private readonly Type _attributeType; private readonly AttributeLanguagesFunc _languagesFunc; private readonly bool _allowNetFramework; private readonly Func<object?, TExtension?>? _coerceFunction; private ImmutableArray<TExtension> _lazyAllExtensions; private ImmutableDictionary<string, ImmutableArray<TExtension>> _lazyExtensionsPerLanguage; private ImmutableSortedDictionary<string, ImmutableSortedSet<string>>? _lazyExtensionTypeNameMap; internal Extensions(AnalyzerFileReference reference, Type attributeType, AttributeLanguagesFunc languagesFunc, bool allowNetFramework, Func<object?, TExtension?>? coerceFunction = null) { _reference = reference; _attributeType = attributeType; _languagesFunc = languagesFunc; _allowNetFramework = allowNetFramework; _coerceFunction = coerceFunction; _lazyAllExtensions = default; _lazyExtensionsPerLanguage = ImmutableDictionary<string, ImmutableArray<TExtension>>.Empty; } internal ImmutableArray<TExtension> GetExtensionsForAllLanguages(bool includeDuplicates) { if (_lazyAllExtensions.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyAllExtensions, CreateExtensionsForAllLanguages(this, includeDuplicates)); } return _lazyAllExtensions; } private static ImmutableArray<TExtension> CreateExtensionsForAllLanguages(Extensions<TExtension> extensions, bool includeDuplicates) { // Get all analyzers in the assembly. var map = ImmutableSortedDictionary.CreateBuilder<string, ImmutableArray<TExtension>>(StringComparer.OrdinalIgnoreCase); extensions.AddExtensions(map); var builder = ImmutableArray.CreateBuilder<TExtension>(); foreach (var analyzers in map.Values) { foreach (var analyzer in analyzers) { builder.Add(analyzer); } } if (includeDuplicates) { return builder.ToImmutable(); } else { return builder.Distinct(ExtTypeComparer.Instance).ToImmutableArray(); } } private class ExtTypeComparer : IEqualityComparer<TExtension> { public static readonly ExtTypeComparer Instance = new(); public bool Equals(TExtension? x, TExtension? y) => object.Equals(x?.GetType(), y?.GetType()); public int GetHashCode(TExtension obj) => obj.GetType().GetHashCode(); } internal ImmutableArray<TExtension> GetExtensions(string language) { if (string.IsNullOrEmpty(language)) { throw new ArgumentException("language"); } return ImmutableInterlocked.GetOrAdd(ref _lazyExtensionsPerLanguage, language, CreateLanguageSpecificExtensions, this); } private static ImmutableArray<TExtension> CreateLanguageSpecificExtensions(string language, Extensions<TExtension> extensions) { // Get all analyzers in the assembly for the given language. var builder = ImmutableArray.CreateBuilder<TExtension>(); extensions.AddExtensions(builder, language); return builder.ToImmutable(); } internal ImmutableSortedDictionary<string, ImmutableSortedSet<string>> GetExtensionTypeNameMap() { if (_lazyExtensionTypeNameMap == null) { var analyzerTypeNameMap = GetAnalyzerTypeNameMap(_reference.FullPath, _attributeType, _languagesFunc); Interlocked.CompareExchange(ref _lazyExtensionTypeNameMap, analyzerTypeNameMap, null); } return _lazyExtensionTypeNameMap; } internal void AddExtensions(ImmutableSortedDictionary<string, ImmutableArray<TExtension>>.Builder builder) { ImmutableSortedDictionary<string, ImmutableSortedSet<string>> analyzerTypeNameMap; Assembly analyzerAssembly; try { analyzerTypeNameMap = GetExtensionTypeNameMap(); if (analyzerTypeNameMap.Count == 0) { return; } analyzerAssembly = _reference.GetAssembly(); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e)); return; } var initialCount = builder.Count; var reportedError = false; // Add language specific analyzers. foreach (var (language, _) in analyzerTypeNameMap) { if (language == null) { continue; } var analyzers = GetLanguageSpecificAnalyzers(analyzerAssembly, analyzerTypeNameMap, language, ref reportedError); builder.Add(language, analyzers); } // If there were types with the attribute but weren't an analyzer, generate a diagnostic. // If we've reported errors already while trying to instantiate types, don't complain that there are no analyzers. if (builder.Count == initialCount && !reportedError) { _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, CodeAnalysisResources.NoAnalyzersFound)); } } internal void AddExtensions(ImmutableArray<TExtension>.Builder builder, string language) { ImmutableSortedDictionary<string, ImmutableSortedSet<string>> analyzerTypeNameMap; Assembly analyzerAssembly; try { analyzerTypeNameMap = GetExtensionTypeNameMap(); // If there are no analyzers, don't load the assembly at all. if (!analyzerTypeNameMap.ContainsKey(language)) { return; } analyzerAssembly = _reference.GetAssembly(); if (analyzerAssembly == null) { // This can be null if NoOpAnalyzerAssemblyLoader is used. return; } } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e)); return; } var initialCount = builder.Count; var reportedError = false; // Add language specific analyzers. var analyzers = GetLanguageSpecificAnalyzers(analyzerAssembly, analyzerTypeNameMap, language, ref reportedError); builder.AddRange(analyzers); // If there were types with the attribute but weren't an analyzer, generate a diagnostic. // If we've reported errors already while trying to instantiate types, don't complain that there are no analyzers. if (builder.Count == initialCount && !reportedError) { _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, CodeAnalysisResources.NoAnalyzersFound)); } } private ImmutableArray<TExtension> GetLanguageSpecificAnalyzers(Assembly analyzerAssembly, ImmutableSortedDictionary<string, ImmutableSortedSet<string>> analyzerTypeNameMap, string language, ref bool reportedError) { ImmutableSortedSet<string>? languageSpecificAnalyzerTypeNames; if (!analyzerTypeNameMap.TryGetValue(language, out languageSpecificAnalyzerTypeNames)) { return ImmutableArray<TExtension>.Empty; } return this.GetAnalyzersForTypeNames(analyzerAssembly, languageSpecificAnalyzerTypeNames, ref reportedError); } private ImmutableArray<TExtension> GetAnalyzersForTypeNames(Assembly analyzerAssembly, IEnumerable<string> analyzerTypeNames, ref bool reportedError) { var analyzers = ImmutableArray.CreateBuilder<TExtension>(); // Given the type names, get the actual System.Type and try to create an instance of the type through reflection. foreach (var typeName in analyzerTypeNames) { Type? type; try { type = analyzerAssembly.GetType(typeName, throwOnError: true, ignoreCase: false); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e, typeName)); reportedError = true; continue; } Debug.Assert(type != null); // check if this references net framework, and issue a diagnostic that this isn't supported if (!_allowNetFramework) { var targetFrameworkAttribute = analyzerAssembly.GetCustomAttribute<TargetFrameworkAttribute>(); if (targetFrameworkAttribute is object && targetFrameworkAttribute.FrameworkName.StartsWith(".NETFramework", StringComparison.OrdinalIgnoreCase)) { _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs( AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework, string.Format(CodeAnalysisResources.AssemblyReferencesNetFramework, typeName), typeNameOpt: typeName)); continue; } } object? typeInstance; try { typeInstance = Activator.CreateInstance(type); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e, typeName)); reportedError = true; continue; } TExtension? analyzer = typeInstance as TExtension ?? _coerceFunction?.Invoke(typeInstance); if (analyzer != null) { analyzers.Add(analyzer); } } return analyzers.ToImmutable(); } } public Assembly GetAssembly() { if (_lazyAssembly == null) { _lazyAssembly = _assemblyLoader.LoadFromPath(FullPath); } return _lazyAssembly; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/StateMachineTypeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class StateMachineTypeSymbol : SynthesizedContainer, ISynthesizedMethodBodyImplementationSymbol { private ImmutableArray<CSharpAttributeData> _attributes; public readonly MethodSymbol KickoffMethod; public StateMachineTypeSymbol(VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, MethodSymbol kickoffMethod, int kickoffMethodOrdinal) : base(MakeName(slotAllocatorOpt, compilationState, kickoffMethod, kickoffMethodOrdinal), kickoffMethod) { Debug.Assert(kickoffMethod != null); this.KickoffMethod = kickoffMethod; } private static string MakeName(VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, MethodSymbol kickoffMethod, int kickoffMethodOrdinal) { return slotAllocatorOpt?.PreviousStateMachineTypeName ?? GeneratedNames.MakeStateMachineTypeName(kickoffMethod.Name, kickoffMethodOrdinal, compilationState.ModuleBuilderOpt.CurrentGenerationOrdinal); } private static int SequenceNumber(MethodSymbol kickoffMethod) { // return a unique sequence number for the async implementation class that is independent of the compilation state. int count = 0; foreach (var m in kickoffMethod.ContainingType.GetMembers(kickoffMethod.Name)) { count++; if ((object)kickoffMethod == m) { return count; } } return count; } public override Symbol ContainingSymbol { get { return KickoffMethod.ContainingType; } } bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency { get { // MoveNext method contains user code from the async/iterator method: return true; } } IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method { get { return KickoffMethod; } } public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { if (_attributes.IsDefault) { Debug.Assert(base.GetAttributes().Length == 0); ArrayBuilder<CSharpAttributeData> builder = null; // Inherit some attributes from the container of the kickoff method var kickoffType = KickoffMethod.ContainingType; foreach (var attribute in kickoffType.GetAttributes()) { if (attribute.IsTargetAttribute(kickoffType, AttributeDescription.DebuggerNonUserCodeAttribute) || attribute.IsTargetAttribute(kickoffType, AttributeDescription.DebuggerStepThroughAttribute)) { if (builder == null) { builder = ArrayBuilder<CSharpAttributeData>.GetInstance(2); // only 2 different attributes are inherited at the moment } builder.Add(attribute); } } ImmutableInterlocked.InterlockedCompareExchange(ref _attributes, builder == null ? ImmutableArray<CSharpAttributeData>.Empty : builder.ToImmutableAndFree(), default(ImmutableArray<CSharpAttributeData>)); } return _attributes; } public sealed override bool AreLocalsZeroed => KickoffMethod.AreLocalsZeroed; internal override bool HasCodeAnalysisEmbeddedAttribute => false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class StateMachineTypeSymbol : SynthesizedContainer, ISynthesizedMethodBodyImplementationSymbol { private ImmutableArray<CSharpAttributeData> _attributes; public readonly MethodSymbol KickoffMethod; public StateMachineTypeSymbol(VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, MethodSymbol kickoffMethod, int kickoffMethodOrdinal) : base(MakeName(slotAllocatorOpt, compilationState, kickoffMethod, kickoffMethodOrdinal), kickoffMethod) { Debug.Assert(kickoffMethod != null); this.KickoffMethod = kickoffMethod; } private static string MakeName(VariableSlotAllocator slotAllocatorOpt, TypeCompilationState compilationState, MethodSymbol kickoffMethod, int kickoffMethodOrdinal) { return slotAllocatorOpt?.PreviousStateMachineTypeName ?? GeneratedNames.MakeStateMachineTypeName(kickoffMethod.Name, kickoffMethodOrdinal, compilationState.ModuleBuilderOpt.CurrentGenerationOrdinal); } private static int SequenceNumber(MethodSymbol kickoffMethod) { // return a unique sequence number for the async implementation class that is independent of the compilation state. int count = 0; foreach (var m in kickoffMethod.ContainingType.GetMembers(kickoffMethod.Name)) { count++; if ((object)kickoffMethod == m) { return count; } } return count; } public override Symbol ContainingSymbol { get { return KickoffMethod.ContainingType; } } bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency { get { // MoveNext method contains user code from the async/iterator method: return true; } } IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method { get { return KickoffMethod; } } public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { if (_attributes.IsDefault) { Debug.Assert(base.GetAttributes().Length == 0); ArrayBuilder<CSharpAttributeData> builder = null; // Inherit some attributes from the container of the kickoff method var kickoffType = KickoffMethod.ContainingType; foreach (var attribute in kickoffType.GetAttributes()) { if (attribute.IsTargetAttribute(kickoffType, AttributeDescription.DebuggerNonUserCodeAttribute) || attribute.IsTargetAttribute(kickoffType, AttributeDescription.DebuggerStepThroughAttribute)) { if (builder == null) { builder = ArrayBuilder<CSharpAttributeData>.GetInstance(2); // only 2 different attributes are inherited at the moment } builder.Add(attribute); } } ImmutableInterlocked.InterlockedCompareExchange(ref _attributes, builder == null ? ImmutableArray<CSharpAttributeData>.Empty : builder.ToImmutableAndFree(), default(ImmutableArray<CSharpAttributeData>)); } return _attributes; } public sealed override bool AreLocalsZeroed => KickoffMethod.AreLocalsZeroed; internal override bool HasCodeAnalysisEmbeddedAttribute => false; } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/Core/Portable/Completion/CompletionContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// The context presented to a <see cref="CompletionProvider"/> when providing completions. /// </summary> public sealed class CompletionContext { private readonly List<CompletionItem> _items; internal IReadOnlyList<CompletionItem> Items => _items; internal CompletionProvider Provider { get; } /// <summary> /// The document that completion was invoked within. /// </summary> public Document Document { get; } /// <summary> /// The caret position when completion was triggered. /// </summary> public int Position { get; } /// <summary> /// The span of the syntax element at the caret position. /// /// This is the most common value used for <see cref="CompletionItem.Span"/> and will /// be automatically assigned to any <see cref="CompletionItem"/> that has no <see cref="CompletionItem.Span"/> specified. /// </summary> [Obsolete("Not used anymore. Use CompletionListSpan instead.", error: true)] public TextSpan DefaultItemSpan { get; } /// <summary> /// The span of the document the completion list corresponds to. It will be set initially to /// the result of <see cref="CompletionService.GetDefaultCompletionListSpan"/>, but it can /// be overwritten during <see cref="CompletionService.GetCompletionsAsync"/>. The purpose /// of the span is to: /// 1. Signify where the completions should be presented. /// 2. Designate any existing text in the document that should be used for filtering. /// 3. Specify, by default, what portion of the text should be replaced when a completion /// item is committed. /// </summary> public TextSpan CompletionListSpan { get; set; } /// <summary> /// The triggering action that caused completion to be started. /// </summary> public CompletionTrigger Trigger { get; } /// <summary> /// The options that completion was started with. /// </summary> public OptionSet Options { get; } /// <summary> /// The cancellation token to use for this operation. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Set to true if the items added here should be the only items presented to the user. /// </summary> public bool IsExclusive { get; set; } /// <summary> /// Set to true if the corresponding provider can provide extended items with current context, /// regardless of whether those items are actually added. i.e. it might be disabled by default, /// but we still want to show the expander so user can explicitly request them to be added to /// completion list if we are in the appropriate context. /// </summary> internal bool ExpandItemsAvailable { get; set; } /// <summary> /// Creates a <see cref="CompletionContext"/> instance. /// </summary> public CompletionContext( CompletionProvider provider, Document document, int position, TextSpan defaultSpan, CompletionTrigger trigger, OptionSet options, CancellationToken cancellationToken) { Provider = provider ?? throw new ArgumentNullException(nameof(provider)); Document = document ?? throw new ArgumentNullException(nameof(document)); Position = position; CompletionListSpan = defaultSpan; Trigger = trigger; Options = options ?? throw new ArgumentNullException(nameof(options)); CancellationToken = cancellationToken; _items = new List<CompletionItem>(); } public void AddItem(CompletionItem item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } item = FixItem(item); _items.Add(item); } public void AddItems(IEnumerable<CompletionItem> items) { if (items == null) { throw new ArgumentNullException(nameof(items)); } foreach (var item in items) { AddItem(item); } } private CompletionItem _suggestionModeItem; /// <summary> /// An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode. /// /// Suggestion mode disables auto-selection of items in the list, giving preference to the text typed by the user unless a specific item is selected manually. /// /// Specifying a <see cref="SuggestionModeItem"/> is a request that the completion host operate in suggestion mode. /// The item specified determines the text displayed and the description associated with it unless a different item is manually selected. /// /// No text is ever inserted when this item is completed, leaving the text the user typed instead. /// </summary> public CompletionItem SuggestionModeItem { get { return _suggestionModeItem; } set { _suggestionModeItem = value; if (_suggestionModeItem != null) { _suggestionModeItem = FixItem(_suggestionModeItem); } } } private CompletionItem FixItem(CompletionItem item) { // remember provider so we can find it again later item.ProviderName = Provider.Name; item.Span = CompletionListSpan; return item; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// The context presented to a <see cref="CompletionProvider"/> when providing completions. /// </summary> public sealed class CompletionContext { private readonly List<CompletionItem> _items; internal IReadOnlyList<CompletionItem> Items => _items; internal CompletionProvider Provider { get; } /// <summary> /// The document that completion was invoked within. /// </summary> public Document Document { get; } /// <summary> /// The caret position when completion was triggered. /// </summary> public int Position { get; } /// <summary> /// The span of the syntax element at the caret position. /// /// This is the most common value used for <see cref="CompletionItem.Span"/> and will /// be automatically assigned to any <see cref="CompletionItem"/> that has no <see cref="CompletionItem.Span"/> specified. /// </summary> [Obsolete("Not used anymore. Use CompletionListSpan instead.", error: true)] public TextSpan DefaultItemSpan { get; } /// <summary> /// The span of the document the completion list corresponds to. It will be set initially to /// the result of <see cref="CompletionService.GetDefaultCompletionListSpan"/>, but it can /// be overwritten during <see cref="CompletionService.GetCompletionsAsync"/>. The purpose /// of the span is to: /// 1. Signify where the completions should be presented. /// 2. Designate any existing text in the document that should be used for filtering. /// 3. Specify, by default, what portion of the text should be replaced when a completion /// item is committed. /// </summary> public TextSpan CompletionListSpan { get; set; } /// <summary> /// The triggering action that caused completion to be started. /// </summary> public CompletionTrigger Trigger { get; } /// <summary> /// The options that completion was started with. /// </summary> public OptionSet Options { get; } /// <summary> /// The cancellation token to use for this operation. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Set to true if the items added here should be the only items presented to the user. /// </summary> public bool IsExclusive { get; set; } /// <summary> /// Set to true if the corresponding provider can provide extended items with current context, /// regardless of whether those items are actually added. i.e. it might be disabled by default, /// but we still want to show the expander so user can explicitly request them to be added to /// completion list if we are in the appropriate context. /// </summary> internal bool ExpandItemsAvailable { get; set; } /// <summary> /// Creates a <see cref="CompletionContext"/> instance. /// </summary> public CompletionContext( CompletionProvider provider, Document document, int position, TextSpan defaultSpan, CompletionTrigger trigger, OptionSet options, CancellationToken cancellationToken) { Provider = provider ?? throw new ArgumentNullException(nameof(provider)); Document = document ?? throw new ArgumentNullException(nameof(document)); Position = position; CompletionListSpan = defaultSpan; Trigger = trigger; Options = options ?? throw new ArgumentNullException(nameof(options)); CancellationToken = cancellationToken; _items = new List<CompletionItem>(); } public void AddItem(CompletionItem item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } item = FixItem(item); _items.Add(item); } public void AddItems(IEnumerable<CompletionItem> items) { if (items == null) { throw new ArgumentNullException(nameof(items)); } foreach (var item in items) { AddItem(item); } } private CompletionItem _suggestionModeItem; /// <summary> /// An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode. /// /// Suggestion mode disables auto-selection of items in the list, giving preference to the text typed by the user unless a specific item is selected manually. /// /// Specifying a <see cref="SuggestionModeItem"/> is a request that the completion host operate in suggestion mode. /// The item specified determines the text displayed and the description associated with it unless a different item is manually selected. /// /// No text is ever inserted when this item is completed, leaving the text the user typed instead. /// </summary> public CompletionItem SuggestionModeItem { get { return _suggestionModeItem; } set { _suggestionModeItem = value; if (_suggestionModeItem != null) { _suggestionModeItem = FixItem(_suggestionModeItem); } } } private CompletionItem FixItem(CompletionItem item) { // remember provider so we can find it again later item.ProviderName = Provider.Name; item.Span = CompletionListSpan; return item; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/Remote/Core/CancellationTokenSourceExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Remote { internal static class CancellationTokenSourceExtensions { /// <summary> /// Automatically cancels the <paramref name="cancellationTokenSource"/> if the input <paramref name="task"/> /// completes in a <see cref="TaskStatus.Canceled"/> or <see cref="TaskStatus.Faulted"/> state. /// </summary> /// <param name="cancellationTokenSource">The cancellation token source.</param> /// <param name="task">The task to monitor.</param> public static void CancelOnAbnormalCompletion(this CancellationTokenSource cancellationTokenSource, Task task) { if (cancellationTokenSource is null) throw new ArgumentNullException(nameof(cancellationTokenSource)); _ = task.ContinueWith( static (_, state) => { try { ((CancellationTokenSource)state!).Cancel(); } catch (ObjectDisposedException) { // cancellation source is already disposed } }, state: cancellationTokenSource, CancellationToken.None, TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Remote { internal static class CancellationTokenSourceExtensions { /// <summary> /// Automatically cancels the <paramref name="cancellationTokenSource"/> if the input <paramref name="task"/> /// completes in a <see cref="TaskStatus.Canceled"/> or <see cref="TaskStatus.Faulted"/> state. /// </summary> /// <param name="cancellationTokenSource">The cancellation token source.</param> /// <param name="task">The task to monitor.</param> public static void CancelOnAbnormalCompletion(this CancellationTokenSource cancellationTokenSource, Task task) { if (cancellationTokenSource is null) throw new ArgumentNullException(nameof(cancellationTokenSource)); _ = task.ContinueWith( static (_, state) => { try { ((CancellationTokenSource)state!).Cancel(); } catch (ObjectDisposedException) { // cancellation source is already disposed } }, state: cancellationTokenSource, CancellationToken.None, TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Portable/FlowAnalysis/DefinitelyAssignedWalker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if DEBUG // See comment in DefiniteAssignment. #define REFERENCE_STATE #endif using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A region analysis walker that computes the set of variables that are definitely assigned /// when a region is entered or exited. /// </summary> internal sealed class DefinitelyAssignedWalker : AbstractRegionDataFlowPass { private readonly HashSet<Symbol> _definitelyAssignedOnEntry = new HashSet<Symbol>(); private readonly HashSet<Symbol> _definitelyAssignedOnExit = new HashSet<Symbol>(); private DefinitelyAssignedWalker( CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) : base(compilation, member, node, firstInRegion, lastInRegion) { } internal static (HashSet<Symbol> entry, HashSet<Symbol> exit) Analyze( CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) { var walker = new DefinitelyAssignedWalker(compilation, member, node, firstInRegion, lastInRegion); try { bool badRegion = false; walker.Analyze(ref badRegion, diagnostics: null); return badRegion ? (new HashSet<Symbol>(), new HashSet<Symbol>()) : (walker._definitelyAssignedOnEntry, walker._definitelyAssignedOnExit); } finally { walker.Free(); } } protected override void EnterRegion() { ProcessRegion(_definitelyAssignedOnEntry); base.EnterRegion(); } protected override void LeaveRegion() { ProcessRegion(_definitelyAssignedOnExit); base.LeaveRegion(); } private void ProcessRegion(HashSet<Symbol> definitelyAssigned) { // this can happen multiple times as flow analysis is multi-pass. Always // take the latest data and use that to determine our result. definitelyAssigned.Clear(); if (this.IsConditionalState) { // We're in a state where there are different flow paths (i.e. when-true and when-false). // In that case, a variable is only definitely assigned if it's definitely assigned through // both paths. this.ProcessState(definitelyAssigned, this.StateWhenTrue, this.StateWhenFalse); } else { this.ProcessState(definitelyAssigned, this.State, state2opt: null); } } #if REFERENCE_STATE private void ProcessState(HashSet<Symbol> definitelyAssigned, LocalState state1, LocalState state2opt) #else private void ProcessState(HashSet<Symbol> definitelyAssigned, LocalState state1, LocalState? state2opt) #endif { foreach (var slot in state1.Assigned.TrueBits()) { if (slot < variableBySlot.Count && state2opt?.IsAssigned(slot) != false && variableBySlot[slot].Symbol is { } symbol && symbol.Kind != SymbolKind.Field) { definitelyAssigned.Add(symbol); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if DEBUG // See comment in DefiniteAssignment. #define REFERENCE_STATE #endif using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A region analysis walker that computes the set of variables that are definitely assigned /// when a region is entered or exited. /// </summary> internal sealed class DefinitelyAssignedWalker : AbstractRegionDataFlowPass { private readonly HashSet<Symbol> _definitelyAssignedOnEntry = new HashSet<Symbol>(); private readonly HashSet<Symbol> _definitelyAssignedOnExit = new HashSet<Symbol>(); private DefinitelyAssignedWalker( CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) : base(compilation, member, node, firstInRegion, lastInRegion) { } internal static (HashSet<Symbol> entry, HashSet<Symbol> exit) Analyze( CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion) { var walker = new DefinitelyAssignedWalker(compilation, member, node, firstInRegion, lastInRegion); try { bool badRegion = false; walker.Analyze(ref badRegion, diagnostics: null); return badRegion ? (new HashSet<Symbol>(), new HashSet<Symbol>()) : (walker._definitelyAssignedOnEntry, walker._definitelyAssignedOnExit); } finally { walker.Free(); } } protected override void EnterRegion() { ProcessRegion(_definitelyAssignedOnEntry); base.EnterRegion(); } protected override void LeaveRegion() { ProcessRegion(_definitelyAssignedOnExit); base.LeaveRegion(); } private void ProcessRegion(HashSet<Symbol> definitelyAssigned) { // this can happen multiple times as flow analysis is multi-pass. Always // take the latest data and use that to determine our result. definitelyAssigned.Clear(); if (this.IsConditionalState) { // We're in a state where there are different flow paths (i.e. when-true and when-false). // In that case, a variable is only definitely assigned if it's definitely assigned through // both paths. this.ProcessState(definitelyAssigned, this.StateWhenTrue, this.StateWhenFalse); } else { this.ProcessState(definitelyAssigned, this.State, state2opt: null); } } #if REFERENCE_STATE private void ProcessState(HashSet<Symbol> definitelyAssigned, LocalState state1, LocalState state2opt) #else private void ProcessState(HashSet<Symbol> definitelyAssigned, LocalState state1, LocalState? state2opt) #endif { foreach (var slot in state1.Assigned.TrueBits()) { if (slot < variableBySlot.Count && state2opt?.IsAssigned(slot) != false && variableBySlot[slot].Symbol is { } symbol && symbol.Kind != SymbolKind.Field) { definitelyAssigned.Add(symbol); } } } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.ParsedSyntaxTree.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public partial class CSharpSyntaxTree { private class ParsedSyntaxTree : CSharpSyntaxTree { private readonly CSharpParseOptions _options; private readonly string _path; private readonly CSharpSyntaxNode _root; private readonly bool _hasCompilationUnitRoot; private readonly Encoding? _encodingOpt; private readonly SourceHashAlgorithm _checksumAlgorithm; private readonly ImmutableDictionary<string, ReportDiagnostic> _diagnosticOptions; private SourceText? _lazyText; internal ParsedSyntaxTree( SourceText? textOpt, Encoding? encodingOpt, SourceHashAlgorithm checksumAlgorithm, string path, CSharpParseOptions options, CSharpSyntaxNode root, Syntax.InternalSyntax.DirectiveStack directives, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool cloneRoot) { Debug.Assert(root != null); Debug.Assert(options != null); Debug.Assert(textOpt == null || textOpt.Encoding == encodingOpt && textOpt.ChecksumAlgorithm == checksumAlgorithm); _lazyText = textOpt; _encodingOpt = encodingOpt ?? textOpt?.Encoding; _checksumAlgorithm = checksumAlgorithm; _options = options; _path = path ?? string.Empty; _root = cloneRoot ? this.CloneNodeAsRoot(root) : root; _hasCompilationUnitRoot = root.Kind() == SyntaxKind.CompilationUnit; _diagnosticOptions = diagnosticOptions ?? EmptyDiagnosticOptions; this.SetDirectiveStack(directives); } public override string FilePath { get { return _path; } } public override SourceText GetText(CancellationToken cancellationToken) { if (_lazyText == null) { Interlocked.CompareExchange(ref _lazyText, this.GetRoot(cancellationToken).GetText(_encodingOpt, _checksumAlgorithm), null); } return _lazyText; } public override bool TryGetText([NotNullWhen(true)] out SourceText? text) { text = _lazyText; return text != null; } public override Encoding? Encoding { get { return _encodingOpt; } } public override int Length { get { return _root.FullSpan.Length; } } public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken) { return _root; } public override bool TryGetRoot(out CSharpSyntaxNode root) { root = _root; return true; } public override bool HasCompilationUnitRoot { get { return _hasCompilationUnitRoot; } } public override CSharpParseOptions Options { get { return _options; } } [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public override ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions => _diagnosticOptions; public override SyntaxReference GetReference(SyntaxNode node) { return new SimpleSyntaxReference(node); } public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options) { if (ReferenceEquals(_root, root) && ReferenceEquals(_options, options)) { return this; } return new ParsedSyntaxTree( textOpt: null, _encodingOpt, _checksumAlgorithm, _path, (CSharpParseOptions)options, (CSharpSyntaxNode)root, _directives, _diagnosticOptions, cloneRoot: true); } public override SyntaxTree WithFilePath(string path) { if (_path == path) { return this; } return new ParsedSyntaxTree( _lazyText, _encodingOpt, _checksumAlgorithm, path, _options, _root, _directives, _diagnosticOptions, cloneRoot: true); } [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public override SyntaxTree WithDiagnosticOptions(ImmutableDictionary<string, ReportDiagnostic> options) { if (options is null) { options = EmptyDiagnosticOptions; } if (ReferenceEquals(_diagnosticOptions, options)) { return this; } return new ParsedSyntaxTree( _lazyText, _encodingOpt, _checksumAlgorithm, _path, _options, _root, _directives, options, cloneRoot: true); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public partial class CSharpSyntaxTree { private class ParsedSyntaxTree : CSharpSyntaxTree { private readonly CSharpParseOptions _options; private readonly string _path; private readonly CSharpSyntaxNode _root; private readonly bool _hasCompilationUnitRoot; private readonly Encoding? _encodingOpt; private readonly SourceHashAlgorithm _checksumAlgorithm; private readonly ImmutableDictionary<string, ReportDiagnostic> _diagnosticOptions; private SourceText? _lazyText; internal ParsedSyntaxTree( SourceText? textOpt, Encoding? encodingOpt, SourceHashAlgorithm checksumAlgorithm, string path, CSharpParseOptions options, CSharpSyntaxNode root, Syntax.InternalSyntax.DirectiveStack directives, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool cloneRoot) { Debug.Assert(root != null); Debug.Assert(options != null); Debug.Assert(textOpt == null || textOpt.Encoding == encodingOpt && textOpt.ChecksumAlgorithm == checksumAlgorithm); _lazyText = textOpt; _encodingOpt = encodingOpt ?? textOpt?.Encoding; _checksumAlgorithm = checksumAlgorithm; _options = options; _path = path ?? string.Empty; _root = cloneRoot ? this.CloneNodeAsRoot(root) : root; _hasCompilationUnitRoot = root.Kind() == SyntaxKind.CompilationUnit; _diagnosticOptions = diagnosticOptions ?? EmptyDiagnosticOptions; this.SetDirectiveStack(directives); } public override string FilePath { get { return _path; } } public override SourceText GetText(CancellationToken cancellationToken) { if (_lazyText == null) { Interlocked.CompareExchange(ref _lazyText, this.GetRoot(cancellationToken).GetText(_encodingOpt, _checksumAlgorithm), null); } return _lazyText; } public override bool TryGetText([NotNullWhen(true)] out SourceText? text) { text = _lazyText; return text != null; } public override Encoding? Encoding { get { return _encodingOpt; } } public override int Length { get { return _root.FullSpan.Length; } } public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken) { return _root; } public override bool TryGetRoot(out CSharpSyntaxNode root) { root = _root; return true; } public override bool HasCompilationUnitRoot { get { return _hasCompilationUnitRoot; } } public override CSharpParseOptions Options { get { return _options; } } [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public override ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions => _diagnosticOptions; public override SyntaxReference GetReference(SyntaxNode node) { return new SimpleSyntaxReference(node); } public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options) { if (ReferenceEquals(_root, root) && ReferenceEquals(_options, options)) { return this; } return new ParsedSyntaxTree( textOpt: null, _encodingOpt, _checksumAlgorithm, _path, (CSharpParseOptions)options, (CSharpSyntaxNode)root, _directives, _diagnosticOptions, cloneRoot: true); } public override SyntaxTree WithFilePath(string path) { if (_path == path) { return this; } return new ParsedSyntaxTree( _lazyText, _encodingOpt, _checksumAlgorithm, path, _options, _root, _directives, _diagnosticOptions, cloneRoot: true); } [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public override SyntaxTree WithDiagnosticOptions(ImmutableDictionary<string, ReportDiagnostic> options) { if (options is null) { options = EmptyDiagnosticOptions; } if (ReferenceEquals(_diagnosticOptions, options)) { return this; } return new ParsedSyntaxTree( _lazyText, _encodingOpt, _checksumAlgorithm, _path, _options, _root, _directives, options, cloneRoot: true); } } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/RecommendationHelpers.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports System.Text Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders Friend Module RecommendationHelpers Friend Function IsOnErrorStatement(node As SyntaxNode) As Boolean Return TypeOf node Is OnErrorGoToStatementSyntax OrElse TypeOf node Is OnErrorResumeNextStatementSyntax End Function ''' <summary> ''' Returns the parent of the node given. node may be null, which will cause this function to return null. ''' </summary> <Extension()> Friend Function GetParentOrNull(node As SyntaxNode) As SyntaxNode Return If(node Is Nothing, Nothing, node.Parent) End Function <Extension()> Friend Function IsFollowingCompleteAsNewClause(token As SyntaxToken) As Boolean Dim asNewClause = token.GetAncestor(Of AsNewClauseSyntax)() If asNewClause Is Nothing Then Return False End If Dim lastToken As SyntaxToken Select Case asNewClause.NewExpression.Kind Case SyntaxKind.ObjectCreationExpression Dim objectCreation = DirectCast(asNewClause.NewExpression, ObjectCreationExpressionSyntax) lastToken = If(objectCreation.ArgumentList IsNot Nothing, objectCreation.ArgumentList.CloseParenToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case SyntaxKind.AnonymousObjectCreationExpression Dim anonymousObjectCreation = DirectCast(asNewClause.NewExpression, AnonymousObjectCreationExpressionSyntax) lastToken = If(anonymousObjectCreation.Initializer IsNot Nothing, anonymousObjectCreation.Initializer.CloseBraceToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case SyntaxKind.ArrayCreationExpression Dim arrayCreation = DirectCast(asNewClause.NewExpression, ArrayCreationExpressionSyntax) lastToken = If(arrayCreation.Initializer IsNot Nothing, arrayCreation.Initializer.CloseBraceToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case Else Throw ExceptionUtilities.UnexpectedValue(asNewClause.NewExpression.Kind) End Select Return token = lastToken End Function <Extension()> Private Function IsLastTokenOfObjectCreation(token As SyntaxToken, objectCreation As ObjectCreationExpressionSyntax) As Boolean If objectCreation Is Nothing Then Return False End If Dim lastToken = If(objectCreation.ArgumentList IsNot Nothing, objectCreation.ArgumentList.CloseParenToken, objectCreation.Type.GetLastToken(includeZeroWidth:=True)) Return token = lastToken End Function <Extension()> Friend Function IsFollowingCompleteObjectCreationInitializer(token As SyntaxToken) As Boolean Dim variableDeclarator = token.GetAncestor(Of VariableDeclaratorSyntax)() If variableDeclarator Is Nothing Then Return False End If Dim objectCreation = token.GetAncestors(Of ObjectCreationExpressionSyntax)() _ .Where(Function(oc) oc.Parent IsNot Nothing AndAlso oc.Parent.Kind <> SyntaxKind.AsNewClause AndAlso variableDeclarator.Initializer IsNot Nothing AndAlso variableDeclarator.Initializer.Value Is oc) _ .FirstOrDefault() Return token.IsLastTokenOfObjectCreation(objectCreation) End Function <Extension()> Friend Function IsFollowingCompleteObjectCreation(token As SyntaxToken) As Boolean Dim objectCreation = token.GetAncestor(Of ObjectCreationExpressionSyntax)() Return token.IsLastTokenOfObjectCreation(objectCreation) End Function <Extension()> Friend Function LastJoinKey(collection As SeparatedSyntaxList(Of JoinConditionSyntax)) As ExpressionSyntax Dim lastJoinCondition = collection.LastOrDefault() If lastJoinCondition IsNot Nothing Then Return lastJoinCondition.Right Else Return Nothing End If End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As IdentifierNameSyntax) As Boolean Return _ identifierSyntax IsNot Nothing AndAlso token = identifierSyntax.Identifier AndAlso identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As ModifiedIdentifierSyntax) As Boolean Return _ identifierSyntax IsNot Nothing AndAlso token = identifierSyntax.Identifier AndAlso identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, node As SyntaxNode) As Boolean If node Is Nothing Then Return False End If Dim identifierName = TryCast(node, IdentifierNameSyntax) If token.IsFromIdentifierNode(identifierName) Then Return True End If Dim modifiedIdentifierName = TryCast(node, ModifiedIdentifierSyntax) If token.IsFromIdentifierNode(modifiedIdentifierName) Then Return True End If Return False End Function <Extension()> Friend Function IsFromIdentifierNode(Of TParent As SyntaxNode)(token As SyntaxToken, identifierNodeSelector As Func(Of TParent, SyntaxNode)) As Boolean Dim ancestor = token.GetAncestor(Of TParent)() If ancestor Is Nothing Then Return False End If Return token.IsFromIdentifierNode(identifierNodeSelector(ancestor)) End Function Friend Function CreateRecommendedKeywordForIntrinsicOperator(kind As SyntaxKind, firstLine As String, glyph As Glyph, intrinsicOperator As AbstractIntrinsicOperatorDocumentation, Optional semanticModel As SemanticModel = Nothing, Optional position As Integer = -1) As RecommendedKeyword Return New RecommendedKeyword(SyntaxFacts.GetText(kind), glyph, Function(c) Dim stringBuilder As New StringBuilder stringBuilder.AppendLine(firstLine) stringBuilder.AppendLine(intrinsicOperator.DocumentationText) Dim appendParts = Sub(parts As IEnumerable(Of SymbolDisplayPart)) For Each part In parts stringBuilder.Append(part.ToString()) Next End Sub appendParts(intrinsicOperator.PrefixParts) For i = 0 To intrinsicOperator.ParameterCount - 1 If i <> 0 Then stringBuilder.Append(", ") End If appendParts(intrinsicOperator.GetParameterDisplayParts(i)) Next appendParts(intrinsicOperator.GetSuffix(semanticModel, position, Nothing, c)) Return stringBuilder.ToString().ToSymbolDisplayParts() End Function, isIntrinsic:=True) End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports System.Text Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders Friend Module RecommendationHelpers Friend Function IsOnErrorStatement(node As SyntaxNode) As Boolean Return TypeOf node Is OnErrorGoToStatementSyntax OrElse TypeOf node Is OnErrorResumeNextStatementSyntax End Function ''' <summary> ''' Returns the parent of the node given. node may be null, which will cause this function to return null. ''' </summary> <Extension()> Friend Function GetParentOrNull(node As SyntaxNode) As SyntaxNode Return If(node Is Nothing, Nothing, node.Parent) End Function <Extension()> Friend Function IsFollowingCompleteAsNewClause(token As SyntaxToken) As Boolean Dim asNewClause = token.GetAncestor(Of AsNewClauseSyntax)() If asNewClause Is Nothing Then Return False End If Dim lastToken As SyntaxToken Select Case asNewClause.NewExpression.Kind Case SyntaxKind.ObjectCreationExpression Dim objectCreation = DirectCast(asNewClause.NewExpression, ObjectCreationExpressionSyntax) lastToken = If(objectCreation.ArgumentList IsNot Nothing, objectCreation.ArgumentList.CloseParenToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case SyntaxKind.AnonymousObjectCreationExpression Dim anonymousObjectCreation = DirectCast(asNewClause.NewExpression, AnonymousObjectCreationExpressionSyntax) lastToken = If(anonymousObjectCreation.Initializer IsNot Nothing, anonymousObjectCreation.Initializer.CloseBraceToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case SyntaxKind.ArrayCreationExpression Dim arrayCreation = DirectCast(asNewClause.NewExpression, ArrayCreationExpressionSyntax) lastToken = If(arrayCreation.Initializer IsNot Nothing, arrayCreation.Initializer.CloseBraceToken, asNewClause.Type.GetLastToken(includeZeroWidth:=True)) Case Else Throw ExceptionUtilities.UnexpectedValue(asNewClause.NewExpression.Kind) End Select Return token = lastToken End Function <Extension()> Private Function IsLastTokenOfObjectCreation(token As SyntaxToken, objectCreation As ObjectCreationExpressionSyntax) As Boolean If objectCreation Is Nothing Then Return False End If Dim lastToken = If(objectCreation.ArgumentList IsNot Nothing, objectCreation.ArgumentList.CloseParenToken, objectCreation.Type.GetLastToken(includeZeroWidth:=True)) Return token = lastToken End Function <Extension()> Friend Function IsFollowingCompleteObjectCreationInitializer(token As SyntaxToken) As Boolean Dim variableDeclarator = token.GetAncestor(Of VariableDeclaratorSyntax)() If variableDeclarator Is Nothing Then Return False End If Dim objectCreation = token.GetAncestors(Of ObjectCreationExpressionSyntax)() _ .Where(Function(oc) oc.Parent IsNot Nothing AndAlso oc.Parent.Kind <> SyntaxKind.AsNewClause AndAlso variableDeclarator.Initializer IsNot Nothing AndAlso variableDeclarator.Initializer.Value Is oc) _ .FirstOrDefault() Return token.IsLastTokenOfObjectCreation(objectCreation) End Function <Extension()> Friend Function IsFollowingCompleteObjectCreation(token As SyntaxToken) As Boolean Dim objectCreation = token.GetAncestor(Of ObjectCreationExpressionSyntax)() Return token.IsLastTokenOfObjectCreation(objectCreation) End Function <Extension()> Friend Function LastJoinKey(collection As SeparatedSyntaxList(Of JoinConditionSyntax)) As ExpressionSyntax Dim lastJoinCondition = collection.LastOrDefault() If lastJoinCondition IsNot Nothing Then Return lastJoinCondition.Right Else Return Nothing End If End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As IdentifierNameSyntax) As Boolean Return _ identifierSyntax IsNot Nothing AndAlso token = identifierSyntax.Identifier AndAlso identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, identifierSyntax As ModifiedIdentifierSyntax) As Boolean Return _ identifierSyntax IsNot Nothing AndAlso token = identifierSyntax.Identifier AndAlso identifierSyntax.Identifier.GetTypeCharacter() = TypeCharacter.None End Function <Extension()> Friend Function IsFromIdentifierNode(token As SyntaxToken, node As SyntaxNode) As Boolean If node Is Nothing Then Return False End If Dim identifierName = TryCast(node, IdentifierNameSyntax) If token.IsFromIdentifierNode(identifierName) Then Return True End If Dim modifiedIdentifierName = TryCast(node, ModifiedIdentifierSyntax) If token.IsFromIdentifierNode(modifiedIdentifierName) Then Return True End If Return False End Function <Extension()> Friend Function IsFromIdentifierNode(Of TParent As SyntaxNode)(token As SyntaxToken, identifierNodeSelector As Func(Of TParent, SyntaxNode)) As Boolean Dim ancestor = token.GetAncestor(Of TParent)() If ancestor Is Nothing Then Return False End If Return token.IsFromIdentifierNode(identifierNodeSelector(ancestor)) End Function Friend Function CreateRecommendedKeywordForIntrinsicOperator(kind As SyntaxKind, firstLine As String, glyph As Glyph, intrinsicOperator As AbstractIntrinsicOperatorDocumentation, Optional semanticModel As SemanticModel = Nothing, Optional position As Integer = -1) As RecommendedKeyword Return New RecommendedKeyword(SyntaxFacts.GetText(kind), glyph, Function(c) Dim stringBuilder As New StringBuilder stringBuilder.AppendLine(firstLine) stringBuilder.AppendLine(intrinsicOperator.DocumentationText) Dim appendParts = Sub(parts As IEnumerable(Of SymbolDisplayPart)) For Each part In parts stringBuilder.Append(part.ToString()) Next End Sub appendParts(intrinsicOperator.PrefixParts) For i = 0 To intrinsicOperator.ParameterCount - 1 If i <> 0 Then stringBuilder.Append(", ") End If appendParts(intrinsicOperator.GetParameterDisplayParts(i)) Next appendParts(intrinsicOperator.GetSuffix(semanticModel, position, Nothing, c)) Return stringBuilder.ToString().ToSymbolDisplayParts() End Function, isIntrinsic:=True) End Function End Module End Namespace
-1