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,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/Compilers/Core/Portable/DiagnosticAnalyzer/DiagnosticStartAnalysisScope.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Scope for setting up analyzers for an entire session, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerAnalysisContext : AnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSessionStartAnalysisScope _scope; public AnalyzerAnalysisContext(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope scope) { _analyzer = analyzer; _scope = scope; } public override void RegisterCompilationStartAction(Action<CompilationStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationStartAction(_analyzer, action); } public override void RegisterCompilationAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void EnableConcurrentExecution() { _scope.EnableConcurrentExecution(_analyzer); } public override void ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags mode) { _scope.ConfigureGeneratedCodeAnalysis(_analyzer, mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCompilationStartAnalysisContext : CompilationStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCompilationStartAnalysisScope _scope; private readonly CompilationAnalysisValueProviderFactory _compilationAnalysisValueProviderFactory; public AnalyzerCompilationStartAnalysisContext( DiagnosticAnalyzer analyzer, HostCompilationStartAnalysisScope scope, Compilation compilation, AnalyzerOptions options, CompilationAnalysisValueProviderFactory compilationAnalysisValueProviderFactory, CancellationToken cancellationToken) : base(compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; _compilationAnalysisValueProviderFactory = compilationAnalysisValueProviderFactory; } public override void RegisterCompilationEndAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationEndAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } internal override bool TryGetValueCore<TKey, TValue>(TKey key, AnalysisValueProvider<TKey, TValue> valueProvider, [MaybeNullWhen(false)] out TValue value) { var compilationAnalysisValueProvider = _compilationAnalysisValueProviderFactory.GetValueProvider(valueProvider); return compilationAnalysisValueProvider.TryGetValue(key, out value); } } /// <summary> /// Scope for setting up analyzers for code within a symbol and its members. /// </summary> internal sealed class AnalyzerSymbolStartAnalysisContext : SymbolStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSymbolStartAnalysisScope _scope; internal AnalyzerSymbolStartAnalysisContext(DiagnosticAnalyzer analyzer, HostSymbolStartAnalysisScope scope, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken) : base(owningSymbol, compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterSymbolEndAction(Action<SymbolAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolEndAction(_analyzer, action); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for a code block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCodeBlockStartAnalysisContext<TLanguageKindEnum> : CodeBlockStartAnalysisContext<TLanguageKindEnum> where TLanguageKindEnum : struct { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCodeBlockStartAnalysisScope<TLanguageKindEnum> _scope; internal AnalyzerCodeBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostCodeBlockStartAnalysisScope<TLanguageKindEnum> scope, SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, CancellationToken cancellationToken) : base(codeBlock, owningSymbol, semanticModel, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterCodeBlockEndAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockEndAction(_analyzer, action); } public override void RegisterSyntaxNodeAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } } /// <summary> /// Scope for setting up analyzers for an operation block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerOperationBlockStartAnalysisContext : OperationBlockStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostOperationBlockStartAnalysisScope _scope; internal AnalyzerOperationBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostOperationBlockStartAnalysisScope scope, ImmutableArray<IOperation> operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, Func<IOperation, ControlFlowGraph> getControlFlowGraph, CancellationToken cancellationToken) : base(operationBlocks, owningSymbol, compilation, options, getControlFlowGraph, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterOperationBlockEndAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockEndAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for an entire session, capable of retrieving the actions. /// </summary> internal sealed class HostSessionStartAnalysisScope : HostAnalysisScope { private ImmutableHashSet<DiagnosticAnalyzer> _concurrentAnalyzers = ImmutableHashSet<DiagnosticAnalyzer>.Empty; private readonly ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags> _generatedCodeConfigurationMap = new ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags>(); public bool IsConcurrentAnalyzer(DiagnosticAnalyzer analyzer) { return _concurrentAnalyzers.Contains(analyzer); } public GeneratedCodeAnalysisFlags GetGeneratedCodeAnalysisFlags(DiagnosticAnalyzer analyzer) { GeneratedCodeAnalysisFlags mode; return _generatedCodeConfigurationMap.TryGetValue(analyzer, out mode) ? mode : AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags; } public void RegisterCompilationStartAction(DiagnosticAnalyzer analyzer, Action<CompilationStartAnalysisContext> action) { CompilationStartAnalyzerAction analyzerAction = new CompilationStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationStartAction(analyzerAction); } public void EnableConcurrentExecution(DiagnosticAnalyzer analyzer) { _concurrentAnalyzers = _concurrentAnalyzers.Add(analyzer); GetOrCreateAnalyzerActions(analyzer).Value.EnableConcurrentExecution(); } public void ConfigureGeneratedCodeAnalysis(DiagnosticAnalyzer analyzer, GeneratedCodeAnalysisFlags mode) { _generatedCodeConfigurationMap.AddOrUpdate(analyzer, addValue: mode, updateValueFactory: (a, c) => mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, capable of retrieving the actions. /// </summary> internal sealed class HostCompilationStartAnalysisScope : HostAnalysisScope { private readonly HostSessionStartAnalysisScope _sessionScope; public HostCompilationStartAnalysisScope(HostSessionStartAnalysisScope sessionScope) { _sessionScope = sessionScope; } public override AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { AnalyzerActions compilationActions = base.GetAnalyzerActions(analyzer); AnalyzerActions sessionActions = _sessionScope.GetAnalyzerActions(analyzer); if (sessionActions.IsEmpty) { return compilationActions; } if (compilationActions.IsEmpty) { return sessionActions; } return compilationActions.Append(in sessionActions); } } /// <summary> /// Scope for setting up analyzers for analyzing a symbol and its members. /// </summary> internal sealed class HostSymbolStartAnalysisScope : HostAnalysisScope { public HostSymbolStartAnalysisScope() { } } /// <summary> /// Scope for setting up analyzers for a code block, capable of retrieving the actions. /// </summary> internal sealed class HostCodeBlockStartAnalysisScope<TLanguageKindEnum> where TLanguageKindEnum : struct { private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; private ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> _syntaxNodeActions = ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.Empty; public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } public ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> SyntaxNodeActions { get { return _syntaxNodeActions; } } internal HostCodeBlockStartAnalysisScope() { } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { _codeBlockEndActions = _codeBlockEndActions.Add(new CodeBlockAnalyzerAction(action, analyzer)); } public void RegisterSyntaxNodeAction(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { _syntaxNodeActions = _syntaxNodeActions.Add(new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer)); } } internal sealed class HostOperationBlockStartAnalysisScope { private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; private ImmutableArray<OperationAnalyzerAction> _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions => _operationBlockEndActions; public ImmutableArray<OperationAnalyzerAction> OperationActions => _operationActions; internal HostOperationBlockStartAnalysisScope() { } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { _operationBlockEndActions = _operationBlockEndActions.Add(new OperationBlockAnalyzerAction(action, analyzer)); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { _operationActions = _operationActions.Add(new OperationAnalyzerAction(action, operationKinds, analyzer)); } } internal abstract class HostAnalysisScope { private readonly ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>> _analyzerActions = new ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>>(); public virtual AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { return this.GetOrCreateAnalyzerActions(analyzer).Value; } public void RegisterCompilationAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationAction(analyzerAction); } public void RegisterCompilationEndAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationEndAction(analyzerAction); } public void RegisterSemanticModelAction(DiagnosticAnalyzer analyzer, Action<SemanticModelAnalysisContext> action) { SemanticModelAnalyzerAction analyzerAction = new SemanticModelAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSemanticModelAction(analyzerAction); } public void RegisterSyntaxTreeAction(DiagnosticAnalyzer analyzer, Action<SyntaxTreeAnalysisContext> action) { SyntaxTreeAnalyzerAction analyzerAction = new SyntaxTreeAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxTreeAction(analyzerAction); } public void RegisterAdditionalFileAction(DiagnosticAnalyzer analyzer, Action<AdditionalFileAnalysisContext> action) { var analyzerAction = new AdditionalFileAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddAdditionalFileAction(analyzerAction); } public void RegisterSymbolAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { SymbolAnalyzerAction analyzerAction = new SymbolAnalyzerAction(action, symbolKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolAction(analyzerAction); // The SymbolAnalyzerAction does not handle SymbolKind.Parameter because the compiler // does not make CompilationEvents for them. As a workaround, handle them specially by // registering further SymbolActions (for Methods) and utilize the results to construct // the necessary SymbolAnalysisContexts. if (symbolKinds.Contains(SymbolKind.Parameter)) { RegisterSymbolAction( analyzer, context => { ImmutableArray<IParameterSymbol> parameters; switch (context.Symbol.Kind) { case SymbolKind.Method: parameters = ((IMethodSymbol)context.Symbol).Parameters; break; case SymbolKind.Property: parameters = ((IPropertySymbol)context.Symbol).Parameters; break; case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)context.Symbol; var delegateInvokeMethod = namedType.DelegateInvokeMethod; parameters = delegateInvokeMethod?.Parameters ?? ImmutableArray.Create<IParameterSymbol>(); break; default: throw new ArgumentException($"{context.Symbol.Kind} is not supported.", nameof(context)); } foreach (var parameter in parameters) { if (!parameter.IsImplicitlyDeclared) { action(new SymbolAnalysisContext( parameter, context.Compilation, context.Options, context.ReportDiagnostic, context.IsSupportedDiagnostic, context.CancellationToken)); } } }, ImmutableArray.Create(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType)); } } public void RegisterSymbolStartAction(DiagnosticAnalyzer analyzer, Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { var analyzerAction = new SymbolStartAnalyzerAction(action, symbolKind, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolStartAction(analyzerAction); } public void RegisterSymbolEndAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action) { var analyzerAction = new SymbolEndAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolEndAction(analyzerAction); } public void RegisterCodeBlockStartAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct { CodeBlockStartAnalyzerAction<TLanguageKindEnum> analyzerAction = new CodeBlockStartAnalyzerAction<TLanguageKindEnum>(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockStartAction(analyzerAction); } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockEndAction(analyzerAction); } public void RegisterCodeBlockAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockAction(analyzerAction); } public void RegisterSyntaxNodeAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct { SyntaxNodeAnalyzerAction<TLanguageKindEnum> analyzerAction = new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxNodeAction(analyzerAction); } public void RegisterOperationBlockStartAction(DiagnosticAnalyzer analyzer, Action<OperationBlockStartAnalysisContext> action) { OperationBlockStartAnalyzerAction analyzerAction = new OperationBlockStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockStartAction(analyzerAction); } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockEndAction(analyzerAction); } public void RegisterOperationBlockAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockAction(analyzerAction); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { OperationAnalyzerAction analyzerAction = new OperationAnalyzerAction(action, operationKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationAction(analyzerAction); } protected StrongBox<AnalyzerActions> GetOrCreateAnalyzerActions(DiagnosticAnalyzer analyzer) { return _analyzerActions.GetOrAdd(analyzer, _ => new StrongBox<AnalyzerActions>(AnalyzerActions.Empty)); } } /// <summary> /// Actions registered by a particular analyzer. /// </summary> // ToDo: AnalyzerActions, and all of the mechanism around it, can be eliminated if the IDE diagnostic analyzer driver // moves from an analyzer-centric model to an action-centric model. For example, the driver would need to stop asking // if a particular analyzer can analyze syntax trees, and instead ask if any syntax tree actions are present. Also, // the driver needs to apply all relevant actions rather then applying the actions of individual analyzers. internal struct AnalyzerActions { public static readonly AnalyzerActions Empty = new AnalyzerActions(concurrent: false); private ImmutableArray<CompilationStartAnalyzerAction> _compilationStartActions; private ImmutableArray<CompilationAnalyzerAction> _compilationEndActions; private ImmutableArray<CompilationAnalyzerAction> _compilationActions; private ImmutableArray<SyntaxTreeAnalyzerAction> _syntaxTreeActions; private ImmutableArray<AdditionalFileAnalyzerAction> _additionalFileActions; private ImmutableArray<SemanticModelAnalyzerAction> _semanticModelActions; private ImmutableArray<SymbolAnalyzerAction> _symbolActions; private ImmutableArray<SymbolStartAnalyzerAction> _symbolStartActions; private ImmutableArray<SymbolEndAnalyzerAction> _symbolEndActions; private ImmutableArray<AnalyzerAction> _codeBlockStartActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockActions; private ImmutableArray<OperationBlockStartAnalyzerAction> _operationBlockStartActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockActions; private ImmutableArray<AnalyzerAction> _syntaxNodeActions; private ImmutableArray<OperationAnalyzerAction> _operationActions; private bool _concurrent; internal AnalyzerActions(bool concurrent) { _compilationStartActions = ImmutableArray<CompilationStartAnalyzerAction>.Empty; _compilationEndActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _compilationActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _syntaxTreeActions = ImmutableArray<SyntaxTreeAnalyzerAction>.Empty; _additionalFileActions = ImmutableArray<AdditionalFileAnalyzerAction>.Empty; _semanticModelActions = ImmutableArray<SemanticModelAnalyzerAction>.Empty; _symbolActions = ImmutableArray<SymbolAnalyzerAction>.Empty; _symbolStartActions = ImmutableArray<SymbolStartAnalyzerAction>.Empty; _symbolEndActions = ImmutableArray<SymbolEndAnalyzerAction>.Empty; _codeBlockStartActions = ImmutableArray<AnalyzerAction>.Empty; _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _codeBlockActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _operationBlockStartActions = ImmutableArray<OperationBlockStartAnalyzerAction>.Empty; _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _operationBlockActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _syntaxNodeActions = ImmutableArray<AnalyzerAction>.Empty; _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; _concurrent = concurrent; IsEmpty = true; } public AnalyzerActions( ImmutableArray<CompilationStartAnalyzerAction> compilationStartActions, ImmutableArray<CompilationAnalyzerAction> compilationEndActions, ImmutableArray<CompilationAnalyzerAction> compilationActions, ImmutableArray<SyntaxTreeAnalyzerAction> syntaxTreeActions, ImmutableArray<AdditionalFileAnalyzerAction> additionalFileActions, ImmutableArray<SemanticModelAnalyzerAction> semanticModelActions, ImmutableArray<SymbolAnalyzerAction> symbolActions, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, ImmutableArray<AnalyzerAction> codeBlockStartActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockEndActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockActions, ImmutableArray<OperationBlockStartAnalyzerAction> operationBlockStartActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockEndActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockActions, ImmutableArray<AnalyzerAction> syntaxNodeActions, ImmutableArray<OperationAnalyzerAction> operationActions, bool concurrent, bool isEmpty) { _compilationStartActions = compilationStartActions; _compilationEndActions = compilationEndActions; _compilationActions = compilationActions; _syntaxTreeActions = syntaxTreeActions; _additionalFileActions = additionalFileActions; _semanticModelActions = semanticModelActions; _symbolActions = symbolActions; _symbolStartActions = symbolStartActions; _symbolEndActions = symbolEndActions; _codeBlockStartActions = codeBlockStartActions; _codeBlockEndActions = codeBlockEndActions; _codeBlockActions = codeBlockActions; _operationBlockStartActions = operationBlockStartActions; _operationBlockEndActions = operationBlockEndActions; _operationBlockActions = operationBlockActions; _syntaxNodeActions = syntaxNodeActions; _operationActions = operationActions; _concurrent = concurrent; IsEmpty = isEmpty; } public readonly int CompilationStartActionsCount { get { return _compilationStartActions.Length; } } public readonly int CompilationEndActionsCount { get { return _compilationEndActions.Length; } } public readonly int CompilationActionsCount { get { return _compilationActions.Length; } } public readonly int SyntaxTreeActionsCount { get { return _syntaxTreeActions.Length; } } public readonly int AdditionalFileActionsCount { get { return _additionalFileActions.Length; } } public readonly int SemanticModelActionsCount { get { return _semanticModelActions.Length; } } public readonly int SymbolActionsCount { get { return _symbolActions.Length; } } public readonly int SymbolStartActionsCount { get { return _symbolStartActions.Length; } } public readonly int SymbolEndActionsCount { get { return _symbolEndActions.Length; } } public readonly int SyntaxNodeActionsCount { get { return _syntaxNodeActions.Length; } } public readonly int OperationActionsCount { get { return _operationActions.Length; } } public readonly int OperationBlockStartActionsCount { get { return _operationBlockStartActions.Length; } } public readonly int OperationBlockEndActionsCount { get { return _operationBlockEndActions.Length; } } public readonly int OperationBlockActionsCount { get { return _operationBlockActions.Length; } } public readonly int CodeBlockStartActionsCount { get { return _codeBlockStartActions.Length; } } public readonly int CodeBlockEndActionsCount { get { return _codeBlockEndActions.Length; } } public readonly int CodeBlockActionsCount { get { return _codeBlockActions.Length; } } public readonly bool Concurrent => _concurrent; public bool IsEmpty { readonly get; private set; } public readonly bool IsDefault => _compilationStartActions.IsDefault; internal readonly ImmutableArray<CompilationStartAnalyzerAction> CompilationStartActions { get { return _compilationStartActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationEndActions { get { return _compilationEndActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationActions { get { return _compilationActions; } } internal readonly ImmutableArray<SyntaxTreeAnalyzerAction> SyntaxTreeActions { get { return _syntaxTreeActions; } } internal readonly ImmutableArray<AdditionalFileAnalyzerAction> AdditionalFileActions { get { return _additionalFileActions; } } internal readonly ImmutableArray<SemanticModelAnalyzerAction> SemanticModelActions { get { return _semanticModelActions; } } internal readonly ImmutableArray<SymbolAnalyzerAction> SymbolActions { get { return _symbolActions; } } internal readonly ImmutableArray<SymbolStartAnalyzerAction> SymbolStartActions { get { return _symbolStartActions; } } internal readonly ImmutableArray<SymbolEndAnalyzerAction> SymbolEndActions { get { return _symbolEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions { get { return _codeBlockActions; } } internal readonly ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> GetCodeBlockStartActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _codeBlockStartActions.OfType<CodeBlockStartAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _syntaxNodeActions.OfType<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>(DiagnosticAnalyzer analyzer) where TLanguageKindEnum : struct { var builder = ArrayBuilder<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.GetInstance(); foreach (var action in _syntaxNodeActions) { if (action.Analyzer == analyzer && action is SyntaxNodeAnalyzerAction<TLanguageKindEnum> syntaxNodeAction) { builder.Add(syntaxNodeAction); } } return builder.ToImmutableAndFree(); } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions { get { return _operationBlockActions; } } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions { get { return _operationBlockEndActions; } } internal readonly ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions { get { return _operationBlockStartActions; } } internal readonly ImmutableArray<OperationAnalyzerAction> OperationActions { get { return _operationActions; } } internal void AddCompilationStartAction(CompilationStartAnalyzerAction action) { _compilationStartActions = _compilationStartActions.Add(action); IsEmpty = false; } internal void AddCompilationEndAction(CompilationAnalyzerAction action) { _compilationEndActions = _compilationEndActions.Add(action); IsEmpty = false; } internal void AddCompilationAction(CompilationAnalyzerAction action) { _compilationActions = _compilationActions.Add(action); IsEmpty = false; } internal void AddSyntaxTreeAction(SyntaxTreeAnalyzerAction action) { _syntaxTreeActions = _syntaxTreeActions.Add(action); IsEmpty = false; } internal void AddAdditionalFileAction(AdditionalFileAnalyzerAction action) { _additionalFileActions = _additionalFileActions.Add(action); IsEmpty = false; } internal void AddSemanticModelAction(SemanticModelAnalyzerAction action) { _semanticModelActions = _semanticModelActions.Add(action); IsEmpty = false; } internal void AddSymbolAction(SymbolAnalyzerAction action) { _symbolActions = _symbolActions.Add(action); IsEmpty = false; } internal void AddSymbolStartAction(SymbolStartAnalyzerAction action) { _symbolStartActions = _symbolStartActions.Add(action); IsEmpty = false; } internal void AddSymbolEndAction(SymbolEndAnalyzerAction action) { _symbolEndActions = _symbolEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockStartAction<TLanguageKindEnum>(CodeBlockStartAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _codeBlockStartActions = _codeBlockStartActions.Add(action); IsEmpty = false; } internal void AddCodeBlockEndAction(CodeBlockAnalyzerAction action) { _codeBlockEndActions = _codeBlockEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockAction(CodeBlockAnalyzerAction action) { _codeBlockActions = _codeBlockActions.Add(action); IsEmpty = false; } internal void AddSyntaxNodeAction<TLanguageKindEnum>(SyntaxNodeAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _syntaxNodeActions = _syntaxNodeActions.Add(action); IsEmpty = false; } internal void AddOperationBlockStartAction(OperationBlockStartAnalyzerAction action) { _operationBlockStartActions = _operationBlockStartActions.Add(action); IsEmpty = false; } internal void AddOperationBlockAction(OperationBlockAnalyzerAction action) { _operationBlockActions = _operationBlockActions.Add(action); IsEmpty = false; } internal void AddOperationBlockEndAction(OperationBlockAnalyzerAction action) { _operationBlockEndActions = _operationBlockEndActions.Add(action); IsEmpty = false; } internal void AddOperationAction(OperationAnalyzerAction action) { _operationActions = _operationActions.Add(action); IsEmpty = false; } internal void EnableConcurrentExecution() { _concurrent = true; } /// <summary> /// Append analyzer actions from <paramref name="otherActions"/> to actions from this instance. /// </summary> /// <param name="otherActions">Analyzer actions to append</param>. public readonly AnalyzerActions Append(in AnalyzerActions otherActions, bool appendSymbolStartAndSymbolEndActions = true) { if (otherActions.IsDefault) { throw new ArgumentNullException(nameof(otherActions)); } AnalyzerActions actions = new AnalyzerActions(concurrent: _concurrent || otherActions.Concurrent); actions._compilationStartActions = _compilationStartActions.AddRange(otherActions._compilationStartActions); actions._compilationEndActions = _compilationEndActions.AddRange(otherActions._compilationEndActions); actions._compilationActions = _compilationActions.AddRange(otherActions._compilationActions); actions._syntaxTreeActions = _syntaxTreeActions.AddRange(otherActions._syntaxTreeActions); actions._additionalFileActions = _additionalFileActions.AddRange(otherActions._additionalFileActions); actions._semanticModelActions = _semanticModelActions.AddRange(otherActions._semanticModelActions); actions._symbolActions = _symbolActions.AddRange(otherActions._symbolActions); actions._symbolStartActions = appendSymbolStartAndSymbolEndActions ? _symbolStartActions.AddRange(otherActions._symbolStartActions) : _symbolStartActions; actions._symbolEndActions = appendSymbolStartAndSymbolEndActions ? _symbolEndActions.AddRange(otherActions._symbolEndActions) : _symbolEndActions; actions._codeBlockStartActions = _codeBlockStartActions.AddRange(otherActions._codeBlockStartActions); actions._codeBlockEndActions = _codeBlockEndActions.AddRange(otherActions._codeBlockEndActions); actions._codeBlockActions = _codeBlockActions.AddRange(otherActions._codeBlockActions); actions._syntaxNodeActions = _syntaxNodeActions.AddRange(otherActions._syntaxNodeActions); actions._operationActions = _operationActions.AddRange(otherActions._operationActions); actions._operationBlockStartActions = _operationBlockStartActions.AddRange(otherActions._operationBlockStartActions); actions._operationBlockEndActions = _operationBlockEndActions.AddRange(otherActions._operationBlockEndActions); actions._operationBlockActions = _operationBlockActions.AddRange(otherActions._operationBlockActions); actions.IsEmpty = IsEmpty && otherActions.IsEmpty; return actions; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Scope for setting up analyzers for an entire session, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerAnalysisContext : AnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSessionStartAnalysisScope _scope; public AnalyzerAnalysisContext(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope scope) { _analyzer = analyzer; _scope = scope; } public override void RegisterCompilationStartAction(Action<CompilationStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationStartAction(_analyzer, action); } public override void RegisterCompilationAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void EnableConcurrentExecution() { _scope.EnableConcurrentExecution(_analyzer); } public override void ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags mode) { _scope.ConfigureGeneratedCodeAnalysis(_analyzer, mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCompilationStartAnalysisContext : CompilationStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCompilationStartAnalysisScope _scope; private readonly CompilationAnalysisValueProviderFactory _compilationAnalysisValueProviderFactory; public AnalyzerCompilationStartAnalysisContext( DiagnosticAnalyzer analyzer, HostCompilationStartAnalysisScope scope, Compilation compilation, AnalyzerOptions options, CompilationAnalysisValueProviderFactory compilationAnalysisValueProviderFactory, CancellationToken cancellationToken) : base(compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; _compilationAnalysisValueProviderFactory = compilationAnalysisValueProviderFactory; } public override void RegisterCompilationEndAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationEndAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } internal override bool TryGetValueCore<TKey, TValue>(TKey key, AnalysisValueProvider<TKey, TValue> valueProvider, [MaybeNullWhen(false)] out TValue value) { var compilationAnalysisValueProvider = _compilationAnalysisValueProviderFactory.GetValueProvider(valueProvider); return compilationAnalysisValueProvider.TryGetValue(key, out value); } } /// <summary> /// Scope for setting up analyzers for code within a symbol and its members. /// </summary> internal sealed class AnalyzerSymbolStartAnalysisContext : SymbolStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSymbolStartAnalysisScope _scope; internal AnalyzerSymbolStartAnalysisContext(DiagnosticAnalyzer analyzer, HostSymbolStartAnalysisScope scope, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken) : base(owningSymbol, compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterSymbolEndAction(Action<SymbolAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolEndAction(_analyzer, action); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for a code block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCodeBlockStartAnalysisContext<TLanguageKindEnum> : CodeBlockStartAnalysisContext<TLanguageKindEnum> where TLanguageKindEnum : struct { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCodeBlockStartAnalysisScope<TLanguageKindEnum> _scope; internal AnalyzerCodeBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostCodeBlockStartAnalysisScope<TLanguageKindEnum> scope, SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, CancellationToken cancellationToken) : base(codeBlock, owningSymbol, semanticModel, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterCodeBlockEndAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockEndAction(_analyzer, action); } public override void RegisterSyntaxNodeAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } } /// <summary> /// Scope for setting up analyzers for an operation block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerOperationBlockStartAnalysisContext : OperationBlockStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostOperationBlockStartAnalysisScope _scope; internal AnalyzerOperationBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostOperationBlockStartAnalysisScope scope, ImmutableArray<IOperation> operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, Func<IOperation, ControlFlowGraph> getControlFlowGraph, CancellationToken cancellationToken) : base(operationBlocks, owningSymbol, compilation, options, getControlFlowGraph, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterOperationBlockEndAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockEndAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for an entire session, capable of retrieving the actions. /// </summary> internal sealed class HostSessionStartAnalysisScope : HostAnalysisScope { private ImmutableHashSet<DiagnosticAnalyzer> _concurrentAnalyzers = ImmutableHashSet<DiagnosticAnalyzer>.Empty; private readonly ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags> _generatedCodeConfigurationMap = new ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags>(); public bool IsConcurrentAnalyzer(DiagnosticAnalyzer analyzer) { return _concurrentAnalyzers.Contains(analyzer); } public GeneratedCodeAnalysisFlags GetGeneratedCodeAnalysisFlags(DiagnosticAnalyzer analyzer) { GeneratedCodeAnalysisFlags mode; return _generatedCodeConfigurationMap.TryGetValue(analyzer, out mode) ? mode : AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags; } public void RegisterCompilationStartAction(DiagnosticAnalyzer analyzer, Action<CompilationStartAnalysisContext> action) { CompilationStartAnalyzerAction analyzerAction = new CompilationStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationStartAction(analyzerAction); } public void EnableConcurrentExecution(DiagnosticAnalyzer analyzer) { _concurrentAnalyzers = _concurrentAnalyzers.Add(analyzer); GetOrCreateAnalyzerActions(analyzer).Value.EnableConcurrentExecution(); } public void ConfigureGeneratedCodeAnalysis(DiagnosticAnalyzer analyzer, GeneratedCodeAnalysisFlags mode) { _generatedCodeConfigurationMap.AddOrUpdate(analyzer, addValue: mode, updateValueFactory: (a, c) => mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, capable of retrieving the actions. /// </summary> internal sealed class HostCompilationStartAnalysisScope : HostAnalysisScope { private readonly HostSessionStartAnalysisScope _sessionScope; public HostCompilationStartAnalysisScope(HostSessionStartAnalysisScope sessionScope) { _sessionScope = sessionScope; } public override AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { AnalyzerActions compilationActions = base.GetAnalyzerActions(analyzer); AnalyzerActions sessionActions = _sessionScope.GetAnalyzerActions(analyzer); if (sessionActions.IsEmpty) { return compilationActions; } if (compilationActions.IsEmpty) { return sessionActions; } return compilationActions.Append(in sessionActions); } } /// <summary> /// Scope for setting up analyzers for analyzing a symbol and its members. /// </summary> internal sealed class HostSymbolStartAnalysisScope : HostAnalysisScope { public HostSymbolStartAnalysisScope() { } } /// <summary> /// Scope for setting up analyzers for a code block, capable of retrieving the actions. /// </summary> internal sealed class HostCodeBlockStartAnalysisScope<TLanguageKindEnum> where TLanguageKindEnum : struct { private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; private ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> _syntaxNodeActions = ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.Empty; public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } public ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> SyntaxNodeActions { get { return _syntaxNodeActions; } } internal HostCodeBlockStartAnalysisScope() { } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { _codeBlockEndActions = _codeBlockEndActions.Add(new CodeBlockAnalyzerAction(action, analyzer)); } public void RegisterSyntaxNodeAction(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { _syntaxNodeActions = _syntaxNodeActions.Add(new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer)); } } internal sealed class HostOperationBlockStartAnalysisScope { private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; private ImmutableArray<OperationAnalyzerAction> _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions => _operationBlockEndActions; public ImmutableArray<OperationAnalyzerAction> OperationActions => _operationActions; internal HostOperationBlockStartAnalysisScope() { } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { _operationBlockEndActions = _operationBlockEndActions.Add(new OperationBlockAnalyzerAction(action, analyzer)); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { _operationActions = _operationActions.Add(new OperationAnalyzerAction(action, operationKinds, analyzer)); } } internal abstract class HostAnalysisScope { private readonly ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>> _analyzerActions = new ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>>(); public virtual AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { return this.GetOrCreateAnalyzerActions(analyzer).Value; } public void RegisterCompilationAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationAction(analyzerAction); } public void RegisterCompilationEndAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationEndAction(analyzerAction); } public void RegisterSemanticModelAction(DiagnosticAnalyzer analyzer, Action<SemanticModelAnalysisContext> action) { SemanticModelAnalyzerAction analyzerAction = new SemanticModelAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSemanticModelAction(analyzerAction); } public void RegisterSyntaxTreeAction(DiagnosticAnalyzer analyzer, Action<SyntaxTreeAnalysisContext> action) { SyntaxTreeAnalyzerAction analyzerAction = new SyntaxTreeAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxTreeAction(analyzerAction); } public void RegisterAdditionalFileAction(DiagnosticAnalyzer analyzer, Action<AdditionalFileAnalysisContext> action) { var analyzerAction = new AdditionalFileAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddAdditionalFileAction(analyzerAction); } public void RegisterSymbolAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { SymbolAnalyzerAction analyzerAction = new SymbolAnalyzerAction(action, symbolKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolAction(analyzerAction); // The SymbolAnalyzerAction does not handle SymbolKind.Parameter because the compiler // does not make CompilationEvents for them. As a workaround, handle them specially by // registering further SymbolActions (for Methods) and utilize the results to construct // the necessary SymbolAnalysisContexts. if (symbolKinds.Contains(SymbolKind.Parameter)) { RegisterSymbolAction( analyzer, context => { ImmutableArray<IParameterSymbol> parameters; switch (context.Symbol.Kind) { case SymbolKind.Method: parameters = ((IMethodSymbol)context.Symbol).Parameters; break; case SymbolKind.Property: parameters = ((IPropertySymbol)context.Symbol).Parameters; break; case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)context.Symbol; var delegateInvokeMethod = namedType.DelegateInvokeMethod; parameters = delegateInvokeMethod?.Parameters ?? ImmutableArray.Create<IParameterSymbol>(); break; default: throw new ArgumentException($"{context.Symbol.Kind} is not supported.", nameof(context)); } foreach (var parameter in parameters) { if (!parameter.IsImplicitlyDeclared) { action(new SymbolAnalysisContext( parameter, context.Compilation, context.Options, context.ReportDiagnostic, context.IsSupportedDiagnostic, context.CancellationToken)); } } }, ImmutableArray.Create(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType)); } } public void RegisterSymbolStartAction(DiagnosticAnalyzer analyzer, Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { var analyzerAction = new SymbolStartAnalyzerAction(action, symbolKind, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolStartAction(analyzerAction); } public void RegisterSymbolEndAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action) { var analyzerAction = new SymbolEndAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolEndAction(analyzerAction); } public void RegisterCodeBlockStartAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct { CodeBlockStartAnalyzerAction<TLanguageKindEnum> analyzerAction = new CodeBlockStartAnalyzerAction<TLanguageKindEnum>(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockStartAction(analyzerAction); } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockEndAction(analyzerAction); } public void RegisterCodeBlockAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockAction(analyzerAction); } public void RegisterSyntaxNodeAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct { SyntaxNodeAnalyzerAction<TLanguageKindEnum> analyzerAction = new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxNodeAction(analyzerAction); } public void RegisterOperationBlockStartAction(DiagnosticAnalyzer analyzer, Action<OperationBlockStartAnalysisContext> action) { OperationBlockStartAnalyzerAction analyzerAction = new OperationBlockStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockStartAction(analyzerAction); } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockEndAction(analyzerAction); } public void RegisterOperationBlockAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockAction(analyzerAction); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { OperationAnalyzerAction analyzerAction = new OperationAnalyzerAction(action, operationKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationAction(analyzerAction); } protected StrongBox<AnalyzerActions> GetOrCreateAnalyzerActions(DiagnosticAnalyzer analyzer) { return _analyzerActions.GetOrAdd(analyzer, _ => new StrongBox<AnalyzerActions>(AnalyzerActions.Empty)); } } /// <summary> /// Actions registered by a particular analyzer. /// </summary> // ToDo: AnalyzerActions, and all of the mechanism around it, can be eliminated if the IDE diagnostic analyzer driver // moves from an analyzer-centric model to an action-centric model. For example, the driver would need to stop asking // if a particular analyzer can analyze syntax trees, and instead ask if any syntax tree actions are present. Also, // the driver needs to apply all relevant actions rather then applying the actions of individual analyzers. internal struct AnalyzerActions { public static readonly AnalyzerActions Empty = new AnalyzerActions(concurrent: false); private ImmutableArray<CompilationStartAnalyzerAction> _compilationStartActions; private ImmutableArray<CompilationAnalyzerAction> _compilationEndActions; private ImmutableArray<CompilationAnalyzerAction> _compilationActions; private ImmutableArray<SyntaxTreeAnalyzerAction> _syntaxTreeActions; private ImmutableArray<AdditionalFileAnalyzerAction> _additionalFileActions; private ImmutableArray<SemanticModelAnalyzerAction> _semanticModelActions; private ImmutableArray<SymbolAnalyzerAction> _symbolActions; private ImmutableArray<SymbolStartAnalyzerAction> _symbolStartActions; private ImmutableArray<SymbolEndAnalyzerAction> _symbolEndActions; private ImmutableArray<AnalyzerAction> _codeBlockStartActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockActions; private ImmutableArray<OperationBlockStartAnalyzerAction> _operationBlockStartActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockActions; private ImmutableArray<AnalyzerAction> _syntaxNodeActions; private ImmutableArray<OperationAnalyzerAction> _operationActions; private bool _concurrent; internal AnalyzerActions(bool concurrent) { _compilationStartActions = ImmutableArray<CompilationStartAnalyzerAction>.Empty; _compilationEndActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _compilationActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _syntaxTreeActions = ImmutableArray<SyntaxTreeAnalyzerAction>.Empty; _additionalFileActions = ImmutableArray<AdditionalFileAnalyzerAction>.Empty; _semanticModelActions = ImmutableArray<SemanticModelAnalyzerAction>.Empty; _symbolActions = ImmutableArray<SymbolAnalyzerAction>.Empty; _symbolStartActions = ImmutableArray<SymbolStartAnalyzerAction>.Empty; _symbolEndActions = ImmutableArray<SymbolEndAnalyzerAction>.Empty; _codeBlockStartActions = ImmutableArray<AnalyzerAction>.Empty; _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _codeBlockActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _operationBlockStartActions = ImmutableArray<OperationBlockStartAnalyzerAction>.Empty; _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _operationBlockActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _syntaxNodeActions = ImmutableArray<AnalyzerAction>.Empty; _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; _concurrent = concurrent; IsEmpty = true; } public AnalyzerActions( ImmutableArray<CompilationStartAnalyzerAction> compilationStartActions, ImmutableArray<CompilationAnalyzerAction> compilationEndActions, ImmutableArray<CompilationAnalyzerAction> compilationActions, ImmutableArray<SyntaxTreeAnalyzerAction> syntaxTreeActions, ImmutableArray<AdditionalFileAnalyzerAction> additionalFileActions, ImmutableArray<SemanticModelAnalyzerAction> semanticModelActions, ImmutableArray<SymbolAnalyzerAction> symbolActions, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, ImmutableArray<AnalyzerAction> codeBlockStartActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockEndActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockActions, ImmutableArray<OperationBlockStartAnalyzerAction> operationBlockStartActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockEndActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockActions, ImmutableArray<AnalyzerAction> syntaxNodeActions, ImmutableArray<OperationAnalyzerAction> operationActions, bool concurrent, bool isEmpty) { _compilationStartActions = compilationStartActions; _compilationEndActions = compilationEndActions; _compilationActions = compilationActions; _syntaxTreeActions = syntaxTreeActions; _additionalFileActions = additionalFileActions; _semanticModelActions = semanticModelActions; _symbolActions = symbolActions; _symbolStartActions = symbolStartActions; _symbolEndActions = symbolEndActions; _codeBlockStartActions = codeBlockStartActions; _codeBlockEndActions = codeBlockEndActions; _codeBlockActions = codeBlockActions; _operationBlockStartActions = operationBlockStartActions; _operationBlockEndActions = operationBlockEndActions; _operationBlockActions = operationBlockActions; _syntaxNodeActions = syntaxNodeActions; _operationActions = operationActions; _concurrent = concurrent; IsEmpty = isEmpty; } public readonly int CompilationStartActionsCount { get { return _compilationStartActions.Length; } } public readonly int CompilationEndActionsCount { get { return _compilationEndActions.Length; } } public readonly int CompilationActionsCount { get { return _compilationActions.Length; } } public readonly int SyntaxTreeActionsCount { get { return _syntaxTreeActions.Length; } } public readonly int AdditionalFileActionsCount { get { return _additionalFileActions.Length; } } public readonly int SemanticModelActionsCount { get { return _semanticModelActions.Length; } } public readonly int SymbolActionsCount { get { return _symbolActions.Length; } } public readonly int SymbolStartActionsCount { get { return _symbolStartActions.Length; } } public readonly int SymbolEndActionsCount { get { return _symbolEndActions.Length; } } public readonly int SyntaxNodeActionsCount { get { return _syntaxNodeActions.Length; } } public readonly int OperationActionsCount { get { return _operationActions.Length; } } public readonly int OperationBlockStartActionsCount { get { return _operationBlockStartActions.Length; } } public readonly int OperationBlockEndActionsCount { get { return _operationBlockEndActions.Length; } } public readonly int OperationBlockActionsCount { get { return _operationBlockActions.Length; } } public readonly int CodeBlockStartActionsCount { get { return _codeBlockStartActions.Length; } } public readonly int CodeBlockEndActionsCount { get { return _codeBlockEndActions.Length; } } public readonly int CodeBlockActionsCount { get { return _codeBlockActions.Length; } } public readonly bool Concurrent => _concurrent; public bool IsEmpty { readonly get; private set; } public readonly bool IsDefault => _compilationStartActions.IsDefault; internal readonly ImmutableArray<CompilationStartAnalyzerAction> CompilationStartActions { get { return _compilationStartActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationEndActions { get { return _compilationEndActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationActions { get { return _compilationActions; } } internal readonly ImmutableArray<SyntaxTreeAnalyzerAction> SyntaxTreeActions { get { return _syntaxTreeActions; } } internal readonly ImmutableArray<AdditionalFileAnalyzerAction> AdditionalFileActions { get { return _additionalFileActions; } } internal readonly ImmutableArray<SemanticModelAnalyzerAction> SemanticModelActions { get { return _semanticModelActions; } } internal readonly ImmutableArray<SymbolAnalyzerAction> SymbolActions { get { return _symbolActions; } } internal readonly ImmutableArray<SymbolStartAnalyzerAction> SymbolStartActions { get { return _symbolStartActions; } } internal readonly ImmutableArray<SymbolEndAnalyzerAction> SymbolEndActions { get { return _symbolEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions { get { return _codeBlockActions; } } internal readonly ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> GetCodeBlockStartActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _codeBlockStartActions.OfType<CodeBlockStartAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _syntaxNodeActions.OfType<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>(DiagnosticAnalyzer analyzer) where TLanguageKindEnum : struct { var builder = ArrayBuilder<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.GetInstance(); foreach (var action in _syntaxNodeActions) { if (action.Analyzer == analyzer && action is SyntaxNodeAnalyzerAction<TLanguageKindEnum> syntaxNodeAction) { builder.Add(syntaxNodeAction); } } return builder.ToImmutableAndFree(); } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions { get { return _operationBlockActions; } } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions { get { return _operationBlockEndActions; } } internal readonly ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions { get { return _operationBlockStartActions; } } internal readonly ImmutableArray<OperationAnalyzerAction> OperationActions { get { return _operationActions; } } internal void AddCompilationStartAction(CompilationStartAnalyzerAction action) { _compilationStartActions = _compilationStartActions.Add(action); IsEmpty = false; } internal void AddCompilationEndAction(CompilationAnalyzerAction action) { _compilationEndActions = _compilationEndActions.Add(action); IsEmpty = false; } internal void AddCompilationAction(CompilationAnalyzerAction action) { _compilationActions = _compilationActions.Add(action); IsEmpty = false; } internal void AddSyntaxTreeAction(SyntaxTreeAnalyzerAction action) { _syntaxTreeActions = _syntaxTreeActions.Add(action); IsEmpty = false; } internal void AddAdditionalFileAction(AdditionalFileAnalyzerAction action) { _additionalFileActions = _additionalFileActions.Add(action); IsEmpty = false; } internal void AddSemanticModelAction(SemanticModelAnalyzerAction action) { _semanticModelActions = _semanticModelActions.Add(action); IsEmpty = false; } internal void AddSymbolAction(SymbolAnalyzerAction action) { _symbolActions = _symbolActions.Add(action); IsEmpty = false; } internal void AddSymbolStartAction(SymbolStartAnalyzerAction action) { _symbolStartActions = _symbolStartActions.Add(action); IsEmpty = false; } internal void AddSymbolEndAction(SymbolEndAnalyzerAction action) { _symbolEndActions = _symbolEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockStartAction<TLanguageKindEnum>(CodeBlockStartAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _codeBlockStartActions = _codeBlockStartActions.Add(action); IsEmpty = false; } internal void AddCodeBlockEndAction(CodeBlockAnalyzerAction action) { _codeBlockEndActions = _codeBlockEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockAction(CodeBlockAnalyzerAction action) { _codeBlockActions = _codeBlockActions.Add(action); IsEmpty = false; } internal void AddSyntaxNodeAction<TLanguageKindEnum>(SyntaxNodeAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _syntaxNodeActions = _syntaxNodeActions.Add(action); IsEmpty = false; } internal void AddOperationBlockStartAction(OperationBlockStartAnalyzerAction action) { _operationBlockStartActions = _operationBlockStartActions.Add(action); IsEmpty = false; } internal void AddOperationBlockAction(OperationBlockAnalyzerAction action) { _operationBlockActions = _operationBlockActions.Add(action); IsEmpty = false; } internal void AddOperationBlockEndAction(OperationBlockAnalyzerAction action) { _operationBlockEndActions = _operationBlockEndActions.Add(action); IsEmpty = false; } internal void AddOperationAction(OperationAnalyzerAction action) { _operationActions = _operationActions.Add(action); IsEmpty = false; } internal void EnableConcurrentExecution() { _concurrent = true; } /// <summary> /// Append analyzer actions from <paramref name="otherActions"/> to actions from this instance. /// </summary> /// <param name="otherActions">Analyzer actions to append</param>. public readonly AnalyzerActions Append(in AnalyzerActions otherActions, bool appendSymbolStartAndSymbolEndActions = true) { if (otherActions.IsDefault) { throw new ArgumentNullException(nameof(otherActions)); } AnalyzerActions actions = new AnalyzerActions(concurrent: _concurrent || otherActions.Concurrent); actions._compilationStartActions = _compilationStartActions.AddRange(otherActions._compilationStartActions); actions._compilationEndActions = _compilationEndActions.AddRange(otherActions._compilationEndActions); actions._compilationActions = _compilationActions.AddRange(otherActions._compilationActions); actions._syntaxTreeActions = _syntaxTreeActions.AddRange(otherActions._syntaxTreeActions); actions._additionalFileActions = _additionalFileActions.AddRange(otherActions._additionalFileActions); actions._semanticModelActions = _semanticModelActions.AddRange(otherActions._semanticModelActions); actions._symbolActions = _symbolActions.AddRange(otherActions._symbolActions); actions._symbolStartActions = appendSymbolStartAndSymbolEndActions ? _symbolStartActions.AddRange(otherActions._symbolStartActions) : _symbolStartActions; actions._symbolEndActions = appendSymbolStartAndSymbolEndActions ? _symbolEndActions.AddRange(otherActions._symbolEndActions) : _symbolEndActions; actions._codeBlockStartActions = _codeBlockStartActions.AddRange(otherActions._codeBlockStartActions); actions._codeBlockEndActions = _codeBlockEndActions.AddRange(otherActions._codeBlockEndActions); actions._codeBlockActions = _codeBlockActions.AddRange(otherActions._codeBlockActions); actions._syntaxNodeActions = _syntaxNodeActions.AddRange(otherActions._syntaxNodeActions); actions._operationActions = _operationActions.AddRange(otherActions._operationActions); actions._operationBlockStartActions = _operationBlockStartActions.AddRange(otherActions._operationBlockStartActions); actions._operationBlockEndActions = _operationBlockEndActions.AddRange(otherActions._operationBlockEndActions); actions._operationBlockActions = _operationBlockActions.AddRange(otherActions._operationBlockActions); actions.IsEmpty = IsEmpty && otherActions.IsEmpty; return actions; } } }
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ValuesSources/ConstantValueSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace Roslyn.Utilities { /// <summary> /// This value source keeps a strong reference to a value. /// </summary> internal sealed class ConstantValueSource<T> : ValueSource<T> { private readonly T _value; private Task<T>? _task; public ConstantValueSource(T value) => _value = value; public override T GetValue(CancellationToken cancellationToken = default) => _value; public override bool TryGetValue([MaybeNullWhen(false)] out T value) { value = _value; return true; } public override Task<T> GetValueAsync(CancellationToken cancellationToken = default) { if (_task == null) { Interlocked.CompareExchange(ref _task, Task.FromResult(_value), null); } return _task; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace Roslyn.Utilities { /// <summary> /// This value source keeps a strong reference to a value. /// </summary> internal sealed class ConstantValueSource<T> : ValueSource<T> { private readonly T _value; private Task<T>? _task; public ConstantValueSource(T value) => _value = value; public override T GetValue(CancellationToken cancellationToken = default) => _value; public override bool TryGetValue([MaybeNullWhen(false)] out T value) { value = _value; return true; } public override Task<T> GetValueAsync(CancellationToken cancellationToken = default) { if (_task == null) { Interlocked.CompareExchange(ref _task, Task.FromResult(_value), null); } return _task; } } }
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/Scripting/CoreTestUtilities/TestConsoleIO.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Text; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting.Test { internal sealed class TestConsoleIO : ConsoleIO { private const ConsoleColor InitialColor = ConsoleColor.Gray; public TestConsoleIO(string input) : this(new Reader(input)) { } private TestConsoleIO(Reader reader) : this(reader, new Writer(reader)) { } private TestConsoleIO(Reader reader, TextWriter output) : base(output: output, error: new TeeWriter(output), input: reader) { } public override void SetForegroundColor(ConsoleColor consoleColor) => ((Writer)Out).CurrentColor = consoleColor; public override void ResetColor() => SetForegroundColor(InitialColor); private sealed class Reader : StringReader { public readonly StringBuilder ContentRead = new StringBuilder(); public Reader(string input) : base(input) { } public override string ReadLine() { string result = base.ReadLine(); ContentRead.AppendLine(result); return result; } } private sealed class Writer : StringWriter { private ConsoleColor _lastColor = InitialColor; public ConsoleColor CurrentColor = InitialColor; public override Encoding Encoding => Encoding.UTF8; private readonly Reader _reader; public Writer(Reader reader) { _reader = reader; } private void OnBeforeWrite() { if (_reader.ContentRead.Length > 0) { GetStringBuilder().Append(_reader.ContentRead.ToString()); _reader.ContentRead.Clear(); } if (_lastColor != CurrentColor) { GetStringBuilder().AppendLine($"«{CurrentColor}»"); _lastColor = CurrentColor; } } public override void Write(char value) { OnBeforeWrite(); base.Write(value); } public override void Write(string value) { OnBeforeWrite(); GetStringBuilder().Append(value); } public override void WriteLine(string value) { OnBeforeWrite(); GetStringBuilder().AppendLine(value); } public override void WriteLine() { OnBeforeWrite(); GetStringBuilder().AppendLine(); } } private sealed class TeeWriter : StringWriter { public override Encoding Encoding => Encoding.UTF8; private readonly TextWriter _other; public TeeWriter(TextWriter other) { _other = other; } public override void Write(char value) { _other.Write(value); GetStringBuilder().Append(value); } public override void Write(string value) { _other.Write(value); GetStringBuilder().Append(value); } public override void WriteLine(string value) { _other.WriteLine(value); GetStringBuilder().AppendLine(value); } public override void WriteLine() { _other.WriteLine(); GetStringBuilder().AppendLine(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Text; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting.Test { internal sealed class TestConsoleIO : ConsoleIO { private const ConsoleColor InitialColor = ConsoleColor.Gray; public TestConsoleIO(string input) : this(new Reader(input)) { } private TestConsoleIO(Reader reader) : this(reader, new Writer(reader)) { } private TestConsoleIO(Reader reader, TextWriter output) : base(output: output, error: new TeeWriter(output), input: reader) { } public override void SetForegroundColor(ConsoleColor consoleColor) => ((Writer)Out).CurrentColor = consoleColor; public override void ResetColor() => SetForegroundColor(InitialColor); private sealed class Reader : StringReader { public readonly StringBuilder ContentRead = new StringBuilder(); public Reader(string input) : base(input) { } public override string ReadLine() { string result = base.ReadLine(); ContentRead.AppendLine(result); return result; } } private sealed class Writer : StringWriter { private ConsoleColor _lastColor = InitialColor; public ConsoleColor CurrentColor = InitialColor; public override Encoding Encoding => Encoding.UTF8; private readonly Reader _reader; public Writer(Reader reader) { _reader = reader; } private void OnBeforeWrite() { if (_reader.ContentRead.Length > 0) { GetStringBuilder().Append(_reader.ContentRead.ToString()); _reader.ContentRead.Clear(); } if (_lastColor != CurrentColor) { GetStringBuilder().AppendLine($"«{CurrentColor}»"); _lastColor = CurrentColor; } } public override void Write(char value) { OnBeforeWrite(); base.Write(value); } public override void Write(string value) { OnBeforeWrite(); GetStringBuilder().Append(value); } public override void WriteLine(string value) { OnBeforeWrite(); GetStringBuilder().AppendLine(value); } public override void WriteLine() { OnBeforeWrite(); GetStringBuilder().AppendLine(); } } private sealed class TeeWriter : StringWriter { public override Encoding Encoding => Encoding.UTF8; private readonly TextWriter _other; public TeeWriter(TextWriter other) { _other = other; } public override void Write(char value) { _other.Write(value); GetStringBuilder().Append(value); } public override void Write(string value) { _other.Write(value); GetStringBuilder().Append(value); } public override void WriteLine(string value) { _other.WriteLine(value); GetStringBuilder().AppendLine(value); } public override void WriteLine() { _other.WriteLine(); GetStringBuilder().AppendLine(); } } } }
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/EditorFeatures/CSharpTest/Extensions/ContextQuery/NamespaceContextTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.IntelliSense.CompletionSetSources { public class NamespaceContextTests : AbstractContextTests { protected override void CheckResult(bool validLocation, int position, SyntaxTree syntaxTree) => Assert.Equal(validLocation, syntaxTree.IsNamespaceContext(position, CancellationToken.None)); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void EmptyFile() => VerifyTrue(@"$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void UsingDirective() => VerifyTrue(@"using $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void InactiveRegion() { VerifyFalse(@"#if false $$ #endif"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void SingleLineComment1() => VerifyFalse(@"// $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void SingleLineComment2() { VerifyTrue(@"class C { // $$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void MultiLineComment() => VerifyFalse(@"/* $$ */"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void SingleLineXmlComment() => VerifyFalse(@"/// $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void MultiLineXmlComment() => VerifyFalse(@"/** $$ */"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void OpenStringLiteral() => VerifyFalse(AddInsideMethod("string s = \"$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void StringLiteral() => VerifyFalse(AddInsideMethod("string s = \"$$\";")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void OpenCharLiteral() => VerifyFalse(AddInsideMethod("char c = '$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void AssemblyAttribute() => VerifyTrue(@"[assembly: $$]"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeAttribute() { VerifyTrue(@"[$$] class CL {}"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeParamAttribute() => VerifyTrue(@"class CL<[A$$]T> {}"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void MethodAttribute() { VerifyTrue(@"class CL { [$$] void Method() {} }"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void MethodTypeParamAttribute() { VerifyTrue(@"class CL{ void Method<[A$$]T> () {} }"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void MethodParamAttribute() { VerifyTrue(@"class CL{ void Method ([$$]int i) {} }"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void NamespaceName() => VerifyFalse(@"namespace $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void UnderNamespace() => VerifyFalse(@"namespace NS { $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void OutsideOfType() { VerifyFalse(@"namespace NS { class CL {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void AfterDot() => VerifyFalse(@"[assembly: A.$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void UsingAlias1() => VerifyTrue(@"using MyType = $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void UsingAlias2() => VerifyFalse(@"using $$ = System"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void IncompleteMember() { VerifyTrue(@"class CL { $$ "); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void IncompleteMemberAccessibility() { VerifyTrue(@"class CL { public $$ "); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void BadStatement() => VerifyTrue(AddInsideMethod(@"var t = $$)c")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeTypeParameter() => VerifyFalse(@"class CL<$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeTypeParameterList() => VerifyFalse(@"class CL<T, $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void CastExpressionTypePart() => VerifyTrue(AddInsideMethod(@"var t = ($$)c")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ObjectCreationExpression() => VerifyTrue(AddInsideMethod(@"var t = new $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ArrayCreationExpression() => VerifyTrue(AddInsideMethod(@"var t = new $$ [")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void StackAllocArrayCreationExpression() => VerifyTrue(AddInsideMethod(@"var t = stackalloc $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void FromClauseTypeOptPart() => VerifyTrue(AddInsideMethod(@"var t = from $$ c")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void JoinClause() => VerifyTrue(AddInsideMethod(@"var t = from c in C join $$ j")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void DeclarationStatement() => VerifyTrue(AddInsideMethod(@"$$ i =")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void FixedVariableDeclaration() => VerifyTrue(AddInsideMethod(@"fixed($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ForEachStatement() => VerifyTrue(AddInsideMethod(@"foreach($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ForEachStatementNoToken() => VerifyFalse(AddInsideMethod(@"foreach $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void CatchDeclaration() => VerifyTrue(AddInsideMethod(@"try {} catch($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void FieldDeclaration() { VerifyTrue(@"class CL { $$ i"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void EventFieldDeclaration() { VerifyTrue(@"class CL { event $$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ConversionOperatorDeclaration() { VerifyTrue(@"class CL { explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ConversionOperatorDeclarationNoToken() { VerifyFalse(@"class CL { explicit $$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void PropertyDeclaration() { VerifyTrue(@"class CL { $$ Prop {"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void EventDeclaration() { VerifyTrue(@"class CL { event $$ Event {"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void IndexerDeclaration() { VerifyTrue(@"class CL { $$ this"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void Parameter() { VerifyTrue(@"class CL { void Method($$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ArrayType() { VerifyTrue(@"class CL { $$ ["); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void PointerType() { VerifyTrue(@"class CL { $$ *"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void NullableType() { VerifyTrue(@"class CL { $$ ?"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void DelegateDeclaration() { VerifyTrue(@"class CL { delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void MethodDeclaration() { VerifyTrue(@"class CL { $$ M("); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void OperatorDeclaration() { VerifyTrue(@"class CL { $$ operator"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ParenthesizedExpression() => VerifyTrue(AddInsideMethod(@"($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void InvocationExpression() => VerifyTrue(AddInsideMethod(@"$$(")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ElementAccessExpression() => VerifyTrue(AddInsideMethod(@"$$[")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void Argument() => VerifyTrue(AddInsideMethod(@"i[$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void CastExpressionExpressionPart() => VerifyTrue(AddInsideMethod(@"(c)$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void FromClauseInPart() => VerifyTrue(AddInsideMethod(@"var t = from c in $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void LetClauseExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C let n = $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void OrderingExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C orderby $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void SelectClauseExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C select $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ExpressionStatement() => VerifyTrue(AddInsideMethod(@"$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ReturnStatement() => VerifyTrue(AddInsideMethod(@"return $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ThrowStatement() => VerifyTrue(AddInsideMethod(@"throw $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void YieldReturnStatement() => VerifyTrue(AddInsideMethod(@"yield return $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ForEachStatementExpressionPart() => VerifyTrue(AddInsideMethod(@"foreach(T t in $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void UsingStatementExpressionPart() => VerifyTrue(AddInsideMethod(@"using($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void LockStatement() => VerifyTrue(AddInsideMethod(@"lock($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void EqualsValueClause() => VerifyTrue(AddInsideMethod(@"var i = $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ForStatementInitializersPart() => VerifyTrue(AddInsideMethod(@"for($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ForStatementConditionOptPart() => VerifyTrue(AddInsideMethod(@"for(i=0;$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ForStatementIncrementorsPart() => VerifyTrue(AddInsideMethod(@"for(i=0;i>10;$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void DoStatementConditionPart() => VerifyTrue(AddInsideMethod(@"do {} while($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void WhileStatementConditionPart() => VerifyTrue(AddInsideMethod(@"while($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ArrayRankSpecifierSizesPart() => VerifyTrue(AddInsideMethod(@"int [$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void PrefixUnaryExpression() => VerifyTrue(AddInsideMethod(@"+$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void PostfixUnaryExpression() => VerifyTrue(AddInsideMethod(@"$$++")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void BinaryExpressionLeftPart() => VerifyTrue(AddInsideMethod(@"$$ + 1")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void BinaryExpressionRightPart() => VerifyTrue(AddInsideMethod(@"1 + $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void AssignmentExpressionLeftPart() => VerifyTrue(AddInsideMethod(@"$$ = 1")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void AssignmentExpressionRightPart() => VerifyTrue(AddInsideMethod(@"1 = $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ConditionalExpressionConditionPart() => VerifyTrue(AddInsideMethod(@"$$? 1:")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ConditionalExpressionWhenTruePart() => VerifyTrue(AddInsideMethod(@"true? $$:")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ConditionalExpressionWhenFalsePart() => VerifyTrue(AddInsideMethod(@"true? 1:$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void JoinClauseInExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C join p in $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void JoinClauseLeftExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C join p in P on $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void JoinClauseRightExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C join p in P on id equals $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void WhereClauseConditionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C where $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void GroupClauseGroupExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C group $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void GroupClauseByExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C group g by $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void IfStatement() => VerifyTrue(AddInsideMethod(@"if ($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void SwitchStatement() => VerifyTrue(AddInsideMethod(@"switch($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void SwitchLabelCase() { VerifyTrue(AddInsideMethod(@"switch(i) { case $$")); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void InitializerExpression() => VerifyTrue(AddInsideMethod(@"var t = new [] { $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeParameterConstraintClause() => VerifyTrue(@"class CL<T> where T : $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeParameterConstraintClauseList() => VerifyTrue(@"class CL<T> where T : A, $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeParameterConstraintClauseAnotherWhere() => VerifyFalse(@"class CL<T> where T : A where$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void BaseList1() => VerifyTrue(@"class CL : $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void BaseList2() => VerifyTrue(@"class CL : B, $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void BaseListWhere() => VerifyFalse(@"class CL<T> : B where$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void AliasedName() => VerifyTrue(AddInsideMethod(@"global::$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ConstructorInitializer() => VerifyFalse(@"class C { C() : $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ExplicitInterfaceImplementationGeneric1() => VerifyFalse(@"class C { void IGoo<$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ExplicitInterfaceImplementationGenericList1() => VerifyFalse(@"class C { void IGoo<T,$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ExplicitInterfaceImplementationGeneric2() => VerifyTrue(@"class C { void IGoo<$$>.Method("); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ExplicitInterfaceImplementationGenericList2() => VerifyTrue(@"class C { void IGoo<T,$$>.Method("); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.IntelliSense.CompletionSetSources { public class NamespaceContextTests : AbstractContextTests { protected override void CheckResult(bool validLocation, int position, SyntaxTree syntaxTree) => Assert.Equal(validLocation, syntaxTree.IsNamespaceContext(position, CancellationToken.None)); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void EmptyFile() => VerifyTrue(@"$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void UsingDirective() => VerifyTrue(@"using $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void InactiveRegion() { VerifyFalse(@"#if false $$ #endif"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void SingleLineComment1() => VerifyFalse(@"// $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void SingleLineComment2() { VerifyTrue(@"class C { // $$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void MultiLineComment() => VerifyFalse(@"/* $$ */"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void SingleLineXmlComment() => VerifyFalse(@"/// $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void MultiLineXmlComment() => VerifyFalse(@"/** $$ */"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void OpenStringLiteral() => VerifyFalse(AddInsideMethod("string s = \"$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void StringLiteral() => VerifyFalse(AddInsideMethod("string s = \"$$\";")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void OpenCharLiteral() => VerifyFalse(AddInsideMethod("char c = '$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void AssemblyAttribute() => VerifyTrue(@"[assembly: $$]"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeAttribute() { VerifyTrue(@"[$$] class CL {}"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeParamAttribute() => VerifyTrue(@"class CL<[A$$]T> {}"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void MethodAttribute() { VerifyTrue(@"class CL { [$$] void Method() {} }"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void MethodTypeParamAttribute() { VerifyTrue(@"class CL{ void Method<[A$$]T> () {} }"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void MethodParamAttribute() { VerifyTrue(@"class CL{ void Method ([$$]int i) {} }"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void NamespaceName() => VerifyFalse(@"namespace $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void UnderNamespace() => VerifyFalse(@"namespace NS { $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void OutsideOfType() { VerifyFalse(@"namespace NS { class CL {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void AfterDot() => VerifyFalse(@"[assembly: A.$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void UsingAlias1() => VerifyTrue(@"using MyType = $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void UsingAlias2() => VerifyFalse(@"using $$ = System"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void IncompleteMember() { VerifyTrue(@"class CL { $$ "); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void IncompleteMemberAccessibility() { VerifyTrue(@"class CL { public $$ "); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void BadStatement() => VerifyTrue(AddInsideMethod(@"var t = $$)c")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeTypeParameter() => VerifyFalse(@"class CL<$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeTypeParameterList() => VerifyFalse(@"class CL<T, $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void CastExpressionTypePart() => VerifyTrue(AddInsideMethod(@"var t = ($$)c")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ObjectCreationExpression() => VerifyTrue(AddInsideMethod(@"var t = new $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ArrayCreationExpression() => VerifyTrue(AddInsideMethod(@"var t = new $$ [")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void StackAllocArrayCreationExpression() => VerifyTrue(AddInsideMethod(@"var t = stackalloc $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void FromClauseTypeOptPart() => VerifyTrue(AddInsideMethod(@"var t = from $$ c")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void JoinClause() => VerifyTrue(AddInsideMethod(@"var t = from c in C join $$ j")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void DeclarationStatement() => VerifyTrue(AddInsideMethod(@"$$ i =")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void FixedVariableDeclaration() => VerifyTrue(AddInsideMethod(@"fixed($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ForEachStatement() => VerifyTrue(AddInsideMethod(@"foreach($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ForEachStatementNoToken() => VerifyFalse(AddInsideMethod(@"foreach $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void CatchDeclaration() => VerifyTrue(AddInsideMethod(@"try {} catch($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void FieldDeclaration() { VerifyTrue(@"class CL { $$ i"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void EventFieldDeclaration() { VerifyTrue(@"class CL { event $$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ConversionOperatorDeclaration() { VerifyTrue(@"class CL { explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ConversionOperatorDeclarationNoToken() { VerifyFalse(@"class CL { explicit $$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void PropertyDeclaration() { VerifyTrue(@"class CL { $$ Prop {"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void EventDeclaration() { VerifyTrue(@"class CL { event $$ Event {"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void IndexerDeclaration() { VerifyTrue(@"class CL { $$ this"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void Parameter() { VerifyTrue(@"class CL { void Method($$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ArrayType() { VerifyTrue(@"class CL { $$ ["); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void PointerType() { VerifyTrue(@"class CL { $$ *"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void NullableType() { VerifyTrue(@"class CL { $$ ?"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void DelegateDeclaration() { VerifyTrue(@"class CL { delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void MethodDeclaration() { VerifyTrue(@"class CL { $$ M("); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void OperatorDeclaration() { VerifyTrue(@"class CL { $$ operator"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ParenthesizedExpression() => VerifyTrue(AddInsideMethod(@"($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void InvocationExpression() => VerifyTrue(AddInsideMethod(@"$$(")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ElementAccessExpression() => VerifyTrue(AddInsideMethod(@"$$[")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void Argument() => VerifyTrue(AddInsideMethod(@"i[$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void CastExpressionExpressionPart() => VerifyTrue(AddInsideMethod(@"(c)$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void FromClauseInPart() => VerifyTrue(AddInsideMethod(@"var t = from c in $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void LetClauseExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C let n = $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void OrderingExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C orderby $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void SelectClauseExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C select $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ExpressionStatement() => VerifyTrue(AddInsideMethod(@"$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ReturnStatement() => VerifyTrue(AddInsideMethod(@"return $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ThrowStatement() => VerifyTrue(AddInsideMethod(@"throw $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void YieldReturnStatement() => VerifyTrue(AddInsideMethod(@"yield return $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ForEachStatementExpressionPart() => VerifyTrue(AddInsideMethod(@"foreach(T t in $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void UsingStatementExpressionPart() => VerifyTrue(AddInsideMethod(@"using($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void LockStatement() => VerifyTrue(AddInsideMethod(@"lock($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void EqualsValueClause() => VerifyTrue(AddInsideMethod(@"var i = $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ForStatementInitializersPart() => VerifyTrue(AddInsideMethod(@"for($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ForStatementConditionOptPart() => VerifyTrue(AddInsideMethod(@"for(i=0;$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ForStatementIncrementorsPart() => VerifyTrue(AddInsideMethod(@"for(i=0;i>10;$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void DoStatementConditionPart() => VerifyTrue(AddInsideMethod(@"do {} while($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void WhileStatementConditionPart() => VerifyTrue(AddInsideMethod(@"while($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ArrayRankSpecifierSizesPart() => VerifyTrue(AddInsideMethod(@"int [$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void PrefixUnaryExpression() => VerifyTrue(AddInsideMethod(@"+$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void PostfixUnaryExpression() => VerifyTrue(AddInsideMethod(@"$$++")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void BinaryExpressionLeftPart() => VerifyTrue(AddInsideMethod(@"$$ + 1")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void BinaryExpressionRightPart() => VerifyTrue(AddInsideMethod(@"1 + $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void AssignmentExpressionLeftPart() => VerifyTrue(AddInsideMethod(@"$$ = 1")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void AssignmentExpressionRightPart() => VerifyTrue(AddInsideMethod(@"1 = $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ConditionalExpressionConditionPart() => VerifyTrue(AddInsideMethod(@"$$? 1:")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ConditionalExpressionWhenTruePart() => VerifyTrue(AddInsideMethod(@"true? $$:")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ConditionalExpressionWhenFalsePart() => VerifyTrue(AddInsideMethod(@"true? 1:$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void JoinClauseInExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C join p in $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void JoinClauseLeftExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C join p in P on $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void JoinClauseRightExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C join p in P on id equals $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void WhereClauseConditionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C where $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void GroupClauseGroupExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C group $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void GroupClauseByExpressionPart() => VerifyTrue(AddInsideMethod(@"var t = from c in C group g by $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void IfStatement() => VerifyTrue(AddInsideMethod(@"if ($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void SwitchStatement() => VerifyTrue(AddInsideMethod(@"switch($$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void SwitchLabelCase() { VerifyTrue(AddInsideMethod(@"switch(i) { case $$")); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void InitializerExpression() => VerifyTrue(AddInsideMethod(@"var t = new [] { $$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeParameterConstraintClause() => VerifyTrue(@"class CL<T> where T : $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeParameterConstraintClauseList() => VerifyTrue(@"class CL<T> where T : A, $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void TypeParameterConstraintClauseAnotherWhere() => VerifyFalse(@"class CL<T> where T : A where$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void BaseList1() => VerifyTrue(@"class CL : $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void BaseList2() => VerifyTrue(@"class CL : B, $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void BaseListWhere() => VerifyFalse(@"class CL<T> : B where$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void AliasedName() => VerifyTrue(AddInsideMethod(@"global::$$")); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ConstructorInitializer() => VerifyFalse(@"class C { C() : $$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ExplicitInterfaceImplementationGeneric1() => VerifyFalse(@"class C { void IGoo<$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ExplicitInterfaceImplementationGenericList1() => VerifyFalse(@"class C { void IGoo<T,$$"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ExplicitInterfaceImplementationGeneric2() => VerifyTrue(@"class C { void IGoo<$$>.Method("); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void ExplicitInterfaceImplementationGenericList2() => VerifyTrue(@"class C { void IGoo<T,$$>.Method("); } }
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeActions/CodeActionRequestPriority.cs
// Licensed to the .NET Foundation under one or more 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.Diagnostics; namespace Microsoft.CodeAnalysis.CodeActions { #pragma warning disable CA1200 // Avoid using cref tags with a prefix internal enum CodeActionRequestPriority { /// <summary> /// No priority specified, all refactoring, code fixes, and analyzers should be run. This is equivalent /// to <see cref="Normal"/> and <see cref="High"/> combined. /// </summary> None = 0, /// <summary> /// Only normal priority refactoring, code fix providers should be run. Specifically, /// providers will be run when <see cref="T:CodeRefactoringProvider.RequestPriority"/> or /// <see cref="T:CodeFixProvider.RequestPriority"/> is <see cref="Normal"/>. <see cref="DiagnosticAnalyzer"/>s /// will be run except for <see cref="DiagnosticAnalyzerExtensions.IsCompilerAnalyzer"/>. /// </summary> Normal = 1, /// <summary> /// Only high priority refactoring, code fix providers should be run. Specifically, /// providers will be run when <see cref="T:CodeRefactoringProvider.RequestPriority"/> or /// <see cref="T:CodeFixProvider.RequestPriority"/> is <see cref="Normal"/>. /// The <see cref="DiagnosticAnalyzerExtensions.IsCompilerAnalyzer"/> <see cref="DiagnosticAnalyzer"/> /// will be run. /// </summary> High = 2, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CodeActions { #pragma warning disable CA1200 // Avoid using cref tags with a prefix internal enum CodeActionRequestPriority { /// <summary> /// No priority specified, all refactoring, code fixes, and analyzers should be run. This is equivalent /// to <see cref="Normal"/> and <see cref="High"/> combined. /// </summary> None = 0, /// <summary> /// Only normal priority refactoring, code fix providers should be run. Specifically, /// providers will be run when <see cref="T:CodeRefactoringProvider.RequestPriority"/> or /// <see cref="T:CodeFixProvider.RequestPriority"/> is <see cref="Normal"/>. <see cref="DiagnosticAnalyzer"/>s /// will be run except for <see cref="DiagnosticAnalyzerExtensions.IsCompilerAnalyzer"/>. /// </summary> Normal = 1, /// <summary> /// Only high priority refactoring, code fix providers should be run. Specifically, /// providers will be run when <see cref="T:CodeRefactoringProvider.RequestPriority"/> or /// <see cref="T:CodeFixProvider.RequestPriority"/> is <see cref="Normal"/>. /// The <see cref="DiagnosticAnalyzerExtensions.IsCompilerAnalyzer"/> <see cref="DiagnosticAnalyzer"/> /// will be run. /// </summary> High = 2, } }
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.pt-BR.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pt-BR" original="../CodeStyleFixesResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Remover este valor quando outro for adicionado.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pt-BR" original="../CodeStyleFixesResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Remover este valor quando outro for adicionado.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/Interactive/csi/csi.coreclr.rsp
# basic references /r:System.Collections /r:System.Collections.Concurrent /r:System.Console /r:System.Diagnostics.Debug /r:System.Diagnostics.Process /r:System.Diagnostics.StackTrace /r:System.Globalization /r:System.IO /r:System.IO.FileSystem /r:System.IO.FileSystem.Primitives /r:System.Reflection /r:System.Reflection.Primitives /r:System.Runtime /r:System.Runtime.Extensions /r:System.Runtime.InteropServices /r:System.Text.Encoding /r:System.Text.Encoding.CodePages /r:System.Text.Encoding.Extensions /r:System.Text.RegularExpressions /r:System.Threading /r:System.Threading.Tasks /r:System.Threading.Tasks.Parallel /r:System.Threading.Thread # extra references /r:System.Dynamic.Runtime /r:System.Linq /r:System.Linq.Expressions /r:System.Runtime.Numerics /r:System.ValueTuple /r:Microsoft.CSharp # imports /u:System /u:System.IO /u:System.Collections.Generic /u:System.Console /u:System.Diagnostics /u:System.Dynamic /u:System.Linq /u:System.Linq.Expressions /u:System.Text /u:System.Threading.Tasks
# basic references /r:System.Collections /r:System.Collections.Concurrent /r:System.Console /r:System.Diagnostics.Debug /r:System.Diagnostics.Process /r:System.Diagnostics.StackTrace /r:System.Globalization /r:System.IO /r:System.IO.FileSystem /r:System.IO.FileSystem.Primitives /r:System.Reflection /r:System.Reflection.Primitives /r:System.Runtime /r:System.Runtime.Extensions /r:System.Runtime.InteropServices /r:System.Text.Encoding /r:System.Text.Encoding.CodePages /r:System.Text.Encoding.Extensions /r:System.Text.RegularExpressions /r:System.Threading /r:System.Threading.Tasks /r:System.Threading.Tasks.Parallel /r:System.Threading.Thread # extra references /r:System.Dynamic.Runtime /r:System.Linq /r:System.Linq.Expressions /r:System.Runtime.Numerics /r:System.ValueTuple /r:Microsoft.CSharp # imports /u:System /u:System.IO /u:System.Collections.Generic /u:System.Console /u:System.Diagnostics /u:System.Dynamic /u:System.Linq /u:System.Linq.Expressions /u:System.Text /u:System.Threading.Tasks
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/Compilers/VisualBasic/Portable/Binding/SubOrFunctionBodyBinder.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A SubOrFunctionBodyBinder provides context for looking up parameters/labels in a body of an executable entity (a method, lambda, or top-level script code), ''' and also for the implementation of ContainingMember, GetLocalForFunctionValue and GetBinder. ''' </summary> Friend MustInherit Class SubOrFunctionBodyBinder Inherits ExecutableCodeBinder Private ReadOnly _methodSymbol As MethodSymbol Protected ReadOnly _parameterMap As Dictionary(Of String, Symbol) Public Sub New(methodOrLambdaSymbol As MethodSymbol, root As SyntaxNode, containingBinder As Binder) MyBase.New(root, containingBinder) _methodSymbol = methodOrLambdaSymbol Dim parameters As ImmutableArray(Of ParameterSymbol) = methodOrLambdaSymbol.Parameters Dim count As Integer = parameters.Length Dim mapSize As Integer = count If Not methodOrLambdaSymbol.IsSub Then mapSize += 1 ' account for possible function return value End If _parameterMap = New Dictionary(Of String, Symbol)(mapSize, CaseInsensitiveComparison.Comparer) For i = 0 To count - 1 Dim parameterSymbol = parameters(i) ' If there are two parameters with the same name, the first takes precedence. ' This is an error condition anyway, but it seems more logical and ' it really doesn't matter which order we use. If Not _parameterMap.ContainsKey(parameterSymbol.Name) Then _parameterMap(parameterSymbol.Name) = parameterSymbol End If Next End Sub Public Overrides ReadOnly Property ContainingMember As Symbol Get Return _methodSymbol End Get End Property Public Overrides ReadOnly Property AdditionalContainingMembers As ImmutableArray(Of Symbol) Get Return ImmutableArray(Of Symbol).Empty End Get End Property Public MustOverride Overrides Function GetLocalForFunctionValue() As LocalSymbol 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) ' Parameters always have arity 0 and are not namespaces or types. If (options And (LookupOptions.NamespacesOrTypesOnly Or LookupOptions.LabelsOnly Or LookupOptions.MustNotBeLocalOrParameter)) = 0 Then Dim parameterSymbol As Symbol = Nothing If _parameterMap.TryGetValue(name, parameterSymbol) Then lookupResult.SetFrom(CheckViability(parameterSymbol, arity, options, Nothing, useSiteInfo)) End If Else MyBase.LookupInSingleBinder(lookupResult, name, arity, options, originalBinder, useSiteInfo) End If End Sub Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) ' UNDONE: additional filtering based on options? If (options And (LookupOptions.NamespacesOrTypesOnly Or LookupOptions.LabelsOnly)) = 0 Then For Each param In _parameterMap.Values If originalBinder.CanAddLookupSymbolInfo(param, options, nameSet, Nothing) Then nameSet.AddSymbol(param, param.Name, 0) End If Next Else MyBase.AddLookupSymbolsInfoInSingleBinder(nameSet, options, originalBinder) 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 System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A SubOrFunctionBodyBinder provides context for looking up parameters/labels in a body of an executable entity (a method, lambda, or top-level script code), ''' and also for the implementation of ContainingMember, GetLocalForFunctionValue and GetBinder. ''' </summary> Friend MustInherit Class SubOrFunctionBodyBinder Inherits ExecutableCodeBinder Private ReadOnly _methodSymbol As MethodSymbol Protected ReadOnly _parameterMap As Dictionary(Of String, Symbol) Public Sub New(methodOrLambdaSymbol As MethodSymbol, root As SyntaxNode, containingBinder As Binder) MyBase.New(root, containingBinder) _methodSymbol = methodOrLambdaSymbol Dim parameters As ImmutableArray(Of ParameterSymbol) = methodOrLambdaSymbol.Parameters Dim count As Integer = parameters.Length Dim mapSize As Integer = count If Not methodOrLambdaSymbol.IsSub Then mapSize += 1 ' account for possible function return value End If _parameterMap = New Dictionary(Of String, Symbol)(mapSize, CaseInsensitiveComparison.Comparer) For i = 0 To count - 1 Dim parameterSymbol = parameters(i) ' If there are two parameters with the same name, the first takes precedence. ' This is an error condition anyway, but it seems more logical and ' it really doesn't matter which order we use. If Not _parameterMap.ContainsKey(parameterSymbol.Name) Then _parameterMap(parameterSymbol.Name) = parameterSymbol End If Next End Sub Public Overrides ReadOnly Property ContainingMember As Symbol Get Return _methodSymbol End Get End Property Public Overrides ReadOnly Property AdditionalContainingMembers As ImmutableArray(Of Symbol) Get Return ImmutableArray(Of Symbol).Empty End Get End Property Public MustOverride Overrides Function GetLocalForFunctionValue() As LocalSymbol 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) ' Parameters always have arity 0 and are not namespaces or types. If (options And (LookupOptions.NamespacesOrTypesOnly Or LookupOptions.LabelsOnly Or LookupOptions.MustNotBeLocalOrParameter)) = 0 Then Dim parameterSymbol As Symbol = Nothing If _parameterMap.TryGetValue(name, parameterSymbol) Then lookupResult.SetFrom(CheckViability(parameterSymbol, arity, options, Nothing, useSiteInfo)) End If Else MyBase.LookupInSingleBinder(lookupResult, name, arity, options, originalBinder, useSiteInfo) End If End Sub Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) ' UNDONE: additional filtering based on options? If (options And (LookupOptions.NamespacesOrTypesOnly Or LookupOptions.LabelsOnly)) = 0 Then For Each param In _parameterMap.Values If originalBinder.CanAddLookupSymbolInfo(param, options, nameSet, Nothing) Then nameSet.AddSymbol(param, param.Name, 0) End If Next Else MyBase.AddLookupSymbolsInfoInSingleBinder(nameSet, options, originalBinder) End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/ContextQuery/VisualBasicSyntaxContextService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery <ExportLanguageService(GetType(ISyntaxContextService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSyntaxContextService Implements ISyntaxContextService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateContext(workspace As Workspace, semanticModel As SemanticModel, position As Integer, cancellationToken As CancellationToken) As SyntaxContext Implements ISyntaxContextService.CreateContext Return VisualBasicSyntaxContext.CreateContext(workspace, semanticModel, position, cancellationToken) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery <ExportLanguageService(GetType(ISyntaxContextService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSyntaxContextService Implements ISyntaxContextService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateContext(workspace As Workspace, semanticModel As SemanticModel, position As Integer, cancellationToken As CancellationToken) As SyntaxContext Implements ISyntaxContextService.CreateContext Return VisualBasicSyntaxContext.CreateContext(workspace, semanticModel, position, cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/Features/VisualBasic/Portable/Completion/CompletionProviders/LastBuiltInCompletionProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers ''' <summary> ''' Provides a completion provider that always appears after all built-in completion providers. This completion ''' provider does not provide any completions. ''' </summary> <ExportCompletionProvider(NameOf(LastBuiltInCompletionProvider), LanguageNames.VisualBasic)> <[Shared]> Friend Class LastBuiltInCompletionProvider Inherits CompletionProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task Return Task.CompletedTask End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers ''' <summary> ''' Provides a completion provider that always appears after all built-in completion providers. This completion ''' provider does not provide any completions. ''' </summary> <ExportCompletionProvider(NameOf(LastBuiltInCompletionProvider), LanguageNames.VisualBasic)> <[Shared]> Friend Class LastBuiltInCompletionProvider Inherits CompletionProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task Return Task.CompletedTask End Function End Class End Namespace
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_LateInvocation.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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter ' TODO: missing/omitted arguments Public Overrides Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode Debug.Assert(node.Member IsNot Nothing, "late invocation always has a member that is invoked") If _inExpressionLambda Then ' just preserve the node to report an error in ExpressionLambdaRewriter Return MyBase.VisitLateInvocation(node) End If If node.Member.Kind = BoundKind.LateMemberAccess Then ' objReceiver.goo(args) Dim member = DirectCast(node.Member, BoundLateMemberAccess) ' NOTE: member is not the receiver of the call, it just represents the latebound access. ' actual receiver of the whole invocation is the member's receiver. Return RewriteLateBoundMemberInvocation(member, member.ReceiverOpt, node.ArgumentsOpt, node.ArgumentNamesOpt, useLateCall:=node.AccessKind = LateBoundAccessKind.Call) Else ' objExpr(args) ' NOTE: member is the receiver of this call. it must be an array or something indexable. Return RewriteLateBoundIndexInvocation(node, node.Member, node.ArgumentsOpt) End If End Function Private Function RewriteLateBoundIndexInvocation(invocation As BoundLateInvocation, receiverExpression As BoundExpression, argExpressions As ImmutableArray(Of BoundExpression)) As BoundExpression Debug.Assert(invocation.AccessKind = LateBoundAccessKind.Get) Debug.Assert(receiverExpression.Kind <> BoundKind.LateMemberAccess) Dim rewrittenReceiver = VisitExpressionNode(invocation.Member) Dim rewrittenArguments = VisitList(argExpressions) Return LateIndexGet(invocation, rewrittenReceiver, rewrittenArguments) End Function Private Function RewriteLateBoundMemberInvocation(memberAccess As BoundLateMemberAccess, receiverExpression As BoundExpression, argExpressions As ImmutableArray(Of BoundExpression), argNames As ImmutableArray(Of String), useLateCall As Boolean) As BoundExpression Dim temps As ArrayBuilder(Of SynthesizedLocal) = Nothing Dim rewrittenReceiver As BoundExpression = VisitExpressionNode(receiverExpression) Dim assignmentArguments As ImmutableArray(Of BoundExpression) = Nothing LateCaptureArgsComplex(temps, argExpressions, assignmentArguments) Dim result As BoundExpression = LateCallOrGet(memberAccess, rewrittenReceiver, argExpressions, assignmentArguments, argNames, useLateCall) Dim tempArray As ImmutableArray(Of SynthesizedLocal) = Nothing If temps IsNot Nothing Then tempArray = temps.ToImmutableAndFree If Not tempArray.IsEmpty Then result = New BoundSequence(memberAccess.Syntax, StaticCast(Of LocalSymbol).From(tempArray), ImmutableArray(Of BoundExpression).Empty, result, result.Type) End If End If Return result 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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter ' TODO: missing/omitted arguments Public Overrides Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode Debug.Assert(node.Member IsNot Nothing, "late invocation always has a member that is invoked") If _inExpressionLambda Then ' just preserve the node to report an error in ExpressionLambdaRewriter Return MyBase.VisitLateInvocation(node) End If If node.Member.Kind = BoundKind.LateMemberAccess Then ' objReceiver.goo(args) Dim member = DirectCast(node.Member, BoundLateMemberAccess) ' NOTE: member is not the receiver of the call, it just represents the latebound access. ' actual receiver of the whole invocation is the member's receiver. Return RewriteLateBoundMemberInvocation(member, member.ReceiverOpt, node.ArgumentsOpt, node.ArgumentNamesOpt, useLateCall:=node.AccessKind = LateBoundAccessKind.Call) Else ' objExpr(args) ' NOTE: member is the receiver of this call. it must be an array or something indexable. Return RewriteLateBoundIndexInvocation(node, node.Member, node.ArgumentsOpt) End If End Function Private Function RewriteLateBoundIndexInvocation(invocation As BoundLateInvocation, receiverExpression As BoundExpression, argExpressions As ImmutableArray(Of BoundExpression)) As BoundExpression Debug.Assert(invocation.AccessKind = LateBoundAccessKind.Get) Debug.Assert(receiverExpression.Kind <> BoundKind.LateMemberAccess) Dim rewrittenReceiver = VisitExpressionNode(invocation.Member) Dim rewrittenArguments = VisitList(argExpressions) Return LateIndexGet(invocation, rewrittenReceiver, rewrittenArguments) End Function Private Function RewriteLateBoundMemberInvocation(memberAccess As BoundLateMemberAccess, receiverExpression As BoundExpression, argExpressions As ImmutableArray(Of BoundExpression), argNames As ImmutableArray(Of String), useLateCall As Boolean) As BoundExpression Dim temps As ArrayBuilder(Of SynthesizedLocal) = Nothing Dim rewrittenReceiver As BoundExpression = VisitExpressionNode(receiverExpression) Dim assignmentArguments As ImmutableArray(Of BoundExpression) = Nothing LateCaptureArgsComplex(temps, argExpressions, assignmentArguments) Dim result As BoundExpression = LateCallOrGet(memberAccess, rewrittenReceiver, argExpressions, assignmentArguments, argNames, useLateCall) Dim tempArray As ImmutableArray(Of SynthesizedLocal) = Nothing If temps IsNot Nothing Then tempArray = temps.ToImmutableAndFree If Not tempArray.IsEmpty Then result = New BoundSequence(memberAccess.Syntax, StaticCast(Of LocalSymbol).From(tempArray), ImmutableArray(Of BoundExpression).Empty, result, result.Type) End If End If Return result End Function End Class End Namespace
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/Features/Core/Portable/SolutionCrawler/HostSolutionCrawlerWorkspaceEventListener.cs
// Licensed to the .NET Foundation under one or more 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.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.SolutionCrawler { [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal class HostSolutionCrawlerWorkspaceEventListener : IEventListener<object>, IEventListenerStoppable { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public HostSolutionCrawlerWorkspaceEventListener() { } public void StartListening(Workspace workspace, object? serviceOpt) { var registration = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registration.Register(workspace); } public void StopListening(Workspace workspace) { // we do this so that we can stop solution crawler faster and fire some telemetry. // this is to reduce a case where we keep going even when VS is shutting down since we don't know about that var registration = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registration.Unregister(workspace, blockingShutdown: 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.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.SolutionCrawler { [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal class HostSolutionCrawlerWorkspaceEventListener : IEventListener<object>, IEventListenerStoppable { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public HostSolutionCrawlerWorkspaceEventListener() { } public void StartListening(Workspace workspace, object? serviceOpt) { var registration = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registration.Register(workspace); } public void StopListening(Workspace workspace) { // we do this so that we can stop solution crawler faster and fire some telemetry. // this is to reduce a case where we keep going even when VS is shutting down since we don't know about that var registration = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registration.Unregister(workspace, blockingShutdown: true); } } }
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/EditorFeatures/Core/Implementation/Interactive/InteractiveLanguageNames.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Interactive { internal class InteractiveLanguageNames { public const string InteractiveCommand = "Interactive Command"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Interactive { internal class InteractiveLanguageNames { public const string InteractiveCommand = "Interactive Command"; } }
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/EditorFeatures/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/DotNetDiagnosticSeverityBasedSeverityConfigurationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureSeverity { public abstract partial class DotNetDiagnosticSeverityBasedSeverityConfigurationTests : AbstractSuppressionDiagnosticTest { private sealed class CustomDiagnosticAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( id: "XYZ0001", title: "Title", messageFormat: "Message", category: "Category", defaultSeverity: DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction( c => c.ReportDiagnostic(Diagnostic.Create(Rule, c.Node.GetLocation())), SyntaxKind.ClassDeclaration); } } protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CustomDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider()); } public class NoneConfigurationTests : DotNetDiagnosticSeverityBasedSeverityConfigurationTests { protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.XYZ0001.severity = suggestion # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.XYZ0001.severity = none # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.XYZ0001.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.XYZ0001.severity = suggestion [*.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainExistingEntry_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestMissingInRegularAndScriptAsync(input); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.XYZ1111.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.XYZ1111.severity = none # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] [WorkItem(45446, "https://github.com/dotnet/roslyn/issues/45446")] public async Task ConfigureEditorconfig_MissingRule_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.severity = none # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexHeaderMatch_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fi*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fi*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexHeaderNonMatch_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fii*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fii*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = warning [*.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureSeverity { public abstract partial class DotNetDiagnosticSeverityBasedSeverityConfigurationTests : AbstractSuppressionDiagnosticTest { private sealed class CustomDiagnosticAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( id: "XYZ0001", title: "Title", messageFormat: "Message", category: "Category", defaultSeverity: DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction( c => c.ReportDiagnostic(Diagnostic.Create(Rule, c.Node.GetLocation())), SyntaxKind.ClassDeclaration); } } protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CustomDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider()); } public class NoneConfigurationTests : DotNetDiagnosticSeverityBasedSeverityConfigurationTests { protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.XYZ0001.severity = suggestion # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.XYZ0001.severity = none # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.XYZ0001.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.XYZ0001.severity = suggestion [*.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainExistingEntry_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestMissingInRegularAndScriptAsync(input); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.XYZ1111.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.XYZ1111.severity = none # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] [WorkItem(45446, "https://github.com/dotnet/roslyn/issues/45446")] public async Task ConfigureEditorconfig_MissingRule_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.severity = none # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexHeaderMatch_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fi*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fi*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexHeaderNonMatch_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fii*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fii*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = warning [*.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/Workspaces/Core/Portable/TodoComments/TodoCommentData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.TodoComments { /// <summary> /// Serialization type used to pass information to/from OOP and VS. /// </summary> [DataContract] internal readonly struct TodoCommentData : IEquatable<TodoCommentData> { [DataMember(Order = 0)] public readonly int Priority; [DataMember(Order = 1)] public readonly string Message; [DataMember(Order = 2)] public readonly DocumentId DocumentId; [DataMember(Order = 3)] public readonly string? MappedFilePath; [DataMember(Order = 4)] public readonly string? OriginalFilePath; [DataMember(Order = 5)] public readonly int MappedLine; [DataMember(Order = 6)] public readonly int MappedColumn; [DataMember(Order = 7)] public readonly int OriginalLine; [DataMember(Order = 8)] public readonly int OriginalColumn; public TodoCommentData(int priority, string message, DocumentId documentId, string? mappedFilePath, string? originalFilePath, int mappedLine, int mappedColumn, int originalLine, int originalColumn) { Priority = priority; Message = message; DocumentId = documentId; MappedFilePath = mappedFilePath; OriginalFilePath = originalFilePath; MappedLine = mappedLine; MappedColumn = mappedColumn; OriginalLine = originalLine; OriginalColumn = originalColumn; } public override bool Equals(object? obj) => obj is TodoCommentData other && Equals(other); public override int GetHashCode() => GetHashCode(this); public override string ToString() => $"{Priority} {Message} {MappedFilePath ?? ""} ({MappedLine}, {MappedColumn}) [original: {OriginalFilePath ?? ""} ({OriginalLine}, {OriginalColumn})"; public bool Equals(TodoCommentData right) => DocumentId == right.DocumentId && Priority == right.Priority && Message == right.Message && OriginalLine == right.OriginalLine && OriginalColumn == right.OriginalColumn; public static int GetHashCode(TodoCommentData item) => Hash.Combine(item.DocumentId, Hash.Combine(item.Priority, Hash.Combine(item.Message, Hash.Combine(item.OriginalLine, Hash.Combine(item.OriginalColumn, 0))))); internal void WriteTo(ObjectWriter writer) { writer.WriteInt32(Priority); writer.WriteString(Message); DocumentId.WriteTo(writer); writer.WriteString(MappedFilePath); writer.WriteString(OriginalFilePath); writer.WriteInt32(MappedLine); writer.WriteInt32(MappedColumn); writer.WriteInt32(OriginalLine); writer.WriteInt32(OriginalColumn); } internal static TodoCommentData ReadFrom(ObjectReader reader) => new(priority: reader.ReadInt32(), message: reader.ReadString(), documentId: DocumentId.ReadFrom(reader), mappedFilePath: reader.ReadString(), originalFilePath: reader.ReadString(), mappedLine: reader.ReadInt32(), mappedColumn: reader.ReadInt32(), originalLine: reader.ReadInt32(), originalColumn: reader.ReadInt32()); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.TodoComments { /// <summary> /// Serialization type used to pass information to/from OOP and VS. /// </summary> [DataContract] internal readonly struct TodoCommentData : IEquatable<TodoCommentData> { [DataMember(Order = 0)] public readonly int Priority; [DataMember(Order = 1)] public readonly string Message; [DataMember(Order = 2)] public readonly DocumentId DocumentId; [DataMember(Order = 3)] public readonly string? MappedFilePath; [DataMember(Order = 4)] public readonly string? OriginalFilePath; [DataMember(Order = 5)] public readonly int MappedLine; [DataMember(Order = 6)] public readonly int MappedColumn; [DataMember(Order = 7)] public readonly int OriginalLine; [DataMember(Order = 8)] public readonly int OriginalColumn; public TodoCommentData(int priority, string message, DocumentId documentId, string? mappedFilePath, string? originalFilePath, int mappedLine, int mappedColumn, int originalLine, int originalColumn) { Priority = priority; Message = message; DocumentId = documentId; MappedFilePath = mappedFilePath; OriginalFilePath = originalFilePath; MappedLine = mappedLine; MappedColumn = mappedColumn; OriginalLine = originalLine; OriginalColumn = originalColumn; } public override bool Equals(object? obj) => obj is TodoCommentData other && Equals(other); public override int GetHashCode() => GetHashCode(this); public override string ToString() => $"{Priority} {Message} {MappedFilePath ?? ""} ({MappedLine}, {MappedColumn}) [original: {OriginalFilePath ?? ""} ({OriginalLine}, {OriginalColumn})"; public bool Equals(TodoCommentData right) => DocumentId == right.DocumentId && Priority == right.Priority && Message == right.Message && OriginalLine == right.OriginalLine && OriginalColumn == right.OriginalColumn; public static int GetHashCode(TodoCommentData item) => Hash.Combine(item.DocumentId, Hash.Combine(item.Priority, Hash.Combine(item.Message, Hash.Combine(item.OriginalLine, Hash.Combine(item.OriginalColumn, 0))))); internal void WriteTo(ObjectWriter writer) { writer.WriteInt32(Priority); writer.WriteString(Message); DocumentId.WriteTo(writer); writer.WriteString(MappedFilePath); writer.WriteString(OriginalFilePath); writer.WriteInt32(MappedLine); writer.WriteInt32(MappedColumn); writer.WriteInt32(OriginalLine); writer.WriteInt32(OriginalColumn); } internal static TodoCommentData ReadFrom(ObjectReader reader) => new(priority: reader.ReadInt32(), message: reader.ReadString(), documentId: DocumentId.ReadFrom(reader), mappedFilePath: reader.ReadString(), originalFilePath: reader.ReadString(), mappedLine: reader.ReadInt32(), mappedColumn: reader.ReadInt32(), originalLine: reader.ReadInt32(), originalColumn: reader.ReadInt32()); } }
-1
dotnet/roslyn
55,599
Shutdown LSP server on streamjsonrpc disconnect
Resolves https://github.com/dotnet/roslyn/issues/54823
dibarbet
2021-08-13T02:05:22Z
2021-08-13T21:58:55Z
db6f6fcb9bb28868434176b1401b27ef91613332
0954614a5d74e843916c84f220a65770efe19b20
Shutdown LSP server on streamjsonrpc disconnect. Resolves https://github.com/dotnet/roslyn/issues/54823
./src/Compilers/CSharp/Portable/Syntax/ThrowStatementSyntax.cs
// Licensed to the .NET Foundation under one or more 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.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class ThrowStatementSyntax { public ThrowStatementSyntax Update(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) => Update(AttributeLists, throwKeyword, expression, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static ThrowStatementSyntax ThrowStatement(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) => ThrowStatement(attributeLists: default, throwKeyword, expression, semicolonToken); } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class ThrowStatementSyntax { public ThrowStatementSyntax Update(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) => Update(AttributeLists, throwKeyword, expression, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static ThrowStatementSyntax ThrowStatement(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken) => ThrowStatement(attributeLists: default, throwKeyword, expression, semicolonToken); } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Workspaces/Core/Portable/Storage/SQLite/v2/Interop/SqlConnection.cs
// Licensed to the .NET Foundation under one or more 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.IO; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.SQLite.Interop; using Roslyn.Utilities; using SQLitePCL; namespace Microsoft.CodeAnalysis.SQLite.v2.Interop { using static SQLitePersistentStorageConstants; /// <summary> /// Encapsulates a connection to a sqlite database. On construction an attempt will be made /// to open the DB if it exists, or create it if it does not. /// /// Connections are considered relatively heavyweight and are pooled until the <see cref="SQLitePersistentStorage"/> /// is <see cref="SQLitePersistentStorage.Dispose"/>d. Connections can be used by different threads, /// but only as long as they are used by one thread at a time. They are not safe for concurrent /// use by several threads. /// /// <see cref="SqlStatement"/>s can be created through the user of <see cref="GetResettableStatement"/>. /// These statements are cached for the lifetime of the connection and are only finalized /// (i.e. destroyed) when the connection is closed. /// </summary> internal class SqlConnection { // Cached utf8 (and null terminated) versions of the common strings we need to pass to sqlite. Used to prevent // having to convert these names to/from utf16 to utf8 on every call. Sqlite requires these be null terminated. private static readonly byte[] s_mainNameWithTrailingZero = GetUtf8BytesWithTrailingZero(Database.Main.GetName()); private static readonly byte[] s_writeCacheNameWithTrailingZero = GetUtf8BytesWithTrailingZero(Database.WriteCache.GetName()); private static readonly byte[] s_solutionTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(SolutionDataTableName); private static readonly byte[] s_projectTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(ProjectDataTableName); private static readonly byte[] s_documentTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(DocumentDataTableName); private static readonly byte[] s_checksumColumnNameWithTrailingZero = GetUtf8BytesWithTrailingZero(ChecksumColumnName); private static readonly byte[] s_dataColumnNameWithTrailingZero = GetUtf8BytesWithTrailingZero(DataColumnName); private static byte[] GetUtf8BytesWithTrailingZero(string value) { var length = Encoding.UTF8.GetByteCount(value); // Add one for the trailing zero. var byteArray = new byte[length + 1]; var wrote = Encoding.UTF8.GetBytes(value, 0, value.Length, byteArray, 0); Contract.ThrowIfFalse(wrote == length); // Paranoia, but write in the trailing zero no matter what. byteArray[^1] = 0; return byteArray; } /// <summary> /// The raw handle to the underlying DB. /// </summary> private readonly SafeSqliteHandle _handle; /// <summary> /// Our cache of prepared statements for given sql strings. /// </summary> private readonly Dictionary<string, SqlStatement> _queryToStatement; /// <summary> /// Whether or not we're in a transaction. We currently don't supported nested transactions. /// If we want that, we can achieve it through sqlite "save points". However, that's adds a /// lot of complexity that is nice to avoid. /// </summary> public bool IsInTransaction { get; private set; } public static SqlConnection Create(IPersistentStorageFaultInjector? faultInjector, string databasePath) { faultInjector?.OnNewConnection(); // Allocate dictionary before doing any sqlite work. That way if it throws // we don't have to do any additional cleanup. var queryToStatement = new Dictionary<string, SqlStatement>(); // Use SQLITE_OPEN_NOMUTEX to enable multi-thread mode, where multiple connections can // be used provided each one is only used from a single thread at a time. // // Use SHAREDCACHE so that we can have an in-memory DB that we dump our writes into. We // need SHAREDCACHE so that all connections see that same in-memory DB. This also // requires OPEN_URI since we need a `file::memory:` uri for them all to refer to. // // see https://sqlite.org/threadsafe.html for more detail var flags = OpenFlags.SQLITE_OPEN_CREATE | OpenFlags.SQLITE_OPEN_READWRITE | OpenFlags.SQLITE_OPEN_NOMUTEX | OpenFlags.SQLITE_OPEN_SHAREDCACHE | OpenFlags.SQLITE_OPEN_URI; var handle = NativeMethods.sqlite3_open_v2(databasePath, (int)flags, vfs: null, out var result); if (result != Result.OK) { handle.Dispose(); throw new SqlException(result, $"Could not open database file: {databasePath} ({result})"); } try { NativeMethods.sqlite3_busy_timeout(handle, (int)TimeSpan.FromMinutes(1).TotalMilliseconds); var connection = new SqlConnection(handle, queryToStatement); // Attach (creating if necessary) a singleton in-memory write cache to this connection. // // From: https://www.sqlite.org/sharedcache.html Enabling shared-cache for an in-memory database allows // two or more database connections in the same process to have access to the same in-memory database. // An in-memory database in shared cache is automatically deleted and memory is reclaimed when the last // connection to that database closes. // Using `?mode=memory&cache=shared as writecache` at the end ensures all connections (to the on-disk // db) see the same db (https://sqlite.org/inmemorydb.html) and the same data when reading and writing. // i.e. if one connection writes data to this, another connection will see that data when reading. // Without this, each connection would get their own private memory db independent of all other // connections. // Workaround https://github.com/ericsink/SQLitePCL.raw/issues/407. On non-windows do not pass in the // uri of the DB on disk we're associating this in-memory cache with. This throws on at least OSX for // reasons that aren't fully understood yet. If more details/fixes emerge in that linked issue, we can // ideally remove this and perform the attachment uniformly on all platforms. var attachString = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"attach database '{new Uri(databasePath).AbsoluteUri}?mode=memory&cache=shared' as {Database.WriteCache.GetName()};" : $"attach database 'file::memory:?cache=shared' as {Database.WriteCache.GetName()};"; connection.ExecuteCommand(attachString); return connection; } catch { // If we failed to create connection, ensure that we still release the sqlite // handle. handle.Dispose(); throw; } } private SqlConnection(SafeSqliteHandle handle, Dictionary<string, SqlStatement> queryToStatement) { _handle = handle; _queryToStatement = queryToStatement; } internal void Close_OnlyForUseBySQLiteConnectionPool() { // Dispose of the underlying handle at the end of cleanup using var _ = _handle; // release all the cached statements we have. // // use the struct-enumerator of our dictionary to prevent any allocations here. We // don't want to risk an allocation causing an OOM which prevents executing the // following cleanup code. foreach (var (_, statement) in _queryToStatement) { statement.Close_OnlyForUseBySqlConnection(); } _queryToStatement.Clear(); } public void ExecuteCommand(string command, bool throwOnError = true) { using var resettableStatement = GetResettableStatement(command); var statement = resettableStatement.Statement; var result = statement.Step(throwOnError); if (result != Result.DONE && throwOnError) { Throw(result); } } public ResettableSqlStatement GetResettableStatement(string query) { if (!_queryToStatement.TryGetValue(query, out var statement)) { var handle = NativeMethods.sqlite3_prepare_v2(_handle, query, out var result); try { ThrowIfNotOk(result); statement = new SqlStatement(this, handle); _queryToStatement[query] = statement; } catch { handle.Dispose(); throw; } } return new ResettableSqlStatement(statement); } public void RunInTransaction<TState>(Action<TState> action, TState state) { RunInTransaction( state => { state.action(state.state); return (object?)null; }, (action, state)); } public TResult RunInTransaction<TState, TResult>(Func<TState, TResult> action, TState state) { try { if (IsInTransaction) { throw new InvalidOperationException("Nested transactions not currently supported"); } IsInTransaction = true; ExecuteCommand("begin transaction"); var result = action(state); ExecuteCommand("commit transaction"); return result; } catch (SqlException ex) when (ex.Result == Result.FULL || ex.Result == Result.IOERR || ex.Result == Result.BUSY || ex.Result == Result.LOCKED || ex.Result == Result.NOMEM) { // See documentation here: https://sqlite.org/lang_transaction.html // If certain kinds of errors occur within a transaction, the transaction // may or may not be rolled back automatically. The errors that can cause // an automatic rollback include: // SQLITE_FULL: database or disk full // SQLITE_IOERR: disk I/ O error // SQLITE_BUSY: database in use by another process // SQLITE_LOCKED: database in use by another connection in the same process // SQLITE_NOMEM: out or memory // It is recommended that applications respond to the errors listed above by // explicitly issuing a ROLLBACK command. If the transaction has already been // rolled back automatically by the error response, then the ROLLBACK command // will fail with an error, but no harm is caused by this. Rollback(throwOnError: false); throw; } catch (Exception) { Rollback(throwOnError: true); throw; } finally { IsInTransaction = false; } } private void Rollback(bool throwOnError) => ExecuteCommand("rollback transaction", throwOnError); public int LastInsertRowId() => (int)NativeMethods.sqlite3_last_insert_rowid(_handle); [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Optional<Stream> ReadDataBlob_MustRunInTransaction(Database database, Table table, long rowId) { return ReadBlob_MustRunInTransaction( database, table, Column.Data, rowId, static (self, blobHandle) => new Optional<Stream>(self.ReadBlob(blobHandle))); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Optional<Checksum.HashData> ReadChecksum_MustRunInTransaction(Database database, Table table, long rowId) { return ReadBlob_MustRunInTransaction( database, table, Column.Checksum, rowId, static (self, blobHandle) => { // If the length of the blob isn't correct, then we can't read a checksum out of this. var length = NativeMethods.sqlite3_blob_bytes(blobHandle); if (length != Checksum.HashSize) return new Optional<Checksum.HashData>(); Span<byte> bytes = stackalloc byte[Checksum.HashSize]; self.ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blobHandle, bytes, offset: 0)); Contract.ThrowIfFalse(MemoryMarshal.TryRead(bytes, out Checksum.HashData result)); return new Optional<Checksum.HashData>(result); }); } private Stream ReadBlob(SafeSqliteBlobHandle blob) { var length = NativeMethods.sqlite3_blob_bytes(blob); // If it's a small blob, just read it into one of our pooled arrays, and then // create a PooledStream over it. if (length <= SQLitePersistentStorage.MaxPooledByteArrayLength) { return ReadBlobIntoPooledStream(blob, length); } else { // Otherwise, it's a large stream. Just take the hit of allocating. var bytes = new byte[length]; ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blob, bytes.AsSpan(), offset: 0)); return new MemoryStream(bytes); } } private Stream ReadBlobIntoPooledStream(SafeSqliteBlobHandle blob, int length) { var bytes = SQLitePersistentStorage.GetPooledBytes(); try { ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blob, new Span<byte>(bytes, start: 0, length), offset: 0)); // Copy those bytes into a pooled stream return SerializableBytes.CreateReadableStream(bytes, length); } finally { // Return our small array back to the pool. SQLitePersistentStorage.ReturnPooledBytes(bytes); } } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Optional<T> ReadBlob_MustRunInTransaction<T>( Database database, Table table, Column column, long rowId, Func<SqlConnection, SafeSqliteBlobHandle, Optional<T>> readBlob) { // NOTE: we do need to do the blob reading in a transaction because of the // following: https://www.sqlite.org/c3ref/blob_open.html // // If the row that a BLOB handle points to is modified by an UPDATE, DELETE, // or by ON CONFLICT side-effects then the BLOB handle is marked as "expired". // This is true if any column of the row is changed, even a column other than // the one the BLOB handle is open on. Calls to sqlite3_blob_read() and // sqlite3_blob_write() for an expired BLOB handle fail with a return code of // SQLITE_ABORT. if (!IsInTransaction) { throw new InvalidOperationException("Must read blobs within a transaction to prevent corruption!"); } var databaseNameBytes = database switch { Database.Main => s_mainNameWithTrailingZero, Database.WriteCache => s_writeCacheNameWithTrailingZero, _ => throw ExceptionUtilities.UnexpectedValue(database), }; var tableNameBytes = table switch { Table.Solution => s_solutionTableNameWithTrailingZero, Table.Project => s_projectTableNameWithTrailingZero, Table.Document => s_documentTableNameWithTrailingZero, _ => throw ExceptionUtilities.UnexpectedValue(table), }; var columnNameBytes = column switch { Column.Data => s_dataColumnNameWithTrailingZero, Column.Checksum => s_checksumColumnNameWithTrailingZero, _ => throw ExceptionUtilities.UnexpectedValue(column), }; unsafe { fixed (byte* databaseNamePtr = databaseNameBytes) fixed (byte* tableNamePtr = tableNameBytes) fixed (byte* columnNamePtr = columnNameBytes) { // sqlite requires a byte* and a length *not* including the trailing zero. So subtract one from all // the array lengths to get the length they expect. const int ReadOnlyFlags = 0; using var blob = NativeMethods.sqlite3_blob_open( _handle, utf8z.FromPtrLen(databaseNamePtr, databaseNameBytes.Length - 1), utf8z.FromPtrLen(tableNamePtr, tableNameBytes.Length - 1), utf8z.FromPtrLen(columnNamePtr, columnNameBytes.Length - 1), rowId, ReadOnlyFlags, out var result); if (result == Result.ERROR) { // can happen when rowId points to a row that hasn't been written to yet. return default; } ThrowIfNotOk(result); return readBlob(this, blob); } } } public void ThrowIfNotOk(int result) => ThrowIfNotOk((Result)result); public void ThrowIfNotOk(Result result) => ThrowIfNotOk(_handle, result); public static void ThrowIfNotOk(SafeSqliteHandle handle, Result result) { if (result != Result.OK) { Throw(handle, result); } } public void Throw(Result result) => Throw(_handle, result); public static void Throw(SafeSqliteHandle handle, Result result) => throw new SqlException(result, NativeMethods.sqlite3_errmsg(handle) + Environment.NewLine + NativeMethods.sqlite3_errstr(NativeMethods.sqlite3_extended_errcode(handle))); } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.SQLite.Interop; using Roslyn.Utilities; using SQLitePCL; namespace Microsoft.CodeAnalysis.SQLite.v2.Interop { using static SQLitePersistentStorageConstants; /// <summary> /// Encapsulates a connection to a sqlite database. On construction an attempt will be made /// to open the DB if it exists, or create it if it does not. /// /// Connections are considered relatively heavyweight and are pooled until the <see cref="SQLitePersistentStorage"/> /// is <see cref="SQLitePersistentStorage.Dispose"/>d. Connections can be used by different threads, /// but only as long as they are used by one thread at a time. They are not safe for concurrent /// use by several threads. /// /// <see cref="SqlStatement"/>s can be created through the user of <see cref="GetResettableStatement"/>. /// These statements are cached for the lifetime of the connection and are only finalized /// (i.e. destroyed) when the connection is closed. /// </summary> internal class SqlConnection { // Cached utf8 (and null terminated) versions of the common strings we need to pass to sqlite. Used to prevent // having to convert these names to/from utf16 to utf8 on every call. Sqlite requires these be null terminated. private static readonly byte[] s_mainNameWithTrailingZero = GetUtf8BytesWithTrailingZero(Database.Main.GetName()); private static readonly byte[] s_writeCacheNameWithTrailingZero = GetUtf8BytesWithTrailingZero(Database.WriteCache.GetName()); private static readonly byte[] s_solutionTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(SolutionDataTableName); private static readonly byte[] s_projectTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(ProjectDataTableName); private static readonly byte[] s_documentTableNameWithTrailingZero = GetUtf8BytesWithTrailingZero(DocumentDataTableName); private static readonly byte[] s_checksumColumnNameWithTrailingZero = GetUtf8BytesWithTrailingZero(ChecksumColumnName); private static readonly byte[] s_dataColumnNameWithTrailingZero = GetUtf8BytesWithTrailingZero(DataColumnName); private static byte[] GetUtf8BytesWithTrailingZero(string value) { var length = Encoding.UTF8.GetByteCount(value); // Add one for the trailing zero. var byteArray = new byte[length + 1]; var wrote = Encoding.UTF8.GetBytes(value, 0, value.Length, byteArray, 0); Contract.ThrowIfFalse(wrote == length); // Paranoia, but write in the trailing zero no matter what. byteArray[^1] = 0; return byteArray; } /// <summary> /// The raw handle to the underlying DB. /// </summary> private readonly SafeSqliteHandle _handle; /// <summary> /// Our cache of prepared statements for given sql strings. /// </summary> private readonly Dictionary<string, SqlStatement> _queryToStatement; /// <summary> /// Whether or not we're in a transaction. We currently don't supported nested transactions. /// If we want that, we can achieve it through sqlite "save points". However, that's adds a /// lot of complexity that is nice to avoid. /// </summary> public bool IsInTransaction { get; private set; } public static SqlConnection Create(IPersistentStorageFaultInjector? faultInjector, string databasePath) { faultInjector?.OnNewConnection(); // Allocate dictionary before doing any sqlite work. That way if it throws // we don't have to do any additional cleanup. var queryToStatement = new Dictionary<string, SqlStatement>(); // Use SQLITE_OPEN_NOMUTEX to enable multi-thread mode, where multiple connections can // be used provided each one is only used from a single thread at a time. // // Use SHAREDCACHE so that we can have an in-memory DB that we dump our writes into. We // need SHAREDCACHE so that all connections see that same in-memory DB. This also // requires OPEN_URI since we need a `file::memory:` uri for them all to refer to. // // see https://sqlite.org/threadsafe.html for more detail var flags = OpenFlags.SQLITE_OPEN_CREATE | OpenFlags.SQLITE_OPEN_READWRITE | OpenFlags.SQLITE_OPEN_NOMUTEX | OpenFlags.SQLITE_OPEN_SHAREDCACHE | OpenFlags.SQLITE_OPEN_URI; var handle = NativeMethods.sqlite3_open_v2(databasePath, (int)flags, vfs: null, out var result); if (result != Result.OK) { handle.Dispose(); throw new SqlException(result, $"Could not open database file: {databasePath} ({result})"); } try { NativeMethods.sqlite3_busy_timeout(handle, (int)TimeSpan.FromMinutes(1).TotalMilliseconds); var connection = new SqlConnection(handle, queryToStatement); // Attach (creating if necessary) a singleton in-memory write cache to this connection. // // From: https://www.sqlite.org/sharedcache.html Enabling shared-cache for an in-memory database allows // two or more database connections in the same process to have access to the same in-memory database. // An in-memory database in shared cache is automatically deleted and memory is reclaimed when the last // connection to that database closes. // Using `?mode=memory&cache=shared as writecache` at the end ensures all connections (to the on-disk // db) see the same db (https://sqlite.org/inmemorydb.html) and the same data when reading and writing. // i.e. if one connection writes data to this, another connection will see that data when reading. // Without this, each connection would get their own private memory db independent of all other // connections. // Workaround https://github.com/ericsink/SQLitePCL.raw/issues/407. On non-windows do not pass in the // uri of the DB on disk we're associating this in-memory cache with. This throws on at least OSX for // reasons that aren't fully understood yet. If more details/fixes emerge in that linked issue, we can // ideally remove this and perform the attachment uniformly on all platforms. var attachString = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"attach database '{new Uri(databasePath).AbsoluteUri}?mode=memory&cache=shared' as {Database.WriteCache.GetName()};" : $"attach database 'file::memory:?cache=shared' as {Database.WriteCache.GetName()};"; connection.ExecuteCommand(attachString); return connection; } catch { // If we failed to create connection, ensure that we still release the sqlite // handle. handle.Dispose(); throw; } } private SqlConnection(SafeSqliteHandle handle, Dictionary<string, SqlStatement> queryToStatement) { _handle = handle; _queryToStatement = queryToStatement; } internal void Close_OnlyForUseBySQLiteConnectionPool() { // Dispose of the underlying handle at the end of cleanup using var _ = _handle; // release all the cached statements we have. // // use the struct-enumerator of our dictionary to prevent any allocations here. We // don't want to risk an allocation causing an OOM which prevents executing the // following cleanup code. foreach (var (_, statement) in _queryToStatement) { statement.Close_OnlyForUseBySqlConnection(); } _queryToStatement.Clear(); } public void ExecuteCommand(string command, bool throwOnError = true) { using var resettableStatement = GetResettableStatement(command); var statement = resettableStatement.Statement; var result = statement.Step(throwOnError); if (result != Result.DONE && throwOnError) { Throw(result); } } public ResettableSqlStatement GetResettableStatement(string query) { if (!_queryToStatement.TryGetValue(query, out var statement)) { var handle = NativeMethods.sqlite3_prepare_v2(_handle, query, out var result); try { ThrowIfNotOk(result); statement = new SqlStatement(this, handle); _queryToStatement[query] = statement; } catch { handle.Dispose(); throw; } } return new ResettableSqlStatement(statement); } public void RunInTransaction<TState>(Action<TState> action, TState state) { RunInTransaction( static state => { state.action(state.state); return (object?)null; }, (action, state)); } public TResult RunInTransaction<TState, TResult>(Func<TState, TResult> action, TState state) { try { if (IsInTransaction) { throw new InvalidOperationException("Nested transactions not currently supported"); } IsInTransaction = true; ExecuteCommand("begin transaction"); var result = action(state); ExecuteCommand("commit transaction"); return result; } catch (SqlException ex) when (ex.Result == Result.FULL || ex.Result == Result.IOERR || ex.Result == Result.BUSY || ex.Result == Result.LOCKED || ex.Result == Result.NOMEM) { // See documentation here: https://sqlite.org/lang_transaction.html // If certain kinds of errors occur within a transaction, the transaction // may or may not be rolled back automatically. The errors that can cause // an automatic rollback include: // SQLITE_FULL: database or disk full // SQLITE_IOERR: disk I/ O error // SQLITE_BUSY: database in use by another process // SQLITE_LOCKED: database in use by another connection in the same process // SQLITE_NOMEM: out or memory // It is recommended that applications respond to the errors listed above by // explicitly issuing a ROLLBACK command. If the transaction has already been // rolled back automatically by the error response, then the ROLLBACK command // will fail with an error, but no harm is caused by this. Rollback(throwOnError: false); throw; } catch (Exception) { Rollback(throwOnError: true); throw; } finally { IsInTransaction = false; } } private void Rollback(bool throwOnError) => ExecuteCommand("rollback transaction", throwOnError); public int LastInsertRowId() => (int)NativeMethods.sqlite3_last_insert_rowid(_handle); [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Optional<Stream> ReadDataBlob_MustRunInTransaction(Database database, Table table, long rowId) { return ReadBlob_MustRunInTransaction( database, table, Column.Data, rowId, static (self, blobHandle) => new Optional<Stream>(self.ReadBlob(blobHandle))); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Optional<Checksum.HashData> ReadChecksum_MustRunInTransaction(Database database, Table table, long rowId) { return ReadBlob_MustRunInTransaction( database, table, Column.Checksum, rowId, static (self, blobHandle) => { // If the length of the blob isn't correct, then we can't read a checksum out of this. var length = NativeMethods.sqlite3_blob_bytes(blobHandle); if (length != Checksum.HashSize) return new Optional<Checksum.HashData>(); Span<byte> bytes = stackalloc byte[Checksum.HashSize]; self.ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blobHandle, bytes, offset: 0)); Contract.ThrowIfFalse(MemoryMarshal.TryRead(bytes, out Checksum.HashData result)); return new Optional<Checksum.HashData>(result); }); } private Stream ReadBlob(SafeSqliteBlobHandle blob) { var length = NativeMethods.sqlite3_blob_bytes(blob); // If it's a small blob, just read it into one of our pooled arrays, and then // create a PooledStream over it. if (length <= SQLitePersistentStorage.MaxPooledByteArrayLength) { return ReadBlobIntoPooledStream(blob, length); } else { // Otherwise, it's a large stream. Just take the hit of allocating. var bytes = new byte[length]; ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blob, bytes.AsSpan(), offset: 0)); return new MemoryStream(bytes); } } private Stream ReadBlobIntoPooledStream(SafeSqliteBlobHandle blob, int length) { var bytes = SQLitePersistentStorage.GetPooledBytes(); try { ThrowIfNotOk(NativeMethods.sqlite3_blob_read(blob, new Span<byte>(bytes, start: 0, length), offset: 0)); // Copy those bytes into a pooled stream return SerializableBytes.CreateReadableStream(bytes, length); } finally { // Return our small array back to the pool. SQLitePersistentStorage.ReturnPooledBytes(bytes); } } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Optional<T> ReadBlob_MustRunInTransaction<T>( Database database, Table table, Column column, long rowId, Func<SqlConnection, SafeSqliteBlobHandle, Optional<T>> readBlob) { // NOTE: we do need to do the blob reading in a transaction because of the // following: https://www.sqlite.org/c3ref/blob_open.html // // If the row that a BLOB handle points to is modified by an UPDATE, DELETE, // or by ON CONFLICT side-effects then the BLOB handle is marked as "expired". // This is true if any column of the row is changed, even a column other than // the one the BLOB handle is open on. Calls to sqlite3_blob_read() and // sqlite3_blob_write() for an expired BLOB handle fail with a return code of // SQLITE_ABORT. if (!IsInTransaction) { throw new InvalidOperationException("Must read blobs within a transaction to prevent corruption!"); } var databaseNameBytes = database switch { Database.Main => s_mainNameWithTrailingZero, Database.WriteCache => s_writeCacheNameWithTrailingZero, _ => throw ExceptionUtilities.UnexpectedValue(database), }; var tableNameBytes = table switch { Table.Solution => s_solutionTableNameWithTrailingZero, Table.Project => s_projectTableNameWithTrailingZero, Table.Document => s_documentTableNameWithTrailingZero, _ => throw ExceptionUtilities.UnexpectedValue(table), }; var columnNameBytes = column switch { Column.Data => s_dataColumnNameWithTrailingZero, Column.Checksum => s_checksumColumnNameWithTrailingZero, _ => throw ExceptionUtilities.UnexpectedValue(column), }; unsafe { fixed (byte* databaseNamePtr = databaseNameBytes) fixed (byte* tableNamePtr = tableNameBytes) fixed (byte* columnNamePtr = columnNameBytes) { // sqlite requires a byte* and a length *not* including the trailing zero. So subtract one from all // the array lengths to get the length they expect. const int ReadOnlyFlags = 0; using var blob = NativeMethods.sqlite3_blob_open( _handle, utf8z.FromPtrLen(databaseNamePtr, databaseNameBytes.Length - 1), utf8z.FromPtrLen(tableNamePtr, tableNameBytes.Length - 1), utf8z.FromPtrLen(columnNamePtr, columnNameBytes.Length - 1), rowId, ReadOnlyFlags, out var result); if (result == Result.ERROR) { // can happen when rowId points to a row that hasn't been written to yet. return default; } ThrowIfNotOk(result); return readBlob(this, blob); } } } public void ThrowIfNotOk(int result) => ThrowIfNotOk((Result)result); public void ThrowIfNotOk(Result result) => ThrowIfNotOk(_handle, result); public static void ThrowIfNotOk(SafeSqliteHandle handle, Result result) { if (result != Result.OK) { Throw(handle, result); } } public void Throw(Result result) => Throw(_handle, result); public static void Throw(SafeSqliteHandle handle, Result result) => throw new SqlException(result, NativeMethods.sqlite3_errmsg(handle) + Environment.NewLine + NativeMethods.sqlite3_errstr(NativeMethods.sqlite3_extended_errcode(handle))); } }
1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SQLite.v2.Interop; using Microsoft.CodeAnalysis.Storage; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SQLite.v2 { using static SQLitePersistentStorageConstants; /// <summary> /// Implementation of an <see cref="IPersistentStorage"/> backed by SQLite. /// </summary> internal partial class SQLitePersistentStorage : AbstractPersistentStorage { private readonly CancellationTokenSource _shutdownTokenSource = new(); private readonly SQLiteConnectionPoolService _connectionPoolService; private readonly ReferenceCountedDisposable<SQLiteConnectionPool> _connectionPool; // Accessors that allow us to retrieve/store data into specific DB tables. The // core Accessor type has logic that we to share across all reading/writing, while // the derived types contain only enough logic to specify how to read/write from // their respective tables. private readonly SolutionAccessor _solutionAccessor; private readonly ProjectAccessor _projectAccessor; private readonly DocumentAccessor _documentAccessor; // cached query strings private readonly string _insert_into_string_table_values_0 = $@"insert into {StringInfoTableName}(""{DataColumnName}"") values (?)"; private readonly string _select_star_from_string_table_where_0_limit_one = $@"select * from {StringInfoTableName} where (""{DataColumnName}"" = ?) limit 1"; private SQLitePersistentStorage( SQLiteConnectionPoolService connectionPoolService, string workingFolderPath, string solutionFilePath, string databaseFile, IAsynchronousOperationListener asyncListener, IPersistentStorageFaultInjector? faultInjector) : base(workingFolderPath, solutionFilePath, databaseFile) { _connectionPoolService = connectionPoolService; _solutionAccessor = new SolutionAccessor(this); _projectAccessor = new ProjectAccessor(this); _documentAccessor = new DocumentAccessor(this); // This assignment violates the declared non-nullability of _connectionPool, but the caller ensures that // the constructed object is only used if the nullability post-conditions are met. _connectionPool = connectionPoolService.TryOpenDatabase( databaseFile, faultInjector, (connection, cancellationToken) => Initialize(connection, cancellationToken), CancellationToken.None)!; // Create a delay to batch up requests to flush. We'll won't flush more than every FlushAllDelayMS. _flushQueue = new AsyncBatchingWorkQueue( TimeSpan.FromMilliseconds(FlushAllDelayMS), FlushInMemoryDataToDiskIfNotShutdownAsync, asyncListener, _shutdownTokenSource.Token); } public static SQLitePersistentStorage? TryCreate( SQLiteConnectionPoolService connectionPoolService, string workingFolderPath, string solutionFilePath, string databaseFile, IAsynchronousOperationListener asyncListener, IPersistentStorageFaultInjector? faultInjector) { var sqlStorage = new SQLitePersistentStorage( connectionPoolService, workingFolderPath, solutionFilePath, databaseFile, asyncListener, faultInjector); if (sqlStorage._connectionPool is null) { // The connection pool failed to initialize return null; } return sqlStorage; } public override void Dispose() { var task = DisposeAsync().AsTask(); task.Wait(); } public override async ValueTask DisposeAsync() { try { // Flush all pending writes so that all data our features wanted written are definitely // persisted to the DB. try { await FlushWritesOnCloseAsync().ConfigureAwait(false); } catch (Exception e) { // Flushing may fail. We still have to close all our connections. StorageDatabaseLogger.LogException(e); } } finally { _connectionPool.Dispose(); } } private static void Initialize(SqlConnection connection, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { // Someone tried to get a connection *after* a call to Dispose the storage system // happened. That should never happen. We only Dispose when the last ref to the // storage system goes away. Once that happens, it's an error for there to be any // future or existing consumers of the storage service. So nothing should be doing // anything that wants to get an connection. throw new InvalidOperationException(); } // Ensure the database has tables for the types we care about. // Enable write-ahead logging to increase write performance by reducing amount of disk writes, // by combining writes at checkpoint, salong with using sequential-only writes to populate the log. // Also, WAL allows for relaxed ("normal") "synchronous" mode, see below. connection.ExecuteCommand("pragma journal_mode=wal", throwOnError: false); // Set "synchronous" mode to "normal" instead of default "full" to reduce the amount of buffer flushing syscalls, // significantly reducing both the blocked time and the amount of context switches. // When coupled with WAL, this (according to https://sqlite.org/pragma.html#pragma_synchronous and // https://www.sqlite.org/wal.html#performance_considerations) is unlikely to significantly affect durability, // while significantly increasing performance, because buffer flushing is done for each checkpoint, instead of each // transaction. While some writes can be lost, they are never reordered, and higher layers will recover from that. connection.ExecuteCommand("pragma synchronous=normal", throwOnError: false); // First, create all string tables in the main on-disk db. These tables // don't need to be in the write-cache as all string looks go to/from the // main db. This isn't a perf problem as we write the strings in bulk, // so there's no need for a write caching layer. This also keeps consistency // totally clear as there's only one source of truth. connection.ExecuteCommand( $@"create table if not exists {StringInfoTableName}( ""{DataIdColumnName}"" integer primary key autoincrement not null, ""{DataColumnName}"" varchar)"); // Ensure that the string-info table's 'Value' column is defined to be 'unique'. // We don't allow duplicate strings in this table. connection.ExecuteCommand( $@"create unique index if not exists ""{StringInfoTableName}_{DataColumnName}"" on {StringInfoTableName}(""{DataColumnName}"")"); // Now make sure we have the individual tables for the solution/project/document info. // We put this in both our persistent table and our in-memory table so that they have // the same shape. EnsureTables(connection, Database.Main); EnsureTables(connection, Database.WriteCache); return; static void EnsureTables(SqlConnection connection, Database database) { var dbName = database.GetName(); connection.ExecuteCommand( $@"create table if not exists {dbName}.{SolutionDataTableName}( ""{DataIdColumnName}"" varchar primary key not null, ""{ChecksumColumnName}"" blob, ""{DataColumnName}"" blob)"); connection.ExecuteCommand( $@"create table if not exists {dbName}.{ProjectDataTableName}( ""{DataIdColumnName}"" integer primary key not null, ""{ChecksumColumnName}"" blob, ""{DataColumnName}"" blob)"); connection.ExecuteCommand( $@"create table if not exists {dbName}.{DocumentDataTableName}( ""{DataIdColumnName}"" integer primary key not null, ""{ChecksumColumnName}"" blob, ""{DataColumnName}"" blob)"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SQLite.v2.Interop; using Microsoft.CodeAnalysis.Storage; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SQLite.v2 { using static SQLitePersistentStorageConstants; /// <summary> /// Implementation of an <see cref="IPersistentStorage"/> backed by SQLite. /// </summary> internal partial class SQLitePersistentStorage : AbstractPersistentStorage { private readonly CancellationTokenSource _shutdownTokenSource = new(); private readonly SQLiteConnectionPoolService _connectionPoolService; private readonly ReferenceCountedDisposable<SQLiteConnectionPool> _connectionPool; private readonly Action _flushInMemoryDataToDisk; // Accessors that allow us to retrieve/store data into specific DB tables. The // core Accessor type has logic that we to share across all reading/writing, while // the derived types contain only enough logic to specify how to read/write from // their respective tables. private readonly SolutionAccessor _solutionAccessor; private readonly ProjectAccessor _projectAccessor; private readonly DocumentAccessor _documentAccessor; // cached query strings private readonly string _insert_into_string_table_values_0 = $@"insert into {StringInfoTableName}(""{DataColumnName}"") values (?)"; private readonly string _select_star_from_string_table_where_0_limit_one = $@"select * from {StringInfoTableName} where (""{DataColumnName}"" = ?) limit 1"; private SQLitePersistentStorage( SQLiteConnectionPoolService connectionPoolService, string workingFolderPath, string solutionFilePath, string databaseFile, IAsynchronousOperationListener asyncListener, IPersistentStorageFaultInjector? faultInjector) : base(workingFolderPath, solutionFilePath, databaseFile) { _connectionPoolService = connectionPoolService; _solutionAccessor = new SolutionAccessor(this); _projectAccessor = new ProjectAccessor(this); _documentAccessor = new DocumentAccessor(this); // This assignment violates the declared non-nullability of _connectionPool, but the caller ensures that // the constructed object is only used if the nullability post-conditions are met. _connectionPool = connectionPoolService.TryOpenDatabase( databaseFile, faultInjector, (connection, cancellationToken) => Initialize(connection, cancellationToken), CancellationToken.None)!; // Create a delay to batch up requests to flush. We'll won't flush more than every FlushAllDelayMS. _flushInMemoryDataToDisk = FlushInMemoryDataToDisk; _flushQueue = new AsyncBatchingWorkQueue( TimeSpan.FromMilliseconds(FlushAllDelayMS), FlushInMemoryDataToDiskIfNotShutdownAsync, asyncListener, _shutdownTokenSource.Token); } public static SQLitePersistentStorage? TryCreate( SQLiteConnectionPoolService connectionPoolService, string workingFolderPath, string solutionFilePath, string databaseFile, IAsynchronousOperationListener asyncListener, IPersistentStorageFaultInjector? faultInjector) { var sqlStorage = new SQLitePersistentStorage( connectionPoolService, workingFolderPath, solutionFilePath, databaseFile, asyncListener, faultInjector); if (sqlStorage._connectionPool is null) { // The connection pool failed to initialize return null; } return sqlStorage; } public override void Dispose() { var task = DisposeAsync().AsTask(); task.Wait(); } public override async ValueTask DisposeAsync() { try { // Flush all pending writes so that all data our features wanted written are definitely // persisted to the DB. try { await FlushWritesOnCloseAsync().ConfigureAwait(false); } catch (Exception e) { // Flushing may fail. We still have to close all our connections. StorageDatabaseLogger.LogException(e); } } finally { _connectionPool.Dispose(); } } private static void Initialize(SqlConnection connection, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { // Someone tried to get a connection *after* a call to Dispose the storage system // happened. That should never happen. We only Dispose when the last ref to the // storage system goes away. Once that happens, it's an error for there to be any // future or existing consumers of the storage service. So nothing should be doing // anything that wants to get an connection. throw new InvalidOperationException(); } // Ensure the database has tables for the types we care about. // Enable write-ahead logging to increase write performance by reducing amount of disk writes, // by combining writes at checkpoint, salong with using sequential-only writes to populate the log. // Also, WAL allows for relaxed ("normal") "synchronous" mode, see below. connection.ExecuteCommand("pragma journal_mode=wal", throwOnError: false); // Set "synchronous" mode to "normal" instead of default "full" to reduce the amount of buffer flushing syscalls, // significantly reducing both the blocked time and the amount of context switches. // When coupled with WAL, this (according to https://sqlite.org/pragma.html#pragma_synchronous and // https://www.sqlite.org/wal.html#performance_considerations) is unlikely to significantly affect durability, // while significantly increasing performance, because buffer flushing is done for each checkpoint, instead of each // transaction. While some writes can be lost, they are never reordered, and higher layers will recover from that. connection.ExecuteCommand("pragma synchronous=normal", throwOnError: false); // First, create all string tables in the main on-disk db. These tables // don't need to be in the write-cache as all string looks go to/from the // main db. This isn't a perf problem as we write the strings in bulk, // so there's no need for a write caching layer. This also keeps consistency // totally clear as there's only one source of truth. connection.ExecuteCommand( $@"create table if not exists {StringInfoTableName}( ""{DataIdColumnName}"" integer primary key autoincrement not null, ""{DataColumnName}"" varchar)"); // Ensure that the string-info table's 'Value' column is defined to be 'unique'. // We don't allow duplicate strings in this table. connection.ExecuteCommand( $@"create unique index if not exists ""{StringInfoTableName}_{DataColumnName}"" on {StringInfoTableName}(""{DataColumnName}"")"); // Now make sure we have the individual tables for the solution/project/document info. // We put this in both our persistent table and our in-memory table so that they have // the same shape. EnsureTables(connection, Database.Main); EnsureTables(connection, Database.WriteCache); return; static void EnsureTables(SqlConnection connection, Database database) { var dbName = database.GetName(); connection.ExecuteCommand( $@"create table if not exists {dbName}.{SolutionDataTableName}( ""{DataIdColumnName}"" varchar primary key not null, ""{ChecksumColumnName}"" blob, ""{DataColumnName}"" blob)"); connection.ExecuteCommand( $@"create table if not exists {dbName}.{ProjectDataTableName}( ""{DataIdColumnName}"" integer primary key not null, ""{ChecksumColumnName}"" blob, ""{DataColumnName}"" blob)"); connection.ExecuteCommand( $@"create table if not exists {dbName}.{DocumentDataTableName}( ""{DataIdColumnName}"" integer primary key not null, ""{ChecksumColumnName}"" blob, ""{DataColumnName}"" blob)"); } } } }
1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_FlushWrites.cs
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SQLite.v2 { internal partial class SQLitePersistentStorage { /// <summary> /// A queue to batch up flush requests and ensure that we don't issue then more often than every <see /// cref="FlushAllDelayMS"/>. /// </summary> private readonly AsyncBatchingWorkQueue _flushQueue; private void EnqueueFlushTask() { _flushQueue.AddWork(); } private async ValueTask FlushInMemoryDataToDiskIfNotShutdownAsync(CancellationToken cancellationToken) { // When we are asked to flush, go actually acquire the write-scheduler and perform the actual writes from // it. Note: this is only called max every FlushAllDelayMS. So we don't bother trying to avoid the delegate // allocation here. await PerformWriteAsync(FlushInMemoryDataToDisk, cancellationToken).ConfigureAwait(false); } private Task FlushWritesOnCloseAsync() { // Issue a write task to write this all out to disk. // // Note: this only happens on close, so we don't try to avoid allocations here. return PerformWriteAsync( () => { // Perform the actual write while having exclusive access to the scheduler. FlushInMemoryDataToDisk(); // Now that we've done this, definitely cancel any further work. From this point on, it is now // invalid for any codepaths to try to acquire a db connection for any purpose (beyond us // disposing things below). // // This will also ensure that if we have a bg flush task still pending, when it wakes up it will // see that we're shutdown and not proceed (and importantly won't acquire a connection). Because // both the bg task and us run serialized, there is no way for it to miss this token // cancellation. If it runs after us, then it sees this. If it runs before us, then we just // block until it finishes. // // We don't have to worry about reads/writes getting connections either. // The only way we can get disposed in the first place is if every user of this storage instance // has released their ref on us. In that case, it would be an error on their part to ever try to // read/write after releasing us. _shutdownTokenSource.Cancel(); }, CancellationToken.None); } private void FlushInMemoryDataToDisk() { // We're writing. This better always be under the exclusive scheduler. Contract.ThrowIfFalse(TaskScheduler.Current == _connectionPoolService.Scheduler.ExclusiveScheduler); // Don't flush from a bg task if we've been asked to shutdown. The shutdown logic in the storage service // will take care of the final writes to the main db. if (_shutdownTokenSource.IsCancellationRequested) return; using var _ = _connectionPool.Target.GetPooledConnection(out var connection); // Dummy value for RunInTransaction signature. var unused = true; connection.RunInTransaction(_ => { _solutionAccessor.FlushInMemoryDataToDisk_MustRunInTransaction(connection); _projectAccessor.FlushInMemoryDataToDisk_MustRunInTransaction(connection); _documentAccessor.FlushInMemoryDataToDisk_MustRunInTransaction(connection); }, unused); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SQLite.v2 { internal partial class SQLitePersistentStorage { /// <summary> /// A queue to batch up flush requests and ensure that we don't issue then more often than every <see /// cref="FlushAllDelayMS"/>. /// </summary> private readonly AsyncBatchingWorkQueue _flushQueue; private void EnqueueFlushTask() { _flushQueue.AddWork(); } private async ValueTask FlushInMemoryDataToDiskIfNotShutdownAsync(CancellationToken cancellationToken) { // When we are asked to flush, go actually acquire the write-scheduler and perform the actual writes from // it. Note: this is only called max every FlushAllDelayMS. So we don't bother trying to avoid the delegate // allocation here. await PerformWriteAsync(_flushInMemoryDataToDisk, cancellationToken).ConfigureAwait(false); } private Task FlushWritesOnCloseAsync() { // Issue a write task to write this all out to disk. // // Note: this only happens on close, so we don't try to avoid allocations here. return PerformWriteAsync( () => { // Perform the actual write while having exclusive access to the scheduler. FlushInMemoryDataToDisk(); // Now that we've done this, definitely cancel any further work. From this point on, it is now // invalid for any codepaths to try to acquire a db connection for any purpose (beyond us // disposing things below). // // This will also ensure that if we have a bg flush task still pending, when it wakes up it will // see that we're shutdown and not proceed (and importantly won't acquire a connection). Because // both the bg task and us run serialized, there is no way for it to miss this token // cancellation. If it runs after us, then it sees this. If it runs before us, then we just // block until it finishes. // // We don't have to worry about reads/writes getting connections either. // The only way we can get disposed in the first place is if every user of this storage instance // has released their ref on us. In that case, it would be an error on their part to ever try to // read/write after releasing us. _shutdownTokenSource.Cancel(); }, CancellationToken.None); } private void FlushInMemoryDataToDisk() { // We're writing. This better always be under the exclusive scheduler. Contract.ThrowIfFalse(TaskScheduler.Current == _connectionPoolService.Scheduler.ExclusiveScheduler); // Don't flush from a bg task if we've been asked to shutdown. The shutdown logic in the storage service // will take care of the final writes to the main db. if (_shutdownTokenSource.IsCancellationRequested) return; using var _ = _connectionPool.Target.GetPooledConnection(out var connection); connection.RunInTransaction(static state => { state.self._solutionAccessor.FlushInMemoryDataToDisk_MustRunInTransaction(state.connection); state.self._projectAccessor.FlushInMemoryDataToDisk_MustRunInTransaction(state.connection); state.self._documentAccessor.FlushInMemoryDataToDisk_MustRunInTransaction(state.connection); }, (self: this, connection)); } } }
1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_Threading.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SQLite.v2 { internal partial class SQLitePersistentStorage { private static async Task<TResult> PerformTaskAsync<TArg, TResult>( Func<TArg, TResult> func, TArg arg, TaskScheduler scheduler, CancellationToken cancellationToken) where TArg : struct { // Get a pooled delegate that can be used to prevent having to alloc a new lambda that calls 'func' while // capturing 'arg'. This is needed as Task.Factory.StartNew has no way to pass extra data around with it // except by boxing it as an object. using var _ = PooledDelegates.GetPooledFunction(func, arg, out var boundFunction); var task = Task.Factory.StartNew(boundFunction, cancellationToken, TaskCreationOptions.None, scheduler); return await task.ConfigureAwait(false); } // Read tasks go to the concurrent-scheduler where they can run concurrently with other read // tasks. private Task<TResult> PerformReadAsync<TArg, TResult>(Func<TArg, TResult> func, TArg arg, CancellationToken cancellationToken) where TArg : struct { // Suppress ExecutionContext flow for asynchronous operations that write to the database. In addition to // avoiding ExecutionContext allocations, this clears the LogicalCallContext and avoids the need to clone // data set by CallContext.LogicalSetData at each yielding await in the task tree. // // ⚠ DO NOT AWAIT INSIDE THE USING. The Dispose method that restores ExecutionContext flow must run on the // same thread where SuppressFlow was originally run. using var _ = FlowControlHelper.TrySuppressFlow(); return PerformTaskAsync(func, arg, _connectionPoolService.Scheduler.ConcurrentScheduler, cancellationToken); } // Write tasks go to the exclusive-scheduler so they run exclusively of all other threading // tasks we need to do. public Task<TResult> PerformWriteAsync<TArg, TResult>(Func<TArg, TResult> func, TArg arg, CancellationToken cancellationToken) where TArg : struct { // Suppress ExecutionContext flow for asynchronous operations that write to the database. In addition to // avoiding ExecutionContext allocations, this clears the LogicalCallContext and avoids the need to clone // data set by CallContext.LogicalSetData at each yielding await in the task tree. // // ⚠ DO NOT AWAIT INSIDE THE USING. The Dispose method that restores ExecutionContext flow must run on the // same thread where SuppressFlow was originally run. using var _ = FlowControlHelper.TrySuppressFlow(); return PerformTaskAsync(func, arg, _connectionPoolService.Scheduler.ExclusiveScheduler, cancellationToken); } public Task PerformWriteAsync(Action action, CancellationToken cancellationToken) => PerformWriteAsync(vt => { vt.Item1(); return true; }, ValueTuple.Create(action), cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SQLite.v2 { internal partial class SQLitePersistentStorage { private static async Task<TResult> PerformTaskAsync<TArg, TResult>( Func<TArg, TResult> func, TArg arg, TaskScheduler scheduler, CancellationToken cancellationToken) where TArg : struct { // Get a pooled delegate that can be used to prevent having to alloc a new lambda that calls 'func' while // capturing 'arg'. This is needed as Task.Factory.StartNew has no way to pass extra data around with it // except by boxing it as an object. using var _ = PooledDelegates.GetPooledFunction(func, arg, out var boundFunction); var task = Task.Factory.StartNew(boundFunction, cancellationToken, TaskCreationOptions.None, scheduler); return await task.ConfigureAwait(false); } // Read tasks go to the concurrent-scheduler where they can run concurrently with other read // tasks. private Task<TResult> PerformReadAsync<TArg, TResult>(Func<TArg, TResult> func, TArg arg, CancellationToken cancellationToken) where TArg : struct { // Suppress ExecutionContext flow for asynchronous operations that write to the database. In addition to // avoiding ExecutionContext allocations, this clears the LogicalCallContext and avoids the need to clone // data set by CallContext.LogicalSetData at each yielding await in the task tree. // // ⚠ DO NOT AWAIT INSIDE THE USING. The Dispose method that restores ExecutionContext flow must run on the // same thread where SuppressFlow was originally run. using var _ = FlowControlHelper.TrySuppressFlow(); return PerformTaskAsync(func, arg, _connectionPoolService.Scheduler.ConcurrentScheduler, cancellationToken); } // Write tasks go to the exclusive-scheduler so they run exclusively of all other threading // tasks we need to do. public Task<TResult> PerformWriteAsync<TArg, TResult>(Func<TArg, TResult> func, TArg arg, CancellationToken cancellationToken) where TArg : struct { // Suppress ExecutionContext flow for asynchronous operations that write to the database. In addition to // avoiding ExecutionContext allocations, this clears the LogicalCallContext and avoids the need to clone // data set by CallContext.LogicalSetData at each yielding await in the task tree. // // ⚠ DO NOT AWAIT INSIDE THE USING. The Dispose method that restores ExecutionContext flow must run on the // same thread where SuppressFlow was originally run. using var _ = FlowControlHelper.TrySuppressFlow(); return PerformTaskAsync(func, arg, _connectionPoolService.Scheduler.ExclusiveScheduler, cancellationToken); } public Task PerformWriteAsync(Action action, CancellationToken cancellationToken) => PerformWriteAsync(static vt => { vt.Item1(); return true; }, ValueTuple.Create(action), cancellationToken); } }
1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Compilers/CSharp/Portable/Parser/CharacterInfo.cs
// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis; using System.Globalization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Defines a set of methods to determine how Unicode characters are treated by the C# compiler. /// </summary> public static partial class SyntaxFacts { /// <summary> /// Returns true if the Unicode character is a hexadecimal digit. /// </summary> /// <param name="c">The Unicode character.</param> /// <returns>true if the character is a hexadecimal digit 0-9, A-F, a-f.</returns> internal static bool IsHexDigit(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } /// <summary> /// Returns true if the Unicode character is a binary (0-1) digit. /// </summary> /// <param name="c">The Unicode character.</param> /// <returns>true if the character is a binary digit.</returns> internal static bool IsBinaryDigit(char c) { return c == '0' | c == '1'; } /// <summary> /// Returns true if the Unicode character is a decimal digit. /// </summary> /// <param name="c">The Unicode character.</param> /// <returns>true if the Unicode character is a decimal digit.</returns> internal static bool IsDecDigit(char c) { return c >= '0' && c <= '9'; } /// <summary> /// Returns the value of a hexadecimal Unicode character. /// </summary> /// <param name="c">The Unicode character.</param> internal static int HexValue(char c) { Debug.Assert(IsHexDigit(c)); return (c >= '0' && c <= '9') ? c - '0' : (c & 0xdf) - 'A' + 10; } /// <summary> /// Returns the value of a binary Unicode character. /// </summary> /// <param name="c">The Unicode character.</param> internal static int BinaryValue(char c) { Debug.Assert(IsBinaryDigit(c)); return c - '0'; } /// <summary> /// Returns the value of a decimal Unicode character. /// </summary> /// <param name="c">The Unicode character.</param> internal static int DecValue(char c) { Debug.Assert(IsDecDigit(c)); return c - '0'; } // UnicodeCategory value | Unicode designation // -----------------------+----------------------- // UppercaseLetter "Lu" (letter, uppercase) // LowercaseLetter "Ll" (letter, lowercase) // TitlecaseLetter "Lt" (letter, titlecase) // ModifierLetter "Lm" (letter, modifier) // OtherLetter "Lo" (letter, other) // NonSpacingMark "Mn" (mark, nonspacing) // SpacingCombiningMark "Mc" (mark, spacing combining) // EnclosingMark "Me" (mark, enclosing) // DecimalDigitNumber "Nd" (number, decimal digit) // LetterNumber "Nl" (number, letter) // OtherNumber "No" (number, other) // SpaceSeparator "Zs" (separator, space) // LineSeparator "Zl" (separator, line) // ParagraphSeparator "Zp" (separator, paragraph) // Control "Cc" (other, control) // Format "Cf" (other, format) // Surrogate "Cs" (other, surrogate) // PrivateUse "Co" (other, private use) // ConnectorPunctuation "Pc" (punctuation, connector) // DashPunctuation "Pd" (punctuation, dash) // OpenPunctuation "Ps" (punctuation, open) // ClosePunctuation "Pe" (punctuation, close) // InitialQuotePunctuation "Pi" (punctuation, initial quote) // FinalQuotePunctuation "Pf" (punctuation, final quote) // OtherPunctuation "Po" (punctuation, other) // MathSymbol "Sm" (symbol, math) // CurrencySymbol "Sc" (symbol, currency) // ModifierSymbol "Sk" (symbol, modifier) // OtherSymbol "So" (symbol, other) // OtherNotAssigned "Cn" (other, not assigned) /// <summary> /// Returns true if the Unicode character represents a whitespace. /// </summary> /// <param name="ch">The Unicode character.</param> public static bool IsWhitespace(char ch) { // whitespace: // Any character with Unicode class Zs // Horizontal tab character (U+0009) // Vertical tab character (U+000B) // Form feed character (U+000C) // Space and no-break space are the only space separators (Zs) in ASCII range return ch == ' ' || ch == '\t' || ch == '\v' || ch == '\f' || ch == '\u00A0' // NO-BREAK SPACE // The native compiler, in ScanToken, recognized both the byte-order // marker '\uFEFF' as well as ^Z '\u001A' as whitespace, although // this is not to spec since neither of these are in Zs. For the // sake of compatibility, we recognize them both here. Note: '\uFEFF' // also happens to be a formatting character (class Cf), which means // that it is a legal non-initial identifier character. So it's // especially funny, because it will be whitespace UNLESS we happen // to be scanning an identifier or keyword, in which case it winds // up in the identifier or keyword. || ch == '\uFEFF' || ch == '\u001A' || (ch > 255 && CharUnicodeInfo.GetUnicodeCategory(ch) == UnicodeCategory.SpaceSeparator); } /// <summary> /// Returns true if the Unicode character is a newline character. /// </summary> /// <param name="ch">The Unicode character.</param> public static bool IsNewLine(char ch) { // new-line-character: // Carriage return character (U+000D) // Line feed character (U+000A) // Next line character (U+0085) // Line separator character (U+2028) // Paragraph separator character (U+2029) return ch == '\r' || ch == '\n' || ch == '\u0085' || ch == '\u2028' || ch == '\u2029'; } /// <summary> /// Returns true if the Unicode character can be the starting character of a C# identifier. /// </summary> /// <param name="ch">The Unicode character.</param> public static bool IsIdentifierStartCharacter(char ch) { return UnicodeCharacterUtilities.IsIdentifierStartCharacter(ch); } /// <summary> /// Returns true if the Unicode character can be a part of a C# identifier. /// </summary> /// <param name="ch">The Unicode character.</param> public static bool IsIdentifierPartCharacter(char ch) { return UnicodeCharacterUtilities.IsIdentifierPartCharacter(ch); } /// <summary> /// Check that the name is a valid identifier. /// </summary> public static bool IsValidIdentifier([NotNullWhen(true)] string? name) { return UnicodeCharacterUtilities.IsValidIdentifier(name); } /// <summary> /// Spec section 2.4.2 says that identifiers are compared without regard /// to leading "@" characters or unicode formatting characters. As in dev10, /// this is actually accomplished by dropping such characters during parsing. /// Unfortunately, metadata names can still contain these characters and will /// not be referenceable from source if they do (lookup will fail since the /// characters will have been dropped from the search string). /// See DevDiv #14432 for more. /// </summary> internal static bool ContainsDroppedIdentifierCharacters(string? name) { if (RoslynString.IsNullOrEmpty(name)) { return false; } if (name[0] == '@') { return true; } int nameLength = name.Length; for (int i = 0; i < nameLength; i++) { if (UnicodeCharacterUtilities.IsFormattingChar(name[i])) { return true; } } return false; } internal static bool IsNonAsciiQuotationMark(char ch) { // CONSIDER: There are others: // http://en.wikipedia.org/wiki/Quotation_mark_glyphs#Quotation_marks_in_Unicode switch (ch) { case '\u2018': //LEFT SINGLE QUOTATION MARK case '\u2019': //RIGHT SINGLE QUOTATION MARK return true; case '\u201C': //LEFT DOUBLE QUOTATION MARK case '\u201D': //RIGHT DOUBLE QUOTATION MARK return true; default: return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Defines a set of methods to determine how Unicode characters are treated by the C# compiler. /// </summary> public static partial class SyntaxFacts { /// <summary> /// Returns true if the Unicode character is a hexadecimal digit. /// </summary> /// <param name="c">The Unicode character.</param> /// <returns>true if the character is a hexadecimal digit 0-9, A-F, a-f.</returns> internal static bool IsHexDigit(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } /// <summary> /// Returns true if the Unicode character is a binary (0-1) digit. /// </summary> /// <param name="c">The Unicode character.</param> /// <returns>true if the character is a binary digit.</returns> internal static bool IsBinaryDigit(char c) { return c == '0' | c == '1'; } /// <summary> /// Returns true if the Unicode character is a decimal digit. /// </summary> /// <param name="c">The Unicode character.</param> /// <returns>true if the Unicode character is a decimal digit.</returns> internal static bool IsDecDigit(char c) { return c >= '0' && c <= '9'; } /// <summary> /// Returns the value of a hexadecimal Unicode character. /// </summary> /// <param name="c">The Unicode character.</param> internal static int HexValue(char c) { Debug.Assert(IsHexDigit(c)); return (c >= '0' && c <= '9') ? c - '0' : (c & 0xdf) - 'A' + 10; } /// <summary> /// Returns the value of a binary Unicode character. /// </summary> /// <param name="c">The Unicode character.</param> internal static int BinaryValue(char c) { Debug.Assert(IsBinaryDigit(c)); return c - '0'; } /// <summary> /// Returns the value of a decimal Unicode character. /// </summary> /// <param name="c">The Unicode character.</param> internal static int DecValue(char c) { Debug.Assert(IsDecDigit(c)); return c - '0'; } // UnicodeCategory value | Unicode designation // -----------------------+----------------------- // UppercaseLetter "Lu" (letter, uppercase) // LowercaseLetter "Ll" (letter, lowercase) // TitlecaseLetter "Lt" (letter, titlecase) // ModifierLetter "Lm" (letter, modifier) // OtherLetter "Lo" (letter, other) // NonSpacingMark "Mn" (mark, nonspacing) // SpacingCombiningMark "Mc" (mark, spacing combining) // EnclosingMark "Me" (mark, enclosing) // DecimalDigitNumber "Nd" (number, decimal digit) // LetterNumber "Nl" (number, letter) // OtherNumber "No" (number, other) // SpaceSeparator "Zs" (separator, space) // LineSeparator "Zl" (separator, line) // ParagraphSeparator "Zp" (separator, paragraph) // Control "Cc" (other, control) // Format "Cf" (other, format) // Surrogate "Cs" (other, surrogate) // PrivateUse "Co" (other, private use) // ConnectorPunctuation "Pc" (punctuation, connector) // DashPunctuation "Pd" (punctuation, dash) // OpenPunctuation "Ps" (punctuation, open) // ClosePunctuation "Pe" (punctuation, close) // InitialQuotePunctuation "Pi" (punctuation, initial quote) // FinalQuotePunctuation "Pf" (punctuation, final quote) // OtherPunctuation "Po" (punctuation, other) // MathSymbol "Sm" (symbol, math) // CurrencySymbol "Sc" (symbol, currency) // ModifierSymbol "Sk" (symbol, modifier) // OtherSymbol "So" (symbol, other) // OtherNotAssigned "Cn" (other, not assigned) /// <summary> /// Returns true if the Unicode character represents a whitespace. /// </summary> /// <param name="ch">The Unicode character.</param> public static bool IsWhitespace(char ch) { // whitespace: // Any character with Unicode class Zs // Horizontal tab character (U+0009) // Vertical tab character (U+000B) // Form feed character (U+000C) // Space and no-break space are the only space separators (Zs) in ASCII range return ch == ' ' || ch == '\t' || ch == '\v' || ch == '\f' || ch == '\u00A0' // NO-BREAK SPACE // The native compiler, in ScanToken, recognized both the byte-order // marker '\uFEFF' as well as ^Z '\u001A' as whitespace, although // this is not to spec since neither of these are in Zs. For the // sake of compatibility, we recognize them both here. Note: '\uFEFF' // also happens to be a formatting character (class Cf), which means // that it is a legal non-initial identifier character. So it's // especially funny, because it will be whitespace UNLESS we happen // to be scanning an identifier or keyword, in which case it winds // up in the identifier or keyword. || ch == '\uFEFF' || ch == '\u001A' || (ch > 255 && CharUnicodeInfo.GetUnicodeCategory(ch) == UnicodeCategory.SpaceSeparator); } /// <summary> /// Returns true if the Unicode character is a newline character. /// </summary> /// <param name="ch">The Unicode character.</param> public static bool IsNewLine(char ch) { // new-line-character: // Carriage return character (U+000D) // Line feed character (U+000A) // Next line character (U+0085) // Line separator character (U+2028) // Paragraph separator character (U+2029) return ch == '\r' || ch == '\n' || ch == '\u0085' || ch == '\u2028' || ch == '\u2029'; } /// <summary> /// Returns true if the Unicode character can be the starting character of a C# identifier. /// </summary> /// <param name="ch">The Unicode character.</param> public static bool IsIdentifierStartCharacter(char ch) { return UnicodeCharacterUtilities.IsIdentifierStartCharacter(ch); } /// <summary> /// Returns true if the Unicode character can be a part of a C# identifier. /// </summary> /// <param name="ch">The Unicode character.</param> public static bool IsIdentifierPartCharacter(char ch) { return UnicodeCharacterUtilities.IsIdentifierPartCharacter(ch); } /// <summary> /// Check that the name is a valid identifier. /// </summary> public static bool IsValidIdentifier([NotNullWhen(true)] string? name) { return UnicodeCharacterUtilities.IsValidIdentifier(name); } /// <summary> /// Spec section 2.4.2 says that identifiers are compared without regard /// to leading "@" characters or unicode formatting characters. As in dev10, /// this is actually accomplished by dropping such characters during parsing. /// Unfortunately, metadata names can still contain these characters and will /// not be referenceable from source if they do (lookup will fail since the /// characters will have been dropped from the search string). /// See DevDiv #14432 for more. /// </summary> internal static bool ContainsDroppedIdentifierCharacters(string? name) { if (RoslynString.IsNullOrEmpty(name)) { return false; } if (name[0] == '@') { return true; } int nameLength = name.Length; for (int i = 0; i < nameLength; i++) { if (UnicodeCharacterUtilities.IsFormattingChar(name[i])) { return true; } } return false; } internal static bool IsNonAsciiQuotationMark(char ch) { // CONSIDER: There are others: // http://en.wikipedia.org/wiki/Quotation_mark_glyphs#Quotation_marks_in_Unicode switch (ch) { case '\u2018': //LEFT SINGLE QUOTATION MARK case '\u2019': //RIGHT SINGLE QUOTATION MARK return true; case '\u201C': //LEFT DOUBLE QUOTATION MARK case '\u201D': //RIGHT DOUBLE QUOTATION MARK return true; default: return false; } } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/Helpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Linq; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { internal static class Helpers { /// <summary> /// Find an `int MyType.Count` or `int MyType.Length` property. /// </summary> public static IPropertySymbol TryGetLengthOrCountProperty(ITypeSymbol namedType) => TryGetNoArgInt32Property(namedType, nameof(string.Length)) ?? TryGetNoArgInt32Property(namedType, nameof(ICollection.Count)); /// <summary> /// Tried to find a public, non-static, int-returning property in the given type with the /// specified <paramref name="name"/>. /// </summary> public static IPropertySymbol TryGetNoArgInt32Property(ITypeSymbol type, string name) => type.GetMembers(name) .OfType<IPropertySymbol>() .Where(p => IsPublicInstance(p) && p.Type.SpecialType == SpecialType.System_Int32) .FirstOrDefault(); public static bool IsPublicInstance(ISymbol symbol) => !symbol.IsStatic && symbol.DeclaredAccessibility == Accessibility.Public; /// <summary> /// Checks if this <paramref name="operation"/> is `expr.Length` where `expr` is equivalent /// to the <paramref name="instance"/> we were originally invoking an accessor/method off /// of. /// </summary> public static bool IsInstanceLengthCheck(IPropertySymbol lengthLikeProperty, IOperation instance, IOperation operation) => operation is IPropertyReferenceOperation propertyRef && propertyRef.Instance != null && lengthLikeProperty.Equals(propertyRef.Property) && CSharpSyntaxFacts.Instance.AreEquivalent(instance.Syntax, propertyRef.Instance.Syntax); /// <summary> /// Checks if <paramref name="operation"/> is a binary subtraction operator. If so, it /// will be returned through <paramref name="subtraction"/>. /// </summary> public static bool IsSubtraction(IOperation operation, out IBinaryOperation subtraction) { if (operation is IBinaryOperation binaryOperation && binaryOperation.OperatorKind == BinaryOperatorKind.Subtract) { subtraction = binaryOperation; return true; } subtraction = null; return false; } /// <summary> /// Look for methods like "SomeType MyType.Get(int)". Also matches against the 'getter' /// of an indexer like 'SomeType MyType.this[int]` /// </summary> public static bool IsIntIndexingMethod(IMethodSymbol method) => method != null && (method.MethodKind == MethodKind.PropertyGet || method.MethodKind == MethodKind.Ordinary) && IsPublicInstance(method) && method.Parameters.Length == 1 && // From: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#decisions-made-during-implementation // // When looking for the pattern members, we look for original definitions, not // constructed members method.OriginalDefinition.Parameters[0].Type.SpecialType == SpecialType.System_Int32; /// <summary> /// Look for methods like "SomeType MyType.Slice(int start, int length)". Note that the /// names of the parameters are checked to ensure they are appropriate slice-like. These /// names were picked by examining the patterns in the BCL for slicing members. /// </summary> public static bool IsTwoArgumentSliceLikeMethod(IMethodSymbol method) { // From: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#decisions-made-during-implementation // // When looking for the pattern members, we look for original definitions, not // constructed members return method != null && IsPublicInstance(method) && method.Parameters.Length == 2 && IsSliceFirstParameter(method.OriginalDefinition.Parameters[0]) && IsSliceSecondParameter(method.OriginalDefinition.Parameters[1]); } /// <summary> /// Look for methods like "SomeType MyType.Slice(int start)". Note that the /// name of the parameter is checked to ensure it is appropriate slice-like. /// This name was picked by examining the patterns in the BCL for slicing members. /// </summary> public static bool IsOneArgumentSliceLikeMethod(IMethodSymbol method) { // From: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#decisions-made-during-implementation // // When looking for the pattern members, we look for original definitions, not // constructed members return method != null && IsPublicInstance(method) && method.Parameters.Length == 1 && IsSliceFirstParameter(method.OriginalDefinition.Parameters[0]); } private static bool IsSliceFirstParameter(IParameterSymbol parameter) => parameter.Type.SpecialType == SpecialType.System_Int32 && (parameter.Name == "start" || parameter.Name == "startIndex"); private static bool IsSliceSecondParameter(IParameterSymbol parameter) => parameter.Type.SpecialType == SpecialType.System_Int32 && (parameter.Name == "count" || parameter.Name == "length"); /// <summary> /// Finds a public, non-static indexer in the given type. The indexer has to accept the /// provided <paramref name="parameterType"/> and must return the provided <paramref /// name="returnType"/>. /// </summary> public static IPropertySymbol GetIndexer(ITypeSymbol type, ITypeSymbol parameterType, ITypeSymbol returnType) => type.GetMembers(WellKnownMemberNames.Indexer) .OfType<IPropertySymbol>() .Where(p => p.IsIndexer && IsPublicInstance(p) && returnType.Equals(p.Type) && p.Parameters.Length == 1 && p.Parameters[0].Type.Equals(parameterType)) .FirstOrDefault(); /// <summary> /// Finds a public, non-static overload of <paramref name="method"/> in the containing type. /// The overload must have the same return type as <paramref name="method"/>. It must only /// have a single parameter, with the provided <paramref name="parameterType"/>. /// </summary> public static IMethodSymbol GetOverload(IMethodSymbol method, ITypeSymbol parameterType) => method.MethodKind != MethodKind.Ordinary ? null : method.ContainingType.GetMembers(method.Name) .OfType<IMethodSymbol>() .Where(m => IsPublicInstance(m) && m.Parameters.Length == 1 && m.Parameters[0].Type.Equals(parameterType) && m.ReturnType.Equals(method.ReturnType)) .FirstOrDefault(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Linq; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { internal static class Helpers { /// <summary> /// Find an `int MyType.Count` or `int MyType.Length` property. /// </summary> public static IPropertySymbol TryGetLengthOrCountProperty(ITypeSymbol namedType) => TryGetNoArgInt32Property(namedType, nameof(string.Length)) ?? TryGetNoArgInt32Property(namedType, nameof(ICollection.Count)); /// <summary> /// Tried to find a public, non-static, int-returning property in the given type with the /// specified <paramref name="name"/>. /// </summary> public static IPropertySymbol TryGetNoArgInt32Property(ITypeSymbol type, string name) => type.GetMembers(name) .OfType<IPropertySymbol>() .Where(p => IsPublicInstance(p) && p.Type.SpecialType == SpecialType.System_Int32) .FirstOrDefault(); public static bool IsPublicInstance(ISymbol symbol) => !symbol.IsStatic && symbol.DeclaredAccessibility == Accessibility.Public; /// <summary> /// Checks if this <paramref name="operation"/> is `expr.Length` where `expr` is equivalent /// to the <paramref name="instance"/> we were originally invoking an accessor/method off /// of. /// </summary> public static bool IsInstanceLengthCheck(IPropertySymbol lengthLikeProperty, IOperation instance, IOperation operation) => operation is IPropertyReferenceOperation propertyRef && propertyRef.Instance != null && lengthLikeProperty.Equals(propertyRef.Property) && CSharpSyntaxFacts.Instance.AreEquivalent(instance.Syntax, propertyRef.Instance.Syntax); /// <summary> /// Checks if <paramref name="operation"/> is a binary subtraction operator. If so, it /// will be returned through <paramref name="subtraction"/>. /// </summary> public static bool IsSubtraction(IOperation operation, out IBinaryOperation subtraction) { if (operation is IBinaryOperation binaryOperation && binaryOperation.OperatorKind == BinaryOperatorKind.Subtract) { subtraction = binaryOperation; return true; } subtraction = null; return false; } /// <summary> /// Look for methods like "SomeType MyType.Get(int)". Also matches against the 'getter' /// of an indexer like 'SomeType MyType.this[int]` /// </summary> public static bool IsIntIndexingMethod(IMethodSymbol method) => method != null && (method.MethodKind == MethodKind.PropertyGet || method.MethodKind == MethodKind.Ordinary) && IsPublicInstance(method) && method.Parameters.Length == 1 && // From: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#decisions-made-during-implementation // // When looking for the pattern members, we look for original definitions, not // constructed members method.OriginalDefinition.Parameters[0].Type.SpecialType == SpecialType.System_Int32; /// <summary> /// Look for methods like "SomeType MyType.Slice(int start, int length)". Note that the /// names of the parameters are checked to ensure they are appropriate slice-like. These /// names were picked by examining the patterns in the BCL for slicing members. /// </summary> public static bool IsTwoArgumentSliceLikeMethod(IMethodSymbol method) { // From: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#decisions-made-during-implementation // // When looking for the pattern members, we look for original definitions, not // constructed members return method != null && IsPublicInstance(method) && method.Parameters.Length == 2 && IsSliceFirstParameter(method.OriginalDefinition.Parameters[0]) && IsSliceSecondParameter(method.OriginalDefinition.Parameters[1]); } /// <summary> /// Look for methods like "SomeType MyType.Slice(int start)". Note that the /// name of the parameter is checked to ensure it is appropriate slice-like. /// This name was picked by examining the patterns in the BCL for slicing members. /// </summary> public static bool IsOneArgumentSliceLikeMethod(IMethodSymbol method) { // From: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#decisions-made-during-implementation // // When looking for the pattern members, we look for original definitions, not // constructed members return method != null && IsPublicInstance(method) && method.Parameters.Length == 1 && IsSliceFirstParameter(method.OriginalDefinition.Parameters[0]); } private static bool IsSliceFirstParameter(IParameterSymbol parameter) => parameter.Type.SpecialType == SpecialType.System_Int32 && (parameter.Name == "start" || parameter.Name == "startIndex"); private static bool IsSliceSecondParameter(IParameterSymbol parameter) => parameter.Type.SpecialType == SpecialType.System_Int32 && (parameter.Name == "count" || parameter.Name == "length"); /// <summary> /// Finds a public, non-static indexer in the given type. The indexer has to accept the /// provided <paramref name="parameterType"/> and must return the provided <paramref /// name="returnType"/>. /// </summary> public static IPropertySymbol GetIndexer(ITypeSymbol type, ITypeSymbol parameterType, ITypeSymbol returnType) => type.GetMembers(WellKnownMemberNames.Indexer) .OfType<IPropertySymbol>() .Where(p => p.IsIndexer && IsPublicInstance(p) && returnType.Equals(p.Type) && p.Parameters.Length == 1 && p.Parameters[0].Type.Equals(parameterType)) .FirstOrDefault(); /// <summary> /// Finds a public, non-static overload of <paramref name="method"/> in the containing type. /// The overload must have the same return type as <paramref name="method"/>. It must only /// have a single parameter, with the provided <paramref name="parameterType"/>. /// </summary> public static IMethodSymbol GetOverload(IMethodSymbol method, ITypeSymbol parameterType) => method.MethodKind != MethodKind.Ordinary ? null : method.ContainingType.GetMembers(method.Name) .OfType<IMethodSymbol>() .Where(m => IsPublicInstance(m) && m.Parameters.Length == 1 && m.Parameters[0].Type.Equals(parameterType) && m.ReturnType.Equals(method.ReturnType)) .FirstOrDefault(); } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypeScriptInlineRenameLocationSet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal sealed class VSTypeScriptInlineRenameLocationSet : IInlineRenameLocationSet { private readonly IVSTypeScriptInlineRenameLocationSet _set; public VSTypeScriptInlineRenameLocationSet(IVSTypeScriptInlineRenameLocationSet set) { Contract.ThrowIfNull(set); _set = set; Locations = set.Locations?.Select(x => new InlineRenameLocation(x.Document, x.TextSpan)).ToList(); } public IList<InlineRenameLocation> Locations { get; } public async Task<IInlineRenameReplacementInfo> GetReplacementsAsync(string replacementText, OptionSet optionSet, CancellationToken cancellationToken) { var info = await _set.GetReplacementsAsync(replacementText, optionSet, cancellationToken).ConfigureAwait(false); if (info != null) { return new VSTypeScriptInlineRenameReplacementInfo(info); } else { 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.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal sealed class VSTypeScriptInlineRenameLocationSet : IInlineRenameLocationSet { private readonly IVSTypeScriptInlineRenameLocationSet _set; public VSTypeScriptInlineRenameLocationSet(IVSTypeScriptInlineRenameLocationSet set) { Contract.ThrowIfNull(set); _set = set; Locations = set.Locations?.Select(x => new InlineRenameLocation(x.Document, x.TextSpan)).ToList(); } public IList<InlineRenameLocation> Locations { get; } public async Task<IInlineRenameReplacementInfo> GetReplacementsAsync(string replacementText, OptionSet optionSet, CancellationToken cancellationToken) { var info = await _set.GetReplacementsAsync(replacementText, optionSet, cancellationToken).ConfigureAwait(false); if (info != null) { return new VSTypeScriptInlineRenameReplacementInfo(info); } else { return null; } } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/VisualStudio/Core/Def/Interactive/ScriptingOleCommandTarget.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.VisualStudio.LanguageServices.Interactive { /// <summary> /// This command target routes commands in interactive window, .csx files and also interactive /// commands in .cs files. /// </summary> internal sealed class ScriptingOleCommandTarget : AbstractOleCommandTarget { internal ScriptingOleCommandTarget( IWpfTextView wpfTextView, IComponentModel componentModel) : base(wpfTextView, componentModel) { } protected override ITextBuffer? GetSubjectBufferContainingCaret() { var result = WpfTextView.GetBufferContainingCaret(contentType: ContentTypeNames.RoslynContentType); if (result == null) { result = WpfTextView.GetBufferContainingCaret(contentType: PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName); } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.VisualStudio.LanguageServices.Interactive { /// <summary> /// This command target routes commands in interactive window, .csx files and also interactive /// commands in .cs files. /// </summary> internal sealed class ScriptingOleCommandTarget : AbstractOleCommandTarget { internal ScriptingOleCommandTarget( IWpfTextView wpfTextView, IComponentModel componentModel) : base(wpfTextView, componentModel) { } protected override ITextBuffer? GetSubjectBufferContainingCaret() { var result = WpfTextView.GetBufferContainingCaret(contentType: ContentTypeNames.RoslynContentType); if (result == null) { result = WpfTextView.GetBufferContainingCaret(contentType: PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName); } return result; } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Scripting/Core/Hosting/AssemblyLoader/InteractiveAssemblyLoader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting.Hosting { /// <summary> /// Implements an assembly loader for interactive compiler and REPL. /// </summary> /// <remarks> /// <para> /// The class is thread-safe. /// </para> /// </remarks> public sealed partial class InteractiveAssemblyLoader : IDisposable { private class LoadedAssembly { /// <summary> /// The original path of the assembly before it was shadow-copied. /// For GAC'd assemblies, this is equal to Assembly.Location no matter what path was used to load them. /// </summary> public string OriginalPath { get; set; } } private readonly AssemblyLoaderImpl _runtimeAssemblyLoader; private readonly MetadataShadowCopyProvider _shadowCopyProvider; // Synchronizes assembly reference tracking. // Needs to be thread-safe since assembly loading may be triggered at any time by CLR type loader. private readonly object _referencesLock = new object(); // loaded assembly -> loaded assembly info private readonly Dictionary<Assembly, LoadedAssembly> _assembliesLoadedFromLocation; // { original full path -> assembly } // Note, that there might be multiple entries for a single GAC'd assembly. private readonly Dictionary<string, AssemblyAndLocation> _assembliesLoadedFromLocationByFullPath; // simple name -> loaded assemblies private readonly Dictionary<string, List<LoadedAssemblyInfo>> _loadedAssembliesBySimpleName; // simple name -> identity and location of a known dependency private readonly Dictionary<string, List<AssemblyIdentityAndLocation>> _dependenciesWithLocationBySimpleName; [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] private struct AssemblyIdentityAndLocation { public readonly AssemblyIdentity Identity; public readonly string Location; public AssemblyIdentityAndLocation(AssemblyIdentity identity, string location) { Debug.Assert(identity != null && location != null); Identity = identity; Location = location; } private string GetDebuggerDisplay() => Identity + " @ " + Location; } [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] private struct LoadedAssemblyInfo { public readonly Assembly Assembly; public readonly AssemblyIdentity Identity; public readonly string LocationOpt; public LoadedAssemblyInfo(Assembly assembly, AssemblyIdentity identity, string locationOpt) { Debug.Assert(assembly != null && identity != null); Assembly = assembly; Identity = identity; LocationOpt = locationOpt; } public bool IsDefault => Assembly == null; private string GetDebuggerDisplay() => IsDefault ? "uninitialized" : Identity.GetDisplayName() + (LocationOpt != null ? " @ " + LocationOpt : ""); } public InteractiveAssemblyLoader(MetadataShadowCopyProvider shadowCopyProvider = null) { _shadowCopyProvider = shadowCopyProvider; _assembliesLoadedFromLocationByFullPath = new Dictionary<string, AssemblyAndLocation>(); _assembliesLoadedFromLocation = new Dictionary<Assembly, LoadedAssembly>(); _loadedAssembliesBySimpleName = new Dictionary<string, List<LoadedAssemblyInfo>>(AssemblyIdentityComparer.SimpleNameComparer); _dependenciesWithLocationBySimpleName = new Dictionary<string, List<AssemblyIdentityAndLocation>>(); _runtimeAssemblyLoader = AssemblyLoaderImpl.Create(this); } public void Dispose() { _runtimeAssemblyLoader.Dispose(); } internal Assembly LoadAssemblyFromStream(Stream peStream, Stream pdbStream) { Assembly assembly = _runtimeAssemblyLoader.LoadFromStream(peStream, pdbStream); RegisterDependency(assembly); return assembly; } private AssemblyAndLocation Load(string reference) { MetadataShadowCopy copy = null; try { if (_shadowCopyProvider != null) { // All modules of the assembly has to be copied at once to keep the metadata consistent. // This API copies the xml doc file and keeps the memory-maps of the metadata. // We don't need that here but presumably the provider is shared with the compilation API that needs both. // Ideally the CLR would expose API to load Assembly given a byte* and not create their own memory-map. copy = _shadowCopyProvider.GetMetadataShadowCopy(reference, MetadataImageKind.Assembly); } var result = _runtimeAssemblyLoader.LoadFromPath((copy != null) ? copy.PrimaryModule.FullPath : reference); if (_shadowCopyProvider != null && result.GlobalAssemblyCache) { _shadowCopyProvider.SuppressShadowCopy(reference); } return result; } catch (FileNotFoundException) { return default(AssemblyAndLocation); } finally { // copy holds on the file handle, we need to keep the handle // open until the file is locked by the CLR assembly loader: copy?.DisposeFileHandles(); } } /// <summary> /// Notifies the assembly loader about a dependency that might be loaded in future. /// </summary> /// <param name="dependency">Assembly identity.</param> /// <param name="path">Assembly location.</param> /// <remarks> /// Associates a full assembly name with its location. The association is used when an assembly /// is being loaded and its name needs to be resolved to a location. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="dependency"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is not an existing path.</exception> public void RegisterDependency(AssemblyIdentity dependency, string path) { if (dependency == null) { throw new ArgumentNullException(nameof(dependency)); } if (!PathUtilities.IsAbsolute(path)) { throw new ArgumentException(ScriptingResources.AbsolutePathExpected, nameof(path)); } lock (_referencesLock) { RegisterDependencyNoLock(new AssemblyIdentityAndLocation(dependency, path)); } } /// <summary> /// Notifies the assembly loader about an in-memory dependency that should be available within the resolution context. /// </summary> /// <param name="dependency">Assembly identity.</param> /// <exception cref="ArgumentNullException"><paramref name="dependency"/> is null.</exception> /// <remarks> /// When another in-memory assembly references the <paramref name="dependency"/> the loader /// responds with the specified dependency if the assembly identity matches the requested one. /// </remarks> public void RegisterDependency(Assembly dependency) { if (dependency == null) { throw new ArgumentNullException(nameof(dependency)); } lock (_referencesLock) { RegisterLoadedAssemblySimpleNameNoLock(dependency, locationOpt: null); } } private void RegisterLoadedAssemblySimpleNameNoLock(Assembly assembly, string locationOpt) { var identity = AssemblyIdentity.FromAssemblyDefinition(assembly); var info = new LoadedAssemblyInfo(assembly, identity, locationOpt); List<LoadedAssemblyInfo> existingInfos; if (_loadedAssembliesBySimpleName.TryGetValue(identity.Name, out existingInfos)) { existingInfos.Add(info); } else { _loadedAssembliesBySimpleName.Add(identity.Name, new List<LoadedAssemblyInfo> { info }); } } private void RegisterDependencyNoLock(AssemblyIdentityAndLocation dependency) { List<AssemblyIdentityAndLocation> sameSimpleNameAssemblyIdentities; string simpleName = dependency.Identity.Name; if (_dependenciesWithLocationBySimpleName.TryGetValue(simpleName, out sameSimpleNameAssemblyIdentities)) { sameSimpleNameAssemblyIdentities.Add(dependency); } else { _dependenciesWithLocationBySimpleName.Add(simpleName, new List<AssemblyIdentityAndLocation> { dependency }); } } internal Assembly ResolveAssembly(string assemblyDisplayName, Assembly requestingAssemblyOpt) { AssemblyIdentity identity; if (!AssemblyIdentity.TryParseDisplayName(assemblyDisplayName, out identity)) { return null; } string loadDirectoryOpt; lock (_referencesLock) { LoadedAssembly loadedAssembly; if (requestingAssemblyOpt != null && _assembliesLoadedFromLocation.TryGetValue(requestingAssemblyOpt, out loadedAssembly)) { loadDirectoryOpt = Path.GetDirectoryName(loadedAssembly.OriginalPath); } else { loadDirectoryOpt = null; } } return ResolveAssembly(identity, loadDirectoryOpt); } internal Assembly ResolveAssembly(AssemblyIdentity identity, string loadDirectoryOpt) { // if the referring assembly is already loaded by our loader, load from its directory: if (loadDirectoryOpt != null) { Assembly assembly; var conflictingLoadedAssemblyOpt = default(LoadedAssemblyInfo); var loadedAssemblyWithEqualNameAndVersionOpt = default(LoadedAssemblyInfo); lock (_referencesLock) { // Has the file already been loaded? assembly = TryGetAssemblyLoadedFromPath(identity, loadDirectoryOpt); if (assembly != null) { return assembly; } // Has an assembly with the same name and version been loaded (possibly from a different directory)? List<LoadedAssemblyInfo> loadedInfos; if (_loadedAssembliesBySimpleName.TryGetValue(identity.Name, out loadedInfos)) { // Desktop FX: A weak-named assembly conflicts with another weak-named assembly of the same simple name, // unless we find an assembly whose identity matches exactly and whose content is exactly the same. // TODO: We shouldn't block this on CoreCLR. https://github.com/dotnet/roslyn/issues/38621 if (!identity.IsStrongName) { conflictingLoadedAssemblyOpt = loadedInfos.FirstOrDefault(info => !info.Identity.IsStrongName); } loadedAssemblyWithEqualNameAndVersionOpt = loadedInfos.FirstOrDefault(info => AssemblyIdentityComparer.SimpleNameComparer.Equals(info.Identity.Name, identity.Name) && info.Identity.Version == identity.Version); } } string assemblyFilePathOpt = FindExistingAssemblyFile(identity.Name, loadDirectoryOpt); if (assemblyFilePathOpt != null) { // TODO: Stop using reflection once ModuleVersionId property once is available in Core contract. if (!loadedAssemblyWithEqualNameAndVersionOpt.IsDefault) { Guid mvid; if (TryReadMvid(assemblyFilePathOpt, out mvid) && loadedAssemblyWithEqualNameAndVersionOpt.Assembly.ManifestModule.ModuleVersionId == mvid) { return loadedAssemblyWithEqualNameAndVersionOpt.Assembly; } // error: attempt to load an assembly with the same identity as already loaded assembly but different content throw new InteractiveAssemblyLoaderException( string.Format(null, ScriptingResources.AssemblyAlreadyLoaded, identity.Name, identity.Version, loadedAssemblyWithEqualNameAndVersionOpt.LocationOpt, assemblyFilePathOpt) ); } // TODO: Desktop FX only https://github.com/dotnet/roslyn/issues/38621 if (!conflictingLoadedAssemblyOpt.IsDefault) { // error: attempt to load an assembly with the same identity as already loaded assembly but different content throw new InteractiveAssemblyLoaderException( string.Format(null, ScriptingResources.AssemblyAlreadyLoadedNotSigned, identity.Name, conflictingLoadedAssemblyOpt.LocationOpt, assemblyFilePathOpt) ); } assembly = ShadowCopyAndLoadDependency(assemblyFilePathOpt).Assembly; if (assembly != null) { return assembly; } } } return GetOrLoadKnownAssembly(identity); } private static string FindExistingAssemblyFile(string simpleName, string directory) { string pathWithoutExtension = Path.Combine(directory, simpleName); foreach (var extension in RuntimeMetadataReferenceResolver.AssemblyExtensions) { string path = pathWithoutExtension + extension; if (File.Exists(path)) { return path; } } return null; } private Assembly TryGetAssemblyLoadedFromPath(AssemblyIdentity identity, string directory) { string pathWithoutExtension = Path.Combine(directory, identity.Name); foreach (var extension in RuntimeMetadataReferenceResolver.AssemblyExtensions) { AssemblyAndLocation assemblyAndLocation; if (_assembliesLoadedFromLocationByFullPath.TryGetValue(pathWithoutExtension + extension, out assemblyAndLocation) && identity.Equals(AssemblyIdentity.FromAssemblyDefinition(assemblyAndLocation.Assembly))) { return assemblyAndLocation.Assembly; } } return null; } private static bool TryReadMvid(string filePath, out Guid mvid) { try { using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) { using (var peReader = new PEReader(stream)) { var metadataReader = peReader.GetMetadataReader(); mvid = metadataReader.GetGuid(metadataReader.GetModuleDefinition().Mvid); return true; } } } catch { mvid = default; return false; } } private Assembly GetOrLoadKnownAssembly(AssemblyIdentity identity) { Assembly assembly = null; string assemblyFileToLoad = null; // Try to find the assembly among assemblies that we loaded, comparing its identity with the requested one. lock (_referencesLock) { // already loaded assemblies: List<LoadedAssemblyInfo> infos; if (_loadedAssembliesBySimpleName.TryGetValue(identity.Name, out infos)) { assembly = FindHighestVersionOrFirstMatchingIdentity(identity, infos); if (assembly != null) { return assembly; } } // names: List<AssemblyIdentityAndLocation> sameSimpleNameIdentities; if (_dependenciesWithLocationBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities)) { var identityAndLocation = FindHighestVersionOrFirstMatchingIdentity(identity, sameSimpleNameIdentities); if (identityAndLocation.Identity != null) { assemblyFileToLoad = identityAndLocation.Location; AssemblyAndLocation assemblyAndLocation; if (_assembliesLoadedFromLocationByFullPath.TryGetValue(assemblyFileToLoad, out assemblyAndLocation)) { return assemblyAndLocation.Assembly; } } } } if (assemblyFileToLoad != null) { assembly = ShadowCopyAndLoadDependency(assemblyFileToLoad).Assembly; } return assembly; } private AssemblyAndLocation ShadowCopyAndLoadDependency(string originalPath) { AssemblyAndLocation assemblyAndLocation = Load(originalPath); if (assemblyAndLocation.IsDefault) { return default(AssemblyAndLocation); } lock (_referencesLock) { // Always remember the path. The assembly might have been loaded from another path or not loaded yet. _assembliesLoadedFromLocationByFullPath[originalPath] = assemblyAndLocation; LoadedAssembly loadedAssembly; if (_assembliesLoadedFromLocation.TryGetValue(assemblyAndLocation.Assembly, out loadedAssembly)) { return assemblyAndLocation; } _assembliesLoadedFromLocation.Add( assemblyAndLocation.Assembly, new LoadedAssembly { OriginalPath = assemblyAndLocation.GlobalAssemblyCache ? assemblyAndLocation.Location : originalPath }); RegisterLoadedAssemblySimpleNameNoLock(assemblyAndLocation.Assembly, assemblyAndLocation.Location); } return assemblyAndLocation; } private static Assembly FindHighestVersionOrFirstMatchingIdentity(AssemblyIdentity identity, IEnumerable<LoadedAssemblyInfo> infos) { Assembly candidate = null; Version candidateVersion = null; foreach (var info in infos) { if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, info.Identity)) { if (candidate == null || candidateVersion < info.Identity.Version) { candidate = info.Assembly; candidateVersion = info.Identity.Version; } } } return candidate; } private static AssemblyIdentityAndLocation FindHighestVersionOrFirstMatchingIdentity(AssemblyIdentity identity, IEnumerable<AssemblyIdentityAndLocation> assemblies) { var candidate = default(AssemblyIdentityAndLocation); foreach (var assembly in assemblies) { if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, assembly.Identity)) { if (candidate.Identity == null || candidate.Identity.Version < assembly.Identity.Version) { candidate = assembly; } } } return candidate; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting.Hosting { /// <summary> /// Implements an assembly loader for interactive compiler and REPL. /// </summary> /// <remarks> /// <para> /// The class is thread-safe. /// </para> /// </remarks> public sealed partial class InteractiveAssemblyLoader : IDisposable { private class LoadedAssembly { /// <summary> /// The original path of the assembly before it was shadow-copied. /// For GAC'd assemblies, this is equal to Assembly.Location no matter what path was used to load them. /// </summary> public string OriginalPath { get; set; } } private readonly AssemblyLoaderImpl _runtimeAssemblyLoader; private readonly MetadataShadowCopyProvider _shadowCopyProvider; // Synchronizes assembly reference tracking. // Needs to be thread-safe since assembly loading may be triggered at any time by CLR type loader. private readonly object _referencesLock = new object(); // loaded assembly -> loaded assembly info private readonly Dictionary<Assembly, LoadedAssembly> _assembliesLoadedFromLocation; // { original full path -> assembly } // Note, that there might be multiple entries for a single GAC'd assembly. private readonly Dictionary<string, AssemblyAndLocation> _assembliesLoadedFromLocationByFullPath; // simple name -> loaded assemblies private readonly Dictionary<string, List<LoadedAssemblyInfo>> _loadedAssembliesBySimpleName; // simple name -> identity and location of a known dependency private readonly Dictionary<string, List<AssemblyIdentityAndLocation>> _dependenciesWithLocationBySimpleName; [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] private struct AssemblyIdentityAndLocation { public readonly AssemblyIdentity Identity; public readonly string Location; public AssemblyIdentityAndLocation(AssemblyIdentity identity, string location) { Debug.Assert(identity != null && location != null); Identity = identity; Location = location; } private string GetDebuggerDisplay() => Identity + " @ " + Location; } [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] private struct LoadedAssemblyInfo { public readonly Assembly Assembly; public readonly AssemblyIdentity Identity; public readonly string LocationOpt; public LoadedAssemblyInfo(Assembly assembly, AssemblyIdentity identity, string locationOpt) { Debug.Assert(assembly != null && identity != null); Assembly = assembly; Identity = identity; LocationOpt = locationOpt; } public bool IsDefault => Assembly == null; private string GetDebuggerDisplay() => IsDefault ? "uninitialized" : Identity.GetDisplayName() + (LocationOpt != null ? " @ " + LocationOpt : ""); } public InteractiveAssemblyLoader(MetadataShadowCopyProvider shadowCopyProvider = null) { _shadowCopyProvider = shadowCopyProvider; _assembliesLoadedFromLocationByFullPath = new Dictionary<string, AssemblyAndLocation>(); _assembliesLoadedFromLocation = new Dictionary<Assembly, LoadedAssembly>(); _loadedAssembliesBySimpleName = new Dictionary<string, List<LoadedAssemblyInfo>>(AssemblyIdentityComparer.SimpleNameComparer); _dependenciesWithLocationBySimpleName = new Dictionary<string, List<AssemblyIdentityAndLocation>>(); _runtimeAssemblyLoader = AssemblyLoaderImpl.Create(this); } public void Dispose() { _runtimeAssemblyLoader.Dispose(); } internal Assembly LoadAssemblyFromStream(Stream peStream, Stream pdbStream) { Assembly assembly = _runtimeAssemblyLoader.LoadFromStream(peStream, pdbStream); RegisterDependency(assembly); return assembly; } private AssemblyAndLocation Load(string reference) { MetadataShadowCopy copy = null; try { if (_shadowCopyProvider != null) { // All modules of the assembly has to be copied at once to keep the metadata consistent. // This API copies the xml doc file and keeps the memory-maps of the metadata. // We don't need that here but presumably the provider is shared with the compilation API that needs both. // Ideally the CLR would expose API to load Assembly given a byte* and not create their own memory-map. copy = _shadowCopyProvider.GetMetadataShadowCopy(reference, MetadataImageKind.Assembly); } var result = _runtimeAssemblyLoader.LoadFromPath((copy != null) ? copy.PrimaryModule.FullPath : reference); if (_shadowCopyProvider != null && result.GlobalAssemblyCache) { _shadowCopyProvider.SuppressShadowCopy(reference); } return result; } catch (FileNotFoundException) { return default(AssemblyAndLocation); } finally { // copy holds on the file handle, we need to keep the handle // open until the file is locked by the CLR assembly loader: copy?.DisposeFileHandles(); } } /// <summary> /// Notifies the assembly loader about a dependency that might be loaded in future. /// </summary> /// <param name="dependency">Assembly identity.</param> /// <param name="path">Assembly location.</param> /// <remarks> /// Associates a full assembly name with its location. The association is used when an assembly /// is being loaded and its name needs to be resolved to a location. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="dependency"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is not an existing path.</exception> public void RegisterDependency(AssemblyIdentity dependency, string path) { if (dependency == null) { throw new ArgumentNullException(nameof(dependency)); } if (!PathUtilities.IsAbsolute(path)) { throw new ArgumentException(ScriptingResources.AbsolutePathExpected, nameof(path)); } lock (_referencesLock) { RegisterDependencyNoLock(new AssemblyIdentityAndLocation(dependency, path)); } } /// <summary> /// Notifies the assembly loader about an in-memory dependency that should be available within the resolution context. /// </summary> /// <param name="dependency">Assembly identity.</param> /// <exception cref="ArgumentNullException"><paramref name="dependency"/> is null.</exception> /// <remarks> /// When another in-memory assembly references the <paramref name="dependency"/> the loader /// responds with the specified dependency if the assembly identity matches the requested one. /// </remarks> public void RegisterDependency(Assembly dependency) { if (dependency == null) { throw new ArgumentNullException(nameof(dependency)); } lock (_referencesLock) { RegisterLoadedAssemblySimpleNameNoLock(dependency, locationOpt: null); } } private void RegisterLoadedAssemblySimpleNameNoLock(Assembly assembly, string locationOpt) { var identity = AssemblyIdentity.FromAssemblyDefinition(assembly); var info = new LoadedAssemblyInfo(assembly, identity, locationOpt); List<LoadedAssemblyInfo> existingInfos; if (_loadedAssembliesBySimpleName.TryGetValue(identity.Name, out existingInfos)) { existingInfos.Add(info); } else { _loadedAssembliesBySimpleName.Add(identity.Name, new List<LoadedAssemblyInfo> { info }); } } private void RegisterDependencyNoLock(AssemblyIdentityAndLocation dependency) { List<AssemblyIdentityAndLocation> sameSimpleNameAssemblyIdentities; string simpleName = dependency.Identity.Name; if (_dependenciesWithLocationBySimpleName.TryGetValue(simpleName, out sameSimpleNameAssemblyIdentities)) { sameSimpleNameAssemblyIdentities.Add(dependency); } else { _dependenciesWithLocationBySimpleName.Add(simpleName, new List<AssemblyIdentityAndLocation> { dependency }); } } internal Assembly ResolveAssembly(string assemblyDisplayName, Assembly requestingAssemblyOpt) { AssemblyIdentity identity; if (!AssemblyIdentity.TryParseDisplayName(assemblyDisplayName, out identity)) { return null; } string loadDirectoryOpt; lock (_referencesLock) { LoadedAssembly loadedAssembly; if (requestingAssemblyOpt != null && _assembliesLoadedFromLocation.TryGetValue(requestingAssemblyOpt, out loadedAssembly)) { loadDirectoryOpt = Path.GetDirectoryName(loadedAssembly.OriginalPath); } else { loadDirectoryOpt = null; } } return ResolveAssembly(identity, loadDirectoryOpt); } internal Assembly ResolveAssembly(AssemblyIdentity identity, string loadDirectoryOpt) { // if the referring assembly is already loaded by our loader, load from its directory: if (loadDirectoryOpt != null) { Assembly assembly; var conflictingLoadedAssemblyOpt = default(LoadedAssemblyInfo); var loadedAssemblyWithEqualNameAndVersionOpt = default(LoadedAssemblyInfo); lock (_referencesLock) { // Has the file already been loaded? assembly = TryGetAssemblyLoadedFromPath(identity, loadDirectoryOpt); if (assembly != null) { return assembly; } // Has an assembly with the same name and version been loaded (possibly from a different directory)? List<LoadedAssemblyInfo> loadedInfos; if (_loadedAssembliesBySimpleName.TryGetValue(identity.Name, out loadedInfos)) { // Desktop FX: A weak-named assembly conflicts with another weak-named assembly of the same simple name, // unless we find an assembly whose identity matches exactly and whose content is exactly the same. // TODO: We shouldn't block this on CoreCLR. https://github.com/dotnet/roslyn/issues/38621 if (!identity.IsStrongName) { conflictingLoadedAssemblyOpt = loadedInfos.FirstOrDefault(info => !info.Identity.IsStrongName); } loadedAssemblyWithEqualNameAndVersionOpt = loadedInfos.FirstOrDefault(info => AssemblyIdentityComparer.SimpleNameComparer.Equals(info.Identity.Name, identity.Name) && info.Identity.Version == identity.Version); } } string assemblyFilePathOpt = FindExistingAssemblyFile(identity.Name, loadDirectoryOpt); if (assemblyFilePathOpt != null) { // TODO: Stop using reflection once ModuleVersionId property once is available in Core contract. if (!loadedAssemblyWithEqualNameAndVersionOpt.IsDefault) { Guid mvid; if (TryReadMvid(assemblyFilePathOpt, out mvid) && loadedAssemblyWithEqualNameAndVersionOpt.Assembly.ManifestModule.ModuleVersionId == mvid) { return loadedAssemblyWithEqualNameAndVersionOpt.Assembly; } // error: attempt to load an assembly with the same identity as already loaded assembly but different content throw new InteractiveAssemblyLoaderException( string.Format(null, ScriptingResources.AssemblyAlreadyLoaded, identity.Name, identity.Version, loadedAssemblyWithEqualNameAndVersionOpt.LocationOpt, assemblyFilePathOpt) ); } // TODO: Desktop FX only https://github.com/dotnet/roslyn/issues/38621 if (!conflictingLoadedAssemblyOpt.IsDefault) { // error: attempt to load an assembly with the same identity as already loaded assembly but different content throw new InteractiveAssemblyLoaderException( string.Format(null, ScriptingResources.AssemblyAlreadyLoadedNotSigned, identity.Name, conflictingLoadedAssemblyOpt.LocationOpt, assemblyFilePathOpt) ); } assembly = ShadowCopyAndLoadDependency(assemblyFilePathOpt).Assembly; if (assembly != null) { return assembly; } } } return GetOrLoadKnownAssembly(identity); } private static string FindExistingAssemblyFile(string simpleName, string directory) { string pathWithoutExtension = Path.Combine(directory, simpleName); foreach (var extension in RuntimeMetadataReferenceResolver.AssemblyExtensions) { string path = pathWithoutExtension + extension; if (File.Exists(path)) { return path; } } return null; } private Assembly TryGetAssemblyLoadedFromPath(AssemblyIdentity identity, string directory) { string pathWithoutExtension = Path.Combine(directory, identity.Name); foreach (var extension in RuntimeMetadataReferenceResolver.AssemblyExtensions) { AssemblyAndLocation assemblyAndLocation; if (_assembliesLoadedFromLocationByFullPath.TryGetValue(pathWithoutExtension + extension, out assemblyAndLocation) && identity.Equals(AssemblyIdentity.FromAssemblyDefinition(assemblyAndLocation.Assembly))) { return assemblyAndLocation.Assembly; } } return null; } private static bool TryReadMvid(string filePath, out Guid mvid) { try { using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) { using (var peReader = new PEReader(stream)) { var metadataReader = peReader.GetMetadataReader(); mvid = metadataReader.GetGuid(metadataReader.GetModuleDefinition().Mvid); return true; } } } catch { mvid = default; return false; } } private Assembly GetOrLoadKnownAssembly(AssemblyIdentity identity) { Assembly assembly = null; string assemblyFileToLoad = null; // Try to find the assembly among assemblies that we loaded, comparing its identity with the requested one. lock (_referencesLock) { // already loaded assemblies: List<LoadedAssemblyInfo> infos; if (_loadedAssembliesBySimpleName.TryGetValue(identity.Name, out infos)) { assembly = FindHighestVersionOrFirstMatchingIdentity(identity, infos); if (assembly != null) { return assembly; } } // names: List<AssemblyIdentityAndLocation> sameSimpleNameIdentities; if (_dependenciesWithLocationBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities)) { var identityAndLocation = FindHighestVersionOrFirstMatchingIdentity(identity, sameSimpleNameIdentities); if (identityAndLocation.Identity != null) { assemblyFileToLoad = identityAndLocation.Location; AssemblyAndLocation assemblyAndLocation; if (_assembliesLoadedFromLocationByFullPath.TryGetValue(assemblyFileToLoad, out assemblyAndLocation)) { return assemblyAndLocation.Assembly; } } } } if (assemblyFileToLoad != null) { assembly = ShadowCopyAndLoadDependency(assemblyFileToLoad).Assembly; } return assembly; } private AssemblyAndLocation ShadowCopyAndLoadDependency(string originalPath) { AssemblyAndLocation assemblyAndLocation = Load(originalPath); if (assemblyAndLocation.IsDefault) { return default(AssemblyAndLocation); } lock (_referencesLock) { // Always remember the path. The assembly might have been loaded from another path or not loaded yet. _assembliesLoadedFromLocationByFullPath[originalPath] = assemblyAndLocation; LoadedAssembly loadedAssembly; if (_assembliesLoadedFromLocation.TryGetValue(assemblyAndLocation.Assembly, out loadedAssembly)) { return assemblyAndLocation; } _assembliesLoadedFromLocation.Add( assemblyAndLocation.Assembly, new LoadedAssembly { OriginalPath = assemblyAndLocation.GlobalAssemblyCache ? assemblyAndLocation.Location : originalPath }); RegisterLoadedAssemblySimpleNameNoLock(assemblyAndLocation.Assembly, assemblyAndLocation.Location); } return assemblyAndLocation; } private static Assembly FindHighestVersionOrFirstMatchingIdentity(AssemblyIdentity identity, IEnumerable<LoadedAssemblyInfo> infos) { Assembly candidate = null; Version candidateVersion = null; foreach (var info in infos) { if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, info.Identity)) { if (candidate == null || candidateVersion < info.Identity.Version) { candidate = info.Assembly; candidateVersion = info.Identity.Version; } } } return candidate; } private static AssemblyIdentityAndLocation FindHighestVersionOrFirstMatchingIdentity(AssemblyIdentity identity, IEnumerable<AssemblyIdentityAndLocation> assemblies) { var candidate = default(AssemblyIdentityAndLocation); foreach (var assembly in assemblies) { if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, assembly.Identity)) { if (candidate.Identity == null || candidate.Identity.Version < assembly.Identity.Version) { candidate = assembly; } } } return candidate; } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/ExpressionEvaluator/Core/Test/FunctionResolver/ParsingTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Test.Utilities; using Roslyn.Test.Utilities; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { public abstract class ParsingTestBase : CSharpTestBase { internal static RequestSignature SignatureNameOnly(Name name) { return new RequestSignature(name, default(ImmutableArray<ParameterSignature>)); } internal static RequestSignature Signature(Name name) { return new RequestSignature(name, ImmutableArray<ParameterSignature>.Empty); } internal static RequestSignature Signature(Name name, params TypeSignature[] parameterTypes) { return Signature(name, parameterTypes.Select(t => new ParameterSignature(t, isByRef: false)).ToArray()); } internal static RequestSignature Signature(Name name, params ParameterSignature[] parameters) { return new RequestSignature(name, ImmutableArray.CreateRange(parameters)); } internal static QualifiedName Name(string name) { return new QualifiedName(null, name); } internal static GenericName Generic(QualifiedName name, params string[] typeArguments) { Assert.True(typeArguments.Length > 0); return new GenericName(name, ImmutableArray.CreateRange(typeArguments)); } internal static QualifiedName Qualified(Name left, string right) { return new QualifiedName(left, right); } internal static QualifiedTypeSignature Identifier(string name) { return new QualifiedTypeSignature(null, name); } internal static GenericTypeSignature Generic(QualifiedTypeSignature name, params TypeSignature[] typeArguments) { Assert.True(typeArguments.Length > 0); return new GenericTypeSignature(name, ImmutableArray.CreateRange(typeArguments)); } internal static QualifiedTypeSignature Qualified(TypeSignature left, string right) { return new QualifiedTypeSignature(left, right); } internal static QualifiedTypeSignature Qualified(params string[] names) { QualifiedTypeSignature signature = null; foreach (var name in names) { signature = new QualifiedTypeSignature(signature, name); } return signature; } internal static ArrayTypeSignature Array(TypeSignature elementType, int rank) { return new ArrayTypeSignature(elementType, rank); } internal static PointerTypeSignature Pointer(TypeSignature pointedAtType) { return new PointerTypeSignature(pointedAtType); } internal static void VerifySignature(RequestSignature actualSignature, RequestSignature expectedSignature) { if (expectedSignature == null) { Assert.Null(actualSignature); } else { Assert.NotNull(actualSignature); Assert.Equal(expectedSignature.MemberName, actualSignature.MemberName, NameComparer.Instance); if (expectedSignature.Parameters.IsDefault) { Assert.True(actualSignature.Parameters.IsDefault); } else { AssertEx.Equal( expectedSignature.Parameters, actualSignature.Parameters, comparer: ParameterComparer.Instance, itemInspector: p => p.Type.GetDebuggerDisplay()); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Test.Utilities; using Roslyn.Test.Utilities; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { public abstract class ParsingTestBase : CSharpTestBase { internal static RequestSignature SignatureNameOnly(Name name) { return new RequestSignature(name, default(ImmutableArray<ParameterSignature>)); } internal static RequestSignature Signature(Name name) { return new RequestSignature(name, ImmutableArray<ParameterSignature>.Empty); } internal static RequestSignature Signature(Name name, params TypeSignature[] parameterTypes) { return Signature(name, parameterTypes.Select(t => new ParameterSignature(t, isByRef: false)).ToArray()); } internal static RequestSignature Signature(Name name, params ParameterSignature[] parameters) { return new RequestSignature(name, ImmutableArray.CreateRange(parameters)); } internal static QualifiedName Name(string name) { return new QualifiedName(null, name); } internal static GenericName Generic(QualifiedName name, params string[] typeArguments) { Assert.True(typeArguments.Length > 0); return new GenericName(name, ImmutableArray.CreateRange(typeArguments)); } internal static QualifiedName Qualified(Name left, string right) { return new QualifiedName(left, right); } internal static QualifiedTypeSignature Identifier(string name) { return new QualifiedTypeSignature(null, name); } internal static GenericTypeSignature Generic(QualifiedTypeSignature name, params TypeSignature[] typeArguments) { Assert.True(typeArguments.Length > 0); return new GenericTypeSignature(name, ImmutableArray.CreateRange(typeArguments)); } internal static QualifiedTypeSignature Qualified(TypeSignature left, string right) { return new QualifiedTypeSignature(left, right); } internal static QualifiedTypeSignature Qualified(params string[] names) { QualifiedTypeSignature signature = null; foreach (var name in names) { signature = new QualifiedTypeSignature(signature, name); } return signature; } internal static ArrayTypeSignature Array(TypeSignature elementType, int rank) { return new ArrayTypeSignature(elementType, rank); } internal static PointerTypeSignature Pointer(TypeSignature pointedAtType) { return new PointerTypeSignature(pointedAtType); } internal static void VerifySignature(RequestSignature actualSignature, RequestSignature expectedSignature) { if (expectedSignature == null) { Assert.Null(actualSignature); } else { Assert.NotNull(actualSignature); Assert.Equal(expectedSignature.MemberName, actualSignature.MemberName, NameComparer.Instance); if (expectedSignature.Parameters.IsDefault) { Assert.True(actualSignature.Parameters.IsDefault); } else { AssertEx.Equal( expectedSignature.Parameters, actualSignature.Parameters, comparer: ParameterComparer.Instance, itemInspector: p => p.Type.GetDebuggerDisplay()); } } } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Compilers/Server/VBCSCompilerTests/TestableDiagnosticListener.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Concurrent; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { internal sealed class TestableDiagnosticListener : IDiagnosticListener { public TimeSpan? KeepAlive { get; set; } public bool KeepAliveHit { get; set; } public List<CompletionData> CompletionDataList { get; set; } = new List<CompletionData>(); public int ConnectionReceivedCount { get; set; } public void ConnectionListening() { } public void ConnectionReceived() => ConnectionReceivedCount++; public void ConnectionCompleted(CompletionData completionData) => CompletionDataList.Add(completionData); public void UpdateKeepAlive(TimeSpan keepAlive) => KeepAlive = keepAlive; public void KeepAliveReached() => KeepAliveHit = true; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { internal sealed class TestableDiagnosticListener : IDiagnosticListener { public TimeSpan? KeepAlive { get; set; } public bool KeepAliveHit { get; set; } public List<CompletionData> CompletionDataList { get; set; } = new List<CompletionData>(); public int ConnectionReceivedCount { get; set; } public void ConnectionListening() { } public void ConnectionReceived() => ConnectionReceivedCount++; public void ConnectionCompleted(CompletionData completionData) => CompletionDataList.Add(completionData); public void UpdateKeepAlive(TimeSpan keepAlive) => KeepAlive = keepAlive; public void KeepAliveReached() => KeepAliveHit = true; } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.DecisionDagRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalRewriter { /// <summary> /// A common base class for lowering a decision dag. /// </summary> private abstract partial class DecisionDagRewriter : PatternLocalRewriter { /// <summary> /// Get the builder for code in the given section of the switch. /// For an is-pattern expression, this is a singleton. /// </summary> protected abstract ArrayBuilder<BoundStatement> BuilderForSection(SyntaxNode section); /// <summary> /// The lowered decision dag. This includes all of the code to decide which pattern /// is matched, but not the code to assign to pattern variables and evaluate when clauses. /// </summary> private ArrayBuilder<BoundStatement> _loweredDecisionDag; /// <summary> /// The label in the code for the beginning of code for each node of the dag. /// </summary> protected readonly PooledDictionary<BoundDecisionDagNode, LabelSymbol> _dagNodeLabels = PooledDictionary<BoundDecisionDagNode, LabelSymbol>.GetInstance(); protected DecisionDagRewriter( SyntaxNode node, LocalRewriter localRewriter, bool generateInstrumentation) : base(node, localRewriter, generateInstrumentation) { } private void ComputeLabelSet(BoundDecisionDag decisionDag) { // Nodes with more than one predecessor are assigned a label var hasPredecessor = PooledHashSet<BoundDecisionDagNode>.GetInstance(); foreach (BoundDecisionDagNode node in decisionDag.TopologicallySortedNodes) { switch (node) { case BoundWhenDecisionDagNode w: GetDagNodeLabel(node); if (w.WhenFalse != null) { GetDagNodeLabel(w.WhenFalse); } break; case BoundLeafDecisionDagNode d: // Leaf can branch directly to the target _dagNodeLabels[node] = d.Label; break; case BoundEvaluationDecisionDagNode e: notePredecessor(e.Next); break; case BoundTestDecisionDagNode p: notePredecessor(p.WhenTrue); notePredecessor(p.WhenFalse); break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } } hasPredecessor.Free(); return; void notePredecessor(BoundDecisionDagNode successor) { if (successor != null && !hasPredecessor.Add(successor)) { GetDagNodeLabel(successor); } } } protected new void Free() { _dagNodeLabels.Free(); base.Free(); } protected virtual LabelSymbol GetDagNodeLabel(BoundDecisionDagNode dag) { if (!_dagNodeLabels.TryGetValue(dag, out LabelSymbol label)) { _dagNodeLabels.Add(dag, label = dag is BoundLeafDecisionDagNode d ? d.Label : _factory.GenerateLabel("dagNode")); } return label; } /// <summary> /// A utility class that is used to scan a when clause to determine if it might assign a pattern variable /// declared in that case, directly or indirectly. Used to determine if we can skip the allocation of /// pattern-matching temporary variables and use user-declared pattern variables instead, because we can /// conclude that they are not mutated by a when clause while the pattern-matching automaton is running. /// </summary> protected sealed class WhenClauseMightAssignPatternVariableWalker : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private bool _mightAssignSomething; public bool MightAssignSomething(BoundExpression expr) { if (expr == null) return false; this._mightAssignSomething = false; this.Visit(expr); return this._mightAssignSomething; } public override BoundNode Visit(BoundNode node) { // A constant expression cannot mutate anything if (node is BoundExpression { ConstantValue: { } }) return null; // Stop visiting once we determine something might get assigned return this._mightAssignSomething ? null : base.Visit(node); } public override BoundNode VisitCall(BoundCall node) { bool mightMutate = // might be a call to a local function that assigns something node.Method.MethodKind == MethodKind.LocalFunction || // or perhaps we are passing a variable by ref and mutating it that way, e.g. `int.Parse(..., out x)` !node.ArgumentRefKindsOpt.IsDefault || // or perhaps we are calling a mutating method of a value type MethodMayMutateReceiver(node.ReceiverOpt, node.Method); if (mightMutate) _mightAssignSomething = true; else base.VisitCall(node); return null; } private static bool MethodMayMutateReceiver(BoundExpression receiver, MethodSymbol method) { return method != null && !method.IsStatic && !method.IsEffectivelyReadOnly && receiver.Type?.IsReferenceType == false && // methods of primitive types do not mutate their receiver !method.ContainingType.SpecialType.IsPrimitiveRecursiveStruct(); } public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) { bool mightMutate = // We only need to check the get accessor because an assignment would cause _mightAssignSomething to be set to true in the caller MethodMayMutateReceiver(node.ReceiverOpt, node.PropertySymbol.GetMethod); if (mightMutate) _mightAssignSomething = true; else base.VisitPropertyAccess(node); return null; } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { _mightAssignSomething = true; return null; } public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { _mightAssignSomething = true; return null; } public override BoundNode VisitConversion(BoundConversion node) { visitConversion(node.Conversion); if (!_mightAssignSomething) base.VisitConversion(node); return null; void visitConversion(Conversion conversion) { switch (conversion.Kind) { case ConversionKind.MethodGroup: if (conversion.Method.MethodKind == MethodKind.LocalFunction) { _mightAssignSomething = true; } break; default: if (!conversion.UnderlyingConversions.IsDefault) { foreach (var underlying in conversion.UnderlyingConversions) { visitConversion(underlying); if (_mightAssignSomething) return; } } break; } } } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { bool mightMutate = node.MethodOpt?.MethodKind == MethodKind.LocalFunction; if (mightMutate) _mightAssignSomething = true; else base.VisitDelegateCreationExpression(node); return null; } public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) { _mightAssignSomething = true; return null; } public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { _mightAssignSomething = true; return null; } public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) { _mightAssignSomething = true; return null; } public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) { // perhaps we are passing a variable by ref and mutating it that way if (!node.ArgumentRefKindsOpt.IsDefault) _mightAssignSomething = true; else base.VisitDynamicInvocation(node); return null; } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { // perhaps we are passing a variable by ref and mutating it that way if (!node.ArgumentRefKindsOpt.IsDefault) _mightAssignSomething = true; else base.VisitObjectCreationExpression(node); return null; } public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { if (!node.ArgumentRefKindsOpt.IsDefault) _mightAssignSomething = true; else base.VisitDynamicObjectCreationExpression(node); return null; } public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) { // Although ref indexers are not declarable in C#, they may be usable if (!node.ArgumentRefKindsOpt.IsDefault) _mightAssignSomething = true; else base.VisitObjectInitializerMember(node); return null; } public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) { bool mightMutate = !node.ArgumentRefKindsOpt.IsDefault || // We only need to check the get accessor because an assignment would cause _mightAssignSomething to be set to true in the caller MethodMayMutateReceiver(node.ReceiverOpt, node.Indexer.GetMethod); if (mightMutate) _mightAssignSomething = true; else base.VisitIndexerAccess(node); return null; } public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { if (!node.ArgumentRefKindsOpt.IsDefault) _mightAssignSomething = true; else base.VisitDynamicIndexerAccess(node); return null; } } protected BoundDecisionDag ShareTempsIfPossibleAndEvaluateInput( BoundDecisionDag decisionDag, BoundExpression loweredSwitchGoverningExpression, ArrayBuilder<BoundStatement> result, out BoundExpression savedInputExpression) { // Note that a when-clause can contain an assignment to a // pattern variable declared in a different when-clause (e.g. in the same section, or // in a different section via the use of a local function), so we need to analyze all // of the when clauses to see if they are all simple enough to conclude that they do // not mutate pattern variables. var mightAssignWalker = new WhenClauseMightAssignPatternVariableWalker(); bool canShareTemps = !decisionDag.TopologicallySortedNodes .Any(node => node is BoundWhenDecisionDagNode w && mightAssignWalker.MightAssignSomething(w.WhenExpression)); if (canShareTemps) { decisionDag = ShareTempsAndEvaluateInput(loweredSwitchGoverningExpression, decisionDag, expr => result.Add(_factory.ExpressionStatement(expr)), out savedInputExpression); } else { // assign the input expression to its temp. BoundExpression inputTemp = _tempAllocator.GetTemp(BoundDagTemp.ForOriginalInput(loweredSwitchGoverningExpression)); Debug.Assert(inputTemp != loweredSwitchGoverningExpression); result.Add(_factory.Assignment(inputTemp, loweredSwitchGoverningExpression)); savedInputExpression = inputTemp; } return decisionDag; } protected ImmutableArray<BoundStatement> LowerDecisionDagCore(BoundDecisionDag decisionDag) { _loweredDecisionDag = ArrayBuilder<BoundStatement>.GetInstance(); ComputeLabelSet(decisionDag); ImmutableArray<BoundDecisionDagNode> sortedNodes = decisionDag.TopologicallySortedNodes; var firstNode = sortedNodes[0]; switch (firstNode) { case BoundWhenDecisionDagNode _: case BoundLeafDecisionDagNode _: // If the first node is a leaf or when clause rather than the code for the // lowered decision dag, jump there to start. _loweredDecisionDag.Add(_factory.Goto(GetDagNodeLabel(firstNode))); break; } // Code for each when clause goes in the separate code section for its switch section. foreach (BoundDecisionDagNode node in sortedNodes) { if (node is BoundWhenDecisionDagNode w) { LowerWhenClause(w); } } ImmutableArray<BoundDecisionDagNode> nodesToLower = sortedNodes.WhereAsArray(n => n.Kind != BoundKind.WhenDecisionDagNode && n.Kind != BoundKind.LeafDecisionDagNode); var loweredNodes = PooledHashSet<BoundDecisionDagNode>.GetInstance(); for (int i = 0, length = nodesToLower.Length; i < length; i++) { BoundDecisionDagNode node = nodesToLower[i]; // A node may have been lowered as part of a switch dispatch, but if it had a label, we'll need to lower it individually as well bool alreadyLowered = loweredNodes.Contains(node); if (alreadyLowered && !_dagNodeLabels.TryGetValue(node, out _)) { continue; } if (_dagNodeLabels.TryGetValue(node, out LabelSymbol label)) { _loweredDecisionDag.Add(_factory.Label(label)); } // If we can generate an IL switch instruction, do so if (!alreadyLowered && GenerateSwitchDispatch(node, loweredNodes)) { continue; } // If we can generate a type test and cast more efficiently as an `is` followed by a null check, do so if (GenerateTypeTestAndCast(node, loweredNodes, nodesToLower, i)) { continue; } // We pass the node that will follow so we can permit a test to fall through if appropriate BoundDecisionDagNode nextNode = ((i + 1) < length) ? nodesToLower[i + 1] : null; if (nextNode != null && loweredNodes.Contains(nextNode)) { nextNode = null; } LowerDecisionDagNode(node, nextNode); } loweredNodes.Free(); var result = _loweredDecisionDag.ToImmutableAndFree(); _loweredDecisionDag = null; return result; } /// <summary> /// If we have a type test followed by a cast to that type, and the types are reference types, /// then we can replace the pair of them by a conversion using `as` and a null check. /// </summary> /// <returns>true if we generated code for the test</returns> private bool GenerateTypeTestAndCast( BoundDecisionDagNode node, HashSet<BoundDecisionDagNode> loweredNodes, ImmutableArray<BoundDecisionDagNode> nodesToLower, int indexOfNode) { Debug.Assert(node == nodesToLower[indexOfNode]); if (node is BoundTestDecisionDagNode testNode && testNode.WhenTrue is BoundEvaluationDecisionDagNode evaluationNode && TryLowerTypeTestAndCast(testNode.Test, evaluationNode.Evaluation, out BoundExpression sideEffect, out BoundExpression test) ) { var whenTrue = evaluationNode.Next; var whenFalse = testNode.WhenFalse; bool canEliminateEvaluationNode = !this._dagNodeLabels.ContainsKey(evaluationNode); if (canEliminateEvaluationNode) loweredNodes.Add(evaluationNode); var nextNode = (indexOfNode + 2 < nodesToLower.Length) && canEliminateEvaluationNode && nodesToLower[indexOfNode + 1] == evaluationNode && !loweredNodes.Contains(nodesToLower[indexOfNode + 2]) ? nodesToLower[indexOfNode + 2] : null; _loweredDecisionDag.Add(_factory.ExpressionStatement(sideEffect)); GenerateTest(test, whenTrue, whenFalse, nextNode); return true; } return false; } private void GenerateTest(BoundExpression test, BoundDecisionDagNode whenTrue, BoundDecisionDagNode whenFalse, BoundDecisionDagNode nextNode) { // Because we have already "optimized" away tests for a constant switch expression, the test should be nontrivial. _factory.Syntax = test.Syntax; Debug.Assert(test != null); if (nextNode == whenFalse) { _loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenTrue), jumpIfTrue: true)); // fall through to false path } else if (nextNode == whenTrue) { _loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenFalse), jumpIfTrue: false)); // fall through to true path } else { _loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenTrue), jumpIfTrue: true)); _loweredDecisionDag.Add(_factory.Goto(GetDagNodeLabel(whenFalse))); } } /// <summary> /// Generate a switch dispatch for a contiguous sequence of dag nodes if applicable. /// Returns true if it was applicable. /// </summary> private bool GenerateSwitchDispatch(BoundDecisionDagNode node, HashSet<BoundDecisionDagNode> loweredNodes) { Debug.Assert(!loweredNodes.Contains(node)); if (!canGenerateSwitchDispatch(node)) return false; var input = ((BoundTestDecisionDagNode)node).Test.Input; ValueDispatchNode n = GatherValueDispatchNodes(node, loweredNodes, input); LowerValueDispatchNode(n, _tempAllocator.GetTemp(input)); return true; bool canGenerateSwitchDispatch(BoundDecisionDagNode node) { switch (node) { // These are the forms worth optimizing. case BoundTestDecisionDagNode { WhenFalse: BoundTestDecisionDagNode test2 } test1: return canDispatch(test1, test2); case BoundTestDecisionDagNode { WhenTrue: BoundTestDecisionDagNode test2 } test1: return canDispatch(test1, test2); default: // Other cases are just as well done with a single test. return false; } bool canDispatch(BoundTestDecisionDagNode test1, BoundTestDecisionDagNode test2) { if (this._dagNodeLabels.ContainsKey(test2)) return false; Debug.Assert(!loweredNodes.Contains(test2)); var t1 = test1.Test; var t2 = test2.Test; if (!(t1 is BoundDagValueTest || t1 is BoundDagRelationalTest)) return false; if (!(t2 is BoundDagValueTest || t2 is BoundDagRelationalTest)) return false; if (!t1.Input.Equals(t2.Input)) return false; return true; } } } private ValueDispatchNode GatherValueDispatchNodes( BoundDecisionDagNode node, HashSet<BoundDecisionDagNode> loweredNodes, BoundDagTemp input) { IValueSetFactory fac = ValueSetFactory.ForType(input.Type); return GatherValueDispatchNodes(node, loweredNodes, input, fac); } private ValueDispatchNode GatherValueDispatchNodes( BoundDecisionDagNode node, HashSet<BoundDecisionDagNode> loweredNodes, BoundDagTemp input, IValueSetFactory fac) { if (loweredNodes.Contains(node)) { bool foundLabel = this._dagNodeLabels.TryGetValue(node, out LabelSymbol label); Debug.Assert(foundLabel); return new ValueDispatchNode.LeafDispatchNode(node.Syntax, label); } if (!(node is BoundTestDecisionDagNode testNode && testNode.Test.Input.Equals(input))) { var label = GetDagNodeLabel(node); return new ValueDispatchNode.LeafDispatchNode(node.Syntax, label); } switch (testNode.Test) { case BoundDagRelationalTest relational: { loweredNodes.Add(testNode); var whenTrue = GatherValueDispatchNodes(testNode.WhenTrue, loweredNodes, input, fac); var whenFalse = GatherValueDispatchNodes(testNode.WhenFalse, loweredNodes, input, fac); return ValueDispatchNode.RelationalDispatch.CreateBalanced(testNode.Syntax, relational.Value, relational.OperatorKind, whenTrue: whenTrue, whenFalse: whenFalse); } case BoundDagValueTest value: { // Gather up the (value, label) pairs, starting with the first one loweredNodes.Add(testNode); var cases = ArrayBuilder<(ConstantValue value, LabelSymbol label)>.GetInstance(); cases.Add((value: value.Value, label: GetDagNodeLabel(testNode.WhenTrue))); BoundTestDecisionDagNode previous = testNode; while (previous.WhenFalse is BoundTestDecisionDagNode p && p.Test is BoundDagValueTest vd && vd.Input.Equals(input) && !this._dagNodeLabels.ContainsKey(p) && !loweredNodes.Contains(p)) { cases.Add((value: vd.Value, label: GetDagNodeLabel(p.WhenTrue))); loweredNodes.Add(p); previous = p; } var otherwise = GatherValueDispatchNodes(previous.WhenFalse, loweredNodes, input, fac); return PushEqualityTestsIntoTree(value.Syntax, otherwise, cases.ToImmutableAndFree(), fac); } default: { var label = GetDagNodeLabel(node); return new ValueDispatchNode.LeafDispatchNode(node.Syntax, label); } } } /// <summary> /// Push the set of equality tests down to the level of the leaves in the value dispatch tree. /// </summary> private ValueDispatchNode PushEqualityTestsIntoTree( SyntaxNode syntax, ValueDispatchNode otherwise, ImmutableArray<(ConstantValue value, LabelSymbol label)> cases, IValueSetFactory fac) { if (cases.IsEmpty) return otherwise; switch (otherwise) { case ValueDispatchNode.LeafDispatchNode leaf: return new ValueDispatchNode.SwitchDispatch(syntax, cases, leaf.Label); case ValueDispatchNode.SwitchDispatch sd: return new ValueDispatchNode.SwitchDispatch(sd.Syntax, sd.Cases.Concat(cases), sd.Otherwise); case ValueDispatchNode.RelationalDispatch { Operator: var op, Value: var value, WhenTrue: var whenTrue, WhenFalse: var whenFalse } rel: var (whenTrueCases, whenFalseCases) = splitCases(cases, op, value); Debug.Assert(cases.Length == whenTrueCases.Length + whenFalseCases.Length); whenTrue = PushEqualityTestsIntoTree(syntax, whenTrue, whenTrueCases, fac); whenFalse = PushEqualityTestsIntoTree(syntax, whenFalse, whenFalseCases, fac); var result = rel.WithTrueAndFalseChildren(whenTrue: whenTrue, whenFalse: whenFalse); return result; default: throw ExceptionUtilities.UnexpectedValue(otherwise); } (ImmutableArray<(ConstantValue value, LabelSymbol label)> whenTrueCases, ImmutableArray<(ConstantValue value, LabelSymbol label)> whenFalseCases) splitCases(ImmutableArray<(ConstantValue value, LabelSymbol label)> cases, BinaryOperatorKind op, ConstantValue value) { var whenTrueBuilder = ArrayBuilder<(ConstantValue value, LabelSymbol label)>.GetInstance(); var whenFalseBuilder = ArrayBuilder<(ConstantValue value, LabelSymbol label)>.GetInstance(); op = op.Operator(); foreach (var pair in cases) { (fac.Related(op, pair.value, value) ? whenTrueBuilder : whenFalseBuilder).Add(pair); } return (whenTrueBuilder.ToImmutableAndFree(), whenFalseBuilder.ToImmutableAndFree()); } } private void LowerValueDispatchNode(ValueDispatchNode n, BoundExpression input) { switch (n) { case ValueDispatchNode.LeafDispatchNode leaf: _loweredDecisionDag.Add(_factory.Goto(leaf.Label)); return; case ValueDispatchNode.SwitchDispatch eq: LowerSwitchDispatchNode(eq, input); return; case ValueDispatchNode.RelationalDispatch rel: LowerRelationalDispatchNode(rel, input); return; default: throw ExceptionUtilities.UnexpectedValue(n); } } private void LowerRelationalDispatchNode(ValueDispatchNode.RelationalDispatch rel, BoundExpression input) { var test = MakeRelationalTest(rel.Syntax, input, rel.Operator, rel.Value); if (rel.WhenTrue is ValueDispatchNode.LeafDispatchNode whenTrue) { LabelSymbol trueLabel = whenTrue.Label; _loweredDecisionDag.Add(_factory.ConditionalGoto(test, trueLabel, jumpIfTrue: true)); LowerValueDispatchNode(rel.WhenFalse, input); } else if (rel.WhenFalse is ValueDispatchNode.LeafDispatchNode whenFalse) { LabelSymbol falseLabel = whenFalse.Label; _loweredDecisionDag.Add(_factory.ConditionalGoto(test, falseLabel, jumpIfTrue: false)); LowerValueDispatchNode(rel.WhenTrue, input); } else { LabelSymbol falseLabel = _factory.GenerateLabel("relationalDispatch"); _loweredDecisionDag.Add(_factory.ConditionalGoto(test, falseLabel, jumpIfTrue: false)); LowerValueDispatchNode(rel.WhenTrue, input); _loweredDecisionDag.Add(_factory.Label(falseLabel)); LowerValueDispatchNode(rel.WhenFalse, input); } } /// <summary> /// A comparer for sorting cases containing values of type float, double, or decimal. /// </summary> private sealed class CasesComparer : IComparer<(ConstantValue value, LabelSymbol label)> { private readonly IValueSetFactory _fac; public CasesComparer(TypeSymbol type) { _fac = ValueSetFactory.ForType(type); Debug.Assert(_fac is { }); } int IComparer<(ConstantValue value, LabelSymbol label)>.Compare((ConstantValue value, LabelSymbol label) left, (ConstantValue value, LabelSymbol label) right) { var x = left.value; var y = right.value; Debug.Assert(x.Discriminator switch { ConstantValueTypeDiscriminator.Decimal => true, ConstantValueTypeDiscriminator.Single => true, ConstantValueTypeDiscriminator.Double => true, ConstantValueTypeDiscriminator.NInt => true, ConstantValueTypeDiscriminator.NUInt => true, _ => false }); Debug.Assert(y.Discriminator == x.Discriminator); // Sort NaN values into the "highest" position so they fall naturally into the last bucket // when partitioned using less-than. return isNaN(x) ? 1 : isNaN(y) ? -1 : _fac.Related(BinaryOperatorKind.LessThanOrEqual, x, y) ? (_fac.Related(BinaryOperatorKind.LessThanOrEqual, y, x) ? 0 : -1) : 1; static bool isNaN(ConstantValue value) => (value.Discriminator == ConstantValueTypeDiscriminator.Single || value.Discriminator == ConstantValueTypeDiscriminator.Double) && double.IsNaN(value.DoubleValue); } } private void LowerSwitchDispatchNode(ValueDispatchNode.SwitchDispatch node, BoundExpression input) { LabelSymbol defaultLabel = node.Otherwise; if (input.Type.IsValidV6SwitchGoverningType()) { // If we are emitting a hash table based string switch, // we need to generate a helper method for computing // string hash value in <PrivateImplementationDetails> class. MethodSymbol stringEquality = null; if (input.Type.SpecialType == SpecialType.System_String) { EnsureStringHashFunction(node.Cases.Length, node.Syntax); stringEquality = _localRewriter.UnsafeGetSpecialTypeMethod(node.Syntax, SpecialMember.System_String__op_Equality); } var dispatch = new BoundSwitchDispatch(node.Syntax, input, node.Cases, defaultLabel, stringEquality); _loweredDecisionDag.Add(dispatch); } else if (input.Type.IsNativeIntegerType) { // Native types need to be dispatched using a larger underlying type so that any // possible high bits are not truncated. ImmutableArray<(ConstantValue value, LabelSymbol label)> cases; switch (input.Type.SpecialType) { case SpecialType.System_IntPtr: { input = _factory.Convert(_factory.SpecialType(SpecialType.System_Int64), input); cases = node.Cases.SelectAsArray(p => (ConstantValue.Create((long)p.value.Int32Value), p.label)); break; } case SpecialType.System_UIntPtr: { input = _factory.Convert(_factory.SpecialType(SpecialType.System_UInt64), input); cases = node.Cases.SelectAsArray(p => (ConstantValue.Create((ulong)p.value.UInt32Value), p.label)); break; } default: throw ExceptionUtilities.UnexpectedValue(input.Type); } var dispatch = new BoundSwitchDispatch(node.Syntax, input, cases, defaultLabel, equalityMethod: null); _loweredDecisionDag.Add(dispatch); } else { // The emitter does not know how to produce a "switch" instruction for float, double, or decimal // (in part because there is no such instruction) so we fake it here by generating a decision tree. var lessThanOrEqualOperator = input.Type.SpecialType switch { SpecialType.System_Single => BinaryOperatorKind.FloatLessThanOrEqual, SpecialType.System_Double => BinaryOperatorKind.DoubleLessThanOrEqual, SpecialType.System_Decimal => BinaryOperatorKind.DecimalLessThanOrEqual, _ => throw ExceptionUtilities.UnexpectedValue(input.Type.SpecialType) }; var cases = node.Cases.Sort(new CasesComparer(input.Type)); lowerFloatDispatch(0, cases.Length); void lowerFloatDispatch(int firstIndex, int count) { if (count <= 3) { for (int i = firstIndex, limit = firstIndex + count; i < limit; i++) { _loweredDecisionDag.Add(_factory.ConditionalGoto(MakeValueTest(node.Syntax, input, cases[i].value), cases[i].label, jumpIfTrue: true)); } _loweredDecisionDag.Add(_factory.Goto(defaultLabel)); } else { int half = count / 2; var gt = _factory.GenerateLabel("greaterThanMidpoint"); _loweredDecisionDag.Add(_factory.ConditionalGoto(MakeRelationalTest(node.Syntax, input, lessThanOrEqualOperator, cases[firstIndex + half - 1].value), gt, jumpIfTrue: false)); lowerFloatDispatch(firstIndex, half); _loweredDecisionDag.Add(_factory.Label(gt)); lowerFloatDispatch(firstIndex + half, count - half); } } } } /// <summary> /// Checks whether we are generating a hash table based string switch and /// we need to generate a new helper method for computing string hash value. /// Creates the method if needed. /// </summary> private void EnsureStringHashFunction(int labelsCount, SyntaxNode syntaxNode) { var module = _localRewriter.EmitModule; if (module == null) { // we're not generating code, so we don't need the hash function return; } // For string switch statements, we need to determine if we are generating a hash // table based jump table or a non hash jump table, i.e. linear string comparisons // with each case label. We use the Dev10 Heuristic to determine this // (see SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch() for details). if (!CodeAnalysis.CodeGen.SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(module, labelsCount)) { return; } // If we are generating a hash table based jump table, we use a simple customizable // hash function to hash the string constants corresponding to the case labels. // See SwitchStringJumpTableEmitter.ComputeStringHash(). // We need to emit this function to compute the hash value into the compiler generated // <PrivateImplementationDetails> class. // If we have at least one string switch statement in a module that needs a // hash table based jump table, we generate a single public string hash synthesized method // that is shared across the module. // If we have already generated the helper, possibly for another switch // or on another thread, we don't need to regenerate it. var privateImplClass = module.GetPrivateImplClass(syntaxNode, _localRewriter._diagnostics.DiagnosticBag); if (privateImplClass.GetMethod(CodeAnalysis.CodeGen.PrivateImplementationDetails.SynthesizedStringHashFunctionName) != null) { return; } // cannot emit hash method if have no access to Chars. var charsMember = _localRewriter._compilation.GetSpecialTypeMember(SpecialMember.System_String__Chars); if ((object)charsMember == null || charsMember.HasUseSiteError) { return; } TypeSymbol returnType = _factory.SpecialType(SpecialType.System_UInt32); TypeSymbol paramType = _factory.SpecialType(SpecialType.System_String); var method = new SynthesizedStringSwitchHashMethod(module.SourceModule, privateImplClass, returnType, paramType); privateImplClass.TryAddSynthesizedMethod(method.GetCciAdapter()); } private void LowerWhenClause(BoundWhenDecisionDagNode whenClause) { // This node is used even when there is no when clause, to record bindings. In the case that there // is no when clause, whenClause.WhenExpression and whenClause.WhenFalse are null, and the syntax for this // node is the case clause. // We need to assign the pattern variables in the code where they are in scope, so we produce a branch // to the section where they are in scope and evaluate the when clause there. var whenTrue = (BoundLeafDecisionDagNode)whenClause.WhenTrue; LabelSymbol labelToSectionScope = GetDagNodeLabel(whenClause); ArrayBuilder<BoundStatement> sectionBuilder = BuilderForSection(whenClause.Syntax); sectionBuilder.Add(_factory.Label(labelToSectionScope)); foreach (BoundPatternBinding binding in whenClause.Bindings) { BoundExpression left = _localRewriter.VisitExpression(binding.VariableAccess); // Since a switch does not add variables to the enclosing scope, the pattern variables // are locals even in a script and rewriting them should have no effect. Debug.Assert(left.Kind == BoundKind.Local && left == binding.VariableAccess); BoundExpression right = _tempAllocator.GetTemp(binding.TempContainingValue); if (left != right) { sectionBuilder.Add(_factory.Assignment(left, right)); } } var whenFalse = whenClause.WhenFalse; var trueLabel = GetDagNodeLabel(whenTrue); if (whenClause.WhenExpression != null && whenClause.WhenExpression.ConstantValue != ConstantValue.True) { _factory.Syntax = whenClause.Syntax; BoundStatement conditionalGoto = _factory.ConditionalGoto(_localRewriter.VisitExpression(whenClause.WhenExpression), trueLabel, jumpIfTrue: true); // Only add instrumentation (such as a sequence point) if the node is not compiler-generated. if (GenerateInstrumentation && !whenClause.WhenExpression.WasCompilerGenerated) { conditionalGoto = _localRewriter._instrumenter.InstrumentSwitchWhenClauseConditionalGotoBody(whenClause.WhenExpression, conditionalGoto); } sectionBuilder.Add(conditionalGoto); Debug.Assert(whenFalse != null); // We hide the jump back into the decision dag, as it is not logically part of the when clause BoundStatement jump = _factory.Goto(GetDagNodeLabel(whenFalse)); sectionBuilder.Add(GenerateInstrumentation ? _factory.HiddenSequencePoint(jump) : jump); } else { Debug.Assert(whenFalse == null); sectionBuilder.Add(_factory.Goto(trueLabel)); } } /// <summary> /// Translate the decision dag for node, given that it will be followed by the translation for nextNode. /// </summary> private void LowerDecisionDagNode(BoundDecisionDagNode node, BoundDecisionDagNode nextNode) { _factory.Syntax = node.Syntax; switch (node) { case BoundEvaluationDecisionDagNode evaluationNode: { BoundExpression sideEffect = LowerEvaluation(evaluationNode.Evaluation); Debug.Assert(sideEffect != null); _loweredDecisionDag.Add(_factory.ExpressionStatement(sideEffect)); // We add a hidden sequence point after the evaluation's side-effect, which may be a call out // to user code such as `Deconstruct` or a property get, to permit edit-and-continue to // synchronize on changes. if (GenerateInstrumentation) _loweredDecisionDag.Add(_factory.HiddenSequencePoint()); if (nextNode != evaluationNode.Next) { // We only need a goto if we would not otherwise fall through to the desired state _loweredDecisionDag.Add(_factory.Goto(GetDagNodeLabel(evaluationNode.Next))); } } break; case BoundTestDecisionDagNode testNode: { BoundExpression test = base.LowerTest(testNode.Test); GenerateTest(test, testNode.WhenTrue, testNode.WhenFalse, nextNode); } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalRewriter { /// <summary> /// A common base class for lowering a decision dag. /// </summary> private abstract partial class DecisionDagRewriter : PatternLocalRewriter { /// <summary> /// Get the builder for code in the given section of the switch. /// For an is-pattern expression, this is a singleton. /// </summary> protected abstract ArrayBuilder<BoundStatement> BuilderForSection(SyntaxNode section); /// <summary> /// The lowered decision dag. This includes all of the code to decide which pattern /// is matched, but not the code to assign to pattern variables and evaluate when clauses. /// </summary> private ArrayBuilder<BoundStatement> _loweredDecisionDag; /// <summary> /// The label in the code for the beginning of code for each node of the dag. /// </summary> protected readonly PooledDictionary<BoundDecisionDagNode, LabelSymbol> _dagNodeLabels = PooledDictionary<BoundDecisionDagNode, LabelSymbol>.GetInstance(); protected DecisionDagRewriter( SyntaxNode node, LocalRewriter localRewriter, bool generateInstrumentation) : base(node, localRewriter, generateInstrumentation) { } private void ComputeLabelSet(BoundDecisionDag decisionDag) { // Nodes with more than one predecessor are assigned a label var hasPredecessor = PooledHashSet<BoundDecisionDagNode>.GetInstance(); foreach (BoundDecisionDagNode node in decisionDag.TopologicallySortedNodes) { switch (node) { case BoundWhenDecisionDagNode w: GetDagNodeLabel(node); if (w.WhenFalse != null) { GetDagNodeLabel(w.WhenFalse); } break; case BoundLeafDecisionDagNode d: // Leaf can branch directly to the target _dagNodeLabels[node] = d.Label; break; case BoundEvaluationDecisionDagNode e: notePredecessor(e.Next); break; case BoundTestDecisionDagNode p: notePredecessor(p.WhenTrue); notePredecessor(p.WhenFalse); break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } } hasPredecessor.Free(); return; void notePredecessor(BoundDecisionDagNode successor) { if (successor != null && !hasPredecessor.Add(successor)) { GetDagNodeLabel(successor); } } } protected new void Free() { _dagNodeLabels.Free(); base.Free(); } protected virtual LabelSymbol GetDagNodeLabel(BoundDecisionDagNode dag) { if (!_dagNodeLabels.TryGetValue(dag, out LabelSymbol label)) { _dagNodeLabels.Add(dag, label = dag is BoundLeafDecisionDagNode d ? d.Label : _factory.GenerateLabel("dagNode")); } return label; } /// <summary> /// A utility class that is used to scan a when clause to determine if it might assign a pattern variable /// declared in that case, directly or indirectly. Used to determine if we can skip the allocation of /// pattern-matching temporary variables and use user-declared pattern variables instead, because we can /// conclude that they are not mutated by a when clause while the pattern-matching automaton is running. /// </summary> protected sealed class WhenClauseMightAssignPatternVariableWalker : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private bool _mightAssignSomething; public bool MightAssignSomething(BoundExpression expr) { if (expr == null) return false; this._mightAssignSomething = false; this.Visit(expr); return this._mightAssignSomething; } public override BoundNode Visit(BoundNode node) { // A constant expression cannot mutate anything if (node is BoundExpression { ConstantValue: { } }) return null; // Stop visiting once we determine something might get assigned return this._mightAssignSomething ? null : base.Visit(node); } public override BoundNode VisitCall(BoundCall node) { bool mightMutate = // might be a call to a local function that assigns something node.Method.MethodKind == MethodKind.LocalFunction || // or perhaps we are passing a variable by ref and mutating it that way, e.g. `int.Parse(..., out x)` !node.ArgumentRefKindsOpt.IsDefault || // or perhaps we are calling a mutating method of a value type MethodMayMutateReceiver(node.ReceiverOpt, node.Method); if (mightMutate) _mightAssignSomething = true; else base.VisitCall(node); return null; } private static bool MethodMayMutateReceiver(BoundExpression receiver, MethodSymbol method) { return method != null && !method.IsStatic && !method.IsEffectivelyReadOnly && receiver.Type?.IsReferenceType == false && // methods of primitive types do not mutate their receiver !method.ContainingType.SpecialType.IsPrimitiveRecursiveStruct(); } public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) { bool mightMutate = // We only need to check the get accessor because an assignment would cause _mightAssignSomething to be set to true in the caller MethodMayMutateReceiver(node.ReceiverOpt, node.PropertySymbol.GetMethod); if (mightMutate) _mightAssignSomething = true; else base.VisitPropertyAccess(node); return null; } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { _mightAssignSomething = true; return null; } public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { _mightAssignSomething = true; return null; } public override BoundNode VisitConversion(BoundConversion node) { visitConversion(node.Conversion); if (!_mightAssignSomething) base.VisitConversion(node); return null; void visitConversion(Conversion conversion) { switch (conversion.Kind) { case ConversionKind.MethodGroup: if (conversion.Method.MethodKind == MethodKind.LocalFunction) { _mightAssignSomething = true; } break; default: if (!conversion.UnderlyingConversions.IsDefault) { foreach (var underlying in conversion.UnderlyingConversions) { visitConversion(underlying); if (_mightAssignSomething) return; } } break; } } } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { bool mightMutate = node.MethodOpt?.MethodKind == MethodKind.LocalFunction; if (mightMutate) _mightAssignSomething = true; else base.VisitDelegateCreationExpression(node); return null; } public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) { _mightAssignSomething = true; return null; } public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { _mightAssignSomething = true; return null; } public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) { _mightAssignSomething = true; return null; } public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) { // perhaps we are passing a variable by ref and mutating it that way if (!node.ArgumentRefKindsOpt.IsDefault) _mightAssignSomething = true; else base.VisitDynamicInvocation(node); return null; } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { // perhaps we are passing a variable by ref and mutating it that way if (!node.ArgumentRefKindsOpt.IsDefault) _mightAssignSomething = true; else base.VisitObjectCreationExpression(node); return null; } public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { if (!node.ArgumentRefKindsOpt.IsDefault) _mightAssignSomething = true; else base.VisitDynamicObjectCreationExpression(node); return null; } public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) { // Although ref indexers are not declarable in C#, they may be usable if (!node.ArgumentRefKindsOpt.IsDefault) _mightAssignSomething = true; else base.VisitObjectInitializerMember(node); return null; } public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) { bool mightMutate = !node.ArgumentRefKindsOpt.IsDefault || // We only need to check the get accessor because an assignment would cause _mightAssignSomething to be set to true in the caller MethodMayMutateReceiver(node.ReceiverOpt, node.Indexer.GetMethod); if (mightMutate) _mightAssignSomething = true; else base.VisitIndexerAccess(node); return null; } public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { if (!node.ArgumentRefKindsOpt.IsDefault) _mightAssignSomething = true; else base.VisitDynamicIndexerAccess(node); return null; } } protected BoundDecisionDag ShareTempsIfPossibleAndEvaluateInput( BoundDecisionDag decisionDag, BoundExpression loweredSwitchGoverningExpression, ArrayBuilder<BoundStatement> result, out BoundExpression savedInputExpression) { // Note that a when-clause can contain an assignment to a // pattern variable declared in a different when-clause (e.g. in the same section, or // in a different section via the use of a local function), so we need to analyze all // of the when clauses to see if they are all simple enough to conclude that they do // not mutate pattern variables. var mightAssignWalker = new WhenClauseMightAssignPatternVariableWalker(); bool canShareTemps = !decisionDag.TopologicallySortedNodes .Any(node => node is BoundWhenDecisionDagNode w && mightAssignWalker.MightAssignSomething(w.WhenExpression)); if (canShareTemps) { decisionDag = ShareTempsAndEvaluateInput(loweredSwitchGoverningExpression, decisionDag, expr => result.Add(_factory.ExpressionStatement(expr)), out savedInputExpression); } else { // assign the input expression to its temp. BoundExpression inputTemp = _tempAllocator.GetTemp(BoundDagTemp.ForOriginalInput(loweredSwitchGoverningExpression)); Debug.Assert(inputTemp != loweredSwitchGoverningExpression); result.Add(_factory.Assignment(inputTemp, loweredSwitchGoverningExpression)); savedInputExpression = inputTemp; } return decisionDag; } protected ImmutableArray<BoundStatement> LowerDecisionDagCore(BoundDecisionDag decisionDag) { _loweredDecisionDag = ArrayBuilder<BoundStatement>.GetInstance(); ComputeLabelSet(decisionDag); ImmutableArray<BoundDecisionDagNode> sortedNodes = decisionDag.TopologicallySortedNodes; var firstNode = sortedNodes[0]; switch (firstNode) { case BoundWhenDecisionDagNode _: case BoundLeafDecisionDagNode _: // If the first node is a leaf or when clause rather than the code for the // lowered decision dag, jump there to start. _loweredDecisionDag.Add(_factory.Goto(GetDagNodeLabel(firstNode))); break; } // Code for each when clause goes in the separate code section for its switch section. foreach (BoundDecisionDagNode node in sortedNodes) { if (node is BoundWhenDecisionDagNode w) { LowerWhenClause(w); } } ImmutableArray<BoundDecisionDagNode> nodesToLower = sortedNodes.WhereAsArray(n => n.Kind != BoundKind.WhenDecisionDagNode && n.Kind != BoundKind.LeafDecisionDagNode); var loweredNodes = PooledHashSet<BoundDecisionDagNode>.GetInstance(); for (int i = 0, length = nodesToLower.Length; i < length; i++) { BoundDecisionDagNode node = nodesToLower[i]; // A node may have been lowered as part of a switch dispatch, but if it had a label, we'll need to lower it individually as well bool alreadyLowered = loweredNodes.Contains(node); if (alreadyLowered && !_dagNodeLabels.TryGetValue(node, out _)) { continue; } if (_dagNodeLabels.TryGetValue(node, out LabelSymbol label)) { _loweredDecisionDag.Add(_factory.Label(label)); } // If we can generate an IL switch instruction, do so if (!alreadyLowered && GenerateSwitchDispatch(node, loweredNodes)) { continue; } // If we can generate a type test and cast more efficiently as an `is` followed by a null check, do so if (GenerateTypeTestAndCast(node, loweredNodes, nodesToLower, i)) { continue; } // We pass the node that will follow so we can permit a test to fall through if appropriate BoundDecisionDagNode nextNode = ((i + 1) < length) ? nodesToLower[i + 1] : null; if (nextNode != null && loweredNodes.Contains(nextNode)) { nextNode = null; } LowerDecisionDagNode(node, nextNode); } loweredNodes.Free(); var result = _loweredDecisionDag.ToImmutableAndFree(); _loweredDecisionDag = null; return result; } /// <summary> /// If we have a type test followed by a cast to that type, and the types are reference types, /// then we can replace the pair of them by a conversion using `as` and a null check. /// </summary> /// <returns>true if we generated code for the test</returns> private bool GenerateTypeTestAndCast( BoundDecisionDagNode node, HashSet<BoundDecisionDagNode> loweredNodes, ImmutableArray<BoundDecisionDagNode> nodesToLower, int indexOfNode) { Debug.Assert(node == nodesToLower[indexOfNode]); if (node is BoundTestDecisionDagNode testNode && testNode.WhenTrue is BoundEvaluationDecisionDagNode evaluationNode && TryLowerTypeTestAndCast(testNode.Test, evaluationNode.Evaluation, out BoundExpression sideEffect, out BoundExpression test) ) { var whenTrue = evaluationNode.Next; var whenFalse = testNode.WhenFalse; bool canEliminateEvaluationNode = !this._dagNodeLabels.ContainsKey(evaluationNode); if (canEliminateEvaluationNode) loweredNodes.Add(evaluationNode); var nextNode = (indexOfNode + 2 < nodesToLower.Length) && canEliminateEvaluationNode && nodesToLower[indexOfNode + 1] == evaluationNode && !loweredNodes.Contains(nodesToLower[indexOfNode + 2]) ? nodesToLower[indexOfNode + 2] : null; _loweredDecisionDag.Add(_factory.ExpressionStatement(sideEffect)); GenerateTest(test, whenTrue, whenFalse, nextNode); return true; } return false; } private void GenerateTest(BoundExpression test, BoundDecisionDagNode whenTrue, BoundDecisionDagNode whenFalse, BoundDecisionDagNode nextNode) { // Because we have already "optimized" away tests for a constant switch expression, the test should be nontrivial. _factory.Syntax = test.Syntax; Debug.Assert(test != null); if (nextNode == whenFalse) { _loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenTrue), jumpIfTrue: true)); // fall through to false path } else if (nextNode == whenTrue) { _loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenFalse), jumpIfTrue: false)); // fall through to true path } else { _loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenTrue), jumpIfTrue: true)); _loweredDecisionDag.Add(_factory.Goto(GetDagNodeLabel(whenFalse))); } } /// <summary> /// Generate a switch dispatch for a contiguous sequence of dag nodes if applicable. /// Returns true if it was applicable. /// </summary> private bool GenerateSwitchDispatch(BoundDecisionDagNode node, HashSet<BoundDecisionDagNode> loweredNodes) { Debug.Assert(!loweredNodes.Contains(node)); if (!canGenerateSwitchDispatch(node)) return false; var input = ((BoundTestDecisionDagNode)node).Test.Input; ValueDispatchNode n = GatherValueDispatchNodes(node, loweredNodes, input); LowerValueDispatchNode(n, _tempAllocator.GetTemp(input)); return true; bool canGenerateSwitchDispatch(BoundDecisionDagNode node) { switch (node) { // These are the forms worth optimizing. case BoundTestDecisionDagNode { WhenFalse: BoundTestDecisionDagNode test2 } test1: return canDispatch(test1, test2); case BoundTestDecisionDagNode { WhenTrue: BoundTestDecisionDagNode test2 } test1: return canDispatch(test1, test2); default: // Other cases are just as well done with a single test. return false; } bool canDispatch(BoundTestDecisionDagNode test1, BoundTestDecisionDagNode test2) { if (this._dagNodeLabels.ContainsKey(test2)) return false; Debug.Assert(!loweredNodes.Contains(test2)); var t1 = test1.Test; var t2 = test2.Test; if (!(t1 is BoundDagValueTest || t1 is BoundDagRelationalTest)) return false; if (!(t2 is BoundDagValueTest || t2 is BoundDagRelationalTest)) return false; if (!t1.Input.Equals(t2.Input)) return false; return true; } } } private ValueDispatchNode GatherValueDispatchNodes( BoundDecisionDagNode node, HashSet<BoundDecisionDagNode> loweredNodes, BoundDagTemp input) { IValueSetFactory fac = ValueSetFactory.ForType(input.Type); return GatherValueDispatchNodes(node, loweredNodes, input, fac); } private ValueDispatchNode GatherValueDispatchNodes( BoundDecisionDagNode node, HashSet<BoundDecisionDagNode> loweredNodes, BoundDagTemp input, IValueSetFactory fac) { if (loweredNodes.Contains(node)) { bool foundLabel = this._dagNodeLabels.TryGetValue(node, out LabelSymbol label); Debug.Assert(foundLabel); return new ValueDispatchNode.LeafDispatchNode(node.Syntax, label); } if (!(node is BoundTestDecisionDagNode testNode && testNode.Test.Input.Equals(input))) { var label = GetDagNodeLabel(node); return new ValueDispatchNode.LeafDispatchNode(node.Syntax, label); } switch (testNode.Test) { case BoundDagRelationalTest relational: { loweredNodes.Add(testNode); var whenTrue = GatherValueDispatchNodes(testNode.WhenTrue, loweredNodes, input, fac); var whenFalse = GatherValueDispatchNodes(testNode.WhenFalse, loweredNodes, input, fac); return ValueDispatchNode.RelationalDispatch.CreateBalanced(testNode.Syntax, relational.Value, relational.OperatorKind, whenTrue: whenTrue, whenFalse: whenFalse); } case BoundDagValueTest value: { // Gather up the (value, label) pairs, starting with the first one loweredNodes.Add(testNode); var cases = ArrayBuilder<(ConstantValue value, LabelSymbol label)>.GetInstance(); cases.Add((value: value.Value, label: GetDagNodeLabel(testNode.WhenTrue))); BoundTestDecisionDagNode previous = testNode; while (previous.WhenFalse is BoundTestDecisionDagNode p && p.Test is BoundDagValueTest vd && vd.Input.Equals(input) && !this._dagNodeLabels.ContainsKey(p) && !loweredNodes.Contains(p)) { cases.Add((value: vd.Value, label: GetDagNodeLabel(p.WhenTrue))); loweredNodes.Add(p); previous = p; } var otherwise = GatherValueDispatchNodes(previous.WhenFalse, loweredNodes, input, fac); return PushEqualityTestsIntoTree(value.Syntax, otherwise, cases.ToImmutableAndFree(), fac); } default: { var label = GetDagNodeLabel(node); return new ValueDispatchNode.LeafDispatchNode(node.Syntax, label); } } } /// <summary> /// Push the set of equality tests down to the level of the leaves in the value dispatch tree. /// </summary> private ValueDispatchNode PushEqualityTestsIntoTree( SyntaxNode syntax, ValueDispatchNode otherwise, ImmutableArray<(ConstantValue value, LabelSymbol label)> cases, IValueSetFactory fac) { if (cases.IsEmpty) return otherwise; switch (otherwise) { case ValueDispatchNode.LeafDispatchNode leaf: return new ValueDispatchNode.SwitchDispatch(syntax, cases, leaf.Label); case ValueDispatchNode.SwitchDispatch sd: return new ValueDispatchNode.SwitchDispatch(sd.Syntax, sd.Cases.Concat(cases), sd.Otherwise); case ValueDispatchNode.RelationalDispatch { Operator: var op, Value: var value, WhenTrue: var whenTrue, WhenFalse: var whenFalse } rel: var (whenTrueCases, whenFalseCases) = splitCases(cases, op, value); Debug.Assert(cases.Length == whenTrueCases.Length + whenFalseCases.Length); whenTrue = PushEqualityTestsIntoTree(syntax, whenTrue, whenTrueCases, fac); whenFalse = PushEqualityTestsIntoTree(syntax, whenFalse, whenFalseCases, fac); var result = rel.WithTrueAndFalseChildren(whenTrue: whenTrue, whenFalse: whenFalse); return result; default: throw ExceptionUtilities.UnexpectedValue(otherwise); } (ImmutableArray<(ConstantValue value, LabelSymbol label)> whenTrueCases, ImmutableArray<(ConstantValue value, LabelSymbol label)> whenFalseCases) splitCases(ImmutableArray<(ConstantValue value, LabelSymbol label)> cases, BinaryOperatorKind op, ConstantValue value) { var whenTrueBuilder = ArrayBuilder<(ConstantValue value, LabelSymbol label)>.GetInstance(); var whenFalseBuilder = ArrayBuilder<(ConstantValue value, LabelSymbol label)>.GetInstance(); op = op.Operator(); foreach (var pair in cases) { (fac.Related(op, pair.value, value) ? whenTrueBuilder : whenFalseBuilder).Add(pair); } return (whenTrueBuilder.ToImmutableAndFree(), whenFalseBuilder.ToImmutableAndFree()); } } private void LowerValueDispatchNode(ValueDispatchNode n, BoundExpression input) { switch (n) { case ValueDispatchNode.LeafDispatchNode leaf: _loweredDecisionDag.Add(_factory.Goto(leaf.Label)); return; case ValueDispatchNode.SwitchDispatch eq: LowerSwitchDispatchNode(eq, input); return; case ValueDispatchNode.RelationalDispatch rel: LowerRelationalDispatchNode(rel, input); return; default: throw ExceptionUtilities.UnexpectedValue(n); } } private void LowerRelationalDispatchNode(ValueDispatchNode.RelationalDispatch rel, BoundExpression input) { var test = MakeRelationalTest(rel.Syntax, input, rel.Operator, rel.Value); if (rel.WhenTrue is ValueDispatchNode.LeafDispatchNode whenTrue) { LabelSymbol trueLabel = whenTrue.Label; _loweredDecisionDag.Add(_factory.ConditionalGoto(test, trueLabel, jumpIfTrue: true)); LowerValueDispatchNode(rel.WhenFalse, input); } else if (rel.WhenFalse is ValueDispatchNode.LeafDispatchNode whenFalse) { LabelSymbol falseLabel = whenFalse.Label; _loweredDecisionDag.Add(_factory.ConditionalGoto(test, falseLabel, jumpIfTrue: false)); LowerValueDispatchNode(rel.WhenTrue, input); } else { LabelSymbol falseLabel = _factory.GenerateLabel("relationalDispatch"); _loweredDecisionDag.Add(_factory.ConditionalGoto(test, falseLabel, jumpIfTrue: false)); LowerValueDispatchNode(rel.WhenTrue, input); _loweredDecisionDag.Add(_factory.Label(falseLabel)); LowerValueDispatchNode(rel.WhenFalse, input); } } /// <summary> /// A comparer for sorting cases containing values of type float, double, or decimal. /// </summary> private sealed class CasesComparer : IComparer<(ConstantValue value, LabelSymbol label)> { private readonly IValueSetFactory _fac; public CasesComparer(TypeSymbol type) { _fac = ValueSetFactory.ForType(type); Debug.Assert(_fac is { }); } int IComparer<(ConstantValue value, LabelSymbol label)>.Compare((ConstantValue value, LabelSymbol label) left, (ConstantValue value, LabelSymbol label) right) { var x = left.value; var y = right.value; Debug.Assert(x.Discriminator switch { ConstantValueTypeDiscriminator.Decimal => true, ConstantValueTypeDiscriminator.Single => true, ConstantValueTypeDiscriminator.Double => true, ConstantValueTypeDiscriminator.NInt => true, ConstantValueTypeDiscriminator.NUInt => true, _ => false }); Debug.Assert(y.Discriminator == x.Discriminator); // Sort NaN values into the "highest" position so they fall naturally into the last bucket // when partitioned using less-than. return isNaN(x) ? 1 : isNaN(y) ? -1 : _fac.Related(BinaryOperatorKind.LessThanOrEqual, x, y) ? (_fac.Related(BinaryOperatorKind.LessThanOrEqual, y, x) ? 0 : -1) : 1; static bool isNaN(ConstantValue value) => (value.Discriminator == ConstantValueTypeDiscriminator.Single || value.Discriminator == ConstantValueTypeDiscriminator.Double) && double.IsNaN(value.DoubleValue); } } private void LowerSwitchDispatchNode(ValueDispatchNode.SwitchDispatch node, BoundExpression input) { LabelSymbol defaultLabel = node.Otherwise; if (input.Type.IsValidV6SwitchGoverningType()) { // If we are emitting a hash table based string switch, // we need to generate a helper method for computing // string hash value in <PrivateImplementationDetails> class. MethodSymbol stringEquality = null; if (input.Type.SpecialType == SpecialType.System_String) { EnsureStringHashFunction(node.Cases.Length, node.Syntax); stringEquality = _localRewriter.UnsafeGetSpecialTypeMethod(node.Syntax, SpecialMember.System_String__op_Equality); } var dispatch = new BoundSwitchDispatch(node.Syntax, input, node.Cases, defaultLabel, stringEquality); _loweredDecisionDag.Add(dispatch); } else if (input.Type.IsNativeIntegerType) { // Native types need to be dispatched using a larger underlying type so that any // possible high bits are not truncated. ImmutableArray<(ConstantValue value, LabelSymbol label)> cases; switch (input.Type.SpecialType) { case SpecialType.System_IntPtr: { input = _factory.Convert(_factory.SpecialType(SpecialType.System_Int64), input); cases = node.Cases.SelectAsArray(p => (ConstantValue.Create((long)p.value.Int32Value), p.label)); break; } case SpecialType.System_UIntPtr: { input = _factory.Convert(_factory.SpecialType(SpecialType.System_UInt64), input); cases = node.Cases.SelectAsArray(p => (ConstantValue.Create((ulong)p.value.UInt32Value), p.label)); break; } default: throw ExceptionUtilities.UnexpectedValue(input.Type); } var dispatch = new BoundSwitchDispatch(node.Syntax, input, cases, defaultLabel, equalityMethod: null); _loweredDecisionDag.Add(dispatch); } else { // The emitter does not know how to produce a "switch" instruction for float, double, or decimal // (in part because there is no such instruction) so we fake it here by generating a decision tree. var lessThanOrEqualOperator = input.Type.SpecialType switch { SpecialType.System_Single => BinaryOperatorKind.FloatLessThanOrEqual, SpecialType.System_Double => BinaryOperatorKind.DoubleLessThanOrEqual, SpecialType.System_Decimal => BinaryOperatorKind.DecimalLessThanOrEqual, _ => throw ExceptionUtilities.UnexpectedValue(input.Type.SpecialType) }; var cases = node.Cases.Sort(new CasesComparer(input.Type)); lowerFloatDispatch(0, cases.Length); void lowerFloatDispatch(int firstIndex, int count) { if (count <= 3) { for (int i = firstIndex, limit = firstIndex + count; i < limit; i++) { _loweredDecisionDag.Add(_factory.ConditionalGoto(MakeValueTest(node.Syntax, input, cases[i].value), cases[i].label, jumpIfTrue: true)); } _loweredDecisionDag.Add(_factory.Goto(defaultLabel)); } else { int half = count / 2; var gt = _factory.GenerateLabel("greaterThanMidpoint"); _loweredDecisionDag.Add(_factory.ConditionalGoto(MakeRelationalTest(node.Syntax, input, lessThanOrEqualOperator, cases[firstIndex + half - 1].value), gt, jumpIfTrue: false)); lowerFloatDispatch(firstIndex, half); _loweredDecisionDag.Add(_factory.Label(gt)); lowerFloatDispatch(firstIndex + half, count - half); } } } } /// <summary> /// Checks whether we are generating a hash table based string switch and /// we need to generate a new helper method for computing string hash value. /// Creates the method if needed. /// </summary> private void EnsureStringHashFunction(int labelsCount, SyntaxNode syntaxNode) { var module = _localRewriter.EmitModule; if (module == null) { // we're not generating code, so we don't need the hash function return; } // For string switch statements, we need to determine if we are generating a hash // table based jump table or a non hash jump table, i.e. linear string comparisons // with each case label. We use the Dev10 Heuristic to determine this // (see SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch() for details). if (!CodeAnalysis.CodeGen.SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(module, labelsCount)) { return; } // If we are generating a hash table based jump table, we use a simple customizable // hash function to hash the string constants corresponding to the case labels. // See SwitchStringJumpTableEmitter.ComputeStringHash(). // We need to emit this function to compute the hash value into the compiler generated // <PrivateImplementationDetails> class. // If we have at least one string switch statement in a module that needs a // hash table based jump table, we generate a single public string hash synthesized method // that is shared across the module. // If we have already generated the helper, possibly for another switch // or on another thread, we don't need to regenerate it. var privateImplClass = module.GetPrivateImplClass(syntaxNode, _localRewriter._diagnostics.DiagnosticBag); if (privateImplClass.GetMethod(CodeAnalysis.CodeGen.PrivateImplementationDetails.SynthesizedStringHashFunctionName) != null) { return; } // cannot emit hash method if have no access to Chars. var charsMember = _localRewriter._compilation.GetSpecialTypeMember(SpecialMember.System_String__Chars); if ((object)charsMember == null || charsMember.HasUseSiteError) { return; } TypeSymbol returnType = _factory.SpecialType(SpecialType.System_UInt32); TypeSymbol paramType = _factory.SpecialType(SpecialType.System_String); var method = new SynthesizedStringSwitchHashMethod(module.SourceModule, privateImplClass, returnType, paramType); privateImplClass.TryAddSynthesizedMethod(method.GetCciAdapter()); } private void LowerWhenClause(BoundWhenDecisionDagNode whenClause) { // This node is used even when there is no when clause, to record bindings. In the case that there // is no when clause, whenClause.WhenExpression and whenClause.WhenFalse are null, and the syntax for this // node is the case clause. // We need to assign the pattern variables in the code where they are in scope, so we produce a branch // to the section where they are in scope and evaluate the when clause there. var whenTrue = (BoundLeafDecisionDagNode)whenClause.WhenTrue; LabelSymbol labelToSectionScope = GetDagNodeLabel(whenClause); ArrayBuilder<BoundStatement> sectionBuilder = BuilderForSection(whenClause.Syntax); sectionBuilder.Add(_factory.Label(labelToSectionScope)); foreach (BoundPatternBinding binding in whenClause.Bindings) { BoundExpression left = _localRewriter.VisitExpression(binding.VariableAccess); // Since a switch does not add variables to the enclosing scope, the pattern variables // are locals even in a script and rewriting them should have no effect. Debug.Assert(left.Kind == BoundKind.Local && left == binding.VariableAccess); BoundExpression right = _tempAllocator.GetTemp(binding.TempContainingValue); if (left != right) { sectionBuilder.Add(_factory.Assignment(left, right)); } } var whenFalse = whenClause.WhenFalse; var trueLabel = GetDagNodeLabel(whenTrue); if (whenClause.WhenExpression != null && whenClause.WhenExpression.ConstantValue != ConstantValue.True) { _factory.Syntax = whenClause.Syntax; BoundStatement conditionalGoto = _factory.ConditionalGoto(_localRewriter.VisitExpression(whenClause.WhenExpression), trueLabel, jumpIfTrue: true); // Only add instrumentation (such as a sequence point) if the node is not compiler-generated. if (GenerateInstrumentation && !whenClause.WhenExpression.WasCompilerGenerated) { conditionalGoto = _localRewriter._instrumenter.InstrumentSwitchWhenClauseConditionalGotoBody(whenClause.WhenExpression, conditionalGoto); } sectionBuilder.Add(conditionalGoto); Debug.Assert(whenFalse != null); // We hide the jump back into the decision dag, as it is not logically part of the when clause BoundStatement jump = _factory.Goto(GetDagNodeLabel(whenFalse)); sectionBuilder.Add(GenerateInstrumentation ? _factory.HiddenSequencePoint(jump) : jump); } else { Debug.Assert(whenFalse == null); sectionBuilder.Add(_factory.Goto(trueLabel)); } } /// <summary> /// Translate the decision dag for node, given that it will be followed by the translation for nextNode. /// </summary> private void LowerDecisionDagNode(BoundDecisionDagNode node, BoundDecisionDagNode nextNode) { _factory.Syntax = node.Syntax; switch (node) { case BoundEvaluationDecisionDagNode evaluationNode: { BoundExpression sideEffect = LowerEvaluation(evaluationNode.Evaluation); Debug.Assert(sideEffect != null); _loweredDecisionDag.Add(_factory.ExpressionStatement(sideEffect)); // We add a hidden sequence point after the evaluation's side-effect, which may be a call out // to user code such as `Deconstruct` or a property get, to permit edit-and-continue to // synchronize on changes. if (GenerateInstrumentation) _loweredDecisionDag.Add(_factory.HiddenSequencePoint()); if (nextNode != evaluationNode.Next) { // We only need a goto if we would not otherwise fall through to the desired state _loweredDecisionDag.Add(_factory.Goto(GetDagNodeLabel(evaluationNode.Next))); } } break; case BoundTestDecisionDagNode testNode: { BoundExpression test = base.LowerTest(testNode.Test); GenerateTest(test, testNode.WhenTrue, testNode.WhenFalse, nextNode); } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } } } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.OrganizeImports { [UseExportProvider] public class OrganizeUsingsTests { protected static async Task CheckAsync( string initial, string final, bool placeSystemNamespaceFirst = false, bool separateImportGroups = false) { using var workspace = new AdhocWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var document = project.AddDocument("Document", initial.NormalizeLineEndings()); var newOptions = workspace.Options.WithChangedOption(new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language), placeSystemNamespaceFirst); newOptions = newOptions.WithChangedOption(new OptionKey(GenerationOptions.SeparateImportDirectiveGroups, document.Project.Language), separateImportGroups); document = document.WithSolutionOptions(newOptions); var newRoot = await (await Formatter.OrganizeImportsAsync(document, CancellationToken.None)).GetRequiredSyntaxRootAsync(default); Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString()); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task EmptyFile() => await CheckAsync(string.Empty, string.Empty); [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SingleUsingStatement() { var initial = @"using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AliasesAtBottom() { var initial = @"using A = B; using C; using D = E; using F;"; var final = @"using C; using F; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task UsingStaticsBetweenUsingsAndAliases() { var initial = @"using static System.Convert; using A = B; using C; using Z; using D = E; using static System.Console; using F;"; var final = @"using C; using F; using Z; using static System.Console; using static System.Convert; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedStatements() { var initial = @"using B; using A; namespace N { using D; using C; namespace N1 { using F; using E; } namespace N2 { using H; using G; } } namespace N3 { using J; using I; namespace N4 { using L; using K; } namespace N5 { using N; using M; } }"; var final = @"using A; using B; namespace N { using C; using D; namespace N1 { using E; using F; } namespace N2 { using G; using H; } } namespace N3 { using I; using J; namespace N4 { using K; using L; } namespace N5 { using M; using N; } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task FileScopedNamespace() { var initial = @"using B; using A; namespace N; using D; using C; "; var final = @"using A; using B; namespace N; using C; using D; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using System; using System.Linq; using M1; using M2; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystemWithUsingStatic() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using System; using System.Linq; using M1; using M2; using static System.BitConverter; using static Microsoft.Win32.Registry; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using M1; using M2; using System; using System.Linq; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystemWithUsingStatics() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using M1; using M2; using System; using System.Linq; using static Microsoft.Win32.Registry; using static System.BitConverter;"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IndentationAfterSorting() { var initial = @"namespace A { using V.W; using U; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; var final = @"namespace A { using U; using V.W; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile3() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile4() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile5() { var initial = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile3() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// I like namespace A using A; /// Copyright (c) Microsoft Corporation. All rights reserved. using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile1() { var initial = @"namespace N { // attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // attached to System using System; // attached to System.Text using System.Text; }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile2() { var initial = @"namespace N { // not attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // not attached to System.Text // attached to System using System; using System.Text; }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSortIfEndIfBlocks() { var initial = @"using D; #if MYCONFIG using C; #else using B; #endif using A; namespace A { } namespace B { } namespace C { } namespace D { }"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task ExternAliases() { var initial = @"extern alias Z; extern alias Y; extern alias X; using C; using U = C.L.T; using O = A.J; using A; using W = A.J.R; using N = B.K; using V = B.K.S; using M = C.L; using B; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; var final = @"extern alias X; extern alias Y; extern alias Z; using A; using B; using C; using M = C.L; using N = B.K; using O = A.J; using U = C.L.T; using V = B.K.S; using W = A.J.R; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DuplicateUsings() { var initial = @"using A; using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InlineComments() { var initial = @"/*00*/using/*01*/D/*02*/;/*03*/ /*04*/using/*05*/C/*06*/;/*07*/ /*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*16*/"; var final = @"/*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*04*/using/*05*/C/*06*/;/*07*/ /*00*/using/*01*/D/*02*/;/*03*/ /*16*/"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AllOnOneLine() { var initial = @"using C; using B; using A;"; var final = @"using A; using B; using C; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideRegionBlock() { var initial = @"#region Using directives using C; using A; using B; #endregion class Class1 { }"; var final = @"#region Using directives using A; using B; using C; #endregion class Class1 { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedRegionBlock() { var initial = @"using C; #region Z using A; #endregion using B;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task MultipleRegionBlocks() { var initial = @"#region Using directives using C; #region Z using A; #endregion using B; #endregion"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InterleavedNewlines() { var initial = @"using B; using A; using C; class D { }"; var final = @"using A; using B; using C; class D { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideIfEndIfBlock() { var initial = @"#if !X using B; using A; using C; #endif"; var final = @"#if !X using A; using B; using C; #endif"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockAbove() { var initial = @"#if !X using C; using B; using F; #endif using D; using A; using E;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockMiddle() { var initial = @"using D; using A; using H; #if !X using C; using B; using I; #endif using F; using E; using G;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockBelow() { var initial = @"using D; using A; using E; #if !X using C; using B; using F; #endif"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task Korean() { var initial = @"using 하; using 파; using 타; using 카; using 차; using 자; using 아; using 사; using 바; using 마; using 라; using 다; using 나; using 가;"; var final = @"using 가; using 나; using 다; using 라; using 마; using 바; using 사; using 아; using 자; using 차; using 카; using 타; using 파; using 하; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem1() { var initial = @"using B; using System.Collections.Generic; using C; using _System; using SystemZ; using D.System; using System; using System.Collections; using A;"; var final = @"using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem2() { var initial = @"extern alias S; extern alias R; extern alias T; using B; using System.Collections.Generic; using C; using _System; using SystemZ; using Y = System.UInt32; using Z = System.Int32; using D.System; using System; using N = System; using M = System.Collections; using System.Collections; using A;"; var final = @"extern alias R; extern alias S; extern alias T; using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; using M = System.Collections; using N = System; using Y = System.UInt32; using Z = System.Int32; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity1() { var initial = @"using Bb; using B; using bB; using b; using Aa; using a; using A; using aa; using aA; using AA; using bb; using BB; using bBb; using bbB; using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using cC; using Cc; using アア; using アア; using アあ; using アア; using アア; using BBb; using BbB; using bBB; using BBB; using c; using C; using bbb; using Bbb; using cc; using cC; using CC; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; var final = @"using a; using A; using aa; using aA; using Aa; using AA; using b; using B; using bb; using bB; using Bb; using BB; using bbb; using bbB; using bBb; using bBB; using Bbb; using BbB; using BBb; using BBB; using c; using C; using cc; using cC; using cC; using Cc; using CC; using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity2() { var initial = @"using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using アア; using アア; using アあ; using アア; using アア;"; var final = @"using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; "; await CheckAsync(initial, final); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping() { var initial = @"// Banner using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using IntList = System.Collections.Generic.List<int>; using static System.Console;"; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping2() { // Make sure we don't insert extra newlines if they're already there. var initial = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.OrganizeImports { [UseExportProvider] public class OrganizeUsingsTests { protected static async Task CheckAsync( string initial, string final, bool placeSystemNamespaceFirst = false, bool separateImportGroups = false) { using var workspace = new AdhocWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var document = project.AddDocument("Document", initial.NormalizeLineEndings()); var newOptions = workspace.Options.WithChangedOption(new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language), placeSystemNamespaceFirst); newOptions = newOptions.WithChangedOption(new OptionKey(GenerationOptions.SeparateImportDirectiveGroups, document.Project.Language), separateImportGroups); document = document.WithSolutionOptions(newOptions); var newRoot = await (await Formatter.OrganizeImportsAsync(document, CancellationToken.None)).GetRequiredSyntaxRootAsync(default); Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString()); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task EmptyFile() => await CheckAsync(string.Empty, string.Empty); [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SingleUsingStatement() { var initial = @"using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AliasesAtBottom() { var initial = @"using A = B; using C; using D = E; using F;"; var final = @"using C; using F; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task UsingStaticsBetweenUsingsAndAliases() { var initial = @"using static System.Convert; using A = B; using C; using Z; using D = E; using static System.Console; using F;"; var final = @"using C; using F; using Z; using static System.Console; using static System.Convert; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedStatements() { var initial = @"using B; using A; namespace N { using D; using C; namespace N1 { using F; using E; } namespace N2 { using H; using G; } } namespace N3 { using J; using I; namespace N4 { using L; using K; } namespace N5 { using N; using M; } }"; var final = @"using A; using B; namespace N { using C; using D; namespace N1 { using E; using F; } namespace N2 { using G; using H; } } namespace N3 { using I; using J; namespace N4 { using K; using L; } namespace N5 { using M; using N; } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task FileScopedNamespace() { var initial = @"using B; using A; namespace N; using D; using C; "; var final = @"using A; using B; namespace N; using C; using D; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using System; using System.Linq; using M1; using M2; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystemWithUsingStatic() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using System; using System.Linq; using M1; using M2; using static System.BitConverter; using static Microsoft.Win32.Registry; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using M1; using M2; using System; using System.Linq; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystemWithUsingStatics() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using M1; using M2; using System; using System.Linq; using static Microsoft.Win32.Registry; using static System.BitConverter;"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IndentationAfterSorting() { var initial = @"namespace A { using V.W; using U; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; var final = @"namespace A { using U; using V.W; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile3() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile4() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile5() { var initial = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile3() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// I like namespace A using A; /// Copyright (c) Microsoft Corporation. All rights reserved. using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile1() { var initial = @"namespace N { // attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // attached to System using System; // attached to System.Text using System.Text; }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile2() { var initial = @"namespace N { // not attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // not attached to System.Text // attached to System using System; using System.Text; }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSortIfEndIfBlocks() { var initial = @"using D; #if MYCONFIG using C; #else using B; #endif using A; namespace A { } namespace B { } namespace C { } namespace D { }"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task ExternAliases() { var initial = @"extern alias Z; extern alias Y; extern alias X; using C; using U = C.L.T; using O = A.J; using A; using W = A.J.R; using N = B.K; using V = B.K.S; using M = C.L; using B; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; var final = @"extern alias X; extern alias Y; extern alias Z; using A; using B; using C; using M = C.L; using N = B.K; using O = A.J; using U = C.L.T; using V = B.K.S; using W = A.J.R; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DuplicateUsings() { var initial = @"using A; using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InlineComments() { var initial = @"/*00*/using/*01*/D/*02*/;/*03*/ /*04*/using/*05*/C/*06*/;/*07*/ /*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*16*/"; var final = @"/*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*04*/using/*05*/C/*06*/;/*07*/ /*00*/using/*01*/D/*02*/;/*03*/ /*16*/"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AllOnOneLine() { var initial = @"using C; using B; using A;"; var final = @"using A; using B; using C; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideRegionBlock() { var initial = @"#region Using directives using C; using A; using B; #endregion class Class1 { }"; var final = @"#region Using directives using A; using B; using C; #endregion class Class1 { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedRegionBlock() { var initial = @"using C; #region Z using A; #endregion using B;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task MultipleRegionBlocks() { var initial = @"#region Using directives using C; #region Z using A; #endregion using B; #endregion"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InterleavedNewlines() { var initial = @"using B; using A; using C; class D { }"; var final = @"using A; using B; using C; class D { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideIfEndIfBlock() { var initial = @"#if !X using B; using A; using C; #endif"; var final = @"#if !X using A; using B; using C; #endif"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockAbove() { var initial = @"#if !X using C; using B; using F; #endif using D; using A; using E;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockMiddle() { var initial = @"using D; using A; using H; #if !X using C; using B; using I; #endif using F; using E; using G;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockBelow() { var initial = @"using D; using A; using E; #if !X using C; using B; using F; #endif"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task Korean() { var initial = @"using 하; using 파; using 타; using 카; using 차; using 자; using 아; using 사; using 바; using 마; using 라; using 다; using 나; using 가;"; var final = @"using 가; using 나; using 다; using 라; using 마; using 바; using 사; using 아; using 자; using 차; using 카; using 타; using 파; using 하; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem1() { var initial = @"using B; using System.Collections.Generic; using C; using _System; using SystemZ; using D.System; using System; using System.Collections; using A;"; var final = @"using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem2() { var initial = @"extern alias S; extern alias R; extern alias T; using B; using System.Collections.Generic; using C; using _System; using SystemZ; using Y = System.UInt32; using Z = System.Int32; using D.System; using System; using N = System; using M = System.Collections; using System.Collections; using A;"; var final = @"extern alias R; extern alias S; extern alias T; using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; using M = System.Collections; using N = System; using Y = System.UInt32; using Z = System.Int32; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity1() { var initial = @"using Bb; using B; using bB; using b; using Aa; using a; using A; using aa; using aA; using AA; using bb; using BB; using bBb; using bbB; using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using cC; using Cc; using アア; using アア; using アあ; using アア; using アア; using BBb; using BbB; using bBB; using BBB; using c; using C; using bbb; using Bbb; using cc; using cC; using CC; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; var final = @"using a; using A; using aa; using aA; using Aa; using AA; using b; using B; using bb; using bB; using Bb; using BB; using bbb; using bbB; using bBb; using bBB; using Bbb; using BbB; using BBb; using BBB; using c; using C; using cc; using cC; using cC; using Cc; using CC; using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity2() { var initial = @"using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using アア; using アア; using アあ; using アア; using アア;"; var final = @"using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; "; await CheckAsync(initial, final); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping() { var initial = @"// Banner using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using IntList = System.Collections.Generic.List<int>; using static System.Console;"; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping2() { // Make sure we don't insert extra newlines if they're already there. var initial = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Analyzers/Core/CodeFixes/AddRequiredParentheses/AddRequiredParenthesesCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.AddRequiredParentheses { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.AddRequiredParentheses), Shared] internal class AddRequiredParenthesesCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public AddRequiredParenthesesCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.AddRequiredParenthesesDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, string equivalenceKey, CancellationToken cancellationToken) => diagnostic.Properties.ContainsKey(AddRequiredParenthesesConstants.IncludeInFixAll) && diagnostic.Properties[AddRequiredParenthesesConstants.EquivalenceKey] == equivalenceKey; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var firstDiagnostic = context.Diagnostics[0]; context.RegisterCodeFix( new MyCodeAction( c => FixAsync(context.Document, firstDiagnostic, c), firstDiagnostic.Properties[AddRequiredParenthesesConstants.EquivalenceKey]), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var generator = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); foreach (var diagnostic in diagnostics) { var location = diagnostic.AdditionalLocations[0]; var node = location.FindNode(findInsideTrivia: true, getInnermostNodeForTie: true, cancellationToken); // Do not add the simplifier annotation. We do not want the simplifier undoing the // work we just did. editor.ReplaceNode(node, (current, _) => generator.AddParentheses( current, includeElasticTrivia: false, addSimplifierAnnotation: false)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(AnalyzersResources.Add_parentheses_for_clarity, createChangedDocument, equivalenceKey) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.AddRequiredParentheses { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.AddRequiredParentheses), Shared] internal class AddRequiredParenthesesCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public AddRequiredParenthesesCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.AddRequiredParenthesesDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, string equivalenceKey, CancellationToken cancellationToken) => diagnostic.Properties.ContainsKey(AddRequiredParenthesesConstants.IncludeInFixAll) && diagnostic.Properties[AddRequiredParenthesesConstants.EquivalenceKey] == equivalenceKey; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var firstDiagnostic = context.Diagnostics[0]; context.RegisterCodeFix( new MyCodeAction( c => FixAsync(context.Document, firstDiagnostic, c), firstDiagnostic.Properties[AddRequiredParenthesesConstants.EquivalenceKey]), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var generator = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); foreach (var diagnostic in diagnostics) { var location = diagnostic.AdditionalLocations[0]; var node = location.FindNode(findInsideTrivia: true, getInnermostNodeForTie: true, cancellationToken); // Do not add the simplifier annotation. We do not want the simplifier undoing the // work we just did. editor.ReplaceNode(node, (current, _) => generator.AddParentheses( current, includeElasticTrivia: false, addSimplifierAnnotation: false)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(AnalyzersResources.Add_parentheses_for_clarity, createChangedDocument, equivalenceKey) { } } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Compilers/Test/Core/ICompilationVerifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Test.Utilities { internal interface ICompilationVerifier { ImmutableArray<ModuleMetadata> GetAllModuleMetadata(); IModuleSymbol GetModuleSymbolForEmittedImage(ImmutableArray<byte> peImage, MetadataImportOptions importOptions); IModuleSymbol GetModuleSymbolForEmittedImage(); ImmutableArray<byte> EmittedAssemblyData { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Test.Utilities { internal interface ICompilationVerifier { ImmutableArray<ModuleMetadata> GetAllModuleMetadata(); IModuleSymbol GetModuleSymbolForEmittedImage(ImmutableArray<byte> peImage, MetadataImportOptions importOptions); IModuleSymbol GetModuleSymbolForEmittedImage(); ImmutableArray<byte> EmittedAssemblyData { get; } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/VisualStudio/Xaml/Impl/Implementation/XamlProjectService_IVsSolutionEvents.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Xaml { internal partial class XamlProjectService : IVsSolutionEvents { int IVsSolutionEvents.OnAfterLoadProject(IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnAfterOpenSolution(object pUnkReserved, int fNewSolution) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnQueryCloseProject(IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnBeforeCloseProject(IVsHierarchy pHierarchy, int fRemoved) { this.OnProjectClosing(pHierarchy); return VSConstants.S_OK; } int IVsSolutionEvents.OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int pfCancel) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnBeforeUnloadProject(IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnQueryCloseSolution(object pUnkReserved, ref int pfCancel) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnBeforeCloseSolution(object pUnkReserved) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnAfterCloseSolution(object pUnkReserved) { return VSConstants.E_NOTIMPL; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Xaml { internal partial class XamlProjectService : IVsSolutionEvents { int IVsSolutionEvents.OnAfterLoadProject(IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnAfterOpenSolution(object pUnkReserved, int fNewSolution) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnQueryCloseProject(IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnBeforeCloseProject(IVsHierarchy pHierarchy, int fRemoved) { this.OnProjectClosing(pHierarchy); return VSConstants.S_OK; } int IVsSolutionEvents.OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int pfCancel) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnBeforeUnloadProject(IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnQueryCloseSolution(object pUnkReserved, ref int pfCancel) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnBeforeCloseSolution(object pUnkReserved) { return VSConstants.E_NOTIMPL; } int IVsSolutionEvents.OnAfterCloseSolution(object pUnkReserved) { return VSConstants.E_NOTIMPL; } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenReadonlyStructTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public class CodeGenReadOnlyStructTests : CompilingTestBase { [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyStaticField() { var text = @" class Program { static readonly S1 sf; static void Main() { System.Console.Write(sf.M1()); System.Console.Write(sf.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 37 (0x25) .maxstack 1 IL_0000: ldsflda ""Program.S1 Program.sf"" IL_0005: call ""string Program.S1.M1()"" IL_000a: call ""void System.Console.Write(string)"" IL_000f: ldsflda ""Program.S1 Program.sf"" IL_0014: constrained. ""Program.S1"" IL_001a: callvirt ""string object.ToString()"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 1 .locals init (Program.S1 V_0) IL_0000: ldsfld ""Program.S1 Program.sf"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""string Program.S1.M1()"" IL_000d: call ""void System.Console.Write(string)"" IL_0012: ldsfld ""Program.S1 Program.sf"" IL_0017: stloc.0 IL_0018: ldloca.s V_0 IL_001a: constrained. ""Program.S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyStaticFieldMetadata() { var text1 = @" public readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var text = @" class Program { static readonly S1 sf; static void Main() { System.Console.Write(sf.M1()); System.Console.Write(sf.ToString()); } } "; var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 37 (0x25) .maxstack 1 IL_0000: ldsflda ""S1 Program.sf"" IL_0005: call ""string S1.M1()"" IL_000a: call ""void System.Console.Write(string)"" IL_000f: ldsflda ""S1 Program.sf"" IL_0014: constrained. ""S1"" IL_001a: callvirt ""string object.ToString()"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret }"); comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 1 .locals init (S1 V_0) IL_0000: ldsfld ""S1 Program.sf"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""string S1.M1()"" IL_000d: call ""void System.Console.Write(string)"" IL_0012: ldsfld ""S1 Program.sf"" IL_0017: stloc.0 IL_0018: ldloca.s V_0 IL_001a: constrained. ""S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceField() { var text = @" class Program { readonly S1 f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1()); System.Console.Write(p.f.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""Program.S1 Program.f"" IL_000b: call ""string Program.S1.M1()"" IL_0010: call ""void System.Console.Write(string)"" IL_0015: ldflda ""Program.S1 Program.f"" IL_001a: constrained. ""Program.S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 49 (0x31) .maxstack 2 .locals init (Program.S1 V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""Program.S1 Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: call ""string Program.S1.M1()"" IL_0013: call ""void System.Console.Write(string)"" IL_0018: ldfld ""Program.S1 Program.f"" IL_001d: stloc.0 IL_001e: ldloca.s V_0 IL_0020: constrained. ""Program.S1"" IL_0026: callvirt ""string object.ToString()"" IL_002b: call ""void System.Console.Write(string)"" IL_0030: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceFieldGeneric() { var text = @" class Program { readonly S1<string> f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1(""hello"")); System.Console.Write(p.f.ToString()); } readonly struct S1<T> { public T M1(T arg) { return arg; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 48 (0x30) .maxstack 3 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""Program.S1<string> Program.f"" IL_000b: ldstr ""hello"" IL_0010: call ""string Program.S1<string>.M1(string)"" IL_0015: call ""void System.Console.Write(string)"" IL_001a: ldflda ""Program.S1<string> Program.f"" IL_001f: constrained. ""Program.S1<string>"" IL_0025: callvirt ""string object.ToString()"" IL_002a: call ""void System.Console.Write(string)"" IL_002f: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (Program.S1<string> V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""Program.S1<string> Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: ldstr ""hello"" IL_0013: call ""string Program.S1<string>.M1(string)"" IL_0018: call ""void System.Console.Write(string)"" IL_001d: ldfld ""Program.S1<string> Program.f"" IL_0022: stloc.0 IL_0023: ldloca.s V_0 IL_0025: constrained. ""Program.S1<string>"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.Write(string)"" IL_0035: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceFieldGenericMetadata() { var text1 = @" readonly public struct S1<T> { public T M1(T arg) { return arg; } public override string ToString() { return ""2""; } } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var text = @" class Program { readonly S1<string> f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1(""hello"")); System.Console.Write(p.f.ToString()); } } "; var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 48 (0x30) .maxstack 3 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""S1<string> Program.f"" IL_000b: ldstr ""hello"" IL_0010: call ""string S1<string>.M1(string)"" IL_0015: call ""void System.Console.Write(string)"" IL_001a: ldflda ""S1<string> Program.f"" IL_001f: constrained. ""S1<string>"" IL_0025: callvirt ""string object.ToString()"" IL_002a: call ""void System.Console.Write(string)"" IL_002f: ret }"); comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (S1<string> V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""S1<string> Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: ldstr ""hello"" IL_0013: call ""string S1<string>.M1(string)"" IL_0018: call ""void System.Console.Write(string)"" IL_001d: ldfld ""S1<string> Program.f"" IL_0022: stloc.0 IL_0023: ldloca.s V_0 IL_0025: constrained. ""S1<string>"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.Write(string)"" IL_0035: ret }"); } [Fact] public void InvokeOnReadOnlyThis() { var text = @" class Program { static void Main() { Test(default(S1)); } static void Test(in S1 arg) { System.Console.Write(arg.M1()); System.Console.Write(arg.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Test", @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string Program.S1.M1()"" IL_0006: call ""void System.Console.Write(string)"" IL_000b: ldarg.0 IL_000c: constrained. ""Program.S1"" IL_0012: callvirt ""string object.ToString()"" IL_0017: call ""void System.Console.Write(string)"" IL_001c: ret }"); } [Fact] public void InvokeOnThis() { var text = @" class Program { static void Main() { default(S1).Test(); } readonly struct S1 { public void Test() { System.Console.Write(this.M1()); System.Console.Write(ToString()); } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.S1.Test()", @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string Program.S1.M1()"" IL_0006: call ""void System.Console.Write(string)"" IL_000b: ldarg.0 IL_000c: constrained. ""Program.S1"" IL_0012: callvirt ""string object.ToString()"" IL_0017: call ""void System.Console.Write(string)"" IL_001c: ret }"); comp.VerifyIL("Program.Main()", @" { // Code size 15 (0xf) .maxstack 2 .locals init (Program.S1 V_0) IL_0000: ldloca.s V_0 IL_0002: dup IL_0003: initobj ""Program.S1"" IL_0009: call ""void Program.S1.Test()"" IL_000e: ret }"); } [Fact] public void InvokeOnThisBaseMethods() { var text = @" class Program { static void Main() { default(S1).Test(); } readonly struct S1 { public void Test() { System.Console.Write(this.GetType()); System.Console.Write(ToString()); } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"Program+S1Program+S1"); comp.VerifyIL("Program.S1.Test()", @" { // Code size 39 (0x27) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldobj ""Program.S1"" IL_0006: box ""Program.S1"" IL_000b: call ""System.Type object.GetType()"" IL_0010: call ""void System.Console.Write(object)"" IL_0015: ldarg.0 IL_0016: constrained. ""Program.S1"" IL_001c: callvirt ""string object.ToString()"" IL_0021: call ""void System.Console.Write(string)"" IL_0026: ret }"); } [Fact] public void AssignThis() { var text = @" class Program { static void Main() { S1 v = new S1(42); System.Console.Write(v.x); S1 v2 = new S1(v); System.Console.Write(v2.x); } readonly struct S1 { public readonly int x; public S1(int i) { x = i; // OK } public S1(S1 arg) { this = arg; // OK } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"4242"); comp.VerifyIL("Program.S1..ctor(int)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int Program.S1.x"" IL_0007: ret }"); comp.VerifyIL("Program.S1..ctor(Program.S1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stobj ""Program.S1"" IL_0007: ret }"); } [Fact] public void AssignThisErr() { var text = @" class Program { static void Main() { } static void TakesRef(ref S1 arg){} static void TakesRef(ref int arg){} readonly struct S1 { readonly int x; public S1(int i) { x = i; // OK } public S1(S1 arg) { this = arg; // OK } public void Test1() { this = default; // error } public void Test2() { TakesRef(ref this); // error } public void Test3() { TakesRef(ref this.x); // error } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (27,13): error CS1604: Cannot assign to 'this' because it is read-only // this = default; // error Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this").WithArguments("this").WithLocation(27, 13), // (32,26): error CS1605: Cannot use 'this' as a ref or out value because it is read-only // TakesRef(ref this); // error Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this").WithLocation(32, 26), // (37,26): error CS0192: A readonly field cannot be used as a ref or out value (except in a constructor) // TakesRef(ref this.x); // error Diagnostic(ErrorCode.ERR_RefReadonly, "this.x").WithLocation(37, 26) ); } [Fact] public void AssignThisNestedMethods() { var text = @" using System; class Program { static void Main() { } static void TakesRef(ref S1 arg){} static void TakesRef(ref int arg){} readonly struct S1 { readonly int x; public S1(int i) { void F() { x = i;} // Error Action a = () => { x = i;}; // Error F(); } public S1(S1 arg) { void F() { this = arg;} // Error Action a = () => { this = arg;}; // Error F(); } public void Test1() { void F() { this = default;} // Error Action a = () => { this = default;}; // Error F(); } public void Test2() { void F() { TakesRef(ref this);} // Error Action a = () => { TakesRef(ref this);}; // Error F(); } public void Test3() { void F() { TakesRef(ref this.x);} // Error Action a = () => { TakesRef(ref this.x);}; // Error F(); } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (19,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { x = i;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(19, 24), // (20,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { x = i;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(20, 32), // (26,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { this = arg;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(26, 24), // (27,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { this = arg;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(27, 32), // (33,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { this = default;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(33, 24), // (34,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { this = default;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(34, 32), // (40,37): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { TakesRef(ref this);} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(40, 37), // (41,45): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { TakesRef(ref this);}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(41, 45), // (47,37): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { TakesRef(ref this.x);} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(47, 37), // (48,45): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { TakesRef(ref this.x);}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(48, 45) ); } [Fact] public void ReadOnlyStructApi() { var text = @" class Program { readonly struct S1 { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } readonly struct S1<T> { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } struct S2 { public S2(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } class C1 { public C1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } delegate int D1(); } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular); // S1 NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); void validate(ModuleSymbol module) { var test = module.ContainingAssembly.GetTypeByMetadataName("Program+S1"); var peModule = (PEModuleSymbol)module; Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PENamedTypeSymbol)test).Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } CompileAndVerify(comp, symbolValidator: validate); // S1<T> namedType = comp.GetTypeByMetadataName("Program+S1`1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // T TypeSymbol type = namedType.TypeParameters[0]; Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<object> namedType = namedType.Construct(comp.ObjectType); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S2 namedType = comp.GetTypeByMetadataName("Program+S2"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind); // C1 namedType = comp.GetTypeByMetadataName("Program+C1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind); // D1 namedType = comp.GetTypeByMetadataName("Program+D1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind); // object[] type = comp.CreateArrayTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // dynamic type = comp.DynamicType; Assert.False(type.IsReadOnly); // object type = comp.ObjectType; Assert.False(type.IsReadOnly); // anonymous type INamedTypeSymbol iNamedType = comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol()), ImmutableArray.Create("qq")); Assert.False(iNamedType.IsReadOnly); // pointer type type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // tuple type iNamedType = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol(), comp.ObjectType.GetPublicSymbol())); Assert.False(iNamedType.IsReadOnly); // S1 from image var clientComp = CreateCompilation("", references: new[] { comp.EmitToImageReference() }); NamedTypeSymbol s1 = clientComp.GetTypeByMetadataName("Program+S1"); Assert.True(s1.IsReadOnly); Assert.Empty(s1.GetAttributes()); Assert.Equal(RefKind.Out, s1.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, s1.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, s1.GetMethod("ToString").ThisParameter.RefKind); } [Fact] public void ReadOnlyStructApiMetadata() { var text1 = @" class Program { readonly struct S1 { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } readonly struct S1<T> { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } struct S2 { public S2(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } class C1 { public C1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } delegate int D1(); } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var comp = CreateCompilation("//NO CODE HERE", new[] { ref1 }, parseOptions: TestOptions.Regular); // S1 NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<T> namedType = comp.GetTypeByMetadataName("Program+S1`1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // T TypeSymbol type = namedType.TypeParameters[0]; Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<object> namedType = namedType.Construct(comp.ObjectType); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S2 namedType = comp.GetTypeByMetadataName("Program+S2"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind); // C1 namedType = comp.GetTypeByMetadataName("Program+C1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind); // D1 namedType = comp.GetTypeByMetadataName("Program+D1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind); // object[] type = comp.CreateArrayTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // dynamic type = comp.DynamicType; Assert.False(type.IsReadOnly); // object type = comp.ObjectType; Assert.False(type.IsReadOnly); // anonymous type INamedTypeSymbol iNamedType = comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol()), ImmutableArray.Create("qq")); Assert.False(iNamedType.IsReadOnly); // pointer type type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // tuple type iNamedType = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol(), comp.ObjectType.GetPublicSymbol())); Assert.False(iNamedType.IsReadOnly); } [Fact] public void CorrectOverloadOfStackAllocSpanChosen() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { unsafe public static void Main() { bool condition = false; var span1 = condition ? stackalloc int[1] : new Span<int>(null, 2); Console.Write(span1.Length); var span2 = condition ? stackalloc int[1] : stackalloc int[4]; Console.Write(span2.Length); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "24", verify: Verification.Fails); } [Fact] public void StackAllocExpressionIL() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { Span<int> x = stackalloc int[10]; Console.WriteLine(x.Length); } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "10", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (System.Span<int> V_0) //x IL_0000: ldc.i4.s 40 IL_0002: conv.u IL_0003: localloc IL_0005: ldc.i4.s 10 IL_0007: newobj ""System.Span<int>..ctor(void*, int)"" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call ""int System.Span<int>.Length.get"" IL_0014: call ""void System.Console.WriteLine(int)"" IL_0019: ret }"); } [Fact] public void StackAllocSpanLengthNotEvaluatedTwice() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { private static int length = 0; private static int GetLength() { return ++length; } public static void Main() { for (int i = 0; i < 5; i++) { Span<int> x = stackalloc int[GetLength()]; Console.Write(x.Length); } } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "12345", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (int V_0, //i System.Span<int> V_1, //x int V_2) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0027 IL_0004: call ""int Test.GetLength()"" IL_0009: stloc.2 IL_000a: ldloc.2 IL_000b: conv.u IL_000c: ldc.i4.4 IL_000d: mul.ovf.un IL_000e: localloc IL_0010: ldloc.2 IL_0011: newobj ""System.Span<int>..ctor(void*, int)"" IL_0016: stloc.1 IL_0017: ldloca.s V_1 IL_0019: call ""int System.Span<int>.Length.get"" IL_001e: call ""void System.Console.Write(int)"" IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.0 IL_0027: ldloc.0 IL_0028: ldc.i4.5 IL_0029: blt.s IL_0004 IL_002b: ret }"); } [Fact] public void StackAllocSpanLengthConstantFolding() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { const int a = 5, b = 6; Span<int> x = stackalloc int[a * b]; Console.Write(x.Length); } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "30", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (System.Span<int> V_0) //x IL_0000: ldc.i4.s 120 IL_0002: conv.u IL_0003: localloc IL_0005: ldc.i4.s 30 IL_0007: newobj ""System.Span<int>..ctor(void*, int)"" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call ""int System.Span<int>.Length.get"" IL_0014: call ""void System.Console.Write(int)"" IL_0019: ret }"); } [Fact] public void StackAllocSpanLengthOverflow() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { static void M() { Span<int> x = stackalloc int[int.MaxValue]; } public static void Main() { try { M(); } catch (OverflowException) { Console.WriteLine(""overflow""); } } }", TestOptions.ReleaseExe); var expectedIL = @" { // Code size 22 (0x16) .maxstack 2 IL_0000: ldc.i4 0x7fffffff IL_0005: conv.u IL_0006: ldc.i4.4 IL_0007: mul.ovf.un IL_0008: localloc IL_000a: ldc.i4 0x7fffffff IL_000f: newobj ""System.Span<int>..ctor(void*, int)"" IL_0014: pop IL_0015: ret }"; var isx86 = (IntPtr.Size == 4); if (isx86) { CompileAndVerify(comp, expectedOutput: "overflow", verify: Verification.Fails).VerifyIL("Test.M", expectedIL); } else { // On 64bit the native int does not overflow, so we get StackOverflow instead // therefore we will just check the IL CompileAndVerify(comp, verify: Verification.Fails).VerifyIL("Test.M", expectedIL); } } [Fact] public void ImplicitCastOperatorOnStackAllocIsLoweredCorrectly() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { Test obj1 = stackalloc int[10]; Console.Write(""|""); Test obj2 = stackalloc double[10]; } public static implicit operator Test(Span<int> value) { Console.Write(""SpanOpCalled""); return default(Test); } public static implicit operator Test(double* value) { Console.Write(""PointerOpCalled""); return default(Test); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "SpanOpCalled|PointerOpCalled", verify: Verification.Fails); } [Fact] public void ExplicitCastOperatorOnStackAllocIsLoweredCorrectly() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { Test obj1 = (Test)stackalloc int[10]; } public static explicit operator Test(Span<int> value) { Console.Write(""SpanOpCalled""); return default(Test); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "SpanOpCalled", verify: Verification.Fails); } [Fact] public void ReadOnlyMembers_Metadata() { var csharp = @" public struct S { public void M1() {} public readonly void M2() {} public int P1 { get; set; } public readonly int P2 => 42; public int P3 { readonly get => 123; set {} } public int P4 { get => 123; readonly set {} } public static int P5 { get; set; } } "; CompileAndVerify(csharp, symbolValidator: validate); void validate(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("S"); var m1 = type.GetMethod("M1"); var m2 = type.GetMethod("M2"); var p1 = type.GetProperty("P1"); var p2 = type.GetProperty("P2"); var p3 = type.GetProperty("P3"); var p4 = type.GetProperty("P4"); var p5 = type.GetProperty("P5"); var peModule = (PEModuleSymbol)module; Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p5).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Signature.ReturnParam.Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } [Fact] public void ReadOnlyMembers_RefReturn_Metadata() { var csharp = @" public struct S { static int i; public ref int M1() => ref i; public readonly ref int M2() => ref i; public ref readonly int M3() => ref i; public readonly ref readonly int M4() => ref i; public ref int P1 { get => ref i; } public readonly ref int P2 { get => ref i; } public ref readonly int P3 { get => ref i; } public readonly ref readonly int P4 { get => ref i; } } "; CompileAndVerify(csharp, symbolValidator: validate); void validate(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("S"); var m1 = type.GetMethod("M1"); var m2 = type.GetMethod("M2"); var m3 = type.GetMethod("M3"); var m4 = type.GetMethod("M4"); var p1 = type.GetProperty("P1"); var p2 = type.GetProperty("P2"); var p3 = type.GetProperty("P3"); var p4 = type.GetProperty("P4"); var peModule = (PEModuleSymbol)module; Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m3).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m3).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m4).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m4).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } [Fact] public void ReadOnlyStruct_ReadOnlyMembers_Metadata() { var csharp = @" // note that both the type and member declarations are marked 'readonly' public readonly struct S { public void M1() {} public readonly void M2() {} public int P1 { get; } public readonly int P2 => 42; public int P3 { readonly get => 123; set {} } public int P4 { get => 123; readonly set {} } public static int P5 { get; set; } } "; CompileAndVerify(csharp, symbolValidator: validate); void validate(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("S"); var m1 = type.GetMethod("M1"); var m2 = type.GetMethod("M2"); var p1 = type.GetProperty("P1"); var p2 = type.GetProperty("P2"); var p3 = type.GetProperty("P3"); var p4 = type.GetProperty("P4"); var p5 = type.GetProperty("P5"); var peModule = (PEModuleSymbol)module; Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p5).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Signature.ReturnParam.Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } [Fact] public void ReadOnlyMembers_MetadataRoundTrip() { var external = @" using System; public struct S1 { public void M1() {} public readonly void M2() {} public int P1 { get; set; } public readonly int P2 => 42; public int P3 { readonly get => 123; set {} } public int P4 { get => 123; readonly set {} } public static int P5 { get; set; } public readonly event Action<EventArgs> E { add {} remove {} } } public readonly struct S2 { public void M1() {} public int P1 { get; } public int P2 => 42; public int P3 { set {} } public static int P4 { get; set; } public event Action<EventArgs> E { add {} remove {} } } "; var externalComp = CreateCompilation(external); externalComp.VerifyDiagnostics(); verify(externalComp); var comp = CreateCompilation("", references: new[] { externalComp.EmitToImageReference() }); verify(comp); var comp2 = CreateCompilation("", references: new[] { externalComp.ToMetadataReference() }); verify(comp2); void verify(CSharpCompilation comp) { var s1 = comp.GetMember<NamedTypeSymbol>("S1"); verifyReadOnly(s1.GetMethod("M1"), false, RefKind.Ref); verifyReadOnly(s1.GetMethod("M2"), true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P1").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P1").SetMethod, false, RefKind.Ref); verifyReadOnly(s1.GetProperty("P2").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P3").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P3").SetMethod, false, RefKind.Ref); verifyReadOnly(s1.GetProperty("P4").GetMethod, false, RefKind.Ref); verifyReadOnly(s1.GetProperty("P4").SetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P5").GetMethod, false, null); verifyReadOnly(s1.GetProperty("P5").SetMethod, false, null); verifyReadOnly(s1.GetEvent("E").AddMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetEvent("E").RemoveMethod, true, RefKind.RefReadOnly); var s2 = comp.GetMember<NamedTypeSymbol>("S2"); verifyReadOnly(s2.GetMethod("M1"), true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P1").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P2").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P3").SetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P4").GetMethod, false, null); verifyReadOnly(s2.GetProperty("P4").SetMethod, false, null); verifyReadOnly(s2.GetEvent("E").AddMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetEvent("E").RemoveMethod, true, RefKind.RefReadOnly); void verifyReadOnly(MethodSymbol method, bool isReadOnly, RefKind? refKind) { Assert.Equal(isReadOnly, method.IsEffectivelyReadOnly); Assert.Equal(refKind, method.ThisParameter?.RefKind); } } } [Fact] public void StaticReadOnlyMethod_FromMetadata() { var il = @" .class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi beforefieldinit System.Runtime.CompilerServices.IsReadOnlyAttribute extends [mscorlib]System.Attribute { // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: ret } // end of method IsReadOnlyAttribute::.ctor } // end of class System.Runtime.CompilerServices.IsReadOnlyAttribute .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .pack 0 .size 1 // Methods .method public hidebysig instance void M1 () cil managed { .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2058 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method S::M1 // Methods .method public hidebysig static void M2 () cil managed { .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2058 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method S::M2 } // end of class S "; var ilRef = CompileIL(il); var comp = CreateCompilation("", references: new[] { ilRef }); var s = comp.GetMember<NamedTypeSymbol>("S"); var m1 = s.GetMethod("M1"); Assert.True(m1.IsDeclaredReadOnly); Assert.True(m1.IsEffectivelyReadOnly); // even though the IsReadOnlyAttribute is in metadata, // we ruled out the possibility of the method being readonly because it's static var m2 = s.GetMethod("M2"); Assert.False(m2.IsDeclaredReadOnly); Assert.False(m2.IsEffectivelyReadOnly); } [Fact] public void ReadOnlyMethod_CallNormalMethod() { var csharp = @" public struct S { public int i; public readonly void M1() { // should create local copy M2(); System.Console.Write(i); // explicit local copy, no warning var copy = this; copy.M2(); System.Console.Write(copy.i); } void M2() { i = 23; } static void Main() { var s = new S { i = 1 }; s.M1(); } } "; var verifier = CompileAndVerify(csharp, expectedOutput: "123"); verifier.VerifyDiagnostics( // (9,9): warning CS8655: Call to non-readonly member 'S.M2()' from a 'readonly' member results in an implicit copy of 'this'. // M2(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "M2").WithArguments("S.M2()", "this").WithLocation(9, 9)); verifier.VerifyIL("S.M1", @" { // Code size 51 (0x33) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.1 IL_0007: ldloca.s V_1 IL_0009: call ""void S.M2()"" IL_000e: ldarg.0 IL_000f: ldfld ""int S.i"" IL_0014: call ""void System.Console.Write(int)"" IL_0019: ldarg.0 IL_001a: ldobj ""S"" IL_001f: stloc.0 IL_0020: ldloca.s V_0 IL_0022: call ""void S.M2()"" IL_0027: ldloc.0 IL_0028: ldfld ""int S.i"" IL_002d: call ""void System.Console.Write(int)"" IL_0032: ret }"); } [Fact] public void InMethod_CallNormalMethod() { var csharp = @" public struct S { public int i; public static void M1(in S s) { // should create local copy s.M2(); System.Console.Write(s.i); // explicit local copy, no warning var copy = s; copy.M2(); System.Console.Write(copy.i); } void M2() { i = 23; } static void Main() { var s = new S { i = 1 }; M1(in s); } } "; var verifier = CompileAndVerify(csharp, expectedOutput: "123"); // should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) verifier.VerifyDiagnostics(); verifier.VerifyIL("S.M1", @" { // Code size 51 (0x33) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.1 IL_0007: ldloca.s V_1 IL_0009: call ""void S.M2()"" IL_000e: ldarg.0 IL_000f: ldfld ""int S.i"" IL_0014: call ""void System.Console.Write(int)"" IL_0019: ldarg.0 IL_001a: ldobj ""S"" IL_001f: stloc.0 IL_0020: ldloca.s V_0 IL_0022: call ""void S.M2()"" IL_0027: ldloc.0 IL_0028: ldfld ""int S.i"" IL_002d: call ""void System.Console.Write(int)"" IL_0032: ret }"); } [Fact] public void InMethod_CallMethodFromMetadata() { var external = @" public struct S { public int i; public readonly void M1() {} public void M2() { i = 23; } } "; var image = CreateCompilation(external).EmitToImageReference(); var csharp = @" public static class C { public static void M1(in S s) { // should not copy, no warning s.M1(); System.Console.Write(s.i); // should create local copy, warn in warning wave s.M2(); System.Console.Write(s.i); // explicit local copy, no warning var copy = s; copy.M2(); System.Console.Write(copy.i); } static void Main() { var s = new S { i = 1 }; M1(in s); } } "; var verifier = CompileAndVerify(csharp, references: new[] { image }, expectedOutput: "1123"); // should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) verifier.VerifyDiagnostics(); verifier.VerifyIL("C.M1", @" { // Code size 68 (0x44) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: call ""readonly void S.M1()"" IL_0006: ldarg.0 IL_0007: ldfld ""int S.i"" IL_000c: call ""void System.Console.Write(int)"" IL_0011: ldarg.0 IL_0012: ldobj ""S"" IL_0017: stloc.1 IL_0018: ldloca.s V_1 IL_001a: call ""void S.M2()"" IL_001f: ldarg.0 IL_0020: ldfld ""int S.i"" IL_0025: call ""void System.Console.Write(int)"" IL_002a: ldarg.0 IL_002b: ldobj ""S"" IL_0030: stloc.0 IL_0031: ldloca.s V_0 IL_0033: call ""void S.M2()"" IL_0038: ldloc.0 IL_0039: ldfld ""int S.i"" IL_003e: call ""void System.Console.Write(int)"" IL_0043: ret }"); } [Fact] public void InMethod_CallGetAccessorFromMetadata() { var external = @" public struct S { public int i; public readonly int P1 => 42; public int P2 => i = 23; } "; var image = CreateCompilation(external).EmitToImageReference(); var csharp = @" public static class C { public static void M1(in S s) { // should not copy, no warning _ = s.P1; System.Console.Write(s.i); // should create local copy, warn in warning wave _ = s.P2; System.Console.Write(s.i); // explicit local copy, no warning var copy = s; _ = copy.P2; System.Console.Write(copy.i); } static void Main() { var s = new S { i = 1 }; M1(in s); } } "; var verifier = CompileAndVerify(csharp, references: new[] { image }, expectedOutput: "1123"); // should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) verifier.VerifyDiagnostics(); verifier.VerifyIL("C.M1", @" { // Code size 71 (0x47) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: call ""readonly int S.P1.get"" IL_0006: pop IL_0007: ldarg.0 IL_0008: ldfld ""int S.i"" IL_000d: call ""void System.Console.Write(int)"" IL_0012: ldarg.0 IL_0013: ldobj ""S"" IL_0018: stloc.1 IL_0019: ldloca.s V_1 IL_001b: call ""int S.P2.get"" IL_0020: pop IL_0021: ldarg.0 IL_0022: ldfld ""int S.i"" IL_0027: call ""void System.Console.Write(int)"" IL_002c: ldarg.0 IL_002d: ldobj ""S"" IL_0032: stloc.0 IL_0033: ldloca.s V_0 IL_0035: call ""int S.P2.get"" IL_003a: pop IL_003b: ldloc.0 IL_003c: ldfld ""int S.i"" IL_0041: call ""void System.Console.Write(int)"" IL_0046: ret }"); } [Fact] public void ReadOnlyMethod_CallReadOnlyMethod() { var csharp = @" public struct S { public int i; public readonly int M1() => M2() + 1; public readonly int M2() => i; } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.M1", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.M2()"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyGetAccessor_CallReadOnlyGetAccessor() { var csharp = @" public struct S { public int i; public readonly int P1 { get => P2 + 1; } public readonly int P2 { get => i; } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.P1.get", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.P2.get"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyGetAccessor_CallAutoGetAccessor() { var csharp = @" public struct S { public readonly int P1 { get => P2 + 1; } public int P2 { get; } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.P1.get", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.P2.get"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void InParam_CallReadOnlyMethod() { var csharp = @" public struct S { public int i; public static int M1(in S s) => s.M2() + 1; public readonly int M2() => i; } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.M1", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.M2()"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyMethod_CallReadOnlyMethodOnField() { var csharp = @" public struct S1 { public readonly void M1() {} } public struct S2 { S1 s1; public readonly void M2() { s1.M1(); } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S2.M2", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""S1 S2.s1"" IL_0006: call ""readonly void S1.M1()"" IL_000b: ret }"); comp.VerifyDiagnostics( // (9,8): warning CS0649: Field 'S2.s1' is never assigned to, and will always have its default value // S1 s1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "s1").WithArguments("S2.s1", "").WithLocation(9, 8) ); } [Fact] public void ReadOnlyMethod_CallNormalMethodOnField() { var csharp = @" public struct S1 { public void M1() {} } public struct S2 { S1 s1; public readonly void M2() { s1.M1(); } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S2.M2", @" { // Code size 15 (0xf) .maxstack 1 .locals init (S1 V_0) IL_0000: ldarg.0 IL_0001: ldfld ""S1 S2.s1"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""void S1.M1()"" IL_000e: ret }"); // should warn about calling s2.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyMethod_CallBaseMethod() { var csharp = @" public struct S { readonly void M() { // no warnings for calls to base members GetType(); ToString(); GetHashCode(); Equals(null); } } "; var comp = CompileAndVerify(csharp); comp.VerifyDiagnostics(); // ToString/GetHashCode/Equals should pass the address of 'this' (not a temp). GetType should box 'this'. comp.VerifyIL("S.M", @" { // Code size 58 (0x3a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: box ""S"" IL_000b: call ""System.Type object.GetType()"" IL_0010: pop IL_0011: ldarg.0 IL_0012: constrained. ""S"" IL_0018: callvirt ""string object.ToString()"" IL_001d: pop IL_001e: ldarg.0 IL_001f: constrained. ""S"" IL_0025: callvirt ""int object.GetHashCode()"" IL_002a: pop IL_002b: ldarg.0 IL_002c: ldnull IL_002d: constrained. ""S"" IL_0033: callvirt ""bool object.Equals(object)"" IL_0038: pop IL_0039: ret }"); } [Fact] public void ReadOnlyMethod_OverrideBaseMethod() { var csharp = @" public struct S { // note: GetType can't be overridden public override string ToString() => throw null; public override int GetHashCode() => throw null; public override bool Equals(object o) => throw null; readonly void M() { // should warn--non-readonly invocation ToString(); GetHashCode(); Equals(null); // ok base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics( // (12,9): warning CS8655: Call to non-readonly member 'S.ToString()' from a 'readonly' member results in an implicit copy of 'this'. // ToString(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "ToString").WithArguments("S.ToString()", "this").WithLocation(12, 9), // (13,9): warning CS8655: Call to non-readonly member 'S.GetHashCode()' from a 'readonly' member results in an implicit copy of 'this'. // GetHashCode(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetHashCode").WithArguments("S.GetHashCode()", "this").WithLocation(13, 9), // (14,9): warning CS8655: Call to non-readonly member 'S.Equals(object)' from a 'readonly' member results in an implicit copy of 'this'. // Equals(null); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "Equals").WithArguments("S.Equals(object)", "this").WithLocation(14, 9)); // Verify that calls to non-readonly overrides pass the address of a temp, not the address of 'this' verifier.VerifyIL("S.M", @" { // Code size 117 (0x75) .maxstack 2 .locals init (S V_0) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: constrained. ""S"" IL_000f: callvirt ""string object.ToString()"" IL_0014: pop IL_0015: ldarg.0 IL_0016: ldobj ""S"" IL_001b: stloc.0 IL_001c: ldloca.s V_0 IL_001e: constrained. ""S"" IL_0024: callvirt ""int object.GetHashCode()"" IL_0029: pop IL_002a: ldarg.0 IL_002b: ldobj ""S"" IL_0030: stloc.0 IL_0031: ldloca.s V_0 IL_0033: ldnull IL_0034: constrained. ""S"" IL_003a: callvirt ""bool object.Equals(object)"" IL_003f: pop IL_0040: ldarg.0 IL_0041: ldobj ""S"" IL_0046: box ""S"" IL_004b: call ""string System.ValueType.ToString()"" IL_0050: pop IL_0051: ldarg.0 IL_0052: ldobj ""S"" IL_0057: box ""S"" IL_005c: call ""int System.ValueType.GetHashCode()"" IL_0061: pop IL_0062: ldarg.0 IL_0063: ldobj ""S"" IL_0068: box ""S"" IL_006d: ldnull IL_006e: call ""bool System.ValueType.Equals(object)"" IL_0073: pop IL_0074: ret }"); } [Fact] public void ReadOnlyMethod_ReadOnlyOverrideBaseMethod() { var csharp = @" public struct S { // note: GetType can't be overridden public readonly override string ToString() => throw null; public readonly override int GetHashCode() => throw null; public readonly override bool Equals(object o) => throw null; readonly void M() { // no warnings ToString(); GetHashCode(); Equals(null); base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics(); // Verify that calls to readonly override members pass the address of 'this' (not a temp) verifier.VerifyIL("S.M", @" { // Code size 93 (0x5d) .maxstack 2 IL_0000: ldarg.0 IL_0001: constrained. ""S"" IL_0007: callvirt ""string object.ToString()"" IL_000c: pop IL_000d: ldarg.0 IL_000e: constrained. ""S"" IL_0014: callvirt ""int object.GetHashCode()"" IL_0019: pop IL_001a: ldarg.0 IL_001b: ldnull IL_001c: constrained. ""S"" IL_0022: callvirt ""bool object.Equals(object)"" IL_0027: pop IL_0028: ldarg.0 IL_0029: ldobj ""S"" IL_002e: box ""S"" IL_0033: call ""string System.ValueType.ToString()"" IL_0038: pop IL_0039: ldarg.0 IL_003a: ldobj ""S"" IL_003f: box ""S"" IL_0044: call ""int System.ValueType.GetHashCode()"" IL_0049: pop IL_004a: ldarg.0 IL_004b: ldobj ""S"" IL_0050: box ""S"" IL_0055: ldnull IL_0056: call ""bool System.ValueType.Equals(object)"" IL_005b: pop IL_005c: ret }"); } [Fact] public void ReadOnlyMethod_NewBaseMethod() { var csharp = @" public struct S { public new System.Type GetType() => throw null; public new string ToString() => throw null; public new int GetHashCode() => throw null; public new bool Equals(object o) => throw null; readonly void M() { // should warn--non-readonly invocation GetType(); ToString(); GetHashCode(); Equals(null); // ok base.GetType(); base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics( // (12,9): warning CS8655: Call to non-readonly member 'S.GetType()' from a 'readonly' member results in an implicit copy of 'this'. // GetType(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetType").WithArguments("S.GetType()", "this").WithLocation(12, 9), // (13,9): warning CS8655: Call to non-readonly member 'S.ToString()' from a 'readonly' member results in an implicit copy of 'this'. // ToString(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "ToString").WithArguments("S.ToString()", "this").WithLocation(13, 9), // (14,9): warning CS8655: Call to non-readonly member 'S.GetHashCode()' from a 'readonly' member results in an implicit copy of 'this'. // GetHashCode(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetHashCode").WithArguments("S.GetHashCode()", "this").WithLocation(14, 9), // (15,9): warning CS8655: Call to non-readonly member 'S.Equals(object)' from a 'readonly' member results in an implicit copy of 'this'. // Equals(null); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "Equals").WithArguments("S.Equals(object)", "this").WithLocation(15, 9)); // Verify that calls to new non-readonly members pass an address to a temp and that calls to base members use a box. verifier.VerifyIL("S.M", @" { // Code size 131 (0x83) .maxstack 2 .locals init (S V_0) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""System.Type S.GetType()"" IL_000e: pop IL_000f: ldarg.0 IL_0010: ldobj ""S"" IL_0015: stloc.0 IL_0016: ldloca.s V_0 IL_0018: call ""string S.ToString()"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldobj ""S"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: call ""int S.GetHashCode()"" IL_002c: pop IL_002d: ldarg.0 IL_002e: ldobj ""S"" IL_0033: stloc.0 IL_0034: ldloca.s V_0 IL_0036: ldnull IL_0037: call ""bool S.Equals(object)"" IL_003c: pop IL_003d: ldarg.0 IL_003e: ldobj ""S"" IL_0043: box ""S"" IL_0048: call ""System.Type object.GetType()"" IL_004d: pop IL_004e: ldarg.0 IL_004f: ldobj ""S"" IL_0054: box ""S"" IL_0059: call ""string System.ValueType.ToString()"" IL_005e: pop IL_005f: ldarg.0 IL_0060: ldobj ""S"" IL_0065: box ""S"" IL_006a: call ""int System.ValueType.GetHashCode()"" IL_006f: pop IL_0070: ldarg.0 IL_0071: ldobj ""S"" IL_0076: box ""S"" IL_007b: ldnull IL_007c: call ""bool System.ValueType.Equals(object)"" IL_0081: pop IL_0082: ret }"); } [Fact] public void ReadOnlyMethod_ReadOnlyNewBaseMethod() { var csharp = @" public struct S { public readonly new System.Type GetType() => throw null; public readonly new string ToString() => throw null; public readonly new int GetHashCode() => throw null; public readonly new bool Equals(object o) => throw null; readonly void M() { // no warnings GetType(); ToString(); GetHashCode(); Equals(null); base.GetType(); base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics(); // Verify that calls to readonly new members pass the address of 'this' (not a temp) and that calls to base members use a box. verifier.VerifyIL("S.M", @" { // Code size 99 (0x63) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly System.Type S.GetType()"" IL_0006: pop IL_0007: ldarg.0 IL_0008: call ""readonly string S.ToString()"" IL_000d: pop IL_000e: ldarg.0 IL_000f: call ""readonly int S.GetHashCode()"" IL_0014: pop IL_0015: ldarg.0 IL_0016: ldnull IL_0017: call ""readonly bool S.Equals(object)"" IL_001c: pop IL_001d: ldarg.0 IL_001e: ldobj ""S"" IL_0023: box ""S"" IL_0028: call ""System.Type object.GetType()"" IL_002d: pop IL_002e: ldarg.0 IL_002f: ldobj ""S"" IL_0034: box ""S"" IL_0039: call ""string System.ValueType.ToString()"" IL_003e: pop IL_003f: ldarg.0 IL_0040: ldobj ""S"" IL_0045: box ""S"" IL_004a: call ""int System.ValueType.GetHashCode()"" IL_004f: pop IL_0050: ldarg.0 IL_0051: ldobj ""S"" IL_0056: box ""S"" IL_005b: ldnull IL_005c: call ""bool System.ValueType.Equals(object)"" IL_0061: pop IL_0062: ret }"); } [Fact] public void ReadOnlyMethod_FixedThis() { var csharp = @" struct S { int i; readonly unsafe void M() { fixed (S* sp = &this) { sp->i = 42; } } static void Main() { var s = new S(); s.M(); System.Console.Write(s.i); } } "; CompileAndVerify(csharp, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "42"); } public static TheoryData<bool, CSharpParseOptions, Verification> ReadOnlyGetter_LangVersion_Data() => new TheoryData<bool, CSharpParseOptions, Verification> { { false, TestOptions.Regular7_3, Verification.Passes }, { true, null, Verification.Fails } }; [Theory] [MemberData(nameof(ReadOnlyGetter_LangVersion_Data))] public void ReadOnlyGetter_LangVersion(bool isReadOnly, CSharpParseOptions parseOptions, Verification verify) { var csharp = @" struct S { public int P { get; } static readonly S Field = default; static void M() { _ = Field.P; } } "; var verifier = CompileAndVerify(csharp, parseOptions: parseOptions, verify: verify); var type = ((CSharpCompilation)verifier.Compilation).GetMember<NamedTypeSymbol>("S"); Assert.Equal(isReadOnly, type.GetProperty("P").GetMethod.IsDeclaredReadOnly); Assert.Equal(isReadOnly, type.GetProperty("P").GetMethod.IsEffectivelyReadOnly); } [Fact] public void ReadOnlyEvent_Emit() { var csharp = @" public struct S { public readonly event System.Action E { add { } remove { } } } "; CompileAndVerify(csharp, symbolValidator: validate).VerifyDiagnostics(); void validate(ModuleSymbol module) { var testStruct = module.ContainingAssembly.GetTypeByMetadataName("S"); var peModule = (PEModuleSymbol)module; Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)testStruct.GetEvent("E").AddMethod).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)testStruct.GetEvent("E").RemoveMethod).Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public class CodeGenReadOnlyStructTests : CompilingTestBase { [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyStaticField() { var text = @" class Program { static readonly S1 sf; static void Main() { System.Console.Write(sf.M1()); System.Console.Write(sf.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 37 (0x25) .maxstack 1 IL_0000: ldsflda ""Program.S1 Program.sf"" IL_0005: call ""string Program.S1.M1()"" IL_000a: call ""void System.Console.Write(string)"" IL_000f: ldsflda ""Program.S1 Program.sf"" IL_0014: constrained. ""Program.S1"" IL_001a: callvirt ""string object.ToString()"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 1 .locals init (Program.S1 V_0) IL_0000: ldsfld ""Program.S1 Program.sf"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""string Program.S1.M1()"" IL_000d: call ""void System.Console.Write(string)"" IL_0012: ldsfld ""Program.S1 Program.sf"" IL_0017: stloc.0 IL_0018: ldloca.s V_0 IL_001a: constrained. ""Program.S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyStaticFieldMetadata() { var text1 = @" public readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var text = @" class Program { static readonly S1 sf; static void Main() { System.Console.Write(sf.M1()); System.Console.Write(sf.ToString()); } } "; var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 37 (0x25) .maxstack 1 IL_0000: ldsflda ""S1 Program.sf"" IL_0005: call ""string S1.M1()"" IL_000a: call ""void System.Console.Write(string)"" IL_000f: ldsflda ""S1 Program.sf"" IL_0014: constrained. ""S1"" IL_001a: callvirt ""string object.ToString()"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret }"); comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 1 .locals init (S1 V_0) IL_0000: ldsfld ""S1 Program.sf"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""string S1.M1()"" IL_000d: call ""void System.Console.Write(string)"" IL_0012: ldsfld ""S1 Program.sf"" IL_0017: stloc.0 IL_0018: ldloca.s V_0 IL_001a: constrained. ""S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceField() { var text = @" class Program { readonly S1 f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1()); System.Console.Write(p.f.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""Program.S1 Program.f"" IL_000b: call ""string Program.S1.M1()"" IL_0010: call ""void System.Console.Write(string)"" IL_0015: ldflda ""Program.S1 Program.f"" IL_001a: constrained. ""Program.S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 49 (0x31) .maxstack 2 .locals init (Program.S1 V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""Program.S1 Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: call ""string Program.S1.M1()"" IL_0013: call ""void System.Console.Write(string)"" IL_0018: ldfld ""Program.S1 Program.f"" IL_001d: stloc.0 IL_001e: ldloca.s V_0 IL_0020: constrained. ""Program.S1"" IL_0026: callvirt ""string object.ToString()"" IL_002b: call ""void System.Console.Write(string)"" IL_0030: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceFieldGeneric() { var text = @" class Program { readonly S1<string> f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1(""hello"")); System.Console.Write(p.f.ToString()); } readonly struct S1<T> { public T M1(T arg) { return arg; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 48 (0x30) .maxstack 3 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""Program.S1<string> Program.f"" IL_000b: ldstr ""hello"" IL_0010: call ""string Program.S1<string>.M1(string)"" IL_0015: call ""void System.Console.Write(string)"" IL_001a: ldflda ""Program.S1<string> Program.f"" IL_001f: constrained. ""Program.S1<string>"" IL_0025: callvirt ""string object.ToString()"" IL_002a: call ""void System.Console.Write(string)"" IL_002f: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (Program.S1<string> V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""Program.S1<string> Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: ldstr ""hello"" IL_0013: call ""string Program.S1<string>.M1(string)"" IL_0018: call ""void System.Console.Write(string)"" IL_001d: ldfld ""Program.S1<string> Program.f"" IL_0022: stloc.0 IL_0023: ldloca.s V_0 IL_0025: constrained. ""Program.S1<string>"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.Write(string)"" IL_0035: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceFieldGenericMetadata() { var text1 = @" readonly public struct S1<T> { public T M1(T arg) { return arg; } public override string ToString() { return ""2""; } } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var text = @" class Program { readonly S1<string> f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1(""hello"")); System.Console.Write(p.f.ToString()); } } "; var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 48 (0x30) .maxstack 3 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""S1<string> Program.f"" IL_000b: ldstr ""hello"" IL_0010: call ""string S1<string>.M1(string)"" IL_0015: call ""void System.Console.Write(string)"" IL_001a: ldflda ""S1<string> Program.f"" IL_001f: constrained. ""S1<string>"" IL_0025: callvirt ""string object.ToString()"" IL_002a: call ""void System.Console.Write(string)"" IL_002f: ret }"); comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (S1<string> V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""S1<string> Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: ldstr ""hello"" IL_0013: call ""string S1<string>.M1(string)"" IL_0018: call ""void System.Console.Write(string)"" IL_001d: ldfld ""S1<string> Program.f"" IL_0022: stloc.0 IL_0023: ldloca.s V_0 IL_0025: constrained. ""S1<string>"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.Write(string)"" IL_0035: ret }"); } [Fact] public void InvokeOnReadOnlyThis() { var text = @" class Program { static void Main() { Test(default(S1)); } static void Test(in S1 arg) { System.Console.Write(arg.M1()); System.Console.Write(arg.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Test", @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string Program.S1.M1()"" IL_0006: call ""void System.Console.Write(string)"" IL_000b: ldarg.0 IL_000c: constrained. ""Program.S1"" IL_0012: callvirt ""string object.ToString()"" IL_0017: call ""void System.Console.Write(string)"" IL_001c: ret }"); } [Fact] public void InvokeOnThis() { var text = @" class Program { static void Main() { default(S1).Test(); } readonly struct S1 { public void Test() { System.Console.Write(this.M1()); System.Console.Write(ToString()); } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.S1.Test()", @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string Program.S1.M1()"" IL_0006: call ""void System.Console.Write(string)"" IL_000b: ldarg.0 IL_000c: constrained. ""Program.S1"" IL_0012: callvirt ""string object.ToString()"" IL_0017: call ""void System.Console.Write(string)"" IL_001c: ret }"); comp.VerifyIL("Program.Main()", @" { // Code size 15 (0xf) .maxstack 2 .locals init (Program.S1 V_0) IL_0000: ldloca.s V_0 IL_0002: dup IL_0003: initobj ""Program.S1"" IL_0009: call ""void Program.S1.Test()"" IL_000e: ret }"); } [Fact] public void InvokeOnThisBaseMethods() { var text = @" class Program { static void Main() { default(S1).Test(); } readonly struct S1 { public void Test() { System.Console.Write(this.GetType()); System.Console.Write(ToString()); } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"Program+S1Program+S1"); comp.VerifyIL("Program.S1.Test()", @" { // Code size 39 (0x27) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldobj ""Program.S1"" IL_0006: box ""Program.S1"" IL_000b: call ""System.Type object.GetType()"" IL_0010: call ""void System.Console.Write(object)"" IL_0015: ldarg.0 IL_0016: constrained. ""Program.S1"" IL_001c: callvirt ""string object.ToString()"" IL_0021: call ""void System.Console.Write(string)"" IL_0026: ret }"); } [Fact] public void AssignThis() { var text = @" class Program { static void Main() { S1 v = new S1(42); System.Console.Write(v.x); S1 v2 = new S1(v); System.Console.Write(v2.x); } readonly struct S1 { public readonly int x; public S1(int i) { x = i; // OK } public S1(S1 arg) { this = arg; // OK } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"4242"); comp.VerifyIL("Program.S1..ctor(int)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int Program.S1.x"" IL_0007: ret }"); comp.VerifyIL("Program.S1..ctor(Program.S1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stobj ""Program.S1"" IL_0007: ret }"); } [Fact] public void AssignThisErr() { var text = @" class Program { static void Main() { } static void TakesRef(ref S1 arg){} static void TakesRef(ref int arg){} readonly struct S1 { readonly int x; public S1(int i) { x = i; // OK } public S1(S1 arg) { this = arg; // OK } public void Test1() { this = default; // error } public void Test2() { TakesRef(ref this); // error } public void Test3() { TakesRef(ref this.x); // error } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (27,13): error CS1604: Cannot assign to 'this' because it is read-only // this = default; // error Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this").WithArguments("this").WithLocation(27, 13), // (32,26): error CS1605: Cannot use 'this' as a ref or out value because it is read-only // TakesRef(ref this); // error Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this").WithLocation(32, 26), // (37,26): error CS0192: A readonly field cannot be used as a ref or out value (except in a constructor) // TakesRef(ref this.x); // error Diagnostic(ErrorCode.ERR_RefReadonly, "this.x").WithLocation(37, 26) ); } [Fact] public void AssignThisNestedMethods() { var text = @" using System; class Program { static void Main() { } static void TakesRef(ref S1 arg){} static void TakesRef(ref int arg){} readonly struct S1 { readonly int x; public S1(int i) { void F() { x = i;} // Error Action a = () => { x = i;}; // Error F(); } public S1(S1 arg) { void F() { this = arg;} // Error Action a = () => { this = arg;}; // Error F(); } public void Test1() { void F() { this = default;} // Error Action a = () => { this = default;}; // Error F(); } public void Test2() { void F() { TakesRef(ref this);} // Error Action a = () => { TakesRef(ref this);}; // Error F(); } public void Test3() { void F() { TakesRef(ref this.x);} // Error Action a = () => { TakesRef(ref this.x);}; // Error F(); } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (19,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { x = i;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(19, 24), // (20,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { x = i;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(20, 32), // (26,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { this = arg;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(26, 24), // (27,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { this = arg;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(27, 32), // (33,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { this = default;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(33, 24), // (34,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { this = default;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(34, 32), // (40,37): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { TakesRef(ref this);} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(40, 37), // (41,45): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { TakesRef(ref this);}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(41, 45), // (47,37): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void F() { TakesRef(ref this.x);} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(47, 37), // (48,45): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { TakesRef(ref this.x);}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(48, 45) ); } [Fact] public void ReadOnlyStructApi() { var text = @" class Program { readonly struct S1 { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } readonly struct S1<T> { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } struct S2 { public S2(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } class C1 { public C1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } delegate int D1(); } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular); // S1 NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); void validate(ModuleSymbol module) { var test = module.ContainingAssembly.GetTypeByMetadataName("Program+S1"); var peModule = (PEModuleSymbol)module; Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PENamedTypeSymbol)test).Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } CompileAndVerify(comp, symbolValidator: validate); // S1<T> namedType = comp.GetTypeByMetadataName("Program+S1`1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // T TypeSymbol type = namedType.TypeParameters[0]; Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<object> namedType = namedType.Construct(comp.ObjectType); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S2 namedType = comp.GetTypeByMetadataName("Program+S2"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind); // C1 namedType = comp.GetTypeByMetadataName("Program+C1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind); // D1 namedType = comp.GetTypeByMetadataName("Program+D1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind); // object[] type = comp.CreateArrayTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // dynamic type = comp.DynamicType; Assert.False(type.IsReadOnly); // object type = comp.ObjectType; Assert.False(type.IsReadOnly); // anonymous type INamedTypeSymbol iNamedType = comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol()), ImmutableArray.Create("qq")); Assert.False(iNamedType.IsReadOnly); // pointer type type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // tuple type iNamedType = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol(), comp.ObjectType.GetPublicSymbol())); Assert.False(iNamedType.IsReadOnly); // S1 from image var clientComp = CreateCompilation("", references: new[] { comp.EmitToImageReference() }); NamedTypeSymbol s1 = clientComp.GetTypeByMetadataName("Program+S1"); Assert.True(s1.IsReadOnly); Assert.Empty(s1.GetAttributes()); Assert.Equal(RefKind.Out, s1.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, s1.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, s1.GetMethod("ToString").ThisParameter.RefKind); } [Fact] public void ReadOnlyStructApiMetadata() { var text1 = @" class Program { readonly struct S1 { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } readonly struct S1<T> { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } struct S2 { public S2(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } class C1 { public C1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } delegate int D1(); } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var comp = CreateCompilation("//NO CODE HERE", new[] { ref1 }, parseOptions: TestOptions.Regular); // S1 NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<T> namedType = comp.GetTypeByMetadataName("Program+S1`1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // T TypeSymbol type = namedType.TypeParameters[0]; Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<object> namedType = namedType.Construct(comp.ObjectType); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S2 namedType = comp.GetTypeByMetadataName("Program+S2"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind); // C1 namedType = comp.GetTypeByMetadataName("Program+C1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind); // D1 namedType = comp.GetTypeByMetadataName("Program+D1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind); // object[] type = comp.CreateArrayTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // dynamic type = comp.DynamicType; Assert.False(type.IsReadOnly); // object type = comp.ObjectType; Assert.False(type.IsReadOnly); // anonymous type INamedTypeSymbol iNamedType = comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol()), ImmutableArray.Create("qq")); Assert.False(iNamedType.IsReadOnly); // pointer type type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // tuple type iNamedType = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol(), comp.ObjectType.GetPublicSymbol())); Assert.False(iNamedType.IsReadOnly); } [Fact] public void CorrectOverloadOfStackAllocSpanChosen() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { unsafe public static void Main() { bool condition = false; var span1 = condition ? stackalloc int[1] : new Span<int>(null, 2); Console.Write(span1.Length); var span2 = condition ? stackalloc int[1] : stackalloc int[4]; Console.Write(span2.Length); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "24", verify: Verification.Fails); } [Fact] public void StackAllocExpressionIL() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { Span<int> x = stackalloc int[10]; Console.WriteLine(x.Length); } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "10", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (System.Span<int> V_0) //x IL_0000: ldc.i4.s 40 IL_0002: conv.u IL_0003: localloc IL_0005: ldc.i4.s 10 IL_0007: newobj ""System.Span<int>..ctor(void*, int)"" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call ""int System.Span<int>.Length.get"" IL_0014: call ""void System.Console.WriteLine(int)"" IL_0019: ret }"); } [Fact] public void StackAllocSpanLengthNotEvaluatedTwice() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { private static int length = 0; private static int GetLength() { return ++length; } public static void Main() { for (int i = 0; i < 5; i++) { Span<int> x = stackalloc int[GetLength()]; Console.Write(x.Length); } } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "12345", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (int V_0, //i System.Span<int> V_1, //x int V_2) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0027 IL_0004: call ""int Test.GetLength()"" IL_0009: stloc.2 IL_000a: ldloc.2 IL_000b: conv.u IL_000c: ldc.i4.4 IL_000d: mul.ovf.un IL_000e: localloc IL_0010: ldloc.2 IL_0011: newobj ""System.Span<int>..ctor(void*, int)"" IL_0016: stloc.1 IL_0017: ldloca.s V_1 IL_0019: call ""int System.Span<int>.Length.get"" IL_001e: call ""void System.Console.Write(int)"" IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.0 IL_0027: ldloc.0 IL_0028: ldc.i4.5 IL_0029: blt.s IL_0004 IL_002b: ret }"); } [Fact] public void StackAllocSpanLengthConstantFolding() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { const int a = 5, b = 6; Span<int> x = stackalloc int[a * b]; Console.Write(x.Length); } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "30", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (System.Span<int> V_0) //x IL_0000: ldc.i4.s 120 IL_0002: conv.u IL_0003: localloc IL_0005: ldc.i4.s 30 IL_0007: newobj ""System.Span<int>..ctor(void*, int)"" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call ""int System.Span<int>.Length.get"" IL_0014: call ""void System.Console.Write(int)"" IL_0019: ret }"); } [Fact] public void StackAllocSpanLengthOverflow() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { static void M() { Span<int> x = stackalloc int[int.MaxValue]; } public static void Main() { try { M(); } catch (OverflowException) { Console.WriteLine(""overflow""); } } }", TestOptions.ReleaseExe); var expectedIL = @" { // Code size 22 (0x16) .maxstack 2 IL_0000: ldc.i4 0x7fffffff IL_0005: conv.u IL_0006: ldc.i4.4 IL_0007: mul.ovf.un IL_0008: localloc IL_000a: ldc.i4 0x7fffffff IL_000f: newobj ""System.Span<int>..ctor(void*, int)"" IL_0014: pop IL_0015: ret }"; var isx86 = (IntPtr.Size == 4); if (isx86) { CompileAndVerify(comp, expectedOutput: "overflow", verify: Verification.Fails).VerifyIL("Test.M", expectedIL); } else { // On 64bit the native int does not overflow, so we get StackOverflow instead // therefore we will just check the IL CompileAndVerify(comp, verify: Verification.Fails).VerifyIL("Test.M", expectedIL); } } [Fact] public void ImplicitCastOperatorOnStackAllocIsLoweredCorrectly() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { Test obj1 = stackalloc int[10]; Console.Write(""|""); Test obj2 = stackalloc double[10]; } public static implicit operator Test(Span<int> value) { Console.Write(""SpanOpCalled""); return default(Test); } public static implicit operator Test(double* value) { Console.Write(""PointerOpCalled""); return default(Test); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "SpanOpCalled|PointerOpCalled", verify: Verification.Fails); } [Fact] public void ExplicitCastOperatorOnStackAllocIsLoweredCorrectly() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { Test obj1 = (Test)stackalloc int[10]; } public static explicit operator Test(Span<int> value) { Console.Write(""SpanOpCalled""); return default(Test); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "SpanOpCalled", verify: Verification.Fails); } [Fact] public void ReadOnlyMembers_Metadata() { var csharp = @" public struct S { public void M1() {} public readonly void M2() {} public int P1 { get; set; } public readonly int P2 => 42; public int P3 { readonly get => 123; set {} } public int P4 { get => 123; readonly set {} } public static int P5 { get; set; } } "; CompileAndVerify(csharp, symbolValidator: validate); void validate(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("S"); var m1 = type.GetMethod("M1"); var m2 = type.GetMethod("M2"); var p1 = type.GetProperty("P1"); var p2 = type.GetProperty("P2"); var p3 = type.GetProperty("P3"); var p4 = type.GetProperty("P4"); var p5 = type.GetProperty("P5"); var peModule = (PEModuleSymbol)module; Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p5).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Signature.ReturnParam.Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } [Fact] public void ReadOnlyMembers_RefReturn_Metadata() { var csharp = @" public struct S { static int i; public ref int M1() => ref i; public readonly ref int M2() => ref i; public ref readonly int M3() => ref i; public readonly ref readonly int M4() => ref i; public ref int P1 { get => ref i; } public readonly ref int P2 { get => ref i; } public ref readonly int P3 { get => ref i; } public readonly ref readonly int P4 { get => ref i; } } "; CompileAndVerify(csharp, symbolValidator: validate); void validate(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("S"); var m1 = type.GetMethod("M1"); var m2 = type.GetMethod("M2"); var m3 = type.GetMethod("M3"); var m4 = type.GetMethod("M4"); var p1 = type.GetProperty("P1"); var p2 = type.GetProperty("P2"); var p3 = type.GetProperty("P3"); var p4 = type.GetProperty("P4"); var peModule = (PEModuleSymbol)module; Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m3).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m3).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m4).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m4).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } [Fact] public void ReadOnlyStruct_ReadOnlyMembers_Metadata() { var csharp = @" // note that both the type and member declarations are marked 'readonly' public readonly struct S { public void M1() {} public readonly void M2() {} public int P1 { get; } public readonly int P2 => 42; public int P3 { readonly get => 123; set {} } public int P4 { get => 123; readonly set {} } public static int P5 { get; set; } } "; CompileAndVerify(csharp, symbolValidator: validate); void validate(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("S"); var m1 = type.GetMethod("M1"); var m2 = type.GetMethod("M2"); var p1 = type.GetProperty("P1"); var p2 = type.GetProperty("P2"); var p3 = type.GetProperty("P3"); var p4 = type.GetProperty("P4"); var p5 = type.GetProperty("P5"); var peModule = (PEModuleSymbol)module; Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p5).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Signature.ReturnParam.Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Handle)); Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Signature.ReturnParam.Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } [Fact] public void ReadOnlyMembers_MetadataRoundTrip() { var external = @" using System; public struct S1 { public void M1() {} public readonly void M2() {} public int P1 { get; set; } public readonly int P2 => 42; public int P3 { readonly get => 123; set {} } public int P4 { get => 123; readonly set {} } public static int P5 { get; set; } public readonly event Action<EventArgs> E { add {} remove {} } } public readonly struct S2 { public void M1() {} public int P1 { get; } public int P2 => 42; public int P3 { set {} } public static int P4 { get; set; } public event Action<EventArgs> E { add {} remove {} } } "; var externalComp = CreateCompilation(external); externalComp.VerifyDiagnostics(); verify(externalComp); var comp = CreateCompilation("", references: new[] { externalComp.EmitToImageReference() }); verify(comp); var comp2 = CreateCompilation("", references: new[] { externalComp.ToMetadataReference() }); verify(comp2); void verify(CSharpCompilation comp) { var s1 = comp.GetMember<NamedTypeSymbol>("S1"); verifyReadOnly(s1.GetMethod("M1"), false, RefKind.Ref); verifyReadOnly(s1.GetMethod("M2"), true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P1").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P1").SetMethod, false, RefKind.Ref); verifyReadOnly(s1.GetProperty("P2").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P3").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P3").SetMethod, false, RefKind.Ref); verifyReadOnly(s1.GetProperty("P4").GetMethod, false, RefKind.Ref); verifyReadOnly(s1.GetProperty("P4").SetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetProperty("P5").GetMethod, false, null); verifyReadOnly(s1.GetProperty("P5").SetMethod, false, null); verifyReadOnly(s1.GetEvent("E").AddMethod, true, RefKind.RefReadOnly); verifyReadOnly(s1.GetEvent("E").RemoveMethod, true, RefKind.RefReadOnly); var s2 = comp.GetMember<NamedTypeSymbol>("S2"); verifyReadOnly(s2.GetMethod("M1"), true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P1").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P2").GetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P3").SetMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetProperty("P4").GetMethod, false, null); verifyReadOnly(s2.GetProperty("P4").SetMethod, false, null); verifyReadOnly(s2.GetEvent("E").AddMethod, true, RefKind.RefReadOnly); verifyReadOnly(s2.GetEvent("E").RemoveMethod, true, RefKind.RefReadOnly); void verifyReadOnly(MethodSymbol method, bool isReadOnly, RefKind? refKind) { Assert.Equal(isReadOnly, method.IsEffectivelyReadOnly); Assert.Equal(refKind, method.ThisParameter?.RefKind); } } } [Fact] public void StaticReadOnlyMethod_FromMetadata() { var il = @" .class private auto ansi '<Module>' { } // end of class <Module> .class public auto ansi beforefieldinit System.Runtime.CompilerServices.IsReadOnlyAttribute extends [mscorlib]System.Attribute { // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: ret } // end of method IsReadOnlyAttribute::.ctor } // end of class System.Runtime.CompilerServices.IsReadOnlyAttribute .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .pack 0 .size 1 // Methods .method public hidebysig instance void M1 () cil managed { .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2058 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method S::M1 // Methods .method public hidebysig static void M2 () cil managed { .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2058 // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method S::M2 } // end of class S "; var ilRef = CompileIL(il); var comp = CreateCompilation("", references: new[] { ilRef }); var s = comp.GetMember<NamedTypeSymbol>("S"); var m1 = s.GetMethod("M1"); Assert.True(m1.IsDeclaredReadOnly); Assert.True(m1.IsEffectivelyReadOnly); // even though the IsReadOnlyAttribute is in metadata, // we ruled out the possibility of the method being readonly because it's static var m2 = s.GetMethod("M2"); Assert.False(m2.IsDeclaredReadOnly); Assert.False(m2.IsEffectivelyReadOnly); } [Fact] public void ReadOnlyMethod_CallNormalMethod() { var csharp = @" public struct S { public int i; public readonly void M1() { // should create local copy M2(); System.Console.Write(i); // explicit local copy, no warning var copy = this; copy.M2(); System.Console.Write(copy.i); } void M2() { i = 23; } static void Main() { var s = new S { i = 1 }; s.M1(); } } "; var verifier = CompileAndVerify(csharp, expectedOutput: "123"); verifier.VerifyDiagnostics( // (9,9): warning CS8655: Call to non-readonly member 'S.M2()' from a 'readonly' member results in an implicit copy of 'this'. // M2(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "M2").WithArguments("S.M2()", "this").WithLocation(9, 9)); verifier.VerifyIL("S.M1", @" { // Code size 51 (0x33) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.1 IL_0007: ldloca.s V_1 IL_0009: call ""void S.M2()"" IL_000e: ldarg.0 IL_000f: ldfld ""int S.i"" IL_0014: call ""void System.Console.Write(int)"" IL_0019: ldarg.0 IL_001a: ldobj ""S"" IL_001f: stloc.0 IL_0020: ldloca.s V_0 IL_0022: call ""void S.M2()"" IL_0027: ldloc.0 IL_0028: ldfld ""int S.i"" IL_002d: call ""void System.Console.Write(int)"" IL_0032: ret }"); } [Fact] public void InMethod_CallNormalMethod() { var csharp = @" public struct S { public int i; public static void M1(in S s) { // should create local copy s.M2(); System.Console.Write(s.i); // explicit local copy, no warning var copy = s; copy.M2(); System.Console.Write(copy.i); } void M2() { i = 23; } static void Main() { var s = new S { i = 1 }; M1(in s); } } "; var verifier = CompileAndVerify(csharp, expectedOutput: "123"); // should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) verifier.VerifyDiagnostics(); verifier.VerifyIL("S.M1", @" { // Code size 51 (0x33) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.1 IL_0007: ldloca.s V_1 IL_0009: call ""void S.M2()"" IL_000e: ldarg.0 IL_000f: ldfld ""int S.i"" IL_0014: call ""void System.Console.Write(int)"" IL_0019: ldarg.0 IL_001a: ldobj ""S"" IL_001f: stloc.0 IL_0020: ldloca.s V_0 IL_0022: call ""void S.M2()"" IL_0027: ldloc.0 IL_0028: ldfld ""int S.i"" IL_002d: call ""void System.Console.Write(int)"" IL_0032: ret }"); } [Fact] public void InMethod_CallMethodFromMetadata() { var external = @" public struct S { public int i; public readonly void M1() {} public void M2() { i = 23; } } "; var image = CreateCompilation(external).EmitToImageReference(); var csharp = @" public static class C { public static void M1(in S s) { // should not copy, no warning s.M1(); System.Console.Write(s.i); // should create local copy, warn in warning wave s.M2(); System.Console.Write(s.i); // explicit local copy, no warning var copy = s; copy.M2(); System.Console.Write(copy.i); } static void Main() { var s = new S { i = 1 }; M1(in s); } } "; var verifier = CompileAndVerify(csharp, references: new[] { image }, expectedOutput: "1123"); // should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) verifier.VerifyDiagnostics(); verifier.VerifyIL("C.M1", @" { // Code size 68 (0x44) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: call ""readonly void S.M1()"" IL_0006: ldarg.0 IL_0007: ldfld ""int S.i"" IL_000c: call ""void System.Console.Write(int)"" IL_0011: ldarg.0 IL_0012: ldobj ""S"" IL_0017: stloc.1 IL_0018: ldloca.s V_1 IL_001a: call ""void S.M2()"" IL_001f: ldarg.0 IL_0020: ldfld ""int S.i"" IL_0025: call ""void System.Console.Write(int)"" IL_002a: ldarg.0 IL_002b: ldobj ""S"" IL_0030: stloc.0 IL_0031: ldloca.s V_0 IL_0033: call ""void S.M2()"" IL_0038: ldloc.0 IL_0039: ldfld ""int S.i"" IL_003e: call ""void System.Console.Write(int)"" IL_0043: ret }"); } [Fact] public void InMethod_CallGetAccessorFromMetadata() { var external = @" public struct S { public int i; public readonly int P1 => 42; public int P2 => i = 23; } "; var image = CreateCompilation(external).EmitToImageReference(); var csharp = @" public static class C { public static void M1(in S s) { // should not copy, no warning _ = s.P1; System.Console.Write(s.i); // should create local copy, warn in warning wave _ = s.P2; System.Console.Write(s.i); // explicit local copy, no warning var copy = s; _ = copy.P2; System.Console.Write(copy.i); } static void Main() { var s = new S { i = 1 }; M1(in s); } } "; var verifier = CompileAndVerify(csharp, references: new[] { image }, expectedOutput: "1123"); // should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) verifier.VerifyDiagnostics(); verifier.VerifyIL("C.M1", @" { // Code size 71 (0x47) .maxstack 1 .locals init (S V_0, //copy S V_1) IL_0000: ldarg.0 IL_0001: call ""readonly int S.P1.get"" IL_0006: pop IL_0007: ldarg.0 IL_0008: ldfld ""int S.i"" IL_000d: call ""void System.Console.Write(int)"" IL_0012: ldarg.0 IL_0013: ldobj ""S"" IL_0018: stloc.1 IL_0019: ldloca.s V_1 IL_001b: call ""int S.P2.get"" IL_0020: pop IL_0021: ldarg.0 IL_0022: ldfld ""int S.i"" IL_0027: call ""void System.Console.Write(int)"" IL_002c: ldarg.0 IL_002d: ldobj ""S"" IL_0032: stloc.0 IL_0033: ldloca.s V_0 IL_0035: call ""int S.P2.get"" IL_003a: pop IL_003b: ldloc.0 IL_003c: ldfld ""int S.i"" IL_0041: call ""void System.Console.Write(int)"" IL_0046: ret }"); } [Fact] public void ReadOnlyMethod_CallReadOnlyMethod() { var csharp = @" public struct S { public int i; public readonly int M1() => M2() + 1; public readonly int M2() => i; } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.M1", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.M2()"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyGetAccessor_CallReadOnlyGetAccessor() { var csharp = @" public struct S { public int i; public readonly int P1 { get => P2 + 1; } public readonly int P2 { get => i; } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.P1.get", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.P2.get"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyGetAccessor_CallAutoGetAccessor() { var csharp = @" public struct S { public readonly int P1 { get => P2 + 1; } public int P2 { get; } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.P1.get", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.P2.get"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void InParam_CallReadOnlyMethod() { var csharp = @" public struct S { public int i; public static int M1(in S s) => s.M2() + 1; public readonly int M2() => i; } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S.M1", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly int S.M2()"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyMethod_CallReadOnlyMethodOnField() { var csharp = @" public struct S1 { public readonly void M1() {} } public struct S2 { S1 s1; public readonly void M2() { s1.M1(); } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S2.M2", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""S1 S2.s1"" IL_0006: call ""readonly void S1.M1()"" IL_000b: ret }"); comp.VerifyDiagnostics( // (9,8): warning CS0649: Field 'S2.s1' is never assigned to, and will always have its default value // S1 s1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "s1").WithArguments("S2.s1", "").WithLocation(9, 8) ); } [Fact] public void ReadOnlyMethod_CallNormalMethodOnField() { var csharp = @" public struct S1 { public void M1() {} } public struct S2 { S1 s1; public readonly void M2() { s1.M1(); } } "; var comp = CompileAndVerify(csharp); comp.VerifyIL("S2.M2", @" { // Code size 15 (0xf) .maxstack 1 .locals init (S1 V_0) IL_0000: ldarg.0 IL_0001: ldfld ""S1 S2.s1"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""void S1.M1()"" IL_000e: ret }"); // should warn about calling s2.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968) comp.VerifyDiagnostics(); } [Fact] public void ReadOnlyMethod_CallBaseMethod() { var csharp = @" public struct S { readonly void M() { // no warnings for calls to base members GetType(); ToString(); GetHashCode(); Equals(null); } } "; var comp = CompileAndVerify(csharp); comp.VerifyDiagnostics(); // ToString/GetHashCode/Equals should pass the address of 'this' (not a temp). GetType should box 'this'. comp.VerifyIL("S.M", @" { // Code size 58 (0x3a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: box ""S"" IL_000b: call ""System.Type object.GetType()"" IL_0010: pop IL_0011: ldarg.0 IL_0012: constrained. ""S"" IL_0018: callvirt ""string object.ToString()"" IL_001d: pop IL_001e: ldarg.0 IL_001f: constrained. ""S"" IL_0025: callvirt ""int object.GetHashCode()"" IL_002a: pop IL_002b: ldarg.0 IL_002c: ldnull IL_002d: constrained. ""S"" IL_0033: callvirt ""bool object.Equals(object)"" IL_0038: pop IL_0039: ret }"); } [Fact] public void ReadOnlyMethod_OverrideBaseMethod() { var csharp = @" public struct S { // note: GetType can't be overridden public override string ToString() => throw null; public override int GetHashCode() => throw null; public override bool Equals(object o) => throw null; readonly void M() { // should warn--non-readonly invocation ToString(); GetHashCode(); Equals(null); // ok base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics( // (12,9): warning CS8655: Call to non-readonly member 'S.ToString()' from a 'readonly' member results in an implicit copy of 'this'. // ToString(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "ToString").WithArguments("S.ToString()", "this").WithLocation(12, 9), // (13,9): warning CS8655: Call to non-readonly member 'S.GetHashCode()' from a 'readonly' member results in an implicit copy of 'this'. // GetHashCode(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetHashCode").WithArguments("S.GetHashCode()", "this").WithLocation(13, 9), // (14,9): warning CS8655: Call to non-readonly member 'S.Equals(object)' from a 'readonly' member results in an implicit copy of 'this'. // Equals(null); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "Equals").WithArguments("S.Equals(object)", "this").WithLocation(14, 9)); // Verify that calls to non-readonly overrides pass the address of a temp, not the address of 'this' verifier.VerifyIL("S.M", @" { // Code size 117 (0x75) .maxstack 2 .locals init (S V_0) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: constrained. ""S"" IL_000f: callvirt ""string object.ToString()"" IL_0014: pop IL_0015: ldarg.0 IL_0016: ldobj ""S"" IL_001b: stloc.0 IL_001c: ldloca.s V_0 IL_001e: constrained. ""S"" IL_0024: callvirt ""int object.GetHashCode()"" IL_0029: pop IL_002a: ldarg.0 IL_002b: ldobj ""S"" IL_0030: stloc.0 IL_0031: ldloca.s V_0 IL_0033: ldnull IL_0034: constrained. ""S"" IL_003a: callvirt ""bool object.Equals(object)"" IL_003f: pop IL_0040: ldarg.0 IL_0041: ldobj ""S"" IL_0046: box ""S"" IL_004b: call ""string System.ValueType.ToString()"" IL_0050: pop IL_0051: ldarg.0 IL_0052: ldobj ""S"" IL_0057: box ""S"" IL_005c: call ""int System.ValueType.GetHashCode()"" IL_0061: pop IL_0062: ldarg.0 IL_0063: ldobj ""S"" IL_0068: box ""S"" IL_006d: ldnull IL_006e: call ""bool System.ValueType.Equals(object)"" IL_0073: pop IL_0074: ret }"); } [Fact] public void ReadOnlyMethod_ReadOnlyOverrideBaseMethod() { var csharp = @" public struct S { // note: GetType can't be overridden public readonly override string ToString() => throw null; public readonly override int GetHashCode() => throw null; public readonly override bool Equals(object o) => throw null; readonly void M() { // no warnings ToString(); GetHashCode(); Equals(null); base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics(); // Verify that calls to readonly override members pass the address of 'this' (not a temp) verifier.VerifyIL("S.M", @" { // Code size 93 (0x5d) .maxstack 2 IL_0000: ldarg.0 IL_0001: constrained. ""S"" IL_0007: callvirt ""string object.ToString()"" IL_000c: pop IL_000d: ldarg.0 IL_000e: constrained. ""S"" IL_0014: callvirt ""int object.GetHashCode()"" IL_0019: pop IL_001a: ldarg.0 IL_001b: ldnull IL_001c: constrained. ""S"" IL_0022: callvirt ""bool object.Equals(object)"" IL_0027: pop IL_0028: ldarg.0 IL_0029: ldobj ""S"" IL_002e: box ""S"" IL_0033: call ""string System.ValueType.ToString()"" IL_0038: pop IL_0039: ldarg.0 IL_003a: ldobj ""S"" IL_003f: box ""S"" IL_0044: call ""int System.ValueType.GetHashCode()"" IL_0049: pop IL_004a: ldarg.0 IL_004b: ldobj ""S"" IL_0050: box ""S"" IL_0055: ldnull IL_0056: call ""bool System.ValueType.Equals(object)"" IL_005b: pop IL_005c: ret }"); } [Fact] public void ReadOnlyMethod_NewBaseMethod() { var csharp = @" public struct S { public new System.Type GetType() => throw null; public new string ToString() => throw null; public new int GetHashCode() => throw null; public new bool Equals(object o) => throw null; readonly void M() { // should warn--non-readonly invocation GetType(); ToString(); GetHashCode(); Equals(null); // ok base.GetType(); base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics( // (12,9): warning CS8655: Call to non-readonly member 'S.GetType()' from a 'readonly' member results in an implicit copy of 'this'. // GetType(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetType").WithArguments("S.GetType()", "this").WithLocation(12, 9), // (13,9): warning CS8655: Call to non-readonly member 'S.ToString()' from a 'readonly' member results in an implicit copy of 'this'. // ToString(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "ToString").WithArguments("S.ToString()", "this").WithLocation(13, 9), // (14,9): warning CS8655: Call to non-readonly member 'S.GetHashCode()' from a 'readonly' member results in an implicit copy of 'this'. // GetHashCode(); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetHashCode").WithArguments("S.GetHashCode()", "this").WithLocation(14, 9), // (15,9): warning CS8655: Call to non-readonly member 'S.Equals(object)' from a 'readonly' member results in an implicit copy of 'this'. // Equals(null); Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "Equals").WithArguments("S.Equals(object)", "this").WithLocation(15, 9)); // Verify that calls to new non-readonly members pass an address to a temp and that calls to base members use a box. verifier.VerifyIL("S.M", @" { // Code size 131 (0x83) .maxstack 2 .locals init (S V_0) IL_0000: ldarg.0 IL_0001: ldobj ""S"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""System.Type S.GetType()"" IL_000e: pop IL_000f: ldarg.0 IL_0010: ldobj ""S"" IL_0015: stloc.0 IL_0016: ldloca.s V_0 IL_0018: call ""string S.ToString()"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldobj ""S"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: call ""int S.GetHashCode()"" IL_002c: pop IL_002d: ldarg.0 IL_002e: ldobj ""S"" IL_0033: stloc.0 IL_0034: ldloca.s V_0 IL_0036: ldnull IL_0037: call ""bool S.Equals(object)"" IL_003c: pop IL_003d: ldarg.0 IL_003e: ldobj ""S"" IL_0043: box ""S"" IL_0048: call ""System.Type object.GetType()"" IL_004d: pop IL_004e: ldarg.0 IL_004f: ldobj ""S"" IL_0054: box ""S"" IL_0059: call ""string System.ValueType.ToString()"" IL_005e: pop IL_005f: ldarg.0 IL_0060: ldobj ""S"" IL_0065: box ""S"" IL_006a: call ""int System.ValueType.GetHashCode()"" IL_006f: pop IL_0070: ldarg.0 IL_0071: ldobj ""S"" IL_0076: box ""S"" IL_007b: ldnull IL_007c: call ""bool System.ValueType.Equals(object)"" IL_0081: pop IL_0082: ret }"); } [Fact] public void ReadOnlyMethod_ReadOnlyNewBaseMethod() { var csharp = @" public struct S { public readonly new System.Type GetType() => throw null; public readonly new string ToString() => throw null; public readonly new int GetHashCode() => throw null; public readonly new bool Equals(object o) => throw null; readonly void M() { // no warnings GetType(); ToString(); GetHashCode(); Equals(null); base.GetType(); base.ToString(); base.GetHashCode(); base.Equals(null); } } "; var verifier = CompileAndVerify(csharp); verifier.VerifyDiagnostics(); // Verify that calls to readonly new members pass the address of 'this' (not a temp) and that calls to base members use a box. verifier.VerifyIL("S.M", @" { // Code size 99 (0x63) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""readonly System.Type S.GetType()"" IL_0006: pop IL_0007: ldarg.0 IL_0008: call ""readonly string S.ToString()"" IL_000d: pop IL_000e: ldarg.0 IL_000f: call ""readonly int S.GetHashCode()"" IL_0014: pop IL_0015: ldarg.0 IL_0016: ldnull IL_0017: call ""readonly bool S.Equals(object)"" IL_001c: pop IL_001d: ldarg.0 IL_001e: ldobj ""S"" IL_0023: box ""S"" IL_0028: call ""System.Type object.GetType()"" IL_002d: pop IL_002e: ldarg.0 IL_002f: ldobj ""S"" IL_0034: box ""S"" IL_0039: call ""string System.ValueType.ToString()"" IL_003e: pop IL_003f: ldarg.0 IL_0040: ldobj ""S"" IL_0045: box ""S"" IL_004a: call ""int System.ValueType.GetHashCode()"" IL_004f: pop IL_0050: ldarg.0 IL_0051: ldobj ""S"" IL_0056: box ""S"" IL_005b: ldnull IL_005c: call ""bool System.ValueType.Equals(object)"" IL_0061: pop IL_0062: ret }"); } [Fact] public void ReadOnlyMethod_FixedThis() { var csharp = @" struct S { int i; readonly unsafe void M() { fixed (S* sp = &this) { sp->i = 42; } } static void Main() { var s = new S(); s.M(); System.Console.Write(s.i); } } "; CompileAndVerify(csharp, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "42"); } public static TheoryData<bool, CSharpParseOptions, Verification> ReadOnlyGetter_LangVersion_Data() => new TheoryData<bool, CSharpParseOptions, Verification> { { false, TestOptions.Regular7_3, Verification.Passes }, { true, null, Verification.Fails } }; [Theory] [MemberData(nameof(ReadOnlyGetter_LangVersion_Data))] public void ReadOnlyGetter_LangVersion(bool isReadOnly, CSharpParseOptions parseOptions, Verification verify) { var csharp = @" struct S { public int P { get; } static readonly S Field = default; static void M() { _ = Field.P; } } "; var verifier = CompileAndVerify(csharp, parseOptions: parseOptions, verify: verify); var type = ((CSharpCompilation)verifier.Compilation).GetMember<NamedTypeSymbol>("S"); Assert.Equal(isReadOnly, type.GetProperty("P").GetMethod.IsDeclaredReadOnly); Assert.Equal(isReadOnly, type.GetProperty("P").GetMethod.IsEffectivelyReadOnly); } [Fact] public void ReadOnlyEvent_Emit() { var csharp = @" public struct S { public readonly event System.Action E { add { } remove { } } } "; CompileAndVerify(csharp, symbolValidator: validate).VerifyDiagnostics(); void validate(ModuleSymbol module) { var testStruct = module.ContainingAssembly.GetTypeByMetadataName("S"); var peModule = (PEModuleSymbol)module; Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)testStruct.GetEvent("E").AddMethod).Handle)); Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)testStruct.GetEvent("E").RemoveMethod).Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IUnaryOperatorExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IUnaryOperatorExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17591")] public void Test_UnaryOperatorExpression_Type_Plus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt32) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int64) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt64) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Single) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Double) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Single) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Double) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt32) (Syntax: '+Method()') Operand: IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int64) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt64) (Syntax: '+Method()') Operand: IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Single) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Double) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Single) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Double) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_LogicalNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/!i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_LogicalNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/!Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt32) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int64) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt64) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt32) (Syntax: '~Method()') Operand: IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int64) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt64) (Syntax: '~Method()') Operand: IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: dynamic) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: dynamic) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: dynamic) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_LogicalNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/!i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: dynamic) (Syntax: '+Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: dynamic) (Syntax: '-Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: dynamic) (Syntax: '~Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_LogicalNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/!Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/+i/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/-i/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/~i/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: Enum) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/+Method()/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()') Operand: IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/-Method()/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/~Method()/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: Enum) (Syntax: '~Method()') Operand: IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/+i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: CustomType CustomType.op_UnaryPlus(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/-i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: CustomType CustomType.op_UnaryNegation(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/~i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: CustomType CustomType.op_OnesComplement(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_LogicalNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/!i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: CustomType CustomType.op_LogicalNot(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '!i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/+Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: CustomType CustomType.op_UnaryPlus(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '+Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/-Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: CustomType CustomType.op_UnaryNegation(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '-Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/~Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: CustomType CustomType.op_OnesComplement(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '~Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_LogicalNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/!Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: CustomType CustomType.op_LogicalNot(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '!Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(18135, "https://github.com/dotnet/roslyn/issues/18135")] [WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")] public void Test_UnaryOperatorExpression_Type_And_TrueFalse() { string source = @" public struct S { private int value; public S(int v) { value = v; } public static S operator |(S x, S y) { return new S(x.value - y.value); } public static S operator &(S x, S y) { return new S(x.value + y.value); } public static bool operator true(S x) { return x.value > 0; } public static bool operator false(S x) { return x.value <= 0; } } class C { public void M() { var x = new S(2); var y = new S(1); /*<bind>*/if (x && y) { }/*</bind>*/ } } "; string expectedOperationTree = @" IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (x && y) { }') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x && y') Operand: IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x && y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }') WhenFalse: null "; VerifyOperationTreeForTest<IfStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(18135, "https://github.com/dotnet/roslyn/issues/18135")] [WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")] public void Test_UnaryOperatorExpression_Type_Or_TrueFalse() { string source = @" public struct S { private int value; public S(int v) { value = v; } public static S operator |(S x, S y) { return new S(x.value - y.value); } public static S operator &(S x, S y) { return new S(x.value + y.value); } public static bool operator true(S x) { return x.value > 0; } public static bool operator false(S x) { return x.value <= 0; } } class C { public void M() { var x = new S(2); var y = new S(1); /*<bind>*/if (x || y) { }/*</bind>*/ } } "; string expectedOperationTree = @" IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (x || y) { }') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x || y') Operand: IBinaryOperation (BinaryOperatorKind.ConditionalOr) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x || y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }') WhenFalse: null "; VerifyOperationTreeForTest<IfStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_NoRightOperator() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/+i/*</bind>*/; } } public struct CustomType { } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_DerivedTypes() { string source = @" class A { BaseType Method() { var i = default(DerivedType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(BaseType x) { return new BaseType(); } } public class DerivedType : BaseType { } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: BaseType BaseType.op_UnaryPlus(BaseType x)) (OperationKind.Unary, Type: BaseType) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: BaseType, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_ImplicitConversion() { string source = @" class A { BaseType Method() { var i = default(DerivedType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(BaseType x) { return new BaseType(); } } public class DerivedType { public static implicit operator BaseType(DerivedType x) { return new BaseType(); } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_ExplicitConversion() { string source = @" class A { BaseType Method() { var i = default(DerivedType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(BaseType x) { return new BaseType(); } } public class DerivedType { public static explicit operator BaseType(DerivedType x) { return new BaseType(); } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_Malformed_Operator() { string source = @" class A { BaseType Method() { var i = default(BaseType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(int x) { return new BaseType(); } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: BaseType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")] public void Test_BinaryExpressionSyntax_Type_And_TrueFalse_Condition() { string source = @" public struct S { private int value; public S(int v) { value = v; } public static S operator |(S x, S y) { return new S(x.value - y.value); } public static S operator &(S x, S y) { return new S(x.value + y.value); } public static bool operator true(S x) { return x.value > 0; } public static bool operator false(S x) { return x.value <= 0; } } class C { public void M() { var x = new S(2); var y = new S(1); if (/*<bind>*/x && y/*</bind>*/) { } } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x && y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y') "; VerifyOperationTreeForTest<BinaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_IncrementExpression() { string source = @" class A { int Method() { var i = 1; return /*<bind>*/++i/*</bind>*/; } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++i') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_DecrementExpression() { string source = @" class A { int Method() { var i = 1; return /*<bind>*/--i/*</bind>*/; } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--i') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Nullable() { string source = @" class A { void Method() { var i = /*<bind>*/(int?)1/*</bind>*/; } } "; string expectedOperationTree = @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?) (Syntax: '(int?)1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<CastExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Pointer() { string source = @" class A { unsafe void Method() { int[] a = new int[5] {10, 20, 30, 40, 50}; fixed (int* p = &a[0]) { int* p2 = p; int p1 = /*<bind>*/*p2/*</bind>*/; } } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '*p2') Children(1): ILocalReferenceOperation: p2 (OperationKind.LocalReference, Type: System.Int32*) (Syntax: 'p2') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyLiftedUnaryOperators1() { var source = @" class C { void F(int? x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus, IsLifted) (OperationKind.Unary, Type: System.Int32?) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyNonLiftedUnaryOperators1() { var source = @" class C { void F(int x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyLiftedUserDefinedUnaryOperators1() { var source = @" struct C { public static C operator -(C c) { } void F(C? x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus, IsLifted) (OperatorMethod: C C.op_UnaryNegation(C c)) (OperationKind.Unary, Type: C?) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C?) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyNonLiftedUserDefinedUnaryOperators1() { var source = @" struct C { public static C operator -(C c) { } void F(C x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: C C.op_UnaryNegation(C c)) (OperationKind.Unary, Type: C) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LogicalNotFlow_01() { string source = @" class P { void M(bool a, bool b) /*<bind>*/{ GetArray()[0] = !(a || b); }/*</bind>*/ static bool[] GetArray() => null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetArray()[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Boolean) (Syntax: 'GetArray()[0]') Array reference: IInvocationOperation (System.Boolean[] P.GetArray()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'GetArray()') Instance Receiver: null Arguments(0) Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Jump if True (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'GetArray()[ ... !(a || b);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'GetArray()[ ... !(a || b)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'GetArray()[0]') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'a || b') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LogicalNotFlow_02() { var source = @" class C { bool F(bool f) /*<bind>*/{ return !f; }/*</bind>*/ }"; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Return) Block[B2] IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!f') Operand: IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'f') Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LogicalNotFlow_03() { var source = @" class C { bool F(bool f) /*<bind>*/{ return !!f; }/*</bind>*/ }"; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Return) Block[B2] IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'f') Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicNotFlow_01() { string source = @" class P { void M(dynamic a, dynamic b) /*<bind>*/{ a = !b; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = !b;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'a = !b') Left: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'a') Right: IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!b') Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] public void VerifyIndexOperator_Int() { var compilation = CreateCompilationWithIndexAndRange(@" class Test { void M(int arg) { var x = /*<bind>*/^arg/*</bind>*/; } }").VerifyDiagnostics(); string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'arg') "; var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree); Assert.Null(operation.OperatorMethod); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] public void VerifyIndexOperator_NullableInt() { var compilation = CreateCompilationWithIndexAndRange(@" class Test { void M(int? arg) { var x = /*<bind>*/^arg/*</bind>*/; } }").VerifyDiagnostics(); string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Hat, IsLifted) (OperationKind.Unary, Type: System.Index?) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'arg') "; var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree); Assert.Null(operation.OperatorMethod); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] public void VerifyIndexOperator_ConvertibleToInt() { var compilation = CreateCompilationWithIndexAndRange(@" class Test { void M(byte arg) { var x = /*<bind>*/^arg/*</bind>*/; } }").VerifyDiagnostics(); string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'arg') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'arg') "; var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree); Assert.Null(operation.OperatorMethod); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IUnaryOperatorExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17591")] public void Test_UnaryOperatorExpression_Type_Plus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt32) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int64) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt64) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Single) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Double) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Single) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Double) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt32) (Syntax: '+Method()') Operand: IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int64) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt64) (Syntax: '+Method()') Operand: IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Single) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Double) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Single) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Double) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_LogicalNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/!i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_LogicalNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/!Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt32) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int64) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt64) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt32) (Syntax: '~Method()') Operand: IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int64) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt64) (Syntax: '~Method()') Operand: IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: dynamic) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: dynamic) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: dynamic) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_LogicalNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/!i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: dynamic) (Syntax: '+Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: dynamic) (Syntax: '-Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: dynamic) (Syntax: '~Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_LogicalNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/!Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/+i/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/-i/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/~i/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: Enum) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/+Method()/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()') Operand: IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/-Method()/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/~Method()/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: Enum) (Syntax: '~Method()') Operand: IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/+i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: CustomType CustomType.op_UnaryPlus(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/-i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: CustomType CustomType.op_UnaryNegation(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/~i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: CustomType CustomType.op_OnesComplement(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_LogicalNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/!i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: CustomType CustomType.op_LogicalNot(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '!i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/+Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: CustomType CustomType.op_UnaryPlus(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '+Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/-Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: CustomType CustomType.op_UnaryNegation(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '-Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/~Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: CustomType CustomType.op_OnesComplement(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '~Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_LogicalNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/!Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: CustomType CustomType.op_LogicalNot(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '!Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(18135, "https://github.com/dotnet/roslyn/issues/18135")] [WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")] public void Test_UnaryOperatorExpression_Type_And_TrueFalse() { string source = @" public struct S { private int value; public S(int v) { value = v; } public static S operator |(S x, S y) { return new S(x.value - y.value); } public static S operator &(S x, S y) { return new S(x.value + y.value); } public static bool operator true(S x) { return x.value > 0; } public static bool operator false(S x) { return x.value <= 0; } } class C { public void M() { var x = new S(2); var y = new S(1); /*<bind>*/if (x && y) { }/*</bind>*/ } } "; string expectedOperationTree = @" IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (x && y) { }') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x && y') Operand: IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x && y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }') WhenFalse: null "; VerifyOperationTreeForTest<IfStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(18135, "https://github.com/dotnet/roslyn/issues/18135")] [WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")] public void Test_UnaryOperatorExpression_Type_Or_TrueFalse() { string source = @" public struct S { private int value; public S(int v) { value = v; } public static S operator |(S x, S y) { return new S(x.value - y.value); } public static S operator &(S x, S y) { return new S(x.value + y.value); } public static bool operator true(S x) { return x.value > 0; } public static bool operator false(S x) { return x.value <= 0; } } class C { public void M() { var x = new S(2); var y = new S(1); /*<bind>*/if (x || y) { }/*</bind>*/ } } "; string expectedOperationTree = @" IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (x || y) { }') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x || y') Operand: IBinaryOperation (BinaryOperatorKind.ConditionalOr) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x || y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }') WhenFalse: null "; VerifyOperationTreeForTest<IfStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_NoRightOperator() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/+i/*</bind>*/; } } public struct CustomType { } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_DerivedTypes() { string source = @" class A { BaseType Method() { var i = default(DerivedType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(BaseType x) { return new BaseType(); } } public class DerivedType : BaseType { } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: BaseType BaseType.op_UnaryPlus(BaseType x)) (OperationKind.Unary, Type: BaseType) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: BaseType, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_ImplicitConversion() { string source = @" class A { BaseType Method() { var i = default(DerivedType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(BaseType x) { return new BaseType(); } } public class DerivedType { public static implicit operator BaseType(DerivedType x) { return new BaseType(); } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_ExplicitConversion() { string source = @" class A { BaseType Method() { var i = default(DerivedType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(BaseType x) { return new BaseType(); } } public class DerivedType { public static explicit operator BaseType(DerivedType x) { return new BaseType(); } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_Malformed_Operator() { string source = @" class A { BaseType Method() { var i = default(BaseType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(int x) { return new BaseType(); } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: BaseType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")] public void Test_BinaryExpressionSyntax_Type_And_TrueFalse_Condition() { string source = @" public struct S { private int value; public S(int v) { value = v; } public static S operator |(S x, S y) { return new S(x.value - y.value); } public static S operator &(S x, S y) { return new S(x.value + y.value); } public static bool operator true(S x) { return x.value > 0; } public static bool operator false(S x) { return x.value <= 0; } } class C { public void M() { var x = new S(2); var y = new S(1); if (/*<bind>*/x && y/*</bind>*/) { } } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x && y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y') "; VerifyOperationTreeForTest<BinaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_IncrementExpression() { string source = @" class A { int Method() { var i = 1; return /*<bind>*/++i/*</bind>*/; } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++i') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_DecrementExpression() { string source = @" class A { int Method() { var i = 1; return /*<bind>*/--i/*</bind>*/; } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--i') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Nullable() { string source = @" class A { void Method() { var i = /*<bind>*/(int?)1/*</bind>*/; } } "; string expectedOperationTree = @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?) (Syntax: '(int?)1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<CastExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Pointer() { string source = @" class A { unsafe void Method() { int[] a = new int[5] {10, 20, 30, 40, 50}; fixed (int* p = &a[0]) { int* p2 = p; int p1 = /*<bind>*/*p2/*</bind>*/; } } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '*p2') Children(1): ILocalReferenceOperation: p2 (OperationKind.LocalReference, Type: System.Int32*) (Syntax: 'p2') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyLiftedUnaryOperators1() { var source = @" class C { void F(int? x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus, IsLifted) (OperationKind.Unary, Type: System.Int32?) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyNonLiftedUnaryOperators1() { var source = @" class C { void F(int x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyLiftedUserDefinedUnaryOperators1() { var source = @" struct C { public static C operator -(C c) { } void F(C? x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus, IsLifted) (OperatorMethod: C C.op_UnaryNegation(C c)) (OperationKind.Unary, Type: C?) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C?) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyNonLiftedUserDefinedUnaryOperators1() { var source = @" struct C { public static C operator -(C c) { } void F(C x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: C C.op_UnaryNegation(C c)) (OperationKind.Unary, Type: C) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LogicalNotFlow_01() { string source = @" class P { void M(bool a, bool b) /*<bind>*/{ GetArray()[0] = !(a || b); }/*</bind>*/ static bool[] GetArray() => null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetArray()[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Boolean) (Syntax: 'GetArray()[0]') Array reference: IInvocationOperation (System.Boolean[] P.GetArray()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'GetArray()') Instance Receiver: null Arguments(0) Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Jump if True (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'GetArray()[ ... !(a || b);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'GetArray()[ ... !(a || b)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'GetArray()[0]') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'a || b') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LogicalNotFlow_02() { var source = @" class C { bool F(bool f) /*<bind>*/{ return !f; }/*</bind>*/ }"; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Return) Block[B2] IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!f') Operand: IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'f') Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LogicalNotFlow_03() { var source = @" class C { bool F(bool f) /*<bind>*/{ return !!f; }/*</bind>*/ }"; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Return) Block[B2] IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'f') Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicNotFlow_01() { string source = @" class P { void M(dynamic a, dynamic b) /*<bind>*/{ a = !b; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = !b;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'a = !b') Left: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'a') Right: IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!b') Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] public void VerifyIndexOperator_Int() { var compilation = CreateCompilationWithIndexAndRange(@" class Test { void M(int arg) { var x = /*<bind>*/^arg/*</bind>*/; } }").VerifyDiagnostics(); string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'arg') "; var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree); Assert.Null(operation.OperatorMethod); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] public void VerifyIndexOperator_NullableInt() { var compilation = CreateCompilationWithIndexAndRange(@" class Test { void M(int? arg) { var x = /*<bind>*/^arg/*</bind>*/; } }").VerifyDiagnostics(); string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Hat, IsLifted) (OperationKind.Unary, Type: System.Index?) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'arg') "; var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree); Assert.Null(operation.OperatorMethod); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] public void VerifyIndexOperator_ConvertibleToInt() { var compilation = CreateCompilationWithIndexAndRange(@" class Test { void M(byte arg) { var x = /*<bind>*/^arg/*</bind>*/; } }").VerifyDiagnostics(); string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'arg') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'arg') "; var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree); Assert.Null(operation.OperatorMethod); } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/VisualStudio/IntegrationTest/TestUtilities/Input/SendKeys_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.Threading; using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Input { internal class SendKeys_InProc : AbstractSendKeys { private readonly VisualStudio_InProc _visualStudioInstance; public SendKeys_InProc(VisualStudio_InProc visualStudioInstance) { _visualStudioInstance = visualStudioInstance; } protected override void ActivateMainWindow() { _visualStudioInstance.ActivateMainWindow(); } protected override void WaitForApplicationIdle(CancellationToken cancellationToken) { _visualStudioInstance.WaitForApplicationIdle(Helper.HangMitigatingTimeout); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Input { internal class SendKeys_InProc : AbstractSendKeys { private readonly VisualStudio_InProc _visualStudioInstance; public SendKeys_InProc(VisualStudio_InProc visualStudioInstance) { _visualStudioInstance = visualStudioInstance; } protected override void ActivateMainWindow() { _visualStudioInstance.ActivateMainWindow(); } protected override void WaitForApplicationIdle(CancellationToken cancellationToken) { _visualStudioInstance.WaitForApplicationIdle(Helper.HangMitigatingTimeout); } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Tools/IdeBenchmarks/MemoryDiagnoserConfig.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 BenchmarkDotNet.Configs; using BenchmarkDotNet.Diagnosers; namespace IdeBenchmarks { public class MemoryDiagnoserConfig : ManualConfig { public MemoryDiagnoserConfig() { AddDiagnoser(MemoryDiagnoser.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. #nullable disable using BenchmarkDotNet.Configs; using BenchmarkDotNet.Diagnosers; namespace IdeBenchmarks { public class MemoryDiagnoserConfig : ManualConfig { public MemoryDiagnoserConfig() { AddDiagnoser(MemoryDiagnoser.Default); } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Features/Core/Portable/GenerateMember/GenerateParameterizedMember/AbstractGenerateMethodService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeActions; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal abstract partial class AbstractGenerateMethodService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> : AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>, IGenerateParameterizedMemberService where TService : AbstractGenerateMethodService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> where TSimpleNameSyntax : TExpressionSyntax where TExpressionSyntax : SyntaxNode where TInvocationExpressionSyntax : TExpressionSyntax { protected abstract bool IsSimpleNameGeneration(SyntaxNode node); protected abstract bool IsExplicitInterfaceGeneration(SyntaxNode node); protected abstract bool TryInitializeExplicitInterfaceState(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken identifierToken, out IMethodSymbol methodSymbol, out INamedTypeSymbol typeToGenerateIn); protected abstract bool TryInitializeSimpleNameState(SemanticDocument document, TSimpleNameSyntax simpleName, CancellationToken cancellationToken, out SyntaxToken identifierToken, out TExpressionSyntax simpleNameOrMemberAccessExpression, out TInvocationExpressionSyntax invocationExpressionOpt, out bool isInConditionalExpression); protected abstract ITypeSymbol DetermineReturnTypeForSimpleNameOrMemberAccessExpression(ITypeInferenceService typeInferenceService, SemanticModel semanticModel, TExpressionSyntax expression, CancellationToken cancellationToken); public async Task<ImmutableArray<CodeAction>> GenerateMethodAsync( Document document, SyntaxNode node, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Refactoring_GenerateMember_GenerateMethod, cancellationToken)) { var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); var state = await State.GenerateMethodStateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false); if (state == null) { return ImmutableArray<CodeAction>.Empty; } return await GetActionsAsync(document, state, cancellationToken).ConfigureAwait(false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal abstract partial class AbstractGenerateMethodService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> : AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>, IGenerateParameterizedMemberService where TService : AbstractGenerateMethodService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> where TSimpleNameSyntax : TExpressionSyntax where TExpressionSyntax : SyntaxNode where TInvocationExpressionSyntax : TExpressionSyntax { protected abstract bool IsSimpleNameGeneration(SyntaxNode node); protected abstract bool IsExplicitInterfaceGeneration(SyntaxNode node); protected abstract bool TryInitializeExplicitInterfaceState(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken identifierToken, out IMethodSymbol methodSymbol, out INamedTypeSymbol typeToGenerateIn); protected abstract bool TryInitializeSimpleNameState(SemanticDocument document, TSimpleNameSyntax simpleName, CancellationToken cancellationToken, out SyntaxToken identifierToken, out TExpressionSyntax simpleNameOrMemberAccessExpression, out TInvocationExpressionSyntax invocationExpressionOpt, out bool isInConditionalExpression); protected abstract ITypeSymbol DetermineReturnTypeForSimpleNameOrMemberAccessExpression(ITypeInferenceService typeInferenceService, SemanticModel semanticModel, TExpressionSyntax expression, CancellationToken cancellationToken); public async Task<ImmutableArray<CodeAction>> GenerateMethodAsync( Document document, SyntaxNode node, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Refactoring_GenerateMember_GenerateMethod, cancellationToken)) { var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); var state = await State.GenerateMethodStateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false); if (state == null) { return ImmutableArray<CodeAction>.Empty; } return await GetActionsAsync(document, state, cancellationToken).ConfigureAwait(false); } } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Workspaces/Core/Portable/Remote/RemoteArguments.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { #region FindReferences [DataContract] internal sealed class SerializableSymbolAndProjectId : IEquatable<SerializableSymbolAndProjectId> { [DataMember(Order = 0)] public readonly string SymbolKeyData; [DataMember(Order = 1)] public readonly ProjectId ProjectId; public SerializableSymbolAndProjectId(string symbolKeyData, ProjectId projectId) { SymbolKeyData = symbolKeyData; ProjectId = projectId; } public override bool Equals(object obj) => Equals(obj as SerializableSymbolAndProjectId); public bool Equals(SerializableSymbolAndProjectId other) { if (this == other) return true; return this.ProjectId == other?.ProjectId && this.SymbolKeyData == other?.SymbolKeyData; } public override int GetHashCode() => Hash.Combine(this.SymbolKeyData, this.ProjectId.GetHashCode()); public static SerializableSymbolAndProjectId Dehydrate( IAliasSymbol alias, Document document, CancellationToken cancellationToken) { return alias == null ? null : Dehydrate(document.Project.Solution, alias, cancellationToken); } public static SerializableSymbolAndProjectId Dehydrate( Solution solution, ISymbol symbol, CancellationToken cancellationToken) { var project = solution.GetOriginatingProject(symbol); Contract.ThrowIfNull(project, WorkspacesResources.Symbols_project_could_not_be_found_in_the_provided_solution); return Create(symbol, project, cancellationToken); } public static SerializableSymbolAndProjectId Create(ISymbol symbol, Project project, CancellationToken cancellationToken) => new(symbol.GetSymbolKey(cancellationToken).ToString(), project.Id); public static bool TryCreate( ISymbol symbol, Solution solution, CancellationToken cancellationToken, out SerializableSymbolAndProjectId result) { var project = solution.GetOriginatingProject(symbol); if (project == null) { result = null; return false; } return TryCreate(symbol, project, cancellationToken, out result); } public static bool TryCreate( ISymbol symbol, Project project, CancellationToken cancellationToken, out SerializableSymbolAndProjectId result) { if (!SymbolKey.CanCreate(symbol, cancellationToken)) { result = null; return false; } result = new SerializableSymbolAndProjectId(SymbolKey.CreateString(symbol, cancellationToken), project.Id); return true; } public async Task<ISymbol> TryRehydrateAsync( Solution solution, CancellationToken cancellationToken) { var projectId = ProjectId; var project = solution.GetProject(projectId); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); // The server and client should both be talking about the same compilation. As such // locations in symbols are save to resolve as we rehydrate the SymbolKey. var symbol = SymbolKey.ResolveString( SymbolKeyData, compilation, out var failureReason, cancellationToken).GetAnySymbol(); if (symbol == null) { try { throw new InvalidOperationException( $"We should always be able to resolve a symbol back on the host side:\r\n{project.Name}\r\n{SymbolKeyData}\r\n{failureReason}"); } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { return null; } } return symbol; } } [DataContract] internal readonly struct SerializableReferenceLocation { [DataMember(Order = 0)] public readonly DocumentId Document; [DataMember(Order = 1)] public readonly SerializableSymbolAndProjectId Alias; [DataMember(Order = 2)] public readonly TextSpan Location; [DataMember(Order = 3)] public readonly bool IsImplicit; [DataMember(Order = 4)] public readonly SymbolUsageInfo SymbolUsageInfo; [DataMember(Order = 5)] public readonly ImmutableDictionary<string, string> AdditionalProperties; [DataMember(Order = 6)] public readonly CandidateReason CandidateReason; public SerializableReferenceLocation( DocumentId document, SerializableSymbolAndProjectId alias, TextSpan location, bool isImplicit, SymbolUsageInfo symbolUsageInfo, ImmutableDictionary<string, string> additionalProperties, CandidateReason candidateReason) { Document = document; Alias = alias; Location = location; IsImplicit = isImplicit; SymbolUsageInfo = symbolUsageInfo; AdditionalProperties = additionalProperties; CandidateReason = candidateReason; } public static SerializableReferenceLocation Dehydrate( ReferenceLocation referenceLocation, CancellationToken cancellationToken) { return new SerializableReferenceLocation( referenceLocation.Document.Id, SerializableSymbolAndProjectId.Dehydrate(referenceLocation.Alias, referenceLocation.Document, cancellationToken), referenceLocation.Location.SourceSpan, referenceLocation.IsImplicit, referenceLocation.SymbolUsageInfo, referenceLocation.AdditionalProperties, referenceLocation.CandidateReason); } public async Task<ReferenceLocation> RehydrateAsync( Solution solution, CancellationToken cancellationToken) { var document = await solution.GetDocumentAsync(this.Document, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var aliasSymbol = await RehydrateAliasAsync(solution, cancellationToken).ConfigureAwait(false); var additionalProperties = this.AdditionalProperties; return new ReferenceLocation( document, aliasSymbol, CodeAnalysis.Location.Create(syntaxTree, Location), isImplicit: IsImplicit, symbolUsageInfo: SymbolUsageInfo, additionalProperties: additionalProperties ?? ImmutableDictionary<string, string>.Empty, candidateReason: CandidateReason); } private async Task<IAliasSymbol> RehydrateAliasAsync( Solution solution, CancellationToken cancellationToken) { if (Alias == null) return null; var symbol = await Alias.TryRehydrateAsync(solution, cancellationToken).ConfigureAwait(false); return symbol as IAliasSymbol; } } [DataContract] internal class SerializableSymbolGroup : IEquatable<SerializableSymbolGroup> { [DataMember(Order = 0)] public readonly HashSet<SerializableSymbolAndProjectId> Symbols; private int _hashCode; public SerializableSymbolGroup(HashSet<SerializableSymbolAndProjectId> symbols) { Symbols = new HashSet<SerializableSymbolAndProjectId>(symbols); } public override bool Equals(object obj) => obj is SerializableSymbolGroup group && Equals(group); public bool Equals(SerializableSymbolGroup other) { if (this == other) return true; return other != null && this.Symbols.SetEquals(other.Symbols); } public override int GetHashCode() { if (_hashCode == 0) { var hashCode = 0; foreach (var symbol in Symbols) hashCode += symbol.SymbolKeyData.GetHashCode(); _hashCode = hashCode; } return _hashCode; } public static SerializableSymbolGroup Dehydrate(Solution solution, SymbolGroup group, CancellationToken cancellationToken) { return new SerializableSymbolGroup(new HashSet<SerializableSymbolAndProjectId>( group.Symbols.Select(s => SerializableSymbolAndProjectId.Dehydrate(solution, s, cancellationToken)))); } } #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.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { #region FindReferences [DataContract] internal sealed class SerializableSymbolAndProjectId : IEquatable<SerializableSymbolAndProjectId> { [DataMember(Order = 0)] public readonly string SymbolKeyData; [DataMember(Order = 1)] public readonly ProjectId ProjectId; public SerializableSymbolAndProjectId(string symbolKeyData, ProjectId projectId) { SymbolKeyData = symbolKeyData; ProjectId = projectId; } public override bool Equals(object obj) => Equals(obj as SerializableSymbolAndProjectId); public bool Equals(SerializableSymbolAndProjectId other) { if (this == other) return true; return this.ProjectId == other?.ProjectId && this.SymbolKeyData == other?.SymbolKeyData; } public override int GetHashCode() => Hash.Combine(this.SymbolKeyData, this.ProjectId.GetHashCode()); public static SerializableSymbolAndProjectId Dehydrate( IAliasSymbol alias, Document document, CancellationToken cancellationToken) { return alias == null ? null : Dehydrate(document.Project.Solution, alias, cancellationToken); } public static SerializableSymbolAndProjectId Dehydrate( Solution solution, ISymbol symbol, CancellationToken cancellationToken) { var project = solution.GetOriginatingProject(symbol); Contract.ThrowIfNull(project, WorkspacesResources.Symbols_project_could_not_be_found_in_the_provided_solution); return Create(symbol, project, cancellationToken); } public static SerializableSymbolAndProjectId Create(ISymbol symbol, Project project, CancellationToken cancellationToken) => new(symbol.GetSymbolKey(cancellationToken).ToString(), project.Id); public static bool TryCreate( ISymbol symbol, Solution solution, CancellationToken cancellationToken, out SerializableSymbolAndProjectId result) { var project = solution.GetOriginatingProject(symbol); if (project == null) { result = null; return false; } return TryCreate(symbol, project, cancellationToken, out result); } public static bool TryCreate( ISymbol symbol, Project project, CancellationToken cancellationToken, out SerializableSymbolAndProjectId result) { if (!SymbolKey.CanCreate(symbol, cancellationToken)) { result = null; return false; } result = new SerializableSymbolAndProjectId(SymbolKey.CreateString(symbol, cancellationToken), project.Id); return true; } public async Task<ISymbol> TryRehydrateAsync( Solution solution, CancellationToken cancellationToken) { var projectId = ProjectId; var project = solution.GetProject(projectId); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); // The server and client should both be talking about the same compilation. As such // locations in symbols are save to resolve as we rehydrate the SymbolKey. var symbol = SymbolKey.ResolveString( SymbolKeyData, compilation, out var failureReason, cancellationToken).GetAnySymbol(); if (symbol == null) { try { throw new InvalidOperationException( $"We should always be able to resolve a symbol back on the host side:\r\n{project.Name}\r\n{SymbolKeyData}\r\n{failureReason}"); } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { return null; } } return symbol; } } [DataContract] internal readonly struct SerializableReferenceLocation { [DataMember(Order = 0)] public readonly DocumentId Document; [DataMember(Order = 1)] public readonly SerializableSymbolAndProjectId Alias; [DataMember(Order = 2)] public readonly TextSpan Location; [DataMember(Order = 3)] public readonly bool IsImplicit; [DataMember(Order = 4)] public readonly SymbolUsageInfo SymbolUsageInfo; [DataMember(Order = 5)] public readonly ImmutableDictionary<string, string> AdditionalProperties; [DataMember(Order = 6)] public readonly CandidateReason CandidateReason; public SerializableReferenceLocation( DocumentId document, SerializableSymbolAndProjectId alias, TextSpan location, bool isImplicit, SymbolUsageInfo symbolUsageInfo, ImmutableDictionary<string, string> additionalProperties, CandidateReason candidateReason) { Document = document; Alias = alias; Location = location; IsImplicit = isImplicit; SymbolUsageInfo = symbolUsageInfo; AdditionalProperties = additionalProperties; CandidateReason = candidateReason; } public static SerializableReferenceLocation Dehydrate( ReferenceLocation referenceLocation, CancellationToken cancellationToken) { return new SerializableReferenceLocation( referenceLocation.Document.Id, SerializableSymbolAndProjectId.Dehydrate(referenceLocation.Alias, referenceLocation.Document, cancellationToken), referenceLocation.Location.SourceSpan, referenceLocation.IsImplicit, referenceLocation.SymbolUsageInfo, referenceLocation.AdditionalProperties, referenceLocation.CandidateReason); } public async Task<ReferenceLocation> RehydrateAsync( Solution solution, CancellationToken cancellationToken) { var document = await solution.GetDocumentAsync(this.Document, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var aliasSymbol = await RehydrateAliasAsync(solution, cancellationToken).ConfigureAwait(false); var additionalProperties = this.AdditionalProperties; return new ReferenceLocation( document, aliasSymbol, CodeAnalysis.Location.Create(syntaxTree, Location), isImplicit: IsImplicit, symbolUsageInfo: SymbolUsageInfo, additionalProperties: additionalProperties ?? ImmutableDictionary<string, string>.Empty, candidateReason: CandidateReason); } private async Task<IAliasSymbol> RehydrateAliasAsync( Solution solution, CancellationToken cancellationToken) { if (Alias == null) return null; var symbol = await Alias.TryRehydrateAsync(solution, cancellationToken).ConfigureAwait(false); return symbol as IAliasSymbol; } } [DataContract] internal class SerializableSymbolGroup : IEquatable<SerializableSymbolGroup> { [DataMember(Order = 0)] public readonly HashSet<SerializableSymbolAndProjectId> Symbols; private int _hashCode; public SerializableSymbolGroup(HashSet<SerializableSymbolAndProjectId> symbols) { Symbols = new HashSet<SerializableSymbolAndProjectId>(symbols); } public override bool Equals(object obj) => obj is SerializableSymbolGroup group && Equals(group); public bool Equals(SerializableSymbolGroup other) { if (this == other) return true; return other != null && this.Symbols.SetEquals(other.Symbols); } public override int GetHashCode() { if (_hashCode == 0) { var hashCode = 0; foreach (var symbol in Symbols) hashCode += symbol.SymbolKeyData.GetHashCode(); _hashCode = hashCode; } return _hashCode; } public static SerializableSymbolGroup Dehydrate(Solution solution, SymbolGroup group, CancellationToken cancellationToken) { return new SerializableSymbolGroup(new HashSet<SerializableSymbolAndProjectId>( group.Symbols.Select(s => SerializableSymbolAndProjectId.Dehydrate(solution, s, cancellationToken)))); } } #endregion }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Features/Core/Portable/QuickInfo/ExportQuickInfoProviderAttribute.cs
// Licensed to the .NET Foundation under one or more 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.Composition; namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// Use this attribute to export a <see cref="QuickInfoProvider"/> so that it will /// be found and used by the per language associated <see cref="QuickInfoService"/>. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal sealed class ExportQuickInfoProviderAttribute : ExportAttribute { public string Name { get; } public string Language { get; } public ExportQuickInfoProviderAttribute(string name, string language) : base(typeof(QuickInfoProvider)) { Name = name ?? throw new ArgumentNullException(nameof(name)); Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// Use this attribute to export a <see cref="QuickInfoProvider"/> so that it will /// be found and used by the per language associated <see cref="QuickInfoService"/>. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal sealed class ExportQuickInfoProviderAttribute : ExportAttribute { public string Name { get; } public string Language { get; } public ExportQuickInfoProviderAttribute(string name, string language) : base(typeof(QuickInfoProvider)) { Name = name ?? throw new ArgumentNullException(nameof(name)); Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Features/CSharp/Portable/Completion/CompletionProviders/AttributeNamedParameterCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(AttributeNamedParameterCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(FirstBuiltInCompletionProvider))] [Shared] internal class AttributeNamedParameterCompletionProvider : LSPCompletionProvider { private const string EqualsString = "="; private const string SpaceEqualsString = " ="; private const string ColonString = ":"; private static readonly CompletionItemRules _spaceItemFilterRule = CompletionItemRules.Default.WithFilterCharacterRule( CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, ' ')); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AttributeNamedParameterCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters; public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.IsInNonUserCode(position, cancellationToken)) { return; } var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (!token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken)) { return; } if (token.Parent.Parent is not AttributeSyntax attributeSyntax || token.Parent is not AttributeArgumentListSyntax attributeArgumentList) { return; } if (IsAfterNameColonArgument(token) || IsAfterNameEqualsArgument(token)) { context.IsExclusive = true; } // We actually want to collect two sets of named parameters to present the user. The // normal named parameters that come from the attribute constructors. These will be // presented like "goo:". And also the named parameters that come from the writable // fields/properties in the attribute. These will be presented like "bar =". var existingNamedParameters = GetExistingNamedParameters(attributeArgumentList, position); var workspace = document.Project.Solution.Workspace; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(attributeSyntax, cancellationToken).ConfigureAwait(false); var nameColonItems = await GetNameColonItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false); var nameEqualsItems = await GetNameEqualsItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false); context.AddItems(nameEqualsItems); // If we're after a name= parameter, then we only want to show name= parameters. // Otherwise, show name: parameters too. if (!IsAfterNameEqualsArgument(token)) { context.AddItems(nameColonItems); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private static bool IsAfterNameColonArgument(SyntaxToken token) { if (token.Kind() == SyntaxKind.CommaToken && token.Parent is AttributeArgumentListSyntax argumentList) { foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { var node = item.AsNode() as AttributeArgumentSyntax; if (node.NameColon != null) { return true; } } } } return false; } private static bool IsAfterNameEqualsArgument(SyntaxToken token) { if (token.Kind() == SyntaxKind.CommaToken && token.Parent is AttributeArgumentListSyntax argumentList) { foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { var node = item.AsNode() as AttributeArgumentSyntax; if (node.NameEquals != null) { return true; } } } } return false; } private static async Task<ImmutableArray<CompletionItem>> GetNameEqualsItemsAsync( CompletionContext context, SemanticModel semanticModel, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters) { var attributeNamedParameters = GetAttributeNamedParameters(semanticModel, context.Position, attributeSyntax, context.CancellationToken); var unspecifiedNamedParameters = attributeNamedParameters.Where(p => !existingNamedParameters.Contains(p.Name)); var text = await semanticModel.SyntaxTree.GetTextAsync(context.CancellationToken).ConfigureAwait(false); var q = from p in attributeNamedParameters where !existingNamedParameters.Contains(p.Name) select SymbolCompletionItem.CreateWithSymbolId( displayText: p.Name.ToIdentifierToken().ToString(), displayTextSuffix: SpaceEqualsString, insertionText: null, symbols: ImmutableArray.Create(p), contextPosition: token.SpanStart, sortText: p.Name, rules: _spaceItemFilterRule); return q.ToImmutableArray(); } private static async Task<IEnumerable<CompletionItem>> GetNameColonItemsAsync( CompletionContext context, SemanticModel semanticModel, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters) { var parameterLists = GetParameterLists(semanticModel, context.Position, attributeSyntax, context.CancellationToken); parameterLists = parameterLists.Where(pl => IsValid(pl, existingNamedParameters)); var text = await semanticModel.SyntaxTree.GetTextAsync(context.CancellationToken).ConfigureAwait(false); return from pl in parameterLists from p in pl where !existingNamedParameters.Contains(p.Name) select SymbolCompletionItem.CreateWithSymbolId( displayText: p.Name.ToIdentifierToken().ToString(), displayTextSuffix: ColonString, insertionText: null, symbols: ImmutableArray.Create(p), contextPosition: token.SpanStart, sortText: p.Name, rules: CompletionItemRules.Default); } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); private static bool IsValid(ImmutableArray<IParameterSymbol> parameterList, ISet<string> existingNamedParameters) => existingNamedParameters.Except(parameterList.Select(p => p.Name)).IsEmpty(); private static ISet<string> GetExistingNamedParameters(AttributeArgumentListSyntax argumentList, int position) { var existingArguments1 = argumentList.Arguments.Where(a => a.Span.End <= position) .Where(a => a.NameColon != null) .Select(a => a.NameColon.Name.Identifier.ValueText); var existingArguments2 = argumentList.Arguments.Where(a => a.Span.End <= position) .Where(a => a.NameEquals != null) .Select(a => a.NameEquals.Name.Identifier.ValueText); return existingArguments1.Concat(existingArguments2).ToSet(); } private static IEnumerable<ImmutableArray<IParameterSymbol>> GetParameterLists( SemanticModel semanticModel, int position, AttributeSyntax attribute, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within != null && semanticModel.GetTypeInfo(attribute, cancellationToken).Type is INamedTypeSymbol attributeType) { return attributeType.InstanceConstructors.Where(c => c.IsAccessibleWithin(within)) .Select(c => c.Parameters); } return SpecializedCollections.EmptyEnumerable<ImmutableArray<IParameterSymbol>>(); } private static IEnumerable<ISymbol> GetAttributeNamedParameters( SemanticModel semanticModel, int position, AttributeSyntax attribute, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol; return attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within); } protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) => Task.FromResult(GetTextChange(selectedItem, ch)); private static TextChange? GetTextChange(CompletionItem selectedItem, char? ch) { var displayText = selectedItem.DisplayText + selectedItem.DisplayTextSuffix; if (ch != null) { // If user types a space, do not complete the " =" (space and equals) at the end of a named parameter. The // typed space character will be passed through to the editor, and they can then type the '='. if (ch == ' ' && displayText.EndsWith(SpaceEqualsString, StringComparison.Ordinal)) { return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - SpaceEqualsString.Length)); } // If the user types '=', do not complete the '=' at the end of the named parameter because the typed '=' // will be passed through to the editor. if (ch == '=' && displayText.EndsWith(EqualsString, StringComparison.Ordinal)) { return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - EqualsString.Length)); } // If the user types ':', do not complete the ':' at the end of the named parameter because the typed ':' // will be passed through to the editor. if (ch == ':' && displayText.EndsWith(ColonString, StringComparison.Ordinal)) { return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - ColonString.Length)); } } return new TextChange(selectedItem.Span, displayText); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(AttributeNamedParameterCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(FirstBuiltInCompletionProvider))] [Shared] internal class AttributeNamedParameterCompletionProvider : LSPCompletionProvider { private const string EqualsString = "="; private const string SpaceEqualsString = " ="; private const string ColonString = ":"; private static readonly CompletionItemRules _spaceItemFilterRule = CompletionItemRules.Default.WithFilterCharacterRule( CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, ' ')); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AttributeNamedParameterCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters; public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.IsInNonUserCode(position, cancellationToken)) { return; } var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (!token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken)) { return; } if (token.Parent.Parent is not AttributeSyntax attributeSyntax || token.Parent is not AttributeArgumentListSyntax attributeArgumentList) { return; } if (IsAfterNameColonArgument(token) || IsAfterNameEqualsArgument(token)) { context.IsExclusive = true; } // We actually want to collect two sets of named parameters to present the user. The // normal named parameters that come from the attribute constructors. These will be // presented like "goo:". And also the named parameters that come from the writable // fields/properties in the attribute. These will be presented like "bar =". var existingNamedParameters = GetExistingNamedParameters(attributeArgumentList, position); var workspace = document.Project.Solution.Workspace; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(attributeSyntax, cancellationToken).ConfigureAwait(false); var nameColonItems = await GetNameColonItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false); var nameEqualsItems = await GetNameEqualsItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false); context.AddItems(nameEqualsItems); // If we're after a name= parameter, then we only want to show name= parameters. // Otherwise, show name: parameters too. if (!IsAfterNameEqualsArgument(token)) { context.AddItems(nameColonItems); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private static bool IsAfterNameColonArgument(SyntaxToken token) { if (token.Kind() == SyntaxKind.CommaToken && token.Parent is AttributeArgumentListSyntax argumentList) { foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { var node = item.AsNode() as AttributeArgumentSyntax; if (node.NameColon != null) { return true; } } } } return false; } private static bool IsAfterNameEqualsArgument(SyntaxToken token) { if (token.Kind() == SyntaxKind.CommaToken && token.Parent is AttributeArgumentListSyntax argumentList) { foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { var node = item.AsNode() as AttributeArgumentSyntax; if (node.NameEquals != null) { return true; } } } } return false; } private static async Task<ImmutableArray<CompletionItem>> GetNameEqualsItemsAsync( CompletionContext context, SemanticModel semanticModel, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters) { var attributeNamedParameters = GetAttributeNamedParameters(semanticModel, context.Position, attributeSyntax, context.CancellationToken); var unspecifiedNamedParameters = attributeNamedParameters.Where(p => !existingNamedParameters.Contains(p.Name)); var text = await semanticModel.SyntaxTree.GetTextAsync(context.CancellationToken).ConfigureAwait(false); var q = from p in attributeNamedParameters where !existingNamedParameters.Contains(p.Name) select SymbolCompletionItem.CreateWithSymbolId( displayText: p.Name.ToIdentifierToken().ToString(), displayTextSuffix: SpaceEqualsString, insertionText: null, symbols: ImmutableArray.Create(p), contextPosition: token.SpanStart, sortText: p.Name, rules: _spaceItemFilterRule); return q.ToImmutableArray(); } private static async Task<IEnumerable<CompletionItem>> GetNameColonItemsAsync( CompletionContext context, SemanticModel semanticModel, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters) { var parameterLists = GetParameterLists(semanticModel, context.Position, attributeSyntax, context.CancellationToken); parameterLists = parameterLists.Where(pl => IsValid(pl, existingNamedParameters)); var text = await semanticModel.SyntaxTree.GetTextAsync(context.CancellationToken).ConfigureAwait(false); return from pl in parameterLists from p in pl where !existingNamedParameters.Contains(p.Name) select SymbolCompletionItem.CreateWithSymbolId( displayText: p.Name.ToIdentifierToken().ToString(), displayTextSuffix: ColonString, insertionText: null, symbols: ImmutableArray.Create(p), contextPosition: token.SpanStart, sortText: p.Name, rules: CompletionItemRules.Default); } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); private static bool IsValid(ImmutableArray<IParameterSymbol> parameterList, ISet<string> existingNamedParameters) => existingNamedParameters.Except(parameterList.Select(p => p.Name)).IsEmpty(); private static ISet<string> GetExistingNamedParameters(AttributeArgumentListSyntax argumentList, int position) { var existingArguments1 = argumentList.Arguments.Where(a => a.Span.End <= position) .Where(a => a.NameColon != null) .Select(a => a.NameColon.Name.Identifier.ValueText); var existingArguments2 = argumentList.Arguments.Where(a => a.Span.End <= position) .Where(a => a.NameEquals != null) .Select(a => a.NameEquals.Name.Identifier.ValueText); return existingArguments1.Concat(existingArguments2).ToSet(); } private static IEnumerable<ImmutableArray<IParameterSymbol>> GetParameterLists( SemanticModel semanticModel, int position, AttributeSyntax attribute, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within != null && semanticModel.GetTypeInfo(attribute, cancellationToken).Type is INamedTypeSymbol attributeType) { return attributeType.InstanceConstructors.Where(c => c.IsAccessibleWithin(within)) .Select(c => c.Parameters); } return SpecializedCollections.EmptyEnumerable<ImmutableArray<IParameterSymbol>>(); } private static IEnumerable<ISymbol> GetAttributeNamedParameters( SemanticModel semanticModel, int position, AttributeSyntax attribute, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol; return attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within); } protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) => Task.FromResult(GetTextChange(selectedItem, ch)); private static TextChange? GetTextChange(CompletionItem selectedItem, char? ch) { var displayText = selectedItem.DisplayText + selectedItem.DisplayTextSuffix; if (ch != null) { // If user types a space, do not complete the " =" (space and equals) at the end of a named parameter. The // typed space character will be passed through to the editor, and they can then type the '='. if (ch == ' ' && displayText.EndsWith(SpaceEqualsString, StringComparison.Ordinal)) { return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - SpaceEqualsString.Length)); } // If the user types '=', do not complete the '=' at the end of the named parameter because the typed '=' // will be passed through to the editor. if (ch == '=' && displayText.EndsWith(EqualsString, StringComparison.Ordinal)) { return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - EqualsString.Length)); } // If the user types ':', do not complete the ':' at the end of the named parameter because the typed ':' // will be passed through to the editor. if (ch == ':' && displayText.EndsWith(ColonString, StringComparison.Ordinal)) { return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - ColonString.Length)); } } return new TextChange(selectedItem.Span, displayText); } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/EditorFeatures/Test/Collections/Immutable/Maps/MapTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Collections.Immutable.Maps { public class MapTests { [Fact] public void TestEnumerator() { var map = ImmutableDictionary.Create<string, int>().Add("1", 1); foreach (var v in map) { Assert.Equal("1", v.Key); Assert.Equal(1, v.Value); } foreach (var v in (IEnumerable)map) { Assert.Equal("1", ((KeyValuePair<string, int>)v).Key); Assert.Equal(1, ((KeyValuePair<string, int>)v).Value); } } [Fact] public void TestCounts() { var map = ImmutableDictionary.Create<string, int>() .Add("1", 1) .Add("2", 2) .Add("3", 3) .Add("4", 4) .Add("5", 5); Assert.Equal(5, map.Count); Assert.Equal(5, map.Keys.Count()); Assert.Equal(5, map.Values.Count()); } [Fact] public void TestRemove() { var map = ImmutableDictionary.Create<string, int>() .Add("1", 1) .Add("2", 2) .Add("3", 3) .Add("4", 4) .Add("5", 5); map = map.Remove("0"); Assert.Equal(5, map.Count); map = map.Remove("1"); Assert.Equal(4, map.Count); map = map.Remove("1"); Assert.Equal(4, map.Count); map = map.Remove("2"); Assert.Equal(3, map.Count); map = map.Remove("3"); Assert.Equal(2, map.Count); map = map.Remove("4"); Assert.Equal(1, map.Count); map = map.Remove("5"); Assert.Equal(0, map.Count); } [Fact] public void TestPathology() { var map = ImmutableDictionary.Create<string, int>(new PathologicalComparer<string>()) .Add("1", 1) .Add("2", 2) .Add("3", 3) .Add("4", 4) .Add("5", 5); Assert.Equal(5, map.Count); Assert.Equal(1, map["1"]); Assert.Equal(2, map["2"]); Assert.Equal(3, map["3"]); map = map.Remove("0"); Assert.Equal(5, map.Count); map = map.Remove("3"); Assert.Equal(4, map.Count); map = map.Remove("3"); Assert.Equal(4, map.Count); map = map.Remove("2"); Assert.Equal(3, map.Count); map = map.Remove("1"); Assert.Equal(2, map.Count); map = map.Remove("4"); Assert.Equal(1, map.Count); map = map.Remove("6"); Assert.Equal(1, map.Count); map = map.Remove("5"); Assert.Equal(0, map.Count); } private class PathologicalComparer<T> : IEqualityComparer<T> { public bool Equals(T x, T y) => EqualityComparer<T>.Default.Equals(x, y); public int GetHashCode(T obj) => 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Collections.Immutable.Maps { public class MapTests { [Fact] public void TestEnumerator() { var map = ImmutableDictionary.Create<string, int>().Add("1", 1); foreach (var v in map) { Assert.Equal("1", v.Key); Assert.Equal(1, v.Value); } foreach (var v in (IEnumerable)map) { Assert.Equal("1", ((KeyValuePair<string, int>)v).Key); Assert.Equal(1, ((KeyValuePair<string, int>)v).Value); } } [Fact] public void TestCounts() { var map = ImmutableDictionary.Create<string, int>() .Add("1", 1) .Add("2", 2) .Add("3", 3) .Add("4", 4) .Add("5", 5); Assert.Equal(5, map.Count); Assert.Equal(5, map.Keys.Count()); Assert.Equal(5, map.Values.Count()); } [Fact] public void TestRemove() { var map = ImmutableDictionary.Create<string, int>() .Add("1", 1) .Add("2", 2) .Add("3", 3) .Add("4", 4) .Add("5", 5); map = map.Remove("0"); Assert.Equal(5, map.Count); map = map.Remove("1"); Assert.Equal(4, map.Count); map = map.Remove("1"); Assert.Equal(4, map.Count); map = map.Remove("2"); Assert.Equal(3, map.Count); map = map.Remove("3"); Assert.Equal(2, map.Count); map = map.Remove("4"); Assert.Equal(1, map.Count); map = map.Remove("5"); Assert.Equal(0, map.Count); } [Fact] public void TestPathology() { var map = ImmutableDictionary.Create<string, int>(new PathologicalComparer<string>()) .Add("1", 1) .Add("2", 2) .Add("3", 3) .Add("4", 4) .Add("5", 5); Assert.Equal(5, map.Count); Assert.Equal(1, map["1"]); Assert.Equal(2, map["2"]); Assert.Equal(3, map["3"]); map = map.Remove("0"); Assert.Equal(5, map.Count); map = map.Remove("3"); Assert.Equal(4, map.Count); map = map.Remove("3"); Assert.Equal(4, map.Count); map = map.Remove("2"); Assert.Equal(3, map.Count); map = map.Remove("1"); Assert.Equal(2, map.Count); map = map.Remove("4"); Assert.Equal(1, map.Count); map = map.Remove("6"); Assert.Equal(1, map.Count); map = map.Remove("5"); Assert.Equal(0, map.Count); } private class PathologicalComparer<T> : IEqualityComparer<T> { public bool Equals(T x, T y) => EqualityComparer<T>.Default.Equals(x, y); public int GetHashCode(T obj) => 0; } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/EditorFeatures/Core/SymbolSearch/SymbolSearchUpdateEngineFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SymbolSearch { /// <summary> /// Factory that will produce the <see cref="ISymbolSearchUpdateEngine"/>. The default /// implementation produces an engine that will run in-process. Implementations at /// other layers can behave differently (for example, running the engine out-of-process). /// </summary> /// <remarks> /// This returns an No-op engine on non-Windows OS, because the backing storage depends on Windows APIs. /// </remarks> internal static partial class SymbolSearchUpdateEngineFactory { public static async Task<ISymbolSearchUpdateEngine> CreateEngineAsync( Workspace workspace, ISymbolSearchLogService logService, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(workspace, cancellationToken).ConfigureAwait(false); if (client != null) { return new RemoteUpdateEngine(client, logService); } // Couldn't go out of proc. Just do everything inside the current process. return CreateEngineInProcess(); } /// <summary> /// This returns a No-op engine if called on non-Windows OS, because the backing storage depends on Windows APIs. /// </summary> public static ISymbolSearchUpdateEngine CreateEngineInProcess() { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? new SymbolSearchUpdateEngine() : (ISymbolSearchUpdateEngine)new NoOpUpdateEngine(); } private sealed class NoOpUpdateEngine : ISymbolSearchUpdateEngine { public ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) => ValueTaskFactory.FromResult(ImmutableArray<PackageWithAssemblyResult>.Empty); public ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(string source, string name, int arity, CancellationToken cancellationToken) => ValueTaskFactory.FromResult(ImmutableArray<PackageWithTypeResult>.Empty); public ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(string name, int arity, CancellationToken cancellationToken) => ValueTaskFactory.FromResult(ImmutableArray<ReferenceAssemblyWithTypeResult>.Empty); public ValueTask UpdateContinuouslyAsync(string sourceName, string localSettingsDirectory, ISymbolSearchLogService logService, CancellationToken cancellationToken) => default; } private sealed class RemoteUpdateEngine : ISymbolSearchUpdateEngine { private readonly RemoteServiceConnection<IRemoteSymbolSearchUpdateService> _connection; public RemoteUpdateEngine(RemoteHostClient client, ISymbolSearchLogService logService) => _connection = client.CreateConnection<IRemoteSymbolSearchUpdateService>(logService); public void Dispose() => _connection.Dispose(); public async ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(string source, string name, int arity, CancellationToken cancellationToken) { var result = await _connection.TryInvokeAsync<ImmutableArray<PackageWithTypeResult>>( (service, cancellationToken) => service.FindPackagesWithTypeAsync(source, name, arity, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<PackageWithTypeResult>.Empty; } public async ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync( string source, string assemblyName, CancellationToken cancellationToken) { var result = await _connection.TryInvokeAsync<ImmutableArray<PackageWithAssemblyResult>>( (service, cancellationToken) => service.FindPackagesWithAssemblyAsync(source, assemblyName, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<PackageWithAssemblyResult>.Empty; } public async ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync( string name, int arity, CancellationToken cancellationToken) { var result = await _connection.TryInvokeAsync<ImmutableArray<ReferenceAssemblyWithTypeResult>>( (service, cancellationToken) => service.FindReferenceAssembliesWithTypeAsync(name, arity, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ReferenceAssemblyWithTypeResult>.Empty; } public async ValueTask UpdateContinuouslyAsync(string sourceName, string localSettingsDirectory, ISymbolSearchLogService logService, CancellationToken cancellationToken) { // logService parameter is ignored since it's already set on the connection as a callback _ = logService; _ = await _connection.TryInvokeAsync( (service, callbackId, cancellationToken) => service.UpdateContinuouslyAsync(callbackId, sourceName, localSettingsDirectory, cancellationToken), cancellationToken).ConfigureAwait(false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SymbolSearch { /// <summary> /// Factory that will produce the <see cref="ISymbolSearchUpdateEngine"/>. The default /// implementation produces an engine that will run in-process. Implementations at /// other layers can behave differently (for example, running the engine out-of-process). /// </summary> /// <remarks> /// This returns an No-op engine on non-Windows OS, because the backing storage depends on Windows APIs. /// </remarks> internal static partial class SymbolSearchUpdateEngineFactory { public static async Task<ISymbolSearchUpdateEngine> CreateEngineAsync( Workspace workspace, ISymbolSearchLogService logService, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(workspace, cancellationToken).ConfigureAwait(false); if (client != null) { return new RemoteUpdateEngine(client, logService); } // Couldn't go out of proc. Just do everything inside the current process. return CreateEngineInProcess(); } /// <summary> /// This returns a No-op engine if called on non-Windows OS, because the backing storage depends on Windows APIs. /// </summary> public static ISymbolSearchUpdateEngine CreateEngineInProcess() { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? new SymbolSearchUpdateEngine() : (ISymbolSearchUpdateEngine)new NoOpUpdateEngine(); } private sealed class NoOpUpdateEngine : ISymbolSearchUpdateEngine { public ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) => ValueTaskFactory.FromResult(ImmutableArray<PackageWithAssemblyResult>.Empty); public ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(string source, string name, int arity, CancellationToken cancellationToken) => ValueTaskFactory.FromResult(ImmutableArray<PackageWithTypeResult>.Empty); public ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(string name, int arity, CancellationToken cancellationToken) => ValueTaskFactory.FromResult(ImmutableArray<ReferenceAssemblyWithTypeResult>.Empty); public ValueTask UpdateContinuouslyAsync(string sourceName, string localSettingsDirectory, ISymbolSearchLogService logService, CancellationToken cancellationToken) => default; } private sealed class RemoteUpdateEngine : ISymbolSearchUpdateEngine { private readonly RemoteServiceConnection<IRemoteSymbolSearchUpdateService> _connection; public RemoteUpdateEngine(RemoteHostClient client, ISymbolSearchLogService logService) => _connection = client.CreateConnection<IRemoteSymbolSearchUpdateService>(logService); public void Dispose() => _connection.Dispose(); public async ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(string source, string name, int arity, CancellationToken cancellationToken) { var result = await _connection.TryInvokeAsync<ImmutableArray<PackageWithTypeResult>>( (service, cancellationToken) => service.FindPackagesWithTypeAsync(source, name, arity, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<PackageWithTypeResult>.Empty; } public async ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync( string source, string assemblyName, CancellationToken cancellationToken) { var result = await _connection.TryInvokeAsync<ImmutableArray<PackageWithAssemblyResult>>( (service, cancellationToken) => service.FindPackagesWithAssemblyAsync(source, assemblyName, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<PackageWithAssemblyResult>.Empty; } public async ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync( string name, int arity, CancellationToken cancellationToken) { var result = await _connection.TryInvokeAsync<ImmutableArray<ReferenceAssemblyWithTypeResult>>( (service, cancellationToken) => service.FindReferenceAssembliesWithTypeAsync(name, arity, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ReferenceAssemblyWithTypeResult>.Empty; } public async ValueTask UpdateContinuouslyAsync(string sourceName, string localSettingsDirectory, ISymbolSearchLogService logService, CancellationToken cancellationToken) { // logService parameter is ignored since it's already set on the connection as a callback _ = logService; _ = await _connection.TryInvokeAsync( (service, callbackId, cancellationToken) => service.UpdateContinuouslyAsync(callbackId, sourceName, localSettingsDirectory, cancellationToken), cancellationToken).ConfigureAwait(false); } } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxTriviaListExtensions.cs
// Licensed to the .NET Foundation under one or more 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.Shared.Extensions { internal static class SyntaxTriviaListExtensions { public static SyntaxTrivia? FirstOrNull(this SyntaxTriviaList triviaList, Func<SyntaxTrivia, bool> predicate) { foreach (var trivia in triviaList) { if (predicate(trivia)) { return trivia; } } return null; } public static SyntaxTrivia LastOrDefault(this SyntaxTriviaList triviaList) => triviaList.Any() ? triviaList.Last() : 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; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SyntaxTriviaListExtensions { public static SyntaxTrivia? FirstOrNull(this SyntaxTriviaList triviaList, Func<SyntaxTrivia, bool> predicate) { foreach (var trivia in triviaList) { if (predicate(trivia)) { return trivia; } } return null; } public static SyntaxTrivia LastOrDefault(this SyntaxTriviaList triviaList) => triviaList.Any() ? triviaList.Last() : default; } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Compilers/CSharp/Portable/Symbols/Source/SourceParameterSymbolBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class for all parameters that are emitted. /// </summary> internal abstract class SourceParameterSymbolBase : ParameterSymbol { private readonly Symbol _containingSymbol; private readonly ushort _ordinal; public SourceParameterSymbolBase(Symbol containingSymbol, int ordinal) { Debug.Assert((object)containingSymbol != null); _ordinal = (ushort)ordinal; _containingSymbol = containingSymbol; } public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) { if (obj == (object)this) { return true; } if (obj is NativeIntegerParameterSymbol nps) { return nps.Equals(this, compareKind); } var symbol = obj as SourceParameterSymbolBase; return (object)symbol != null && symbol.Ordinal == this.Ordinal && symbol._containingSymbol.Equals(_containingSymbol, compareKind); } public sealed override int GetHashCode() { return Hash.Combine(_containingSymbol.GetHashCode(), this.Ordinal); } public sealed override int Ordinal { get { return _ordinal; } } public sealed override Symbol ContainingSymbol { get { return _containingSymbol; } } public sealed override AssemblySymbol ContainingAssembly { get { return _containingSymbol.ContainingAssembly; } } internal abstract ConstantValue DefaultValueFromAttributes { get; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = this.DeclaringCompilation; if (this.IsParams) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_ParamArrayAttribute__ctor)); } // Synthesize DecimalConstantAttribute if we don't have an explicit custom attribute already: var defaultValue = this.ExplicitDefaultConstantValue; if (defaultValue != ConstantValue.NotAvailable && defaultValue.SpecialType == SpecialType.System_Decimal && DefaultValueFromAttributes == ConstantValue.NotAvailable) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDecimalConstantAttribute(defaultValue.DecimalValue)); } var type = this.TypeWithAnnotations; if (type.Type.ContainsDynamic()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type.Type, type.CustomModifiers.Length + this.RefCustomModifiers.Length, this.RefKind)); } if (type.Type.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type.Type)); } if (type.Type.ContainsTupleNames()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(type.Type)); } if (this.RefKind == RefKind.RefReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, GetNullableContextValue(), type)); } } internal abstract ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class for all parameters that are emitted. /// </summary> internal abstract class SourceParameterSymbolBase : ParameterSymbol { private readonly Symbol _containingSymbol; private readonly ushort _ordinal; public SourceParameterSymbolBase(Symbol containingSymbol, int ordinal) { Debug.Assert((object)containingSymbol != null); _ordinal = (ushort)ordinal; _containingSymbol = containingSymbol; } public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) { if (obj == (object)this) { return true; } if (obj is NativeIntegerParameterSymbol nps) { return nps.Equals(this, compareKind); } var symbol = obj as SourceParameterSymbolBase; return (object)symbol != null && symbol.Ordinal == this.Ordinal && symbol._containingSymbol.Equals(_containingSymbol, compareKind); } public sealed override int GetHashCode() { return Hash.Combine(_containingSymbol.GetHashCode(), this.Ordinal); } public sealed override int Ordinal { get { return _ordinal; } } public sealed override Symbol ContainingSymbol { get { return _containingSymbol; } } public sealed override AssemblySymbol ContainingAssembly { get { return _containingSymbol.ContainingAssembly; } } internal abstract ConstantValue DefaultValueFromAttributes { get; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = this.DeclaringCompilation; if (this.IsParams) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_ParamArrayAttribute__ctor)); } // Synthesize DecimalConstantAttribute if we don't have an explicit custom attribute already: var defaultValue = this.ExplicitDefaultConstantValue; if (defaultValue != ConstantValue.NotAvailable && defaultValue.SpecialType == SpecialType.System_Decimal && DefaultValueFromAttributes == ConstantValue.NotAvailable) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDecimalConstantAttribute(defaultValue.DecimalValue)); } var type = this.TypeWithAnnotations; if (type.Type.ContainsDynamic()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type.Type, type.CustomModifiers.Length + this.RefCustomModifiers.Length, this.RefKind)); } if (type.Type.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type.Type)); } if (type.Type.ContainsTupleNames()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(type.Type)); } if (this.RefKind == RefKind.RefReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, GetNullableContextValue(), type)); } } internal abstract ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams); } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VisualStudioDiagnosticsWindow.vsct.zh-Hant.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../VisualStudioDiagnosticsWindow.vsct"> <body> <trans-unit id="cmdIDRoslynDiagnosticWindow|CommandName"> <source>cmdIDRoslynDiagnosticWindow</source> <target state="translated">cmdIDRoslynDiagnosticWindow</target> <note /> </trans-unit> <trans-unit id="cmdIDRoslynDiagnosticWindow|ButtonText"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 診斷</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../VisualStudioDiagnosticsWindow.vsct"> <body> <trans-unit id="cmdIDRoslynDiagnosticWindow|CommandName"> <source>cmdIDRoslynDiagnosticWindow</source> <target state="translated">cmdIDRoslynDiagnosticWindow</target> <note /> </trans-unit> <trans-unit id="cmdIDRoslynDiagnosticWindow|ButtonText"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 診斷</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Tools/ExternalAccess/FSharp/ExternalAccessFSharpResources.resx
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="AddAssemblyReference" xml:space="preserve"> <value>Add an assembly reference to '{0}'</value> </data> <data name="AddNewKeyword" xml:space="preserve"> <value>Add 'new' keyword</value> </data> <data name="AddProjectReference" xml:space="preserve"> <value>Add a project reference to '{0}'</value> </data> <data name="CannotDetermineSymbol" xml:space="preserve"> <value>Cannot determine the symbol under the caret</value> </data> <data name="CannotNavigateUnknown" xml:space="preserve"> <value>Cannot navigate to the requested location</value> </data> <data name="ExceptionsHeader" xml:space="preserve"> <value>Exceptions:</value> </data> <data name="FSharpDisposablesClassificationType" xml:space="preserve"> <value>F# Disposable Types</value> </data> <data name="FSharpFunctionsOrMethodsClassificationType" xml:space="preserve"> <value>F# Functions / Methods</value> </data> <data name="FSharpMutableVarsClassificationType" xml:space="preserve"> <value>F# Mutable Variables / Reference Cells</value> </data> <data name="FSharpPrintfFormatClassificationType" xml:space="preserve"> <value>F# Printf Format</value> </data> <data name="FSharpPropertiesClassificationType" xml:space="preserve"> <value>F# Properties</value> </data> <data name="GenericParametersHeader" xml:space="preserve"> <value>Generic parameters:</value> </data> <data name="ImplementInterface" xml:space="preserve"> <value>Implement interface</value> </data> <data name="ImplementInterfaceWithoutTypeAnnotation" xml:space="preserve"> <value>Implement interface without type annotation</value> </data> <data name="LocatingSymbol" xml:space="preserve"> <value>Locating the symbol under the caret...</value> </data> <data name="NameCanBeSimplified" xml:space="preserve"> <value>Name can be simplified.</value> </data> <data name="NavigateToFailed" xml:space="preserve"> <value>Navigate to symbol failed: {0}</value> </data> <data name="NavigatingTo" xml:space="preserve"> <value>Navigating to symbol...</value> </data> <data name="PrefixValueNameWithUnderscore" xml:space="preserve"> <value>Prefix '{0}' with underscore</value> </data> <data name="RemoveUnusedOpens" xml:space="preserve"> <value>Remove unused open declarations</value> </data> <data name="RenameValueToDoubleUnderscore" xml:space="preserve"> <value>Rename '{0}' to '__'</value> </data> <data name="RenameValueToUnderscore" xml:space="preserve"> <value>Rename '{0}' to '_'</value> </data> <data name="SimplifyName" xml:space="preserve"> <value>Simplify name</value> </data> <data name="TheValueIsUnused" xml:space="preserve"> <value>The value is unused</value> </data> <data name="UnusedOpens" xml:space="preserve"> <value>Open declaration can be removed.</value> </data> </root>
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="AddAssemblyReference" xml:space="preserve"> <value>Add an assembly reference to '{0}'</value> </data> <data name="AddNewKeyword" xml:space="preserve"> <value>Add 'new' keyword</value> </data> <data name="AddProjectReference" xml:space="preserve"> <value>Add a project reference to '{0}'</value> </data> <data name="CannotDetermineSymbol" xml:space="preserve"> <value>Cannot determine the symbol under the caret</value> </data> <data name="CannotNavigateUnknown" xml:space="preserve"> <value>Cannot navigate to the requested location</value> </data> <data name="ExceptionsHeader" xml:space="preserve"> <value>Exceptions:</value> </data> <data name="FSharpDisposablesClassificationType" xml:space="preserve"> <value>F# Disposable Types</value> </data> <data name="FSharpFunctionsOrMethodsClassificationType" xml:space="preserve"> <value>F# Functions / Methods</value> </data> <data name="FSharpMutableVarsClassificationType" xml:space="preserve"> <value>F# Mutable Variables / Reference Cells</value> </data> <data name="FSharpPrintfFormatClassificationType" xml:space="preserve"> <value>F# Printf Format</value> </data> <data name="FSharpPropertiesClassificationType" xml:space="preserve"> <value>F# Properties</value> </data> <data name="GenericParametersHeader" xml:space="preserve"> <value>Generic parameters:</value> </data> <data name="ImplementInterface" xml:space="preserve"> <value>Implement interface</value> </data> <data name="ImplementInterfaceWithoutTypeAnnotation" xml:space="preserve"> <value>Implement interface without type annotation</value> </data> <data name="LocatingSymbol" xml:space="preserve"> <value>Locating the symbol under the caret...</value> </data> <data name="NameCanBeSimplified" xml:space="preserve"> <value>Name can be simplified.</value> </data> <data name="NavigateToFailed" xml:space="preserve"> <value>Navigate to symbol failed: {0}</value> </data> <data name="NavigatingTo" xml:space="preserve"> <value>Navigating to symbol...</value> </data> <data name="PrefixValueNameWithUnderscore" xml:space="preserve"> <value>Prefix '{0}' with underscore</value> </data> <data name="RemoveUnusedOpens" xml:space="preserve"> <value>Remove unused open declarations</value> </data> <data name="RenameValueToDoubleUnderscore" xml:space="preserve"> <value>Rename '{0}' to '__'</value> </data> <data name="RenameValueToUnderscore" xml:space="preserve"> <value>Rename '{0}' to '_'</value> </data> <data name="SimplifyName" xml:space="preserve"> <value>Simplify name</value> </data> <data name="TheValueIsUnused" xml:space="preserve"> <value>The value is unused</value> </data> <data name="UnusedOpens" xml:space="preserve"> <value>Open declaration can be removed.</value> </data> </root>
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/EditorFeatures/CSharp/Highlighting/KeywordHighlighters/LoopHighlighter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp)] internal class LoopHighlighter : AbstractKeywordHighlighter { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LoopHighlighter() { } protected override bool IsHighlightableNode(SyntaxNode node) => node.IsContinuableConstruct(); protected override void AddHighlightsForNode( SyntaxNode node, List<TextSpan> spans, CancellationToken cancellationToken) { switch (node) { case DoStatementSyntax doStatement: HighlightDoStatement(doStatement, spans); break; case ForStatementSyntax forStatement: HighlightForStatement(forStatement, spans); break; case CommonForEachStatementSyntax forEachStatement: HighlightForEachStatement(forEachStatement, spans); break; case WhileStatementSyntax whileStatement: HighlightWhileStatement(whileStatement, spans); break; } HighlightRelatedKeywords(node, spans, highlightBreaks: true, highlightContinues: true); } private static void HighlightDoStatement(DoStatementSyntax statement, List<TextSpan> spans) { spans.Add(statement.DoKeyword.Span); spans.Add(statement.WhileKeyword.Span); spans.Add(EmptySpan(statement.SemicolonToken.Span.End)); } private static void HighlightForStatement(ForStatementSyntax statement, List<TextSpan> spans) => spans.Add(statement.ForKeyword.Span); private static void HighlightForEachStatement(CommonForEachStatementSyntax statement, List<TextSpan> spans) => spans.Add(statement.ForEachKeyword.Span); private static void HighlightWhileStatement(WhileStatementSyntax statement, List<TextSpan> spans) => spans.Add(statement.WhileKeyword.Span); /// <summary> /// Finds all breaks and continues that are a child of this node, and adds the appropriate spans to the spans list. /// </summary> private void HighlightRelatedKeywords(SyntaxNode node, List<TextSpan> spans, bool highlightBreaks, bool highlightContinues) { Debug.Assert(highlightBreaks || highlightContinues); if (highlightBreaks && node is BreakStatementSyntax breakStatement) { spans.Add(breakStatement.BreakKeyword.Span); spans.Add(EmptySpan(breakStatement.SemicolonToken.Span.End)); } else if (highlightContinues && node is ContinueStatementSyntax continueStatement) { spans.Add(continueStatement.ContinueKeyword.Span); spans.Add(EmptySpan(continueStatement.SemicolonToken.Span.End)); } else { foreach (var child in node.ChildNodes()) { var highlightBreaksForChild = highlightBreaks && !child.IsBreakableConstruct(); var highlightContinuesForChild = highlightContinues && !child.IsContinuableConstruct(); // Only recurse if we have anything to do if (highlightBreaksForChild || highlightContinuesForChild) { HighlightRelatedKeywords(child, spans, highlightBreaksForChild, highlightContinuesForChild); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp)] internal class LoopHighlighter : AbstractKeywordHighlighter { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LoopHighlighter() { } protected override bool IsHighlightableNode(SyntaxNode node) => node.IsContinuableConstruct(); protected override void AddHighlightsForNode( SyntaxNode node, List<TextSpan> spans, CancellationToken cancellationToken) { switch (node) { case DoStatementSyntax doStatement: HighlightDoStatement(doStatement, spans); break; case ForStatementSyntax forStatement: HighlightForStatement(forStatement, spans); break; case CommonForEachStatementSyntax forEachStatement: HighlightForEachStatement(forEachStatement, spans); break; case WhileStatementSyntax whileStatement: HighlightWhileStatement(whileStatement, spans); break; } HighlightRelatedKeywords(node, spans, highlightBreaks: true, highlightContinues: true); } private static void HighlightDoStatement(DoStatementSyntax statement, List<TextSpan> spans) { spans.Add(statement.DoKeyword.Span); spans.Add(statement.WhileKeyword.Span); spans.Add(EmptySpan(statement.SemicolonToken.Span.End)); } private static void HighlightForStatement(ForStatementSyntax statement, List<TextSpan> spans) => spans.Add(statement.ForKeyword.Span); private static void HighlightForEachStatement(CommonForEachStatementSyntax statement, List<TextSpan> spans) => spans.Add(statement.ForEachKeyword.Span); private static void HighlightWhileStatement(WhileStatementSyntax statement, List<TextSpan> spans) => spans.Add(statement.WhileKeyword.Span); /// <summary> /// Finds all breaks and continues that are a child of this node, and adds the appropriate spans to the spans list. /// </summary> private void HighlightRelatedKeywords(SyntaxNode node, List<TextSpan> spans, bool highlightBreaks, bool highlightContinues) { Debug.Assert(highlightBreaks || highlightContinues); if (highlightBreaks && node is BreakStatementSyntax breakStatement) { spans.Add(breakStatement.BreakKeyword.Span); spans.Add(EmptySpan(breakStatement.SemicolonToken.Span.End)); } else if (highlightContinues && node is ContinueStatementSyntax continueStatement) { spans.Add(continueStatement.ContinueKeyword.Span); spans.Add(EmptySpan(continueStatement.SemicolonToken.Span.End)); } else { foreach (var child in node.ChildNodes()) { var highlightBreaksForChild = highlightBreaks && !child.IsBreakableConstruct(); var highlightContinuesForChild = highlightContinues && !child.IsContinuableConstruct(); // Only recurse if we have anything to do if (highlightBreaksForChild || highlightContinuesForChild) { HighlightRelatedKeywords(child, spans, highlightBreaksForChild, highlightContinuesForChild); } } } } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/VisualStudio/IntegrationTest/TestUtilities/Harness/MessageFilter.cs
// Licensed to the .NET Foundation under one or more 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 IMessageFilter = Microsoft.VisualStudio.OLE.Interop.IMessageFilter; using INTERFACEINFO = Microsoft.VisualStudio.OLE.Interop.INTERFACEINFO; using PENDINGMSG = Microsoft.VisualStudio.OLE.Interop.PENDINGMSG; using SERVERCALL = Microsoft.VisualStudio.OLE.Interop.SERVERCALL; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Harness { public sealed class MessageFilter : IMessageFilter, IDisposable { private const uint CancelCall = ~0U; private readonly MessageFilterSafeHandle _messageFilterRegistration; private readonly TimeSpan _timeout; private readonly TimeSpan _retryDelay; public MessageFilter() : this(timeout: TimeSpan.FromSeconds(60), retryDelay: TimeSpan.FromMilliseconds(150)) { } public MessageFilter(TimeSpan timeout, TimeSpan retryDelay) { _timeout = timeout; _retryDelay = retryDelay; _messageFilterRegistration = MessageFilterSafeHandle.Register(this); } public uint HandleInComingCall(uint dwCallType, IntPtr htaskCaller, uint dwTickCount, INTERFACEINFO[] lpInterfaceInfo) { return (uint)SERVERCALL.SERVERCALL_ISHANDLED; } public uint RetryRejectedCall(IntPtr htaskCallee, uint dwTickCount, uint dwRejectType) { if ((SERVERCALL)dwRejectType != SERVERCALL.SERVERCALL_RETRYLATER && (SERVERCALL)dwRejectType != SERVERCALL.SERVERCALL_REJECTED) { return CancelCall; } if (dwTickCount >= _timeout.TotalMilliseconds) { return CancelCall; } return (uint)_retryDelay.TotalMilliseconds; } public uint MessagePending(IntPtr htaskCallee, uint dwTickCount, uint dwPendingType) { return (uint)PENDINGMSG.PENDINGMSG_WAITDEFPROCESS; } public void Dispose() { _messageFilterRegistration.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 IMessageFilter = Microsoft.VisualStudio.OLE.Interop.IMessageFilter; using INTERFACEINFO = Microsoft.VisualStudio.OLE.Interop.INTERFACEINFO; using PENDINGMSG = Microsoft.VisualStudio.OLE.Interop.PENDINGMSG; using SERVERCALL = Microsoft.VisualStudio.OLE.Interop.SERVERCALL; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Harness { public sealed class MessageFilter : IMessageFilter, IDisposable { private const uint CancelCall = ~0U; private readonly MessageFilterSafeHandle _messageFilterRegistration; private readonly TimeSpan _timeout; private readonly TimeSpan _retryDelay; public MessageFilter() : this(timeout: TimeSpan.FromSeconds(60), retryDelay: TimeSpan.FromMilliseconds(150)) { } public MessageFilter(TimeSpan timeout, TimeSpan retryDelay) { _timeout = timeout; _retryDelay = retryDelay; _messageFilterRegistration = MessageFilterSafeHandle.Register(this); } public uint HandleInComingCall(uint dwCallType, IntPtr htaskCaller, uint dwTickCount, INTERFACEINFO[] lpInterfaceInfo) { return (uint)SERVERCALL.SERVERCALL_ISHANDLED; } public uint RetryRejectedCall(IntPtr htaskCallee, uint dwTickCount, uint dwRejectType) { if ((SERVERCALL)dwRejectType != SERVERCALL.SERVERCALL_RETRYLATER && (SERVERCALL)dwRejectType != SERVERCALL.SERVERCALL_REJECTED) { return CancelCall; } if (dwTickCount >= _timeout.TotalMilliseconds) { return CancelCall; } return (uint)_retryDelay.TotalMilliseconds; } public uint MessagePending(IntPtr htaskCallee, uint dwTickCount, uint dwPendingType) { return (uint)PENDINGMSG.PENDINGMSG_WAITDEFPROCESS; } public void Dispose() { _messageFilterRegistration.Dispose(); } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/EditorFeatures/Core/Implementation/Formatting/FormatCommandHandler.FormatDocument.cs
// Licensed to the .NET Foundation under one or more 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.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.Formatting { internal partial class FormatCommandHandler { public CommandState GetCommandState(FormatDocumentCommandArgs args) => GetCommandState(args.SubjectBuffer); public bool ExecuteCommand(FormatDocumentCommandArgs args, CommandExecutionContext context) { if (!CanExecuteCommand(args.SubjectBuffer)) { return false; } var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return false; } var formattingService = document.GetLanguageService<IFormattingInteractionService>(); if (formattingService == null || !formattingService.SupportsFormatDocument) { return false; } using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Formatting_document)) { Format(args.TextView, document, null, context.OperationContext.UserCancellationToken); } 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 Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.Formatting { internal partial class FormatCommandHandler { public CommandState GetCommandState(FormatDocumentCommandArgs args) => GetCommandState(args.SubjectBuffer); public bool ExecuteCommand(FormatDocumentCommandArgs args, CommandExecutionContext context) { if (!CanExecuteCommand(args.SubjectBuffer)) { return false; } var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return false; } var formattingService = document.GetLanguageService<IFormattingInteractionService>(); if (formattingService == null || !formattingService.SupportsFormatDocument) { return false; } using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Formatting_document)) { Format(args.TextView, document, null, context.OperationContext.UserCancellationToken); } return true; } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/EditorFeatures/CSharpTest/KeywordHighlighting/RegionHighlighterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class RegionHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(RegionHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_1() { await TestAsync( @"class C { {|Cursor:[|#region|]|} Main static void Main() { } [|#endregion|] }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_2() { await TestAsync( @"class C { [|#region|] Main static void Main() { } {|Cursor:[|#endregion|]|} }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_1() { await TestAsync( @"class C { {|Cursor:[|#region|]|} Main static void Main() { #region body #endregion } [|#endregion|] }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_2() { await TestAsync( @"class C { #region Main static void Main() { {|Cursor:[|#region|]|} body [|#endregion|] } #endregion }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_3() { await TestAsync( @"class C { #region Main static void Main() { [|#region|] body {|Cursor:[|#endregion|]|} } #endregion }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_4() { await TestAsync( @"class C { [|#region|] Main static void Main() { #region body #endregion } {|Cursor:[|#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.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class RegionHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(RegionHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_1() { await TestAsync( @"class C { {|Cursor:[|#region|]|} Main static void Main() { } [|#endregion|] }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_2() { await TestAsync( @"class C { [|#region|] Main static void Main() { } {|Cursor:[|#endregion|]|} }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_1() { await TestAsync( @"class C { {|Cursor:[|#region|]|} Main static void Main() { #region body #endregion } [|#endregion|] }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_2() { await TestAsync( @"class C { #region Main static void Main() { {|Cursor:[|#region|]|} body [|#endregion|] } #endregion }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_3() { await TestAsync( @"class C { #region Main static void Main() { [|#region|] body {|Cursor:[|#endregion|]|} } #endregion }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_4() { await TestAsync( @"class C { [|#region|] Main static void Main() { #region body #endregion } {|Cursor:[|#endregion|]|} }"); } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Features/Core/Portable/SolutionCrawler/SolutionCrawlerRegistrationService.cs
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { [ExportWorkspaceService(typeof(ISolutionCrawlerRegistrationService), ServiceLayer.Host), Shared] internal partial class SolutionCrawlerRegistrationService : ISolutionCrawlerRegistrationService { private const string Default = "*"; private readonly object _gate; private readonly SolutionCrawlerProgressReporter _progressReporter; private readonly IAsynchronousOperationListener _listener; private readonly Dictionary<Workspace, WorkCoordinator> _documentWorkCoordinatorMap; private ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> _analyzerProviders; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SolutionCrawlerRegistrationService( [ImportMany] IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders, IAsynchronousOperationListenerProvider listenerProvider) { _gate = new object(); _analyzerProviders = analyzerProviders.GroupBy(kv => kv.Metadata.Name).ToImmutableDictionary(g => g.Key, g => g.ToImmutableArray()); AssertAnalyzerProviders(_analyzerProviders); _documentWorkCoordinatorMap = new Dictionary<Workspace, WorkCoordinator>(ReferenceEqualityComparer.Instance); _listener = listenerProvider.GetListener(FeatureAttribute.SolutionCrawler); _progressReporter = new SolutionCrawlerProgressReporter(); } public void Register(Workspace workspace) => EnsureRegistration(workspace, initializeLazily: true); /// <summary> /// make sure solution cralwer is registered for the given workspace. /// </summary> /// <param name="workspace"><see cref="Workspace"/> this solution crawler runs for</param> /// <param name="initializeLazily"> /// when true, solution crawler will be initialized when there is the first workspace event fired. /// otherwise, it will be initialized when workspace is registered right away. /// something like "Build" will use initializeLazily:false to make sure diagnostic analyzer engine (incremental analyzer) /// is initialized. otherwise, if build is called before workspace is fully populated, we will think some errors from build /// doesn't belong to us since diagnostic analyzer engine is not there yet and /// let project system to take care of these unknown errors. /// </param> public void EnsureRegistration(Workspace workspace, bool initializeLazily) { Contract.ThrowIfNull(workspace.Kind); var correlationId = LogAggregator.GetNextId(); lock (_gate) { if (_documentWorkCoordinatorMap.ContainsKey(workspace)) { // already registered. return; } var coordinator = new WorkCoordinator( _listener, GetAnalyzerProviders(workspace.Kind), initializeLazily, new Registration(correlationId, workspace, _progressReporter)); _documentWorkCoordinatorMap.Add(workspace, coordinator); } SolutionCrawlerLogger.LogRegistration(correlationId, workspace); } public void Unregister(Workspace workspace, bool blockingShutdown = false) { WorkCoordinator? coordinator; lock (_gate) { if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out coordinator)) { // already unregistered return; } _documentWorkCoordinatorMap.Remove(workspace); coordinator.Shutdown(blockingShutdown); } SolutionCrawlerLogger.LogUnregistration(coordinator.CorrelationId); } public void AddAnalyzerProvider(IIncrementalAnalyzerProvider provider, IncrementalAnalyzerProviderMetadata metadata) { // now update all existing work coordinator lock (_gate) { var lazyProvider = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => provider, metadata); // update existing map for future solution crawler registration - no need for interlock but this makes add or update easier ImmutableInterlocked.AddOrUpdate(ref _analyzerProviders, metadata.Name, n => ImmutableArray.Create(lazyProvider), (n, v) => v.Add(lazyProvider)); // assert map integrity AssertAnalyzerProviders(_analyzerProviders); // find existing coordinator to update var lazyProviders = _analyzerProviders[metadata.Name]; foreach (var (workspace, coordinator) in _documentWorkCoordinatorMap) { Contract.ThrowIfNull(workspace.Kind); if (!TryGetProvider(workspace.Kind, lazyProviders, out var picked) || picked != lazyProvider) { // check whether new provider belong to current workspace continue; } var analyzer = lazyProvider.Value.CreateIncrementalAnalyzer(workspace); if (analyzer != null) { coordinator.AddAnalyzer(analyzer, metadata.HighPriorityForActiveFile); } } } } public void Reanalyze(Workspace workspace, IIncrementalAnalyzer analyzer, IEnumerable<ProjectId>? projectIds, IEnumerable<DocumentId>? documentIds, bool highPriority) { lock (_gate) { if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out var coordinator)) { // this can happen if solution crawler is already unregistered from workspace. // one of those example will be VS shutting down so roslyn package is disposed but there is a pending // async operation. return; } // no specific projects or documents provided if (projectIds == null && documentIds == null) { coordinator.Reanalyze(analyzer, new ReanalyzeScope(workspace.CurrentSolution.Id), highPriority); return; } coordinator.Reanalyze(analyzer, new ReanalyzeScope(projectIds, documentIds), highPriority); } } private IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> GetAnalyzerProviders(string workspaceKind) { foreach (var (_, lazyProviders) in _analyzerProviders) { // try get provider for the specific workspace kind if (TryGetProvider(workspaceKind, lazyProviders, out var lazyProvider)) { yield return lazyProvider; continue; } // try get default provider if (TryGetProvider(Default, lazyProviders, out lazyProvider)) { yield return lazyProvider; } } } private static bool TryGetProvider( string kind, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> lazyProviders, [NotNullWhen(true)] out Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>? lazyProvider) { // set out param lazyProvider = null; // try find provider for specific workspace kind if (kind != Default) { foreach (var provider in lazyProviders) { if (provider.Metadata.WorkspaceKinds?.Any(wk => wk == kind) == true) { lazyProvider = provider; return true; } } return false; } // try find default provider foreach (var provider in lazyProviders) { if (IsDefaultProvider(provider.Metadata)) { lazyProvider = provider; return true; } return false; } return false; } [Conditional("DEBUG")] private static void AssertAnalyzerProviders( ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> analyzerProviders) { #if DEBUG // make sure there is duplicated provider defined for same workspace. var set = new HashSet<string>(); foreach (var kv in analyzerProviders) { foreach (var lazyProvider in kv.Value) { if (IsDefaultProvider(lazyProvider.Metadata)) { Debug.Assert(set.Add(Default)); continue; } foreach (var kind in lazyProvider.Metadata.WorkspaceKinds!) { Debug.Assert(set.Add(kind)); } } set.Clear(); } #endif } private static bool IsDefaultProvider(IncrementalAnalyzerProviderMetadata providerMetadata) => providerMetadata.WorkspaceKinds == null || providerMetadata.WorkspaceKinds.Count == 0; internal TestAccessor GetTestAccessor() { return new TestAccessor(this); } internal readonly struct TestAccessor { private readonly SolutionCrawlerRegistrationService _solutionCrawlerRegistrationService; internal TestAccessor(SolutionCrawlerRegistrationService solutionCrawlerRegistrationService) { _solutionCrawlerRegistrationService = solutionCrawlerRegistrationService; } internal ref ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> AnalyzerProviders => ref _solutionCrawlerRegistrationService._analyzerProviders; internal bool TryGetWorkCoordinator(Workspace workspace, [NotNullWhen(true)] out WorkCoordinator? coordinator) { lock (_solutionCrawlerRegistrationService._gate) { return _solutionCrawlerRegistrationService._documentWorkCoordinatorMap.TryGetValue(workspace, out coordinator); } } internal void WaitUntilCompletion(Workspace workspace, ImmutableArray<IIncrementalAnalyzer> workers) { if (TryGetWorkCoordinator(workspace, out var coordinator)) { coordinator.GetTestAccessor().WaitUntilCompletion(workers); } } internal void WaitUntilCompletion(Workspace workspace) { if (TryGetWorkCoordinator(workspace, out var coordinator)) { coordinator.GetTestAccessor().WaitUntilCompletion(); } } } internal sealed class Registration { public readonly int CorrelationId; public readonly Workspace Workspace; public readonly SolutionCrawlerProgressReporter ProgressReporter; public Registration(int correlationId, Workspace workspace, SolutionCrawlerProgressReporter progressReporter) { CorrelationId = correlationId; Workspace = workspace; ProgressReporter = progressReporter; } public Solution GetSolutionToAnalyze() => Workspace.CurrentSolution; } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { [ExportWorkspaceService(typeof(ISolutionCrawlerRegistrationService), ServiceLayer.Host), Shared] internal partial class SolutionCrawlerRegistrationService : ISolutionCrawlerRegistrationService { private const string Default = "*"; private readonly object _gate; private readonly SolutionCrawlerProgressReporter _progressReporter; private readonly IAsynchronousOperationListener _listener; private readonly Dictionary<Workspace, WorkCoordinator> _documentWorkCoordinatorMap; private ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> _analyzerProviders; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SolutionCrawlerRegistrationService( [ImportMany] IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders, IAsynchronousOperationListenerProvider listenerProvider) { _gate = new object(); _analyzerProviders = analyzerProviders.GroupBy(kv => kv.Metadata.Name).ToImmutableDictionary(g => g.Key, g => g.ToImmutableArray()); AssertAnalyzerProviders(_analyzerProviders); _documentWorkCoordinatorMap = new Dictionary<Workspace, WorkCoordinator>(ReferenceEqualityComparer.Instance); _listener = listenerProvider.GetListener(FeatureAttribute.SolutionCrawler); _progressReporter = new SolutionCrawlerProgressReporter(); } public void Register(Workspace workspace) => EnsureRegistration(workspace, initializeLazily: true); /// <summary> /// make sure solution cralwer is registered for the given workspace. /// </summary> /// <param name="workspace"><see cref="Workspace"/> this solution crawler runs for</param> /// <param name="initializeLazily"> /// when true, solution crawler will be initialized when there is the first workspace event fired. /// otherwise, it will be initialized when workspace is registered right away. /// something like "Build" will use initializeLazily:false to make sure diagnostic analyzer engine (incremental analyzer) /// is initialized. otherwise, if build is called before workspace is fully populated, we will think some errors from build /// doesn't belong to us since diagnostic analyzer engine is not there yet and /// let project system to take care of these unknown errors. /// </param> public void EnsureRegistration(Workspace workspace, bool initializeLazily) { Contract.ThrowIfNull(workspace.Kind); var correlationId = LogAggregator.GetNextId(); lock (_gate) { if (_documentWorkCoordinatorMap.ContainsKey(workspace)) { // already registered. return; } var coordinator = new WorkCoordinator( _listener, GetAnalyzerProviders(workspace.Kind), initializeLazily, new Registration(correlationId, workspace, _progressReporter)); _documentWorkCoordinatorMap.Add(workspace, coordinator); } SolutionCrawlerLogger.LogRegistration(correlationId, workspace); } public void Unregister(Workspace workspace, bool blockingShutdown = false) { WorkCoordinator? coordinator; lock (_gate) { if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out coordinator)) { // already unregistered return; } _documentWorkCoordinatorMap.Remove(workspace); coordinator.Shutdown(blockingShutdown); } SolutionCrawlerLogger.LogUnregistration(coordinator.CorrelationId); } public void AddAnalyzerProvider(IIncrementalAnalyzerProvider provider, IncrementalAnalyzerProviderMetadata metadata) { // now update all existing work coordinator lock (_gate) { var lazyProvider = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => provider, metadata); // update existing map for future solution crawler registration - no need for interlock but this makes add or update easier ImmutableInterlocked.AddOrUpdate(ref _analyzerProviders, metadata.Name, n => ImmutableArray.Create(lazyProvider), (n, v) => v.Add(lazyProvider)); // assert map integrity AssertAnalyzerProviders(_analyzerProviders); // find existing coordinator to update var lazyProviders = _analyzerProviders[metadata.Name]; foreach (var (workspace, coordinator) in _documentWorkCoordinatorMap) { Contract.ThrowIfNull(workspace.Kind); if (!TryGetProvider(workspace.Kind, lazyProviders, out var picked) || picked != lazyProvider) { // check whether new provider belong to current workspace continue; } var analyzer = lazyProvider.Value.CreateIncrementalAnalyzer(workspace); if (analyzer != null) { coordinator.AddAnalyzer(analyzer, metadata.HighPriorityForActiveFile); } } } } public void Reanalyze(Workspace workspace, IIncrementalAnalyzer analyzer, IEnumerable<ProjectId>? projectIds, IEnumerable<DocumentId>? documentIds, bool highPriority) { lock (_gate) { if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out var coordinator)) { // this can happen if solution crawler is already unregistered from workspace. // one of those example will be VS shutting down so roslyn package is disposed but there is a pending // async operation. return; } // no specific projects or documents provided if (projectIds == null && documentIds == null) { coordinator.Reanalyze(analyzer, new ReanalyzeScope(workspace.CurrentSolution.Id), highPriority); return; } coordinator.Reanalyze(analyzer, new ReanalyzeScope(projectIds, documentIds), highPriority); } } private IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> GetAnalyzerProviders(string workspaceKind) { foreach (var (_, lazyProviders) in _analyzerProviders) { // try get provider for the specific workspace kind if (TryGetProvider(workspaceKind, lazyProviders, out var lazyProvider)) { yield return lazyProvider; continue; } // try get default provider if (TryGetProvider(Default, lazyProviders, out lazyProvider)) { yield return lazyProvider; } } } private static bool TryGetProvider( string kind, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> lazyProviders, [NotNullWhen(true)] out Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>? lazyProvider) { // set out param lazyProvider = null; // try find provider for specific workspace kind if (kind != Default) { foreach (var provider in lazyProviders) { if (provider.Metadata.WorkspaceKinds?.Any(wk => wk == kind) == true) { lazyProvider = provider; return true; } } return false; } // try find default provider foreach (var provider in lazyProviders) { if (IsDefaultProvider(provider.Metadata)) { lazyProvider = provider; return true; } return false; } return false; } [Conditional("DEBUG")] private static void AssertAnalyzerProviders( ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> analyzerProviders) { #if DEBUG // make sure there is duplicated provider defined for same workspace. var set = new HashSet<string>(); foreach (var kv in analyzerProviders) { foreach (var lazyProvider in kv.Value) { if (IsDefaultProvider(lazyProvider.Metadata)) { Debug.Assert(set.Add(Default)); continue; } foreach (var kind in lazyProvider.Metadata.WorkspaceKinds!) { Debug.Assert(set.Add(kind)); } } set.Clear(); } #endif } private static bool IsDefaultProvider(IncrementalAnalyzerProviderMetadata providerMetadata) => providerMetadata.WorkspaceKinds == null || providerMetadata.WorkspaceKinds.Count == 0; internal TestAccessor GetTestAccessor() { return new TestAccessor(this); } internal readonly struct TestAccessor { private readonly SolutionCrawlerRegistrationService _solutionCrawlerRegistrationService; internal TestAccessor(SolutionCrawlerRegistrationService solutionCrawlerRegistrationService) { _solutionCrawlerRegistrationService = solutionCrawlerRegistrationService; } internal ref ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> AnalyzerProviders => ref _solutionCrawlerRegistrationService._analyzerProviders; internal bool TryGetWorkCoordinator(Workspace workspace, [NotNullWhen(true)] out WorkCoordinator? coordinator) { lock (_solutionCrawlerRegistrationService._gate) { return _solutionCrawlerRegistrationService._documentWorkCoordinatorMap.TryGetValue(workspace, out coordinator); } } internal void WaitUntilCompletion(Workspace workspace, ImmutableArray<IIncrementalAnalyzer> workers) { if (TryGetWorkCoordinator(workspace, out var coordinator)) { coordinator.GetTestAccessor().WaitUntilCompletion(workers); } } internal void WaitUntilCompletion(Workspace workspace) { if (TryGetWorkCoordinator(workspace, out var coordinator)) { coordinator.GetTestAccessor().WaitUntilCompletion(); } } } internal sealed class Registration { public readonly int CorrelationId; public readonly Workspace Workspace; public readonly SolutionCrawlerProgressReporter ProgressReporter; public Registration(int correlationId, Workspace workspace, SolutionCrawlerProgressReporter progressReporter) { CorrelationId = correlationId; Workspace = workspace; ProgressReporter = progressReporter; } public Solution GetSolutionToAnalyze() => Workspace.CurrentSolution; } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/xlf/VisualBasicWorkspaceExtensionsResources.it.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../VisualBasicWorkspaceExtensionsResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Rimuovere questo valore quando ne viene aggiunto un altro.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../VisualBasicWorkspaceExtensionsResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Rimuovere questo valore quando ne viene aggiunto un altro.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Compilers/CSharp/Portable/Syntax/ArgumentSyntax.cs
// Licensed to the .NET Foundation under one or more 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.ComponentModel; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public sealed partial class ArgumentSyntax { /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement property <see cref="RefKindKeyword"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public SyntaxToken RefOrOutKeyword { get => this.RefKindKeyword; } /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement method <see cref="Update"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public ArgumentSyntax WithRefOrOutKeyword(SyntaxToken refOrOutKeyword) { return this.Update(this.NameColon, refOrOutKeyword, this.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. using System.ComponentModel; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public sealed partial class ArgumentSyntax { /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement property <see cref="RefKindKeyword"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public SyntaxToken RefOrOutKeyword { get => this.RefKindKeyword; } /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement method <see cref="Update"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public ArgumentSyntax WithRefOrOutKeyword(SyntaxToken refOrOutKeyword) { return this.Update(this.NameColon, refOrOutKeyword, this.Expression); } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Features/Core/Portable/Debugging/DebugMode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Debugging { internal enum DebugMode { Design, Break, Run } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Debugging { internal enum DebugMode { Design, Break, Run } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Features/Lsif/GeneratorTest/Utilities/TestLsifJsonWriter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.Utilities ''' <summary> ''' A implementation of <see cref="ILsifJsonWriter" /> for use in unit tests. It does additional validation of the ''' correctness of the output, And stores the entire output And offers useful helpers to inspect the result. ''' </summary> Friend Class TestLsifJsonWriter Implements ILsifJsonWriter Private ReadOnly _gate As Object = New Object() Private ReadOnly _elementsById As Dictionary(Of Id(Of Element), Element) = New Dictionary(Of Id(Of Element), Element) Private ReadOnly _edgesByOutVertex As Dictionary(Of Vertex, List(Of Edge)) = New Dictionary(Of Vertex, List(Of Edge)) Private Sub ILsifJsonWriter_WriteAll(elements As List(Of Element)) Implements ILsifJsonWriter.WriteAll For Each element In elements ILsifJsonWriter_Write(element) Next End Sub Private Sub ILsifJsonWriter_Write(element As Element) Implements ILsifJsonWriter.Write SyncLock _gate ' We intentionally use Add so it'll throw if we have a duplicate ID. _elementsById.Add(element.Id, element) Dim edge = TryCast(element, Edge) If edge IsNot Nothing Then ' Fetch all the out And in vertices, which validates they exist. This ensures we satisfy the rule ' that an edge can only be written after all the vertices it writes to already exist. Dim outVertex = GetElementById(edge.OutVertex) For Each inVertexId In edge.InVertices ' We are ignoring the return, but this call implicitly validates the element ' exists and is of the correct type. GetElementById(inVertexId) Next ' Record the edge in a map of edges exiting this outVertex. We could do a nested Dictionary ' for this but that seems a bit expensive when many nodes may only have one item. Dim edgesForOutVertex As List(Of Edge) = Nothing If Not _edgesByOutVertex.TryGetValue(outVertex, edgesForOutVertex) Then edgesForOutVertex = New List(Of Edge)(capacity:=1) _edgesByOutVertex.Add(outVertex, edgesForOutVertex) End If ' It's possible to have more than one item edge, but for anything else we really only expect one. If edge.Label <> "item" Then If (edgesForOutVertex.Any(Function(e) e.Label = edge.Label)) Then Throw New InvalidOperationException($"The outVertex {outVertex} already has an edge with label {edge.Label}.") End If End If edgesForOutVertex.Add(edge) End If End SyncLock End Sub ''' <summary> ''' Returns all the vertices linked to the given vertex by the edge type. ''' </summary> Public Function GetLinkedVertices(Of T As Vertex)(vertex As Graph.Vertex, edgeLabel As String) As ImmutableArray(Of T) SyncLock _gate Dim builder = ImmutableArray.CreateBuilder(Of T) Dim edges As List(Of Edge) = Nothing If _edgesByOutVertex.TryGetValue(vertex, edges) Then Dim inVerticesId = edges.Where(Function(e) e.Label = edgeLabel).SelectMany(Function(e) e.InVertices) For Each inVertexId In inVerticesId ' This is an unsafe "cast" if you will converting the ID to the expected type; ' GetElementById checks the real vertex type so thta will stay safe in the end. builder.Add(GetElementById(Of T)(New Id(Of T)(inVertexId.NumericId))) Next End If Return builder.ToImmutable() End SyncLock End Function Public ReadOnly Property Vertices As ImmutableArray(Of Vertex) Get SyncLock _gate Return _elementsById.Values.OfType(Of Vertex).ToImmutableArray() End SyncLock End Get End Property Public Function GetElementById(Of T As Element)(id As Id(Of T)) As T SyncLock _gate Dim element As Element = Nothing ' TODO: why am I unable to use the extension method As here? If Not _elementsById.TryGetValue(New Id(Of Element)(id.NumericId), element) Then Throw New Exception($"Element {id} could not be found.") End If Return Assert.IsAssignableFrom(Of T)(element) End SyncLock End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.Utilities ''' <summary> ''' A implementation of <see cref="ILsifJsonWriter" /> for use in unit tests. It does additional validation of the ''' correctness of the output, And stores the entire output And offers useful helpers to inspect the result. ''' </summary> Friend Class TestLsifJsonWriter Implements ILsifJsonWriter Private ReadOnly _gate As Object = New Object() Private ReadOnly _elementsById As Dictionary(Of Id(Of Element), Element) = New Dictionary(Of Id(Of Element), Element) Private ReadOnly _edgesByOutVertex As Dictionary(Of Vertex, List(Of Edge)) = New Dictionary(Of Vertex, List(Of Edge)) Private Sub ILsifJsonWriter_WriteAll(elements As List(Of Element)) Implements ILsifJsonWriter.WriteAll For Each element In elements ILsifJsonWriter_Write(element) Next End Sub Private Sub ILsifJsonWriter_Write(element As Element) Implements ILsifJsonWriter.Write SyncLock _gate ' We intentionally use Add so it'll throw if we have a duplicate ID. _elementsById.Add(element.Id, element) Dim edge = TryCast(element, Edge) If edge IsNot Nothing Then ' Fetch all the out And in vertices, which validates they exist. This ensures we satisfy the rule ' that an edge can only be written after all the vertices it writes to already exist. Dim outVertex = GetElementById(edge.OutVertex) For Each inVertexId In edge.InVertices ' We are ignoring the return, but this call implicitly validates the element ' exists and is of the correct type. GetElementById(inVertexId) Next ' Record the edge in a map of edges exiting this outVertex. We could do a nested Dictionary ' for this but that seems a bit expensive when many nodes may only have one item. Dim edgesForOutVertex As List(Of Edge) = Nothing If Not _edgesByOutVertex.TryGetValue(outVertex, edgesForOutVertex) Then edgesForOutVertex = New List(Of Edge)(capacity:=1) _edgesByOutVertex.Add(outVertex, edgesForOutVertex) End If ' It's possible to have more than one item edge, but for anything else we really only expect one. If edge.Label <> "item" Then If (edgesForOutVertex.Any(Function(e) e.Label = edge.Label)) Then Throw New InvalidOperationException($"The outVertex {outVertex} already has an edge with label {edge.Label}.") End If End If edgesForOutVertex.Add(edge) End If End SyncLock End Sub ''' <summary> ''' Returns all the vertices linked to the given vertex by the edge type. ''' </summary> Public Function GetLinkedVertices(Of T As Vertex)(vertex As Graph.Vertex, edgeLabel As String) As ImmutableArray(Of T) SyncLock _gate Dim builder = ImmutableArray.CreateBuilder(Of T) Dim edges As List(Of Edge) = Nothing If _edgesByOutVertex.TryGetValue(vertex, edges) Then Dim inVerticesId = edges.Where(Function(e) e.Label = edgeLabel).SelectMany(Function(e) e.InVertices) For Each inVertexId In inVerticesId ' This is an unsafe "cast" if you will converting the ID to the expected type; ' GetElementById checks the real vertex type so thta will stay safe in the end. builder.Add(GetElementById(Of T)(New Id(Of T)(inVertexId.NumericId))) Next End If Return builder.ToImmutable() End SyncLock End Function Public ReadOnly Property Vertices As ImmutableArray(Of Vertex) Get SyncLock _gate Return _elementsById.Values.OfType(Of Vertex).ToImmutableArray() End SyncLock End Get End Property Public Function GetElementById(Of T As Element)(id As Id(Of T)) As T SyncLock _gate Dim element As Element = Nothing ' TODO: why am I unable to use the extension method As here? If Not _elementsById.TryGetValue(New Id(Of Element)(id.NumericId), element) Then Throw New Exception($"Element {id} could not be found.") End If Return Assert.IsAssignableFrom(Of T)(element) End SyncLock End Function End Class End Namespace
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFindUsagesService.cs
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.ExternalAccess.VSTypeScript { [ExportLanguageService(typeof(IFindUsagesService), InternalLanguageNames.TypeScript), Shared] internal class VSTypeScriptFindUsagesService : IFindUsagesService { private readonly IVSTypeScriptFindUsagesService _underlyingService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptFindUsagesService(IVSTypeScriptFindUsagesService underlyingService) { _underlyingService = underlyingService; } public Task FindReferencesAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindReferencesAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); public Task FindImplementationsAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindImplementationsAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); private class VSTypeScriptFindUsagesContext : IVSTypeScriptFindUsagesContext { private readonly IFindUsagesContext _context; private readonly Dictionary<VSTypeScriptDefinitionItem, DefinitionItem> _definitionItemMap = new(); public VSTypeScriptFindUsagesContext(IFindUsagesContext context) { _context = context; } public IVSTypeScriptStreamingProgressTracker ProgressTracker => new VSTypeScriptStreamingProgressTracker(_context.ProgressTracker); public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _context.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _context.SetSearchTitleAsync(title, cancellationToken); private DefinitionItem GetOrCreateDefinitionItem(VSTypeScriptDefinitionItem item) { lock (_definitionItemMap) { if (!_definitionItemMap.TryGetValue(item, out var result)) { result = DefinitionItem.Create( item.Tags, item.DisplayParts, item.SourceSpans, item.NameDisplayParts, item.Properties, item.DisplayableProperties, item.DisplayIfNoReferences); _definitionItemMap.Add(item, result); } return result; } } public ValueTask OnDefinitionFoundAsync(VSTypeScriptDefinitionItem definition, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(definition); return _context.OnDefinitionFoundAsync(item, cancellationToken); } public ValueTask OnReferenceFoundAsync(VSTypeScriptSourceReferenceItem reference, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(reference.Definition); return _context.OnReferenceFoundAsync(new SourceReferenceItem(item, reference.SourceSpan, reference.SymbolUsageInfo), cancellationToken); } } private class VSTypeScriptStreamingProgressTracker : IVSTypeScriptStreamingProgressTracker { private readonly IStreamingProgressTracker _progressTracker; public VSTypeScriptStreamingProgressTracker(IStreamingProgressTracker progressTracker) { _progressTracker = progressTracker; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _progressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _progressTracker.ItemCompletedAsync(cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.ExternalAccess.VSTypeScript { [ExportLanguageService(typeof(IFindUsagesService), InternalLanguageNames.TypeScript), Shared] internal class VSTypeScriptFindUsagesService : IFindUsagesService { private readonly IVSTypeScriptFindUsagesService _underlyingService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptFindUsagesService(IVSTypeScriptFindUsagesService underlyingService) { _underlyingService = underlyingService; } public Task FindReferencesAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindReferencesAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); public Task FindImplementationsAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindImplementationsAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); private class VSTypeScriptFindUsagesContext : IVSTypeScriptFindUsagesContext { private readonly IFindUsagesContext _context; private readonly Dictionary<VSTypeScriptDefinitionItem, DefinitionItem> _definitionItemMap = new(); public VSTypeScriptFindUsagesContext(IFindUsagesContext context) { _context = context; } public IVSTypeScriptStreamingProgressTracker ProgressTracker => new VSTypeScriptStreamingProgressTracker(_context.ProgressTracker); public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _context.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _context.SetSearchTitleAsync(title, cancellationToken); private DefinitionItem GetOrCreateDefinitionItem(VSTypeScriptDefinitionItem item) { lock (_definitionItemMap) { if (!_definitionItemMap.TryGetValue(item, out var result)) { result = DefinitionItem.Create( item.Tags, item.DisplayParts, item.SourceSpans, item.NameDisplayParts, item.Properties, item.DisplayableProperties, item.DisplayIfNoReferences); _definitionItemMap.Add(item, result); } return result; } } public ValueTask OnDefinitionFoundAsync(VSTypeScriptDefinitionItem definition, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(definition); return _context.OnDefinitionFoundAsync(item, cancellationToken); } public ValueTask OnReferenceFoundAsync(VSTypeScriptSourceReferenceItem reference, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(reference.Definition); return _context.OnReferenceFoundAsync(new SourceReferenceItem(item, reference.SourceSpan, reference.SymbolUsageInfo), cancellationToken); } } private class VSTypeScriptStreamingProgressTracker : IVSTypeScriptStreamingProgressTracker { private readonly IStreamingProgressTracker _progressTracker; public VSTypeScriptStreamingProgressTracker(IStreamingProgressTracker progressTracker) { _progressTracker = progressTracker; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _progressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _progressTracker.ItemCompletedAsync(cancellationToken); } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Compilers/CSharp/Portable/Symbols/Synthesized/GeneratedLabelSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class GeneratedLabelSymbol : LabelSymbol { private readonly string _name; public GeneratedLabelSymbol(string name) { _name = LabelName(name); #if DEBUG NameNoSequence = $"<{name}>"; #endif } public override string Name { get { return _name; } } #if DEBUG internal string NameNoSequence { get; } private static int s_sequence = 1; #endif private static string LabelName(string name) { #if DEBUG int seq = System.Threading.Interlocked.Add(ref s_sequence, 1); return "<" + name + "-" + (seq & 0xffff) + ">"; #else return name; #endif } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } public override bool IsImplicitlyDeclared { get { 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.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class GeneratedLabelSymbol : LabelSymbol { private readonly string _name; public GeneratedLabelSymbol(string name) { _name = LabelName(name); #if DEBUG NameNoSequence = $"<{name}>"; #endif } public override string Name { get { return _name; } } #if DEBUG internal string NameNoSequence { get; } private static int s_sequence = 1; #endif private static string LabelName(string name) { #if DEBUG int seq = System.Threading.Interlocked.Add(ref s_sequence, 1); return "<" + name + "-" + (seq & 0xffff) + ">"; #else return name; #endif } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } public override bool IsImplicitlyDeclared { get { return true; } } } }
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/CodeStyle/CSharp/CodeFixes/CSharpCodeStyleFixesResources.resx
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="EmptyResource" xml:space="preserve"> <value>Remove this value when another is added.</value> <comment>https://github.com/Microsoft/msbuild/issues/1661</comment> </data> </root>
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="EmptyResource" xml:space="preserve"> <value>Remove this value when another is added.</value> <comment>https://github.com/Microsoft/msbuild/issues/1661</comment> </data> </root>
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/Compilers/VisualBasic/Portable/Lowering/Instrumentation/Instrumenter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A base class for components that instrument various portions of executable code. ''' It provides a set of APIs that are called by <see cref="LocalRewriter"/> to instrument ''' specific portions of the code. These APIs often have two parameters: ''' - original bound node produced by the <see cref="Binder"/> for the relevant portion of the code; ''' - rewritten bound node created by the <see cref="LocalRewriter"/> for the original node. ''' The APIs are expected to return new state of the rewritten node, after they apply appropriate ''' modifications, if any. ''' ''' The base class provides default implementation for all APIs, which simply returns the rewritten node. ''' </summary> Friend Class Instrumenter ''' <summary> ''' The singleton NoOp instrumenter, can be used to terminate the chain of <see cref="CompoundInstrumenter"/>s. ''' </summary> Public Shared ReadOnly NoOp As New Instrumenter() Public Sub New() End Sub Private Shared Function InstrumentStatement(original As BoundStatement, rewritten As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.SyntaxTree IsNot Nothing) Return rewritten End Function Public Overridable Function InstrumentExpressionStatement(original As BoundExpressionStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentStopStatement(original As BoundStopStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentEndStatement(original As BoundEndStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentContinueStatement(original As BoundContinueStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentExitStatement(original As BoundExitStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentGotoStatement(original As BoundGotoStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentLabelStatement(original As BoundLabelStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentRaiseEventStatement(original As BoundRaiseEventStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentReturnStatement(original As BoundReturnStatement, rewritten As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated OrElse (original.ExpressionOpt IsNot Nothing AndAlso Not original.ExpressionOpt.WasCompilerGenerated AndAlso original.Syntax Is original.ExpressionOpt.Syntax)) Debug.Assert(original.SyntaxTree IsNot Nothing) Return rewritten End Function Public Overridable Function InstrumentThrowStatement(original As BoundThrowStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentOnErrorStatement(original As BoundOnErrorStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentResumeStatement(original As BoundResumeStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentAddHandlerStatement(original As BoundAddHandlerStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentRemoveHandlerStatement(original As BoundRemoveHandlerStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function ''' <summary> ''' Return a node that is associated with an entry of the block. OK to return Nothing. ''' </summary> Public Overridable Function CreateBlockPrologue(trueOriginal As BoundBlock, original As BoundBlock, ByRef synthesizedLocal As LocalSymbol) As BoundStatement synthesizedLocal = Nothing Return Nothing End Function Public Overridable Function InstrumentTopLevelExpressionInQuery(original As BoundExpression, rewritten As BoundExpression) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewritten End Function Public Overridable Function InstrumentQueryLambdaBody(original As BoundQueryLambda, rewritten As BoundStatement) As BoundStatement Debug.Assert(original.LambdaSymbol.SynthesizedKind = SynthesizedLambdaKind.AggregateQueryLambda OrElse original.LambdaSymbol.SynthesizedKind = SynthesizedLambdaKind.LetVariableQueryLambda) Return rewritten End Function ''' <summary> ''' Ok to return Nothing when <paramref name="epilogueOpt"/> is Nothing. ''' </summary> Public Overridable Function InstrumentDoLoopEpilogue(original As BoundDoLoopStatement, epilogueOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(DirectCast(original.Syntax, DoLoopBlockSyntax).LoopStatement IsNot Nothing) Return epilogueOpt End Function ''' <summary> ''' Return a prologue. Ok to return Nothing. ''' </summary> Public Overridable Function CreateSyncLockStatementPrologue(original As BoundSyncLockStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.SyncLockBlock) Return Nothing End Function Public Overridable Function InstrumentSyncLockObjectCapture(original As BoundSyncLockStatement, rewritten As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.SyncLockBlock) Return rewritten End Function ''' <summary> ''' Return an epilogue. Ok to return Nothing. ''' </summary> Public Overridable Function CreateSyncLockExitDueToExceptionEpilogue(original As BoundSyncLockStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.SyncLockBlock) Return Nothing End Function ''' <summary> ''' Return an epilogue. Ok to return Nothing. ''' </summary> Public Overridable Function CreateSyncLockExitNormallyEpilogue(original As BoundSyncLockStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.SyncLockBlock) Return Nothing End Function ''' <summary> ''' Ok to return Nothing when <paramref name="epilogueOpt"/> is Nothing. ''' </summary> Public Overridable Function InstrumentWhileEpilogue(original As BoundWhileStatement, epilogueOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.WhileBlock) Return epilogueOpt End Function Public Overridable Function InstrumentWhileStatementConditionalGotoStart(original As BoundWhileStatement, ifConditionGotoStart As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.WhileBlock) Return ifConditionGotoStart End Function ''' <summary> ''' Ok to return Nothing when <paramref name="ifConditionGotoStartOpt"/> is Nothing. ''' </summary> Public Overridable Function InstrumentDoLoopStatementEntryOrConditionalGotoStart(original As BoundDoLoopStatement, ifConditionGotoStartOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(TypeOf original.Syntax Is DoLoopBlockSyntax) Return ifConditionGotoStartOpt End Function Public Overridable Function InstrumentForEachStatementConditionalGotoStart(original As BoundForEachStatement, ifConditionGotoStart As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.ForEachBlock) Return ifConditionGotoStart End Function Public Overridable Function InstrumentIfStatementConditionalGoto(original As BoundIfStatement, condGoto As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.MultiLineIfBlock OrElse original.Syntax.Kind = SyntaxKind.ElseIfBlock OrElse original.Syntax.Kind = SyntaxKind.SingleLineIfStatement) Return condGoto End Function Public Overridable Function InstrumentIfStatementAfterIfStatement(original As BoundIfStatement, afterIfStatement As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.MultiLineIfBlock) Return afterIfStatement End Function ''' <summary> ''' Ok to return Nothing when <paramref name="epilogueOpt"/> is Nothing. ''' </summary> Public Overridable Function InstrumentIfStatementConsequenceEpilogue(original As BoundIfStatement, epilogueOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.MultiLineIfBlock OrElse original.Syntax.Kind = SyntaxKind.ElseIfBlock OrElse original.Syntax.Kind = SyntaxKind.SingleLineIfStatement) Return epilogueOpt End Function ''' <summary> ''' Ok to return Nothing when <paramref name="epilogueOpt"/> is Nothing. ''' </summary> Public Overridable Function InstrumentIfStatementAlternativeEpilogue(original As BoundIfStatement, epilogueOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.AlternativeOpt.Syntax.Kind = SyntaxKind.ElseBlock) Debug.Assert(original.AlternativeOpt.Syntax.Parent.Kind = SyntaxKind.MultiLineIfBlock) Return epilogueOpt End Function ''' <summary> ''' Return a node that is associated with an entry of the Else block. Ok to return Nothing. ''' </summary> Public Overridable Function CreateIfStatementAlternativePrologue(original As BoundIfStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.AlternativeOpt.Syntax.Kind = SyntaxKind.ElseBlock OrElse original.AlternativeOpt.Syntax.Kind = SyntaxKind.SingleLineElseClause) Return Nothing End Function Public Overridable Function InstrumentDoLoopStatementCondition(original As BoundDoLoopStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenCondition End Function Public Overridable Function InstrumentWhileStatementCondition(original As BoundWhileStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenCondition End Function Public Overridable Function InstrumentForEachStatementCondition(original As BoundForEachStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenCondition End Function Public Overridable Function InstrumentObjectForLoopInitCondition(original As BoundForToStatement, rewrittenInitCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenInitCondition End Function Public Overridable Function InstrumentObjectForLoopCondition(original As BoundForToStatement, rewrittenLoopCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenLoopCondition End Function Public Overridable Function InstrumentIfStatementCondition(original As BoundIfStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenCondition End Function Public Overridable Function InstrumentCatchBlockFilter(original As BoundCatchBlock, rewrittenFilter As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.CatchBlock) Debug.Assert(original.ExceptionFilterOpt IsNot Nothing) Debug.Assert(original.ExceptionFilterOpt.Syntax.Parent.IsKind(SyntaxKind.CatchFilterClause)) Return rewrittenFilter End Function ''' <summary> ''' Return a node that is associated with an entry of the block. Ok to return Nothing. ''' Note, this method is only called for a catch block without Filter. ''' If there is a filter, <see cref="InstrumentCatchBlockFilter"/> is called instead. ''' </summary> Public Overridable Function CreateCatchBlockPrologue(original As BoundCatchBlock) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.CatchBlock) Debug.Assert(original.ExceptionFilterOpt Is Nothing) Return Nothing End Function ''' <summary> ''' Return a node that is associated with an entry of the Finally block. Ok to return Nothing. ''' </summary> Public Overridable Function CreateFinallyBlockPrologue(original As BoundTryStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.TryBlock) Debug.Assert(original.FinallyBlockOpt IsNot Nothing) Debug.Assert(original.FinallyBlockOpt.Syntax.Kind = SyntaxKind.FinallyBlock) Return Nothing End Function ''' <summary> ''' Return a node that is associated with an entry of the Try block. Ok to return Nothing. ''' </summary> Public Overridable Function CreateTryBlockPrologue(original As BoundTryStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.TryBlock) Return Nothing End Function Public Overridable Function InstrumentTryStatement(original As BoundTryStatement, rewritten As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.TryBlock) Return rewritten End Function ''' <summary> ''' Ok to return Nothing. ''' </summary> Public Overridable Function CreateSelectStatementPrologue(original As BoundSelectStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Return Nothing End Function Public Overridable Function InstrumentSelectStatementCaseCondition(original As BoundSelectStatement, rewrittenCaseCondition As BoundExpression, currentMethodOrLambda As MethodSymbol, ByRef lazyConditionalBranchLocal As LocalSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenCaseCondition End Function Public Overridable Function InstrumentCaseBlockConditionalGoto(original As BoundCaseBlock, condGoto As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Return condGoto End Function Public Overridable Function InstrumentCaseElseBlock(original As BoundCaseBlock, rewritten As BoundBlock) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Return rewritten End Function ''' <summary> ''' Ok to return Nothing when <paramref name="epilogueOpt"/> is Nothing. ''' If <paramref name="epilogueOpt"/> is not Nothing, add to the end, not to the front. ''' </summary> Public Overridable Function InstrumentSelectStatementEpilogue(original As BoundSelectStatement, epilogueOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.SelectBlock) Return epilogueOpt End Function Public Overridable Function InstrumentFieldOrPropertyInitializer(original As BoundFieldOrPropertyInitializer, rewritten As BoundStatement, symbolIndex As Integer, createTemporary As Boolean) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.IsKind(SyntaxKind.AsNewClause) OrElse ' Dim a As New C(); Dim a,b As New C(); Property P As New C() original.Syntax.IsKind(SyntaxKind.ModifiedIdentifier) OrElse ' Dim a(1) As Integer original.Syntax.IsKind(SyntaxKind.EqualsValue)) ' Dim a = 1; Property P As Integer = 1 Return rewritten End Function Public Overridable Function InstrumentForEachLoopInitialization(original As BoundForEachStatement, initialization As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.ForEachBlock) Return initialization End Function ''' <summary> ''' Ok to return Nothing when <paramref name="epilogueOpt"/> is Nothing. ''' If <paramref name="epilogueOpt"/> is not Nothing, add to the end, not to the front. ''' </summary> Public Overridable Function InstrumentForEachLoopEpilogue(original As BoundForEachStatement, epilogueOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.ForEachBlock) Return epilogueOpt End Function Public Overridable Function InstrumentForLoopInitialization(original As BoundForToStatement, initialization As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.ForBlock) Return initialization End Function Public Overridable Function InstrumentForLoopIncrement(original As BoundForToStatement, increment As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.ForBlock) Return increment End Function Public Overridable Function InstrumentLocalInitialization(original As BoundLocalDeclaration, rewritten As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.ModifiedIdentifier) Debug.Assert(original.Syntax.Parent.Kind = SyntaxKind.VariableDeclarator) Return rewritten End Function ''' <summary> ''' Ok to return Nothing. ''' </summary> Public Overridable Function CreateUsingStatementPrologue(original As BoundUsingStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.UsingBlock) Return Nothing End Function Public Overridable Function InstrumentUsingStatementResourceCapture(original As BoundUsingStatement, resourceIndex As Integer, rewritten As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.UsingBlock) Return rewritten End Function ''' <summary> ''' Ok to return Nothing. ''' </summary> Public Overridable Function CreateUsingStatementDisposePrologue(original As BoundUsingStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.UsingBlock) Return Nothing End Function ''' <summary> ''' Ok to return Nothing. ''' </summary> Public Overridable Function CreateWithStatementPrologue(original As BoundWithStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.WithBlock) Return Nothing End Function ''' <summary> ''' Ok to return Nothing. ''' </summary> Public Overridable Function CreateWithStatementEpilogue(original As BoundWithStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.WithBlock) Return Nothing End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A base class for components that instrument various portions of executable code. ''' It provides a set of APIs that are called by <see cref="LocalRewriter"/> to instrument ''' specific portions of the code. These APIs often have two parameters: ''' - original bound node produced by the <see cref="Binder"/> for the relevant portion of the code; ''' - rewritten bound node created by the <see cref="LocalRewriter"/> for the original node. ''' The APIs are expected to return new state of the rewritten node, after they apply appropriate ''' modifications, if any. ''' ''' The base class provides default implementation for all APIs, which simply returns the rewritten node. ''' </summary> Friend Class Instrumenter ''' <summary> ''' The singleton NoOp instrumenter, can be used to terminate the chain of <see cref="CompoundInstrumenter"/>s. ''' </summary> Public Shared ReadOnly NoOp As New Instrumenter() Public Sub New() End Sub Private Shared Function InstrumentStatement(original As BoundStatement, rewritten As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.SyntaxTree IsNot Nothing) Return rewritten End Function Public Overridable Function InstrumentExpressionStatement(original As BoundExpressionStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentStopStatement(original As BoundStopStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentEndStatement(original As BoundEndStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentContinueStatement(original As BoundContinueStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentExitStatement(original As BoundExitStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentGotoStatement(original As BoundGotoStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentLabelStatement(original As BoundLabelStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentRaiseEventStatement(original As BoundRaiseEventStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentReturnStatement(original As BoundReturnStatement, rewritten As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated OrElse (original.ExpressionOpt IsNot Nothing AndAlso Not original.ExpressionOpt.WasCompilerGenerated AndAlso original.Syntax Is original.ExpressionOpt.Syntax)) Debug.Assert(original.SyntaxTree IsNot Nothing) Return rewritten End Function Public Overridable Function InstrumentThrowStatement(original As BoundThrowStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentOnErrorStatement(original As BoundOnErrorStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentResumeStatement(original As BoundResumeStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentAddHandlerStatement(original As BoundAddHandlerStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function Public Overridable Function InstrumentRemoveHandlerStatement(original As BoundRemoveHandlerStatement, rewritten As BoundStatement) As BoundStatement Return InstrumentStatement(original, rewritten) End Function ''' <summary> ''' Return a node that is associated with an entry of the block. OK to return Nothing. ''' </summary> Public Overridable Function CreateBlockPrologue(trueOriginal As BoundBlock, original As BoundBlock, ByRef synthesizedLocal As LocalSymbol) As BoundStatement synthesizedLocal = Nothing Return Nothing End Function Public Overridable Function InstrumentTopLevelExpressionInQuery(original As BoundExpression, rewritten As BoundExpression) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewritten End Function Public Overridable Function InstrumentQueryLambdaBody(original As BoundQueryLambda, rewritten As BoundStatement) As BoundStatement Debug.Assert(original.LambdaSymbol.SynthesizedKind = SynthesizedLambdaKind.AggregateQueryLambda OrElse original.LambdaSymbol.SynthesizedKind = SynthesizedLambdaKind.LetVariableQueryLambda) Return rewritten End Function ''' <summary> ''' Ok to return Nothing when <paramref name="epilogueOpt"/> is Nothing. ''' </summary> Public Overridable Function InstrumentDoLoopEpilogue(original As BoundDoLoopStatement, epilogueOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(DirectCast(original.Syntax, DoLoopBlockSyntax).LoopStatement IsNot Nothing) Return epilogueOpt End Function ''' <summary> ''' Return a prologue. Ok to return Nothing. ''' </summary> Public Overridable Function CreateSyncLockStatementPrologue(original As BoundSyncLockStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.SyncLockBlock) Return Nothing End Function Public Overridable Function InstrumentSyncLockObjectCapture(original As BoundSyncLockStatement, rewritten As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.SyncLockBlock) Return rewritten End Function ''' <summary> ''' Return an epilogue. Ok to return Nothing. ''' </summary> Public Overridable Function CreateSyncLockExitDueToExceptionEpilogue(original As BoundSyncLockStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.SyncLockBlock) Return Nothing End Function ''' <summary> ''' Return an epilogue. Ok to return Nothing. ''' </summary> Public Overridable Function CreateSyncLockExitNormallyEpilogue(original As BoundSyncLockStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.SyncLockBlock) Return Nothing End Function ''' <summary> ''' Ok to return Nothing when <paramref name="epilogueOpt"/> is Nothing. ''' </summary> Public Overridable Function InstrumentWhileEpilogue(original As BoundWhileStatement, epilogueOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.WhileBlock) Return epilogueOpt End Function Public Overridable Function InstrumentWhileStatementConditionalGotoStart(original As BoundWhileStatement, ifConditionGotoStart As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.WhileBlock) Return ifConditionGotoStart End Function ''' <summary> ''' Ok to return Nothing when <paramref name="ifConditionGotoStartOpt"/> is Nothing. ''' </summary> Public Overridable Function InstrumentDoLoopStatementEntryOrConditionalGotoStart(original As BoundDoLoopStatement, ifConditionGotoStartOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(TypeOf original.Syntax Is DoLoopBlockSyntax) Return ifConditionGotoStartOpt End Function Public Overridable Function InstrumentForEachStatementConditionalGotoStart(original As BoundForEachStatement, ifConditionGotoStart As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.ForEachBlock) Return ifConditionGotoStart End Function Public Overridable Function InstrumentIfStatementConditionalGoto(original As BoundIfStatement, condGoto As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.MultiLineIfBlock OrElse original.Syntax.Kind = SyntaxKind.ElseIfBlock OrElse original.Syntax.Kind = SyntaxKind.SingleLineIfStatement) Return condGoto End Function Public Overridable Function InstrumentIfStatementAfterIfStatement(original As BoundIfStatement, afterIfStatement As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.MultiLineIfBlock) Return afterIfStatement End Function ''' <summary> ''' Ok to return Nothing when <paramref name="epilogueOpt"/> is Nothing. ''' </summary> Public Overridable Function InstrumentIfStatementConsequenceEpilogue(original As BoundIfStatement, epilogueOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.MultiLineIfBlock OrElse original.Syntax.Kind = SyntaxKind.ElseIfBlock OrElse original.Syntax.Kind = SyntaxKind.SingleLineIfStatement) Return epilogueOpt End Function ''' <summary> ''' Ok to return Nothing when <paramref name="epilogueOpt"/> is Nothing. ''' </summary> Public Overridable Function InstrumentIfStatementAlternativeEpilogue(original As BoundIfStatement, epilogueOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.AlternativeOpt.Syntax.Kind = SyntaxKind.ElseBlock) Debug.Assert(original.AlternativeOpt.Syntax.Parent.Kind = SyntaxKind.MultiLineIfBlock) Return epilogueOpt End Function ''' <summary> ''' Return a node that is associated with an entry of the Else block. Ok to return Nothing. ''' </summary> Public Overridable Function CreateIfStatementAlternativePrologue(original As BoundIfStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.AlternativeOpt.Syntax.Kind = SyntaxKind.ElseBlock OrElse original.AlternativeOpt.Syntax.Kind = SyntaxKind.SingleLineElseClause) Return Nothing End Function Public Overridable Function InstrumentDoLoopStatementCondition(original As BoundDoLoopStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenCondition End Function Public Overridable Function InstrumentWhileStatementCondition(original As BoundWhileStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenCondition End Function Public Overridable Function InstrumentForEachStatementCondition(original As BoundForEachStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenCondition End Function Public Overridable Function InstrumentObjectForLoopInitCondition(original As BoundForToStatement, rewrittenInitCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenInitCondition End Function Public Overridable Function InstrumentObjectForLoopCondition(original As BoundForToStatement, rewrittenLoopCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenLoopCondition End Function Public Overridable Function InstrumentIfStatementCondition(original As BoundIfStatement, rewrittenCondition As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenCondition End Function Public Overridable Function InstrumentCatchBlockFilter(original As BoundCatchBlock, rewrittenFilter As BoundExpression, currentMethodOrLambda As MethodSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.CatchBlock) Debug.Assert(original.ExceptionFilterOpt IsNot Nothing) Debug.Assert(original.ExceptionFilterOpt.Syntax.Parent.IsKind(SyntaxKind.CatchFilterClause)) Return rewrittenFilter End Function ''' <summary> ''' Return a node that is associated with an entry of the block. Ok to return Nothing. ''' Note, this method is only called for a catch block without Filter. ''' If there is a filter, <see cref="InstrumentCatchBlockFilter"/> is called instead. ''' </summary> Public Overridable Function CreateCatchBlockPrologue(original As BoundCatchBlock) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.CatchBlock) Debug.Assert(original.ExceptionFilterOpt Is Nothing) Return Nothing End Function ''' <summary> ''' Return a node that is associated with an entry of the Finally block. Ok to return Nothing. ''' </summary> Public Overridable Function CreateFinallyBlockPrologue(original As BoundTryStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.TryBlock) Debug.Assert(original.FinallyBlockOpt IsNot Nothing) Debug.Assert(original.FinallyBlockOpt.Syntax.Kind = SyntaxKind.FinallyBlock) Return Nothing End Function ''' <summary> ''' Return a node that is associated with an entry of the Try block. Ok to return Nothing. ''' </summary> Public Overridable Function CreateTryBlockPrologue(original As BoundTryStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.TryBlock) Return Nothing End Function Public Overridable Function InstrumentTryStatement(original As BoundTryStatement, rewritten As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.TryBlock) Return rewritten End Function ''' <summary> ''' Ok to return Nothing. ''' </summary> Public Overridable Function CreateSelectStatementPrologue(original As BoundSelectStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Return Nothing End Function Public Overridable Function InstrumentSelectStatementCaseCondition(original As BoundSelectStatement, rewrittenCaseCondition As BoundExpression, currentMethodOrLambda As MethodSymbol, ByRef lazyConditionalBranchLocal As LocalSymbol) As BoundExpression Debug.Assert(Not original.WasCompilerGenerated) Return rewrittenCaseCondition End Function Public Overridable Function InstrumentCaseBlockConditionalGoto(original As BoundCaseBlock, condGoto As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Return condGoto End Function Public Overridable Function InstrumentCaseElseBlock(original As BoundCaseBlock, rewritten As BoundBlock) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Return rewritten End Function ''' <summary> ''' Ok to return Nothing when <paramref name="epilogueOpt"/> is Nothing. ''' If <paramref name="epilogueOpt"/> is not Nothing, add to the end, not to the front. ''' </summary> Public Overridable Function InstrumentSelectStatementEpilogue(original As BoundSelectStatement, epilogueOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.SelectBlock) Return epilogueOpt End Function Public Overridable Function InstrumentFieldOrPropertyInitializer(original As BoundFieldOrPropertyInitializer, rewritten As BoundStatement, symbolIndex As Integer, createTemporary As Boolean) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.IsKind(SyntaxKind.AsNewClause) OrElse ' Dim a As New C(); Dim a,b As New C(); Property P As New C() original.Syntax.IsKind(SyntaxKind.ModifiedIdentifier) OrElse ' Dim a(1) As Integer original.Syntax.IsKind(SyntaxKind.EqualsValue)) ' Dim a = 1; Property P As Integer = 1 Return rewritten End Function Public Overridable Function InstrumentForEachLoopInitialization(original As BoundForEachStatement, initialization As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.ForEachBlock) Return initialization End Function ''' <summary> ''' Ok to return Nothing when <paramref name="epilogueOpt"/> is Nothing. ''' If <paramref name="epilogueOpt"/> is not Nothing, add to the end, not to the front. ''' </summary> Public Overridable Function InstrumentForEachLoopEpilogue(original As BoundForEachStatement, epilogueOpt As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.ForEachBlock) Return epilogueOpt End Function Public Overridable Function InstrumentForLoopInitialization(original As BoundForToStatement, initialization As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.ForBlock) Return initialization End Function Public Overridable Function InstrumentForLoopIncrement(original As BoundForToStatement, increment As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.ForBlock) Return increment End Function Public Overridable Function InstrumentLocalInitialization(original As BoundLocalDeclaration, rewritten As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.ModifiedIdentifier) Debug.Assert(original.Syntax.Parent.Kind = SyntaxKind.VariableDeclarator) Return rewritten End Function ''' <summary> ''' Ok to return Nothing. ''' </summary> Public Overridable Function CreateUsingStatementPrologue(original As BoundUsingStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.UsingBlock) Return Nothing End Function Public Overridable Function InstrumentUsingStatementResourceCapture(original As BoundUsingStatement, resourceIndex As Integer, rewritten As BoundStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.UsingBlock) Return rewritten End Function ''' <summary> ''' Ok to return Nothing. ''' </summary> Public Overridable Function CreateUsingStatementDisposePrologue(original As BoundUsingStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.UsingBlock) Return Nothing End Function ''' <summary> ''' Ok to return Nothing. ''' </summary> Public Overridable Function CreateWithStatementPrologue(original As BoundWithStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.WithBlock) Return Nothing End Function ''' <summary> ''' Ok to return Nothing. ''' </summary> Public Overridable Function CreateWithStatementEpilogue(original As BoundWithStatement) As BoundStatement Debug.Assert(Not original.WasCompilerGenerated) Debug.Assert(original.Syntax.Kind = SyntaxKind.WithBlock) Return Nothing End Function End Class End Namespace
-1
dotnet/roslyn
55,585
Avoid delegate allocations in SQLite code
Minor improvements observed in passing.
sharwell
2021-08-12T22:10:54Z
2021-08-13T00:34:38Z
675a588e5421c81379992eb7c40aa6d1b074dafb
1f9a56c2d8934e1bb42f2bf06af9b29f1dbb0af5
Avoid delegate allocations in SQLite code. Minor improvements observed in passing.
./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/TypeBlockTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class TypeBlockTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterClassStatement() VerifyStatementEndConstructApplied( before:="Class c1", beforeCaret:={0, -1}, after:="Class c1 End Class", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterModuleStatement() VerifyStatementEndConstructApplied( before:="Module m1", beforeCaret:={0, -1}, after:="Module m1 End Module", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyForMatchedClass() VerifyStatementEndConstructNotApplied( text:="Class c1 End Class", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterInterfaceStatement() VerifyStatementEndConstructApplied( before:="Interface IGoo", beforeCaret:={0, -1}, after:="Interface IGoo End Interface", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterStructureStatement() VerifyStatementEndConstructApplied( before:="Structure Goo", beforeCaret:={0, -1}, after:="Structure Goo End Structure", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterEnumStatement() VerifyStatementEndConstructApplied( before:="Enum Goo", beforeCaret:={0, -1}, after:="Enum Goo End Enum", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyGenericClass() VerifyStatementEndConstructApplied( before:="NameSpace X Class C(of T)", beforeCaret:={1, -1}, after:="NameSpace X Class C(of T) End Class", afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyStructInAClass() VerifyStatementEndConstructApplied( before:="Class C Structure s End Class", beforeCaret:={1, -1}, after:="Class C Structure s End Structure End Class", afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyClassInAModule() VerifyStatementEndConstructApplied( before:="Module M Class C End Module", beforeCaret:={1, -1}, after:="Module M Class C End Class End Module", afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyClassDeclaration() VerifyStatementEndConstructApplied( before:="Partial Friend MustInherit Class C", beforeCaret:={0, -1}, after:="Partial Friend MustInherit Class C End Class", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyEnumInAClass() VerifyStatementEndConstructApplied( before:="Class C Public Enum e End Class", beforeCaret:={1, -1}, after:="Class C Public Enum e End Enum End Class", afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSyntax() VerifyStatementEndConstructNotApplied( text:="Class EC Sub S Class B End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSyntax01() VerifyStatementEndConstructNotApplied( text:="Enum e(Of T)", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSyntax02() VerifyStatementEndConstructNotApplied( text:="Class C Class", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyInheritsDecl() VerifyStatementEndConstructApplied( before:="Class C : Inherits B", beforeCaret:={0, -1}, after:="Class C : Inherits B End Class", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInheritsDeclNotApplied() VerifyStatementEndConstructNotApplied( text:="Class C : Inherits B End Class", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyImplementsDecl() VerifyStatementEndConstructApplied( before:="Class C : Implements IB", beforeCaret:={0, -1}, after:="Class C : Implements IB End Class", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyImplementsDeclNotApplied() VerifyStatementEndConstructNotApplied( text:="Class C : Implements IB End Class", caret:={0, -1}) 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class TypeBlockTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterClassStatement() VerifyStatementEndConstructApplied( before:="Class c1", beforeCaret:={0, -1}, after:="Class c1 End Class", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterModuleStatement() VerifyStatementEndConstructApplied( before:="Module m1", beforeCaret:={0, -1}, after:="Module m1 End Module", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyForMatchedClass() VerifyStatementEndConstructNotApplied( text:="Class c1 End Class", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterInterfaceStatement() VerifyStatementEndConstructApplied( before:="Interface IGoo", beforeCaret:={0, -1}, after:="Interface IGoo End Interface", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterStructureStatement() VerifyStatementEndConstructApplied( before:="Structure Goo", beforeCaret:={0, -1}, after:="Structure Goo End Structure", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterEnumStatement() VerifyStatementEndConstructApplied( before:="Enum Goo", beforeCaret:={0, -1}, after:="Enum Goo End Enum", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyGenericClass() VerifyStatementEndConstructApplied( before:="NameSpace X Class C(of T)", beforeCaret:={1, -1}, after:="NameSpace X Class C(of T) End Class", afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyStructInAClass() VerifyStatementEndConstructApplied( before:="Class C Structure s End Class", beforeCaret:={1, -1}, after:="Class C Structure s End Structure End Class", afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyClassInAModule() VerifyStatementEndConstructApplied( before:="Module M Class C End Module", beforeCaret:={1, -1}, after:="Module M Class C End Class End Module", afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyClassDeclaration() VerifyStatementEndConstructApplied( before:="Partial Friend MustInherit Class C", beforeCaret:={0, -1}, after:="Partial Friend MustInherit Class C End Class", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyEnumInAClass() VerifyStatementEndConstructApplied( before:="Class C Public Enum e End Class", beforeCaret:={1, -1}, after:="Class C Public Enum e End Enum End Class", afterCaret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSyntax() VerifyStatementEndConstructNotApplied( text:="Class EC Sub S Class B End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSyntax01() VerifyStatementEndConstructNotApplied( text:="Enum e(Of T)", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSyntax02() VerifyStatementEndConstructNotApplied( text:="Class C Class", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyInheritsDecl() VerifyStatementEndConstructApplied( before:="Class C : Inherits B", beforeCaret:={0, -1}, after:="Class C : Inherits B End Class", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInheritsDeclNotApplied() VerifyStatementEndConstructNotApplied( text:="Class C : Inherits B End Class", caret:={0, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestVerifyImplementsDecl() VerifyStatementEndConstructApplied( before:="Class C : Implements IB", beforeCaret:={0, -1}, after:="Class C : Implements IB End Class", afterCaret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyImplementsDeclNotApplied() VerifyStatementEndConstructNotApplied( text:="Class C : Implements IB End Class", caret:={0, -1}) End Sub End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/ItemManager.cs
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal class ItemManager : IAsyncCompletionItemManager { /// <summary> /// Used for filtering non-Roslyn data only. /// </summary> private readonly CompletionHelper _defaultCompletionHelper; private readonly RecentItemsManager _recentItemsManager; /// <summary> /// For telemetry. /// </summary> private readonly object _targetTypeCompletionFilterChosenMarker = new(); internal ItemManager(RecentItemsManager recentItemsManager) { // Let us make the completion Helper used for non-Roslyn items case-sensitive. // We can change this if get requests from partner teams. _defaultCompletionHelper = new CompletionHelper(isCaseSensitive: true); _recentItemsManager = recentItemsManager; } public Task<ImmutableArray<VSCompletionItem>> SortCompletionListAsync( IAsyncCompletionSession session, AsyncCompletionSessionInitialDataSnapshot data, CancellationToken cancellationToken) { if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isTargetTypeFilterEnabled) && isTargetTypeFilterEnabled) { AsyncCompletionLogger.LogSessionHasTargetTypeFilterEnabled(); // This method is called exactly once, so use the opportunity to set a baseline for telemetry. if (data.InitialList.Any(i => i.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches))) { AsyncCompletionLogger.LogSessionContainsTargetTypeFilter(); } } if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTypeImportCompletionEnabled) && isTypeImportCompletionEnabled) { AsyncCompletionLogger.LogSessionWithTypeImportCompletionEnabled(); } // Sort by default comparer of Roslyn CompletionItem var sortedItems = data.InitialList.OrderBy(GetOrAddRoslynCompletionItem).ToImmutableArray(); return Task.FromResult(sortedItems); } public Task<FilteredCompletionModel?> UpdateCompletionListAsync( IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken cancellationToken) => Task.FromResult(UpdateCompletionList(session, data, cancellationToken)); // We might need to handle large amount of items with import completion enabled, // so use a dedicated pool to minimize/avoid array allocations (especially in LOH) // Set the size of pool to 1 because we don't expect UpdateCompletionListAsync to be // called concurrently, which essentially makes the pooled list a singleton, // but we still use ObjectPool for concurrency handling just to be robust. private static readonly ObjectPool<List<MatchResult<VSCompletionItem>>> s_listOfMatchResultPool = new(factory: () => new(), size: 1); private FilteredCompletionModel? UpdateCompletionList( IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken cancellationToken) { if (!session.Properties.TryGetProperty(CompletionSource.HasSuggestionItemOptions, out bool hasSuggestedItemOptions)) { // This is the scenario when the session is created out of Roslyn, in some other provider, e.g. in Debugger. // For now, the default hasSuggestedItemOptions is false. hasSuggestedItemOptions = false; } hasSuggestedItemOptions |= data.DisplaySuggestionItem; var filterText = session.ApplicableToSpan.GetText(data.Snapshot); var reason = data.Trigger.Reason; var initialRoslynTriggerKind = Helpers.GetRoslynTriggerKind(data.InitialTrigger); // Check if the user is typing a number. If so, only proceed if it's a number // directly after a <dot>. That's because it is actually reasonable for completion // to be brought up after a <dot> and for the user to want to filter completion // items based on a number that exists in the name of the item. However, when // we are not after a dot (i.e. we're being brought up after <space> is typed) // then we don't want to filter things. Consider the user writing: // // dim i =<space> // // We'll bring up the completion list here (as VB has completion on <space>). // If the user then types '3', we don't want to match against Int32. if (filterText.Length > 0 && char.IsNumber(filterText[0])) { if (!IsAfterDot(data.Snapshot, session.ApplicableToSpan)) { // Dismiss the session. return null; } } // We need to filter if // 1. a non-empty strict subset of filters are selected // 2. a non-empty set of expanders are unselected var nonExpanderFilterStates = data.SelectedFilters.WhereAsArray(f => !(f.Filter is CompletionExpander)); var selectedNonExpanderFilters = nonExpanderFilterStates.SelectAsArray(f => f.IsSelected, f => f.Filter); var needToFilter = selectedNonExpanderFilters.Length > 0 && selectedNonExpanderFilters.Length < nonExpanderFilterStates.Length; var unselectedExpanders = data.SelectedFilters.SelectAsArray(f => !f.IsSelected && f.Filter is CompletionExpander, f => f.Filter); var needToFilterExpanded = unselectedExpanders.Length > 0; if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled) { // Telemetry: Want to know % of sessions with the "Target type matches" filter where that filter is actually enabled if (needToFilter && !session.Properties.ContainsProperty(_targetTypeCompletionFilterChosenMarker) && selectedNonExpanderFilters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) { AsyncCompletionLogger.LogTargetTypeFilterChosenInSession(); // Make sure we only record one enabling of the filter per session session.Properties.AddProperty(_targetTypeCompletionFilterChosenMarker, _targetTypeCompletionFilterChosenMarker); } } var filterReason = Helpers.GetFilterReason(data.Trigger); // We prefer using the original snapshot, which should always be available from items provided by Roslyn's CompletionSource. // Only use data.Snapshot in the theoretically possible but rare case when all items we are handling are from some non-Roslyn CompletionSource. var snapshotForDocument = TryGetInitialTriggerLocation(data, out var intialTriggerLocation) ? intialTriggerLocation.Snapshot : data.Snapshot; var document = snapshotForDocument?.TextBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); var completionService = document?.GetLanguageService<CompletionService>(); var completionRules = completionService?.GetRules() ?? CompletionRules.Default; var completionHelper = document != null ? CompletionHelper.GetHelper(document) : _defaultCompletionHelper; // DismissIfLastCharacterDeleted should be applied only when started with Insertion, and then Deleted all characters typed. // This conforms with the original VS 2010 behavior. if (initialRoslynTriggerKind == CompletionTriggerKind.Insertion && data.Trigger.Reason == CompletionTriggerReason.Backspace && completionRules.DismissIfLastCharacterDeleted && session.ApplicableToSpan.GetText(data.Snapshot).Length == 0) { // Dismiss the session return null; } var options = document?.Project.Solution.Options; var highlightMatchingPortions = options?.GetOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, document?.Project.Language) ?? false; // Nothing to highlight if user hasn't typed anything yet. highlightMatchingPortions = highlightMatchingPortions && filterText.Length > 0; // Use a monotonically increasing integer to keep track the original alphabetical order of each item. var currentIndex = 0; var initialListOfItemsToBeIncluded = s_listOfMatchResultPool.Allocate(); try { // Filter items based on the selected filters and matching. foreach (var item in data.InitialSortedList) { cancellationToken.ThrowIfCancellationRequested(); if (needToFilter && ShouldBeFilteredOutOfCompletionList(item, selectedNonExpanderFilters)) { continue; } if (needToFilterExpanded && ShouldBeFilteredOutOfExpandedCompletionList(item, unselectedExpanders)) { continue; } if (TryCreateMatchResult( completionHelper, item, filterText, initialRoslynTriggerKind, filterReason, _recentItemsManager.RecentItems, highlightMatchingPortions: highlightMatchingPortions, currentIndex, out var matchResult)) { initialListOfItemsToBeIncluded.Add(matchResult); currentIndex++; } } if (initialListOfItemsToBeIncluded.Count == 0) { return HandleAllItemsFilteredOut(reason, data.SelectedFilters, completionRules); } // Sort the items by pattern matching results. // Note that we want to preserve the original alphabetical order for items with same pattern match score, // but `List<T>.Sort` isn't stable. Therefore we have to add a monotonically increasing integer // to `MatchResult` to achieve this. initialListOfItemsToBeIncluded.Sort(MatchResult<VSCompletionItem>.SortingComparer); var showCompletionItemFilters = options?.GetOption(CompletionOptions.ShowCompletionItemFilters, document?.Project.Language) ?? true; var updatedFilters = showCompletionItemFilters ? GetUpdatedFilters(initialListOfItemsToBeIncluded, data.SelectedFilters) : ImmutableArray<CompletionFilterWithState>.Empty; // If this was deletion, then we control the entire behavior of deletion ourselves. if (initialRoslynTriggerKind == CompletionTriggerKind.Deletion) { return HandleDeletionTrigger(reason, initialListOfItemsToBeIncluded, filterText, updatedFilters, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper); } Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod; if (completionService == null) { filterMethod = (itemsWithPatternMatches, text) => CompletionService.FilterItems(completionHelper, itemsWithPatternMatches); } else { filterMethod = (itemsWithPatternMatches, text) => completionService.FilterItems(document, itemsWithPatternMatches, text); } return HandleNormalFiltering( filterMethod, filterText, updatedFilters, filterReason, data.Trigger.Character, initialListOfItemsToBeIncluded, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper); } finally { // Don't call ClearAndFree, which resets the capacity to a default value. initialListOfItemsToBeIncluded.Clear(); s_listOfMatchResultPool.Free(initialListOfItemsToBeIncluded); } static bool TryGetInitialTriggerLocation(AsyncCompletionSessionDataSnapshot data, out SnapshotPoint intialTriggerLocation) { var firstItem = data.InitialSortedList.FirstOrDefault(static item => item.Properties.ContainsProperty(CompletionSource.TriggerLocation)); if (firstItem != null) { return firstItem.Properties.TryGetProperty(CompletionSource.TriggerLocation, out intialTriggerLocation); } intialTriggerLocation = default; return false; } static bool ShouldBeFilteredOutOfCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> activeNonExpanderFilters) { if (item.Filters.Any(filter => activeNonExpanderFilters.Contains(filter))) { return false; } return true; } static bool ShouldBeFilteredOutOfExpandedCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> unselectedExpanders) { var associatedWithUnselectedExpander = false; foreach (var itemFilter in item.Filters) { if (itemFilter is CompletionExpander) { if (!unselectedExpanders.Contains(itemFilter)) { // If any of the associated expander is selected, the item should be included in the expanded list. return false; } associatedWithUnselectedExpander = true; } } // at this point, the item either: // 1. has no expander filter, therefore should be included // 2. or, all associated expanders are unselected, therefore should be excluded return associatedWithUnselectedExpander; } } private static bool IsAfterDot(ITextSnapshot snapshot, ITrackingSpan applicableToSpan) { var position = applicableToSpan.GetStartPoint(snapshot).Position; return position > 0 && snapshot[position - 1] == '.'; } private FilteredCompletionModel? HandleNormalFiltering( Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod, string filterText, ImmutableArray<CompletionFilterWithState> filters, CompletionFilterReason filterReason, char typeChar, List<MatchResult<VSCompletionItem>> itemsInList, bool hasSuggestedItemOptions, bool highlightMatchingPortions, CompletionHelper completionHelper) { // Not deletion. Defer to the language to decide which item it thinks best // matches the text typed so far. // Ask the language to determine which of the *matched* items it wants to select. var matchingItems = itemsInList.Where(r => r.MatchedFilterText) .SelectAsArray(t => (t.RoslynCompletionItem, t.PatternMatch)); var chosenItems = filterMethod(matchingItems, filterText); int selectedItemIndex; VSCompletionItem? uniqueItem = null; MatchResult<VSCompletionItem> bestOrFirstMatchResult; if (chosenItems.Length == 0) { // We do not have matches: pick the one with longest common prefix or the first item from the list. selectedItemIndex = 0; bestOrFirstMatchResult = itemsInList[0]; var longestCommonPrefixLength = bestOrFirstMatchResult.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText); for (var i = 1; i < itemsInList.Count; ++i) { var item = itemsInList[i]; var commonPrefixLength = item.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText); if (commonPrefixLength > longestCommonPrefixLength) { selectedItemIndex = i; bestOrFirstMatchResult = item; longestCommonPrefixLength = commonPrefixLength; } } } else { var recentItems = _recentItemsManager.RecentItems; // Of the items the service returned, pick the one most recently committed var bestItem = GetBestCompletionItemBasedOnMRU(chosenItems, recentItems); // Determine if we should consider this item 'unique' or not. A unique item // will be automatically committed if the user hits the 'invoke completion' // without bringing up the completion list. An item is unique if it was the // only item to match the text typed so far, and there was at least some text // typed. i.e. if we have "Console.$$" we don't want to commit something // like "WriteLine" since no filter text has actually been provided. However, // if "Console.WriteL$$" is typed, then we do want "WriteLine" to be committed. selectedItemIndex = itemsInList.IndexOf(i => Equals(i.RoslynCompletionItem, bestItem)); bestOrFirstMatchResult = itemsInList[selectedItemIndex]; var deduplicatedListCount = matchingItems.Count(r => !r.RoslynCompletionItem.IsPreferredItem()); if (deduplicatedListCount == 1 && filterText.Length > 0) { uniqueItem = itemsInList[selectedItemIndex].EditorCompletionItem; } } // Check that it is a filter symbol. We can be called for a non-filter symbol. // If inserting a non-filter character (neither IsPotentialFilterCharacter, nor Helpers.IsFilterCharacter), we should dismiss completion // except cases where this is the first symbol typed for the completion session (string.IsNullOrEmpty(filterText) or string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase)). // In the latter case, we should keep the completion because it was confirmed just before in InitializeCompletion. if (filterReason == CompletionFilterReason.Insertion && !string.IsNullOrEmpty(filterText) && !string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase) && !IsPotentialFilterCharacter(typeChar) && !Helpers.IsFilterCharacter(bestOrFirstMatchResult.RoslynCompletionItem, typeChar, filterText)) { return null; } var isHardSelection = IsHardSelection( filterText, bestOrFirstMatchResult.RoslynCompletionItem, bestOrFirstMatchResult.MatchedFilterText, hasSuggestedItemOptions); var updateSelectionHint = isHardSelection ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected; return new FilteredCompletionModel( GetHighlightedList(itemsInList, filterText, highlightMatchingPortions, completionHelper), selectedItemIndex, filters, updateSelectionHint, centerSelection: true, uniqueItem); } private static FilteredCompletionModel? HandleDeletionTrigger( CompletionTriggerReason filterTriggerKind, List<MatchResult<VSCompletionItem>> matchResults, string filterText, ImmutableArray<CompletionFilterWithState> filters, bool hasSuggestedItemOptions, bool highlightMatchingSpans, CompletionHelper completionHelper) { var matchingItems = matchResults.Where(r => r.MatchedFilterText); if (filterTriggerKind == CompletionTriggerReason.Insertion && !matchingItems.Any()) { // The user has typed something, but nothing in the actual list matched what // they were typing. In this case, we want to dismiss completion entirely. // The thought process is as follows: we aggressively brought up completion // to help them when they typed delete (in case they wanted to pick another // item). However, they're typing something that doesn't seem to match at all // The completion list is just distracting at this point. return null; } MatchResult<VSCompletionItem>? bestMatchResult = null; var moreThanOneMatchWithSamePriority = false; foreach (var currentMatchResult in matchingItems) { if (bestMatchResult == null) { // We had no best result yet, so this is now our best result. bestMatchResult = currentMatchResult; } else { var match = currentMatchResult.CompareTo(bestMatchResult.Value, filterText); if (match > 0) { moreThanOneMatchWithSamePriority = false; bestMatchResult = currentMatchResult; } else if (match == 0) { moreThanOneMatchWithSamePriority = true; } } } int index; bool hardSelect; // If we had a matching item, then pick the best of the matching items and // choose that one to be hard selected. If we had no actual matching items // (which can happen if the user deletes down to a single character and we // include everything), then we just soft select the first item. if (bestMatchResult != null) { // Only hard select this result if it's a prefix match // We need to do this so that // * deleting and retyping a dot in a member access does not change the // text that originally appeared before the dot // * deleting through a word from the end keeps that word selected // This also preserves the behavior the VB had through Dev12. hardSelect = !hasSuggestedItemOptions && bestMatchResult.Value.EditorCompletionItem.FilterText.StartsWith(filterText, StringComparison.CurrentCultureIgnoreCase); index = matchResults.IndexOf(bestMatchResult.Value); } else { index = 0; hardSelect = false; } return new FilteredCompletionModel( GetHighlightedList(matchResults, filterText, highlightMatchingSpans, completionHelper), index, filters, hardSelect ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected, centerSelection: true, uniqueItem: moreThanOneMatchWithSamePriority ? null : bestMatchResult.GetValueOrDefault().EditorCompletionItem); } private static ImmutableArray<CompletionItemWithHighlight> GetHighlightedList( List<MatchResult<VSCompletionItem>> matchResults, string filterText, bool highlightMatchingPortions, CompletionHelper completionHelper) { return matchResults.SelectAsArray(matchResult => { var highlightedSpans = GetHighlightedSpans(matchResult, completionHelper, filterText, highlightMatchingPortions); return new CompletionItemWithHighlight(matchResult.EditorCompletionItem, highlightedSpans); }); static ImmutableArray<Span> GetHighlightedSpans( MatchResult<VSCompletionItem> matchResult, CompletionHelper completionHelper, string filterText, bool highlightMatchingPortions) { if (highlightMatchingPortions) { if (matchResult.RoslynCompletionItem.HasDifferentFilterText) { // The PatternMatch in MatchResult is calculated based on Roslyn item's FilterText, // which can be used to calculate highlighted span for VSCompletion item's DisplayText w/o doing the matching again. // However, if the Roslyn item's FilterText is different from its DisplayText, // we need to do the match against the display text of the VS item directly to get the highlighted spans. return completionHelper.GetHighlightedSpans( matchResult.EditorCompletionItem.DisplayText, filterText, CultureInfo.CurrentCulture).SelectAsArray(s => s.ToSpan()); } var patternMatch = matchResult.PatternMatch; if (patternMatch.HasValue) { // Since VS item's display text is created as Prefix + DisplayText + Suffix, // we can calculate the highlighted span by adding an offset that is the length of the Prefix. return patternMatch.Value.MatchedSpans.SelectAsArray(s_highlightSpanGetter, matchResult.RoslynCompletionItem); } } // If there's no match for Roslyn item's filter text which is identical to its display text, // then we can safely assume there'd be no matching to VS item's display text. return ImmutableArray<Span>.Empty; } } private static FilteredCompletionModel? HandleAllItemsFilteredOut( CompletionTriggerReason triggerReason, ImmutableArray<CompletionFilterWithState> filters, CompletionRules completionRules) { if (triggerReason == CompletionTriggerReason.Insertion) { // If the user was just typing, and the list went to empty *and* this is a // language that wants to dismiss on empty, then just return a null model // to stop the completion session. if (completionRules.DismissIfEmpty) { return null; } } // If the user has turned on some filtering states, and we filtered down to // nothing, then we do want the UI to show that to them. That way the user // can turn off filters they don't want and get the right set of items. // If we are going to filter everything out, then just preserve the existing // model (and all the previously filtered items), but switch over to soft // selection. var selection = UpdateSelectionHint.SoftSelected; return new FilteredCompletionModel( ImmutableArray<CompletionItemWithHighlight>.Empty, selectedItemIndex: 0, filters, selection, centerSelection: true, uniqueItem: null); } private static ImmutableArray<CompletionFilterWithState> GetUpdatedFilters( List<MatchResult<VSCompletionItem>> filteredList, ImmutableArray<CompletionFilterWithState> filters) { // See which filters might be enabled based on the typed code using var _ = PooledHashSet<CompletionFilter>.GetInstance(out var textFilteredFilters); textFilteredFilters.AddRange(filteredList.SelectMany(n => n.EditorCompletionItem.Filters)); // When no items are available for a given filter, it becomes unavailable. // Expanders always appear available as long as it's presented. return filters.SelectAsArray(n => n.WithAvailability(n.Filter is CompletionExpander ? true : textFilteredFilters.Contains(n.Filter))); } /// <summary> /// Given multiple possible chosen completion items, pick the one that has the /// best MRU index. /// </summary> private static RoslynCompletionItem GetBestCompletionItemBasedOnMRU( ImmutableArray<RoslynCompletionItem> chosenItems, ImmutableArray<string> recentItems) { // Try to find the chosen item has been most recently used. var bestItem = chosenItems.First(); for (int i = 0, n = chosenItems.Length; i < n; i++) { var chosenItem = chosenItems[i]; var mruIndex1 = GetRecentItemIndex(recentItems, bestItem); var mruIndex2 = GetRecentItemIndex(recentItems, chosenItem); if ((mruIndex2 < mruIndex1) || (mruIndex2 == mruIndex1 && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem())) { bestItem = chosenItem; } } // If our best item appeared in the MRU list, use it if (GetRecentItemIndex(recentItems, bestItem) <= 0) { return bestItem; } // Otherwise use the chosen item that has the highest // matchPriority. for (int i = 1, n = chosenItems.Length; i < n; i++) { var chosenItem = chosenItems[i]; var bestItemPriority = bestItem.Rules.MatchPriority; var currentItemPriority = chosenItem.Rules.MatchPriority; if ((currentItemPriority > bestItemPriority) || ((currentItemPriority == bestItemPriority) && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem())) { bestItem = chosenItem; } } return bestItem; } private static int GetRecentItemIndex(ImmutableArray<string> recentItems, RoslynCompletionItem item) { var index = recentItems.IndexOf(item.FilterText); return -index; } private static RoslynCompletionItem GetOrAddRoslynCompletionItem(VSCompletionItem vsItem) { if (!vsItem.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem)) { roslynItem = RoslynCompletionItem.Create( displayText: vsItem.DisplayText, filterText: vsItem.FilterText, sortText: vsItem.SortText, displayTextSuffix: vsItem.Suffix); vsItem.Properties.AddProperty(CompletionSource.RoslynItem, roslynItem); } return roslynItem; } private static bool TryCreateMatchResult( CompletionHelper completionHelper, VSCompletionItem item, string filterText, CompletionTriggerKind initialTriggerKind, CompletionFilterReason filterReason, ImmutableArray<string> recentItems, bool highlightMatchingPortions, int currentIndex, out MatchResult<VSCompletionItem> matchResult) { var roslynItem = GetOrAddRoslynCompletionItem(item); return CompletionHelper.TryCreateMatchResult(completionHelper, roslynItem, item, filterText, initialTriggerKind, filterReason, recentItems, highlightMatchingPortions, currentIndex, out matchResult); } // PERF: Create a singleton to avoid lambda allocation on hot path private static readonly Func<TextSpan, RoslynCompletionItem, Span> s_highlightSpanGetter = (span, item) => span.MoveTo(item.DisplayTextPrefix?.Length ?? 0).ToSpan(); private static bool IsHardSelection( string filterText, RoslynCompletionItem item, bool matchedFilterText, bool useSuggestionMode) { if (item == null || useSuggestionMode) { return false; } // We don't have a builder and we have a best match. Normally this will be hard // selected, except for a few cases. Specifically, if no filter text has been // provided, and this is not a preselect match then we will soft select it. This // happens when the completion list comes up implicitly and there is something in // the MRU list. In this case we do want to select it, but not with a hard // selection. Otherwise you can end up with the following problem: // // dim i as integer =<space> // // Completion will comes up after = with 'integer' selected (Because of MRU). We do // not want 'space' to commit this. // If all that has been typed is punctuation, then don't hard select anything. // It's possible the user is just typing language punctuation and selecting // anything in the list will interfere. We only allow this if the filter text // exactly matches something in the list already. if (filterText.Length > 0 && IsAllPunctuation(filterText) && filterText != item.DisplayText) { return false; } // If the user hasn't actually typed anything, then don't hard select any item. // The only exception to this is if the completion provider has requested the // item be preselected. if (filterText.Length == 0) { // Item didn't want to be hard selected with no filter text. // So definitely soft select it. if (item.Rules.SelectionBehavior != CompletionItemSelectionBehavior.HardSelection) { return false; } // Item did not ask to be preselected. So definitely soft select it. if (item.Rules.MatchPriority == MatchPriority.Default) { return false; } } // The user typed something, or the item asked to be preselected. In // either case, don't soft select this. Debug.Assert(filterText.Length > 0 || item.Rules.MatchPriority != MatchPriority.Default); // If the user moved the caret left after they started typing, the 'best' match may not match at all // against the full text span that this item would be replacing. if (!matchedFilterText) { return false; } // There was either filter text, or this was a preselect match. In either case, we // can hard select this. return true; } private static bool IsAllPunctuation(string filterText) { foreach (var ch in filterText) { if (!char.IsPunctuation(ch)) { return false; } } return true; } /// <summary> /// A potential filter character is something that can filter a completion lists and is /// *guaranteed* to not be a commit character. /// </summary> private static bool IsPotentialFilterCharacter(char c) { // TODO(cyrusn): Actually use the right Unicode categories here. return char.IsLetter(c) || char.IsNumber(c) || 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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal class ItemManager : IAsyncCompletionItemManager { /// <summary> /// Used for filtering non-Roslyn data only. /// </summary> private readonly CompletionHelper _defaultCompletionHelper; private readonly RecentItemsManager _recentItemsManager; /// <summary> /// For telemetry. /// </summary> private readonly object _targetTypeCompletionFilterChosenMarker = new(); internal ItemManager(RecentItemsManager recentItemsManager) { // Let us make the completion Helper used for non-Roslyn items case-sensitive. // We can change this if get requests from partner teams. _defaultCompletionHelper = new CompletionHelper(isCaseSensitive: true); _recentItemsManager = recentItemsManager; } public Task<ImmutableArray<VSCompletionItem>> SortCompletionListAsync( IAsyncCompletionSession session, AsyncCompletionSessionInitialDataSnapshot data, CancellationToken cancellationToken) { if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isTargetTypeFilterEnabled) && isTargetTypeFilterEnabled) { AsyncCompletionLogger.LogSessionHasTargetTypeFilterEnabled(); // This method is called exactly once, so use the opportunity to set a baseline for telemetry. if (data.InitialList.Any(i => i.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches))) { AsyncCompletionLogger.LogSessionContainsTargetTypeFilter(); } } if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTypeImportCompletionEnabled) && isTypeImportCompletionEnabled) { AsyncCompletionLogger.LogSessionWithTypeImportCompletionEnabled(); } // Sort by default comparer of Roslyn CompletionItem var sortedItems = data.InitialList.OrderBy(GetOrAddRoslynCompletionItem).ToImmutableArray(); return Task.FromResult(sortedItems); } public Task<FilteredCompletionModel?> UpdateCompletionListAsync( IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken cancellationToken) => Task.FromResult(UpdateCompletionList(session, data, cancellationToken)); // We might need to handle large amount of items with import completion enabled, // so use a dedicated pool to minimize/avoid array allocations (especially in LOH) // Set the size of pool to 1 because we don't expect UpdateCompletionListAsync to be // called concurrently, which essentially makes the pooled list a singleton, // but we still use ObjectPool for concurrency handling just to be robust. private static readonly ObjectPool<List<MatchResult<VSCompletionItem>>> s_listOfMatchResultPool = new(factory: () => new(), size: 1); private FilteredCompletionModel? UpdateCompletionList( IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken cancellationToken) { if (!session.Properties.TryGetProperty(CompletionSource.HasSuggestionItemOptions, out bool hasSuggestedItemOptions)) { // This is the scenario when the session is created out of Roslyn, in some other provider, e.g. in Debugger. // For now, the default hasSuggestedItemOptions is false. hasSuggestedItemOptions = false; } hasSuggestedItemOptions |= data.DisplaySuggestionItem; var filterText = session.ApplicableToSpan.GetText(data.Snapshot); var reason = data.Trigger.Reason; var initialRoslynTriggerKind = Helpers.GetRoslynTriggerKind(data.InitialTrigger); // Check if the user is typing a number. If so, only proceed if it's a number // directly after a <dot>. That's because it is actually reasonable for completion // to be brought up after a <dot> and for the user to want to filter completion // items based on a number that exists in the name of the item. However, when // we are not after a dot (i.e. we're being brought up after <space> is typed) // then we don't want to filter things. Consider the user writing: // // dim i =<space> // // We'll bring up the completion list here (as VB has completion on <space>). // If the user then types '3', we don't want to match against Int32. if (filterText.Length > 0 && char.IsNumber(filterText[0])) { if (!IsAfterDot(data.Snapshot, session.ApplicableToSpan)) { // Dismiss the session. return null; } } // We need to filter if // 1. a non-empty strict subset of filters are selected // 2. a non-empty set of expanders are unselected var nonExpanderFilterStates = data.SelectedFilters.WhereAsArray(f => !(f.Filter is CompletionExpander)); var selectedNonExpanderFilters = nonExpanderFilterStates.SelectAsArray(f => f.IsSelected, f => f.Filter); var needToFilter = selectedNonExpanderFilters.Length > 0 && selectedNonExpanderFilters.Length < nonExpanderFilterStates.Length; var unselectedExpanders = data.SelectedFilters.SelectAsArray(f => !f.IsSelected && f.Filter is CompletionExpander, f => f.Filter); var needToFilterExpanded = unselectedExpanders.Length > 0; if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled) { // Telemetry: Want to know % of sessions with the "Target type matches" filter where that filter is actually enabled if (needToFilter && !session.Properties.ContainsProperty(_targetTypeCompletionFilterChosenMarker) && selectedNonExpanderFilters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) { AsyncCompletionLogger.LogTargetTypeFilterChosenInSession(); // Make sure we only record one enabling of the filter per session session.Properties.AddProperty(_targetTypeCompletionFilterChosenMarker, _targetTypeCompletionFilterChosenMarker); } } var filterReason = Helpers.GetFilterReason(data.Trigger); // We prefer using the original snapshot, which should always be available from items provided by Roslyn's CompletionSource. // Only use data.Snapshot in the theoretically possible but rare case when all items we are handling are from some non-Roslyn CompletionSource. var snapshotForDocument = TryGetInitialTriggerLocation(data, out var intialTriggerLocation) ? intialTriggerLocation.Snapshot : data.Snapshot; var document = snapshotForDocument?.TextBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); var completionService = document?.GetLanguageService<CompletionService>(); var completionRules = completionService?.GetRules() ?? CompletionRules.Default; var completionHelper = document != null ? CompletionHelper.GetHelper(document) : _defaultCompletionHelper; // DismissIfLastCharacterDeleted should be applied only when started with Insertion, and then Deleted all characters typed. // This conforms with the original VS 2010 behavior. if (initialRoslynTriggerKind == CompletionTriggerKind.Insertion && data.Trigger.Reason == CompletionTriggerReason.Backspace && completionRules.DismissIfLastCharacterDeleted && session.ApplicableToSpan.GetText(data.Snapshot).Length == 0) { // Dismiss the session return null; } var options = document?.Project.Solution.Options; var highlightMatchingPortions = options?.GetOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, document?.Project.Language) ?? false; // Nothing to highlight if user hasn't typed anything yet. highlightMatchingPortions = highlightMatchingPortions && filterText.Length > 0; // Use a monotonically increasing integer to keep track the original alphabetical order of each item. var currentIndex = 0; var initialListOfItemsToBeIncluded = s_listOfMatchResultPool.Allocate(); try { // Filter items based on the selected filters and matching. foreach (var item in data.InitialSortedList) { cancellationToken.ThrowIfCancellationRequested(); if (needToFilter && ShouldBeFilteredOutOfCompletionList(item, selectedNonExpanderFilters)) { continue; } if (needToFilterExpanded && ShouldBeFilteredOutOfExpandedCompletionList(item, unselectedExpanders)) { continue; } if (TryCreateMatchResult( completionHelper, item, filterText, initialRoslynTriggerKind, filterReason, _recentItemsManager.RecentItems, highlightMatchingPortions: highlightMatchingPortions, currentIndex, out var matchResult)) { initialListOfItemsToBeIncluded.Add(matchResult); currentIndex++; } } if (initialListOfItemsToBeIncluded.Count == 0) { return HandleAllItemsFilteredOut(reason, data.SelectedFilters, completionRules); } // Sort the items by pattern matching results. // Note that we want to preserve the original alphabetical order for items with same pattern match score, // but `List<T>.Sort` isn't stable. Therefore we have to add a monotonically increasing integer // to `MatchResult` to achieve this. initialListOfItemsToBeIncluded.Sort(MatchResult<VSCompletionItem>.SortingComparer); var showCompletionItemFilters = options?.GetOption(CompletionOptions.ShowCompletionItemFilters, document?.Project.Language) ?? true; var updatedFilters = showCompletionItemFilters ? GetUpdatedFilters(initialListOfItemsToBeIncluded, data.SelectedFilters) : ImmutableArray<CompletionFilterWithState>.Empty; // If this was deletion, then we control the entire behavior of deletion ourselves. if (initialRoslynTriggerKind == CompletionTriggerKind.Deletion) { return HandleDeletionTrigger(reason, initialListOfItemsToBeIncluded, filterText, updatedFilters, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper); } Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod; if (completionService == null) { filterMethod = (itemsWithPatternMatches, text) => CompletionService.FilterItems(completionHelper, itemsWithPatternMatches, text); } else { filterMethod = (itemsWithPatternMatches, text) => completionService.FilterItems(document, itemsWithPatternMatches, text); } return HandleNormalFiltering( filterMethod, filterText, updatedFilters, filterReason, data.Trigger.Character, initialListOfItemsToBeIncluded, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper); } finally { // Don't call ClearAndFree, which resets the capacity to a default value. initialListOfItemsToBeIncluded.Clear(); s_listOfMatchResultPool.Free(initialListOfItemsToBeIncluded); } static bool TryGetInitialTriggerLocation(AsyncCompletionSessionDataSnapshot data, out SnapshotPoint intialTriggerLocation) { var firstItem = data.InitialSortedList.FirstOrDefault(static item => item.Properties.ContainsProperty(CompletionSource.TriggerLocation)); if (firstItem != null) { return firstItem.Properties.TryGetProperty(CompletionSource.TriggerLocation, out intialTriggerLocation); } intialTriggerLocation = default; return false; } static bool ShouldBeFilteredOutOfCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> activeNonExpanderFilters) { if (item.Filters.Any(filter => activeNonExpanderFilters.Contains(filter))) { return false; } return true; } static bool ShouldBeFilteredOutOfExpandedCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> unselectedExpanders) { var associatedWithUnselectedExpander = false; foreach (var itemFilter in item.Filters) { if (itemFilter is CompletionExpander) { if (!unselectedExpanders.Contains(itemFilter)) { // If any of the associated expander is selected, the item should be included in the expanded list. return false; } associatedWithUnselectedExpander = true; } } // at this point, the item either: // 1. has no expander filter, therefore should be included // 2. or, all associated expanders are unselected, therefore should be excluded return associatedWithUnselectedExpander; } } private static bool IsAfterDot(ITextSnapshot snapshot, ITrackingSpan applicableToSpan) { var position = applicableToSpan.GetStartPoint(snapshot).Position; return position > 0 && snapshot[position - 1] == '.'; } private FilteredCompletionModel? HandleNormalFiltering( Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod, string filterText, ImmutableArray<CompletionFilterWithState> filters, CompletionFilterReason filterReason, char typeChar, List<MatchResult<VSCompletionItem>> itemsInList, bool hasSuggestedItemOptions, bool highlightMatchingPortions, CompletionHelper completionHelper) { // Not deletion. Defer to the language to decide which item it thinks best // matches the text typed so far. // Ask the language to determine which of the *matched* items it wants to select. var matchingItems = itemsInList.Where(r => r.MatchedFilterText) .SelectAsArray(t => (t.RoslynCompletionItem, t.PatternMatch)); var chosenItems = filterMethod(matchingItems, filterText); int selectedItemIndex; VSCompletionItem? uniqueItem = null; MatchResult<VSCompletionItem> bestOrFirstMatchResult; if (chosenItems.Length == 0) { // We do not have matches: pick the one with longest common prefix or the first item from the list. selectedItemIndex = 0; bestOrFirstMatchResult = itemsInList[0]; var longestCommonPrefixLength = bestOrFirstMatchResult.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText); for (var i = 1; i < itemsInList.Count; ++i) { var item = itemsInList[i]; var commonPrefixLength = item.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText); if (commonPrefixLength > longestCommonPrefixLength) { selectedItemIndex = i; bestOrFirstMatchResult = item; longestCommonPrefixLength = commonPrefixLength; } } } else { var recentItems = _recentItemsManager.RecentItems; // Of the items the service returned, pick the one most recently committed var bestItem = GetBestCompletionItemBasedOnMRU(chosenItems, recentItems); // Determine if we should consider this item 'unique' or not. A unique item // will be automatically committed if the user hits the 'invoke completion' // without bringing up the completion list. An item is unique if it was the // only item to match the text typed so far, and there was at least some text // typed. i.e. if we have "Console.$$" we don't want to commit something // like "WriteLine" since no filter text has actually been provided. However, // if "Console.WriteL$$" is typed, then we do want "WriteLine" to be committed. selectedItemIndex = itemsInList.IndexOf(i => Equals(i.RoslynCompletionItem, bestItem)); bestOrFirstMatchResult = itemsInList[selectedItemIndex]; var deduplicatedListCount = matchingItems.Count(r => !r.RoslynCompletionItem.IsPreferredItem()); if (deduplicatedListCount == 1 && filterText.Length > 0) { uniqueItem = itemsInList[selectedItemIndex].EditorCompletionItem; } } // Check that it is a filter symbol. We can be called for a non-filter symbol. // If inserting a non-filter character (neither IsPotentialFilterCharacter, nor Helpers.IsFilterCharacter), we should dismiss completion // except cases where this is the first symbol typed for the completion session (string.IsNullOrEmpty(filterText) or string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase)). // In the latter case, we should keep the completion because it was confirmed just before in InitializeCompletion. if (filterReason == CompletionFilterReason.Insertion && !string.IsNullOrEmpty(filterText) && !string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase) && !IsPotentialFilterCharacter(typeChar) && !Helpers.IsFilterCharacter(bestOrFirstMatchResult.RoslynCompletionItem, typeChar, filterText)) { return null; } var isHardSelection = IsHardSelection( filterText, bestOrFirstMatchResult.RoslynCompletionItem, bestOrFirstMatchResult.MatchedFilterText, hasSuggestedItemOptions); var updateSelectionHint = isHardSelection ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected; return new FilteredCompletionModel( GetHighlightedList(itemsInList, filterText, highlightMatchingPortions, completionHelper), selectedItemIndex, filters, updateSelectionHint, centerSelection: true, uniqueItem); } private static FilteredCompletionModel? HandleDeletionTrigger( CompletionTriggerReason filterTriggerKind, List<MatchResult<VSCompletionItem>> matchResults, string filterText, ImmutableArray<CompletionFilterWithState> filters, bool hasSuggestedItemOptions, bool highlightMatchingSpans, CompletionHelper completionHelper) { var matchingItems = matchResults.Where(r => r.MatchedFilterText); if (filterTriggerKind == CompletionTriggerReason.Insertion && !matchingItems.Any()) { // The user has typed something, but nothing in the actual list matched what // they were typing. In this case, we want to dismiss completion entirely. // The thought process is as follows: we aggressively brought up completion // to help them when they typed delete (in case they wanted to pick another // item). However, they're typing something that doesn't seem to match at all // The completion list is just distracting at this point. return null; } MatchResult<VSCompletionItem>? bestMatchResult = null; var moreThanOneMatchWithSamePriority = false; foreach (var currentMatchResult in matchingItems) { if (bestMatchResult == null) { // We had no best result yet, so this is now our best result. bestMatchResult = currentMatchResult; } else { var match = currentMatchResult.CompareTo(bestMatchResult.Value, filterText); if (match > 0) { moreThanOneMatchWithSamePriority = false; bestMatchResult = currentMatchResult; } else if (match == 0) { moreThanOneMatchWithSamePriority = true; } } } int index; bool hardSelect; // If we had a matching item, then pick the best of the matching items and // choose that one to be hard selected. If we had no actual matching items // (which can happen if the user deletes down to a single character and we // include everything), then we just soft select the first item. if (bestMatchResult != null) { // Only hard select this result if it's a prefix match // We need to do this so that // * deleting and retyping a dot in a member access does not change the // text that originally appeared before the dot // * deleting through a word from the end keeps that word selected // This also preserves the behavior the VB had through Dev12. hardSelect = !hasSuggestedItemOptions && bestMatchResult.Value.EditorCompletionItem.FilterText.StartsWith(filterText, StringComparison.CurrentCultureIgnoreCase); index = matchResults.IndexOf(bestMatchResult.Value); } else { index = 0; hardSelect = false; } return new FilteredCompletionModel( GetHighlightedList(matchResults, filterText, highlightMatchingSpans, completionHelper), index, filters, hardSelect ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected, centerSelection: true, uniqueItem: moreThanOneMatchWithSamePriority ? null : bestMatchResult.GetValueOrDefault().EditorCompletionItem); } private static ImmutableArray<CompletionItemWithHighlight> GetHighlightedList( List<MatchResult<VSCompletionItem>> matchResults, string filterText, bool highlightMatchingPortions, CompletionHelper completionHelper) { return matchResults.SelectAsArray(matchResult => { var highlightedSpans = GetHighlightedSpans(matchResult, completionHelper, filterText, highlightMatchingPortions); return new CompletionItemWithHighlight(matchResult.EditorCompletionItem, highlightedSpans); }); static ImmutableArray<Span> GetHighlightedSpans( MatchResult<VSCompletionItem> matchResult, CompletionHelper completionHelper, string filterText, bool highlightMatchingPortions) { if (highlightMatchingPortions) { if (matchResult.RoslynCompletionItem.HasDifferentFilterText) { // The PatternMatch in MatchResult is calculated based on Roslyn item's FilterText, // which can be used to calculate highlighted span for VSCompletion item's DisplayText w/o doing the matching again. // However, if the Roslyn item's FilterText is different from its DisplayText, // we need to do the match against the display text of the VS item directly to get the highlighted spans. return completionHelper.GetHighlightedSpans( matchResult.EditorCompletionItem.DisplayText, filterText, CultureInfo.CurrentCulture).SelectAsArray(s => s.ToSpan()); } var patternMatch = matchResult.PatternMatch; if (patternMatch.HasValue) { // Since VS item's display text is created as Prefix + DisplayText + Suffix, // we can calculate the highlighted span by adding an offset that is the length of the Prefix. return patternMatch.Value.MatchedSpans.SelectAsArray(s_highlightSpanGetter, matchResult.RoslynCompletionItem); } } // If there's no match for Roslyn item's filter text which is identical to its display text, // then we can safely assume there'd be no matching to VS item's display text. return ImmutableArray<Span>.Empty; } } private static FilteredCompletionModel? HandleAllItemsFilteredOut( CompletionTriggerReason triggerReason, ImmutableArray<CompletionFilterWithState> filters, CompletionRules completionRules) { if (triggerReason == CompletionTriggerReason.Insertion) { // If the user was just typing, and the list went to empty *and* this is a // language that wants to dismiss on empty, then just return a null model // to stop the completion session. if (completionRules.DismissIfEmpty) { return null; } } // If the user has turned on some filtering states, and we filtered down to // nothing, then we do want the UI to show that to them. That way the user // can turn off filters they don't want and get the right set of items. // If we are going to filter everything out, then just preserve the existing // model (and all the previously filtered items), but switch over to soft // selection. var selection = UpdateSelectionHint.SoftSelected; return new FilteredCompletionModel( ImmutableArray<CompletionItemWithHighlight>.Empty, selectedItemIndex: 0, filters, selection, centerSelection: true, uniqueItem: null); } private static ImmutableArray<CompletionFilterWithState> GetUpdatedFilters( List<MatchResult<VSCompletionItem>> filteredList, ImmutableArray<CompletionFilterWithState> filters) { // See which filters might be enabled based on the typed code using var _ = PooledHashSet<CompletionFilter>.GetInstance(out var textFilteredFilters); textFilteredFilters.AddRange(filteredList.SelectMany(n => n.EditorCompletionItem.Filters)); // When no items are available for a given filter, it becomes unavailable. // Expanders always appear available as long as it's presented. return filters.SelectAsArray(n => n.WithAvailability(n.Filter is CompletionExpander ? true : textFilteredFilters.Contains(n.Filter))); } /// <summary> /// Given multiple possible chosen completion items, pick the one that has the /// best MRU index, or the one with highest MatchPriority if none in MRU. /// </summary> private static RoslynCompletionItem GetBestCompletionItemBasedOnMRU( ImmutableArray<RoslynCompletionItem> chosenItems, ImmutableArray<string> recentItems) { Debug.Assert(chosenItems.Length > 0); // Try to find the chosen item has been most recently used. var bestItem = chosenItems[0]; for (int i = 1, n = chosenItems.Length; i < n; i++) { var chosenItem = chosenItems[i]; var mruIndex1 = GetRecentItemIndex(recentItems, bestItem); var mruIndex2 = GetRecentItemIndex(recentItems, chosenItem); if ((mruIndex2 < mruIndex1) || (mruIndex2 == mruIndex1 && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem())) { bestItem = chosenItem; } } // If our best item appeared in the MRU list, use it if (GetRecentItemIndex(recentItems, bestItem) <= 0) { return bestItem; } // Otherwise use the chosen item that has the highest // matchPriority. for (int i = 1, n = chosenItems.Length; i < n; i++) { var chosenItem = chosenItems[i]; var bestItemPriority = bestItem.Rules.MatchPriority; var currentItemPriority = chosenItem.Rules.MatchPriority; if ((currentItemPriority > bestItemPriority) || ((currentItemPriority == bestItemPriority) && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem())) { bestItem = chosenItem; } } return bestItem; } private static int GetRecentItemIndex(ImmutableArray<string> recentItems, RoslynCompletionItem item) { var index = recentItems.IndexOf(item.FilterText); return -index; } private static RoslynCompletionItem GetOrAddRoslynCompletionItem(VSCompletionItem vsItem) { if (!vsItem.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem)) { roslynItem = RoslynCompletionItem.Create( displayText: vsItem.DisplayText, filterText: vsItem.FilterText, sortText: vsItem.SortText, displayTextSuffix: vsItem.Suffix); vsItem.Properties.AddProperty(CompletionSource.RoslynItem, roslynItem); } return roslynItem; } private static bool TryCreateMatchResult( CompletionHelper completionHelper, VSCompletionItem item, string filterText, CompletionTriggerKind initialTriggerKind, CompletionFilterReason filterReason, ImmutableArray<string> recentItems, bool highlightMatchingPortions, int currentIndex, out MatchResult<VSCompletionItem> matchResult) { var roslynItem = GetOrAddRoslynCompletionItem(item); return CompletionHelper.TryCreateMatchResult(completionHelper, roslynItem, item, filterText, initialTriggerKind, filterReason, recentItems, highlightMatchingPortions, currentIndex, out matchResult); } // PERF: Create a singleton to avoid lambda allocation on hot path private static readonly Func<TextSpan, RoslynCompletionItem, Span> s_highlightSpanGetter = (span, item) => span.MoveTo(item.DisplayTextPrefix?.Length ?? 0).ToSpan(); private static bool IsHardSelection( string filterText, RoslynCompletionItem item, bool matchedFilterText, bool useSuggestionMode) { if (item == null || useSuggestionMode) { return false; } // We don't have a builder and we have a best match. Normally this will be hard // selected, except for a few cases. Specifically, if no filter text has been // provided, and this is not a preselect match then we will soft select it. This // happens when the completion list comes up implicitly and there is something in // the MRU list. In this case we do want to select it, but not with a hard // selection. Otherwise you can end up with the following problem: // // dim i as integer =<space> // // Completion will comes up after = with 'integer' selected (Because of MRU). We do // not want 'space' to commit this. // If all that has been typed is punctuation, then don't hard select anything. // It's possible the user is just typing language punctuation and selecting // anything in the list will interfere. We only allow this if the filter text // exactly matches something in the list already. if (filterText.Length > 0 && IsAllPunctuation(filterText) && filterText != item.DisplayText) { return false; } // If the user hasn't actually typed anything, then don't hard select any item. // The only exception to this is if the completion provider has requested the // item be preselected. if (filterText.Length == 0) { // Item didn't want to be hard selected with no filter text. // So definitely soft select it. if (item.Rules.SelectionBehavior != CompletionItemSelectionBehavior.HardSelection) { return false; } // Item did not ask to be preselected. So definitely soft select it. if (item.Rules.MatchPriority == MatchPriority.Default) { return false; } } // The user typed something, or the item asked to be preselected. In // either case, don't soft select this. Debug.Assert(filterText.Length > 0 || item.Rules.MatchPriority != MatchPriority.Default); // If the user moved the caret left after they started typing, the 'best' match may not match at all // against the full text span that this item would be replacing. if (!matchedFilterText) { return false; } // There was either filter text, or this was a preselect match. In either case, we // can hard select this. return true; } private static bool IsAllPunctuation(string filterText) { foreach (var ch in filterText) { if (!char.IsPunctuation(ch)) { return false; } } return true; } /// <summary> /// A potential filter character is something that can filter a completion lists and is /// *guaranteed* to not be a commit character. /// </summary> private static bool IsPotentialFilterCharacter(char c) { // TODO(cyrusn): Actually use the right Unicode categories here. return char.IsLetter(c) || char.IsNumber(c) || c == '_'; } } }
1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.CSharp Imports Microsoft.CodeAnalysis.CSharp.Formatting Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Tags Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Text.Projection Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class CSharpCompletionCommandHandlerTests <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_FirstNested(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 CProperty { get; set; } } public class C2 { public int IntProperty { get; set; } void M(C c) { _ = c is { CProperty$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=False) state.SendTypeChars("IP") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 2 }") Await state.AssertNoCompletionSession() Assert.Contains("c is { CProperty.IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnListPattern_FirstNested(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { } public class C2 { public C2 CProperty { get; set; } public int IntProperty { get; set; } void M(C c) { _ = c is { $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) ' This is the expected behavior until we implement support for list-patterns. state.SendTypeChars("CP") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_Hidden(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" LanguageVersion="Preview" CommonReferences="true"> <ProjectReference>VBAssembly1</ProjectReference> <Document FilePath="C.cs"> public class C3 { void M(C c) { _ = c is { CProperty$$ } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <Document><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Property CProperty As C2 End Class Public Class C2 Public Property IntProperty As Integer End Class ]]></Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=False) state.SendTypeChars("IP") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 2 }") Await state.AssertNoCompletionSession() Assert.Contains("c is { CProperty.IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_SecondNested(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 C2Property { get; set; } } public class C2 { public C3 C3Property { get; set; } } public class C3 { public int IntProperty { get; set; } void M(C c) { _ = c is { C2Property.C3Property$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=False) state.SendTypeChars("IP") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 2 }") Await state.AssertNoCompletionSession() Assert.Contains("c is { C2Property.C3Property.IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_SecondNested_Fields(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 C2Field; } public class C2 { public C3 C3Field; } public class C3 { public int IntField; void M(C c) { _ = c is { C2Field$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem(displayText:="C3Field:", isHardSelected:=False) state.SendTypeChars("CF") Await state.AssertSelectedCompletionItem(displayText:="C3Field:", isHardSelected:=True) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem(displayText:="IntField:", isHardSelected:=False) state.SendTypeChars("IF") Await state.AssertSelectedCompletionItem(displayText:="IntField:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 2 }") Await state.AssertNoCompletionSession() Assert.Contains("c is { C2Field.C3Field.IntField: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_ErrorProperty(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public int IntProperty { get; set; } void M(C c) { _ = c is { Error$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(".") Await state.AssertNoCompletionSession() state.SendTypeChars("IP") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 CProperty { get; set; } } public class C2 { public int IntProperty { get; set; } void M(C c) { _ = c is $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars("{ ") Await state.AssertSelectedCompletionItem(displayText:="CProperty:", isHardSelected:=False) state.SendTypeChars("CP") Await state.AssertSelectedCompletionItem(displayText:="CProperty:", isHardSelected:=True) state.SendTypeChars(".") Assert.Contains("c is { CProperty.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=False) state.SendTypeChars("IP") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 2 }") Await state.AssertNoCompletionSession() Assert.Contains("c is { CProperty.IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_AlreadyTestedBySimplePattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 CProperty { get; set; } } public class C2 { public int IntProperty { get; set; } void M(C c) { _ = c is { CProperty: 2$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) ' No second completion since already tested at top-level state.SendTypeChars(", ") Await state.AssertNoCompletionSession() state.SendTypeChars("CP") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_AlreadyTestedByExtendedPattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 CProperty { get; set; } } public class C2 { public int IntProperty { get; set; } public short ShortProperty { get; set; } void M(C c) { _ = c is { CProperty.IntProperty: 2$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(", ") Await state.AssertSelectedCompletionItem(displayText:="CProperty:", isHardSelected:=False) state.SendTypeChars("CP") Await state.AssertSelectedCompletionItem(displayText:="CProperty:", isHardSelected:=True) state.SendTypeChars(".") Assert.Contains("is { CProperty.IntProperty: 2, CProperty.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) ' Note: same completion is offered a second time Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=False) state.SendTypeChars("SP") Await state.AssertSelectedCompletionItem(displayText:="ShortProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 3") Await state.AssertNoCompletionSession() Assert.Contains("is { CProperty.IntProperty: 2, CProperty.ShortProperty: 3", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_AlreadyTestedByNestedPattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 CProperty { get; set; } } public class C2 { public int IntProperty { get; set; } public short ShortProperty { get; set; } void M(C c) { _ = c is { CProperty: { IntProperty: 2 }$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(", ") Await state.AssertNoCompletionSession() state.SendTypeChars("CProperty") Await state.AssertNoCompletionSession() state.SendTypeChars(".") Assert.Contains("is { CProperty: { IntProperty: 2 }, CProperty.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) ' Note: same completion is offered a second time Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=False) state.SendTypeChars("SP") Await state.AssertSelectedCompletionItem(displayText:="ShortProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 3") Await state.AssertNoCompletionSession() Assert.Contains("is { CProperty: { IntProperty: 2 }, CProperty.ShortProperty: 3", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_BeforeAnotherPattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 CProperty { get; set; } } public class C2 { public int IntProperty { get; set; } public short ShortProperty { get; set; } void M(C c) { _ = c is {$$ CProperty.IntProperty: 2 } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="CProperty:", isHardSelected:=False) state.SendTypeChars("CP") Await state.AssertSelectedCompletionItem(displayText:="CProperty:", isHardSelected:=True) state.SendTypeChars(".") Assert.Contains("is { CProperty. CProperty.IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertSelectedCompletionItem(displayText:="Equals", isHardSelected:=False) state.SendTypeChars("SP") Await state.AssertSelectedCompletionItem(displayText:="ShortProperty", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 3,") Await state.AssertNoCompletionSession() Assert.Contains("is { CProperty.ShortProperty: 3, CProperty.IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnPropertyPattern_BeforeAnotherPattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public int IntProperty { get; set; } public short ShortProperty { get; set; } } public class C2 { void M(C c) { _ = c is {$$ IntProperty: 2 } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="ShortProperty:", isHardSelected:=False) state.SendTypeChars("SP") Await state.AssertSelectedCompletionItem(displayText:="ShortProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 3,") Await state.AssertNoCompletionSession() Assert.Contains("is { ShortProperty: 3, IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnRecordBaseType(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> record Base(int Alice, int Bob); record Derived(int Other) : [|Base$$|] </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp9) state.SendTypeChars("(") If showCompletionInArgumentLists Then Await state.AssertSelectedCompletionItem(displayText:="Alice:", isHardSelected:=False) End If state.SendTypeChars("A") If showCompletionInArgumentLists Then Await state.AssertSelectedCompletionItem(displayText:="Alice:", isHardSelected:=True) End If state.SendTypeChars(": 1, B") If showCompletionInArgumentLists Then Await state.AssertSelectedCompletionItem(displayText:="Bob:", isHardSelected:=True) End If state.SendTab() state.SendTypeChars(": 2)") Await state.AssertNoCompletionSession() Assert.Contains(": Base(Alice: 1, Bob: 2)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(46397, "https://github.com/dotnet/roslyn/issues/46397")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnImplicitObjectCreationExpressionInitializer(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public int Alice; public int Bob; void M(int value) { C c = new() $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp9) state.SendTypeChars("{ ") Await state.AssertSelectedCompletionItem(displayText:="Alice", isHardSelected:=False) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("new() { Alice", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars(" = va") Await state.AssertSelectedCompletionItem(displayText:="value", isHardSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("new() { Alice = value", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(44921, "https://github.com/dotnet/roslyn/issues/44921")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnWithExpressionInitializer(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> record Base(int Alice, int Bob) { void M(int value) { _ = this with $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp9) state.SendTypeChars("{ ") Await state.AssertSelectedCompletionItem(displayText:="Alice", isHardSelected:=False) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("with { Alice", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars(" = va") Await state.AssertSelectedCompletionItem(displayText:="value", isHardSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("with { Alice = value", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(44921, "https://github.com/dotnet/roslyn/issues/44921")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnWithExpressionInitializer_AfterComma(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> record Base(int Alice, int Bob) { void M(int value) { _ = this with { Alice = value$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp9) state.SendTypeChars(", ") Await state.AssertSelectedCompletionItem(displayText:="Bob", isHardSelected:=False) state.SendTab() Await state.AssertNoCompletionSession() state.SendTypeChars(" = va") Await state.AssertSelectedCompletionItem(displayText:="value", isHardSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("with { Alice = value, Bob = value", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(47430, "https://github.com/dotnet/roslyn/issues/47430")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnWithExpressionForTypeParameter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public abstract record MyRecord { public string Name { get; init; } } public static class Test { public static TRecord WithNameSuffix&lt;TRecord&gt;(this TRecord record, string nameSuffix) where TRecord : MyRecord => record with { $$ }; } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp9) state.SendTypeChars("N") Await state.AssertSelectedCompletionItem(displayText:="Name", isHardSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("Name", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnWithExpressionInitializer_AnonymousType(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M() { var a = new { Property = 1 }; _ = a $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars("w") Await state.AssertSelectedCompletionItem(displayText:="with", isHardSelected:=False) state.SendTab() state.SendTypeChars(" { ") Await state.AssertSelectedCompletionItem(displayText:="Property", isHardSelected:=False) state.SendTypeChars("P") Await state.AssertSelectedCompletionItem(displayText:="Property", isHardSelected:=True) state.SendTypeChars(" = 2") Await state.AssertNoCompletionSession() Assert.Contains("with { Property = 2", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(44921, "https://github.com/dotnet/roslyn/issues/44921")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnObjectCreation(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { int Alice { get; set; } void M() { _ = new C() $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("{ ") Await state.AssertSelectedCompletionItem(displayText:="Alice", isHardSelected:=False) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("new C() { Alice", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(541201, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541201")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TabCommitsWithoutAUniqueMatch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("using System.Ne") Await state.AssertSelectedCompletionItem(displayText:="Net", isHardSelected:=True) state.SendTypeChars("x") Await state.AssertSelectedCompletionItem(displayText:="Net", isSoftSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("using System.Net", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBetweenTwoDotsInNamespaceName(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace N.O.P { } namespace N$$.P { } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem(displayText:="O", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAtEndOfFile(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document>$$</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("usi") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("using", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(44459, "https://github.com/dotnet/roslyn/issues/44459")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectUsingOverUshort(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' 'us' should select 'using' instead of 'ushort' (even though 'ushort' sorts higher in the list textually). state.SendTypeChars("us") Await state.AssertSelectedCompletionItem(displayText:="using", isHardSelected:=True) Await state.AssertCompletionItemsContain("ushort", "") ' even after 'ushort' is selected, deleting the 'h' should still take us back to 'using'. state.SendTypeChars("h") Await state.AssertSelectedCompletionItem(displayText:="ushort", isHardSelected:=True) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="using", isHardSelected:=True) End Using End Function <WorkItem(44459, "https://github.com/dotnet/roslyn/issues/44459")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectUshortOverUsingOnceInMRU(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ush") Await state.AssertCompletionItemsContain("ushort", "") state.SendTab() Assert.Contains("ushort", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendDeleteWordToLeft() ' 'ushort' should be in the MRU now. so typing 'us' should select it instead of 'using'. state.SendTypeChars("us") Await state.AssertSelectedCompletionItem(displayText:="ushort", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDeletingWholeWordResetCompletionToTheDefaultItem(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void M() { var replyUri = new Uri(""); $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendTypeChars("repl") state.SendTab() For i = 1 To 7 state.SendBackspace() Await state.WaitForAsynchronousOperationsAsync() Next Await state.AssertCompletionSession() state.SendBackspace() Await state.AssertSelectedCompletionItem("AccessViolationException") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestTabsDoNotTriggerCompletion(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void M() { var replyUri = new Uri(""); replyUri$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTab() state.SendTab() Assert.Equal(" replyUri" & vbTab & vbTab, state.GetLineTextFromCaretPosition()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEnterDoesNotTriggerCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void M() { String.Equals("foo", "bar", $$StringComparison.CurrentCulture) } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendReturn() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotAtStartOfExistingWord(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document>$$using</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("u") Await state.AssertNoCompletionSession() Assert.Contains("using", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMSCorLibTypes(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class c : $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("A") Await state.AssertCompletionItemsContainAll("Attribute", "Exception", "IDisposable") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFiltering1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class c { $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Sy") Await state.AssertCompletionItemsContainAll("OperatingSystem", "System", "SystemException") Await state.AssertCompletionItemsDoNotContainAny("Exception", "Activator") End Using End Function ' NOTE(cyrusn): This should just be a unit test for SymbolCompletionProvider. However, I'm ' just porting the integration tests to here for now. <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMultipleTypes(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { $$ } struct S { } enum E { } interface I { } delegate void D(); </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("C") Await state.AssertCompletionItemsContainAll("C", "S", "E", "I", "D") End Using End Function ' NOTE(cyrusn): This should just be a unit test for KeywordCompletionProvider. However, I'm ' just porting the integration tests to here for now. <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInEmptyFile(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("abstract", "class", "namespace") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotAfterTypingDotAfterIntegerLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class c { void M() { 3$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterExplicitInvokeAfterDotAfterIntegerLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class c { void M() { 3.$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("ToString") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TestTypingDotBeforeExistingDot(showCompletionInArgumentLists As Boolean) As Task ' Starting C# 8.0 two dots are considered as a DotDotToken of a Range expression. ' However, typing dot before a single dot (and adding the second one) should lead to a completion ' in the context of the previous token if this completion exists. Using state = TestStateFactory.CreateCSharpTestState( <Document> class c { void M() { this$$.ToString() } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionItemsContainAll("ToString") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypingDotAfterExistingDot(showCompletionInArgumentLists As Boolean) As Task ' Starting C# 8.0 two dots are considered as a DotDotToken of a Range expression. ' A test above (TestTypingDotBeforeExistingDot) verifies that the completion happens ' if we type dot before a single dot. ' However, we should not have a completion if typing dot after a dot. Using state = TestStateFactory.CreateCSharpTestState( <Document> class c { void M() { this.$$ToString() } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TestInvokingCompletionBetweenTwoDots(showCompletionInArgumentLists As Boolean) As Task ' Starting C# 8.0 two dots are considered as a DotDotToken of a Range expression. ' However, we may want to have a completion when invoking it aqfter the first dot. Using state = TestStateFactory.CreateCSharpTestState( <Document> class c { void M() { this.$$.ToString() } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("ToString") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestEnterIsConsumed(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> class Class1 { void Main(string[] args) { $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("System.TimeSpan.FromMin") state.SendReturn() Assert.Equal(<text> class Class1 { void Main(string[] args) { System.TimeSpan.FromMinutes } }</text>.NormalizedValue, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestEnterIsConsumedWithAfterFullyTypedWordOption_NotFullyTyped(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> class Class1 { void Main(string[] args) { $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.EnterKeyBehavior, LanguageNames.CSharp, EnterKeyRule.AfterFullyTypedWord))) state.SendTypeChars("System.TimeSpan.FromMin") state.SendReturn() Assert.Equal(<text> class Class1 { void Main(string[] args) { System.TimeSpan.FromMinutes } }</text>.NormalizedValue, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestEnterIsConsumedWithAfterFullyTypedWordOption_FullyTyped(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> class Class1 { void Main(string[] args) { $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.EnterKeyBehavior, LanguageNames.CSharp, EnterKeyRule.AfterFullyTypedWord))) state.SendTypeChars("System.TimeSpan.FromMinutes") state.SendReturn() Assert.Equal(<text> class Class1 { void Main(string[] args) { System.TimeSpan.FromMinutes } }</text>.NormalizedValue, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDescription1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; /// <summary> /// TestDocComment /// </summary> class TestException : Exception { } class MyException : $$]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Test") Await state.AssertSelectedCompletionItem(description:="class TestException" & vbCrLf & "TestDocComment") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestObjectCreationPreselection1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections.Generic; class C { public void Goo() { List<int> list = new$$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True) Await state.AssertCompletionItemsContainAll("LinkedList", "List", "System") state.SendTypeChars("Li") Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True) Await state.AssertCompletionItemsContainAll("LinkedList", "List") Await state.AssertCompletionItemsDoNotContainAny("System") state.SendTypeChars("n") Await state.AssertSelectedCompletionItem(displayText:="LinkedList", displayTextSuffix:="<>", isHardSelected:=True) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True) state.SendTab() Assert.Contains("new List<int>", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDeconstructionDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { var ($$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("i") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDeconstructionDeclaration2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { var (a, $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("i") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDeconstructionDeclaration3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { var ($$) = (1, 2); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("i") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedDeconstructionDeclarationWithVar(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var a$$) = (1, 2); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem(displayText:="as", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedDeconstructionDeclarationWithVarAfterComma(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var a, var a$$) = (1, 2); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem(displayText:="as", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedVarDeconstructionDeclarationWithVar(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var a, var ($$)) = (1, 2); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("a") Await state.AssertNoCompletionSession() state.SendTypeChars(", a") Await state.AssertNoCompletionSession() Assert.Contains("(var a, var (a, a)) = ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestVarDeconstructionDeclarationWithVar(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" (a") Await state.AssertNoCompletionSession() state.SendTypeChars(", a") Await state.AssertNoCompletionSession() Assert.Contains("var (a, a", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedDeconstructionDeclarationWithSymbol(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { ($$) = (1, 2); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("vari") Await state.AssertSelectedCompletionItem(displayText:="Variable", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(Variable ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertNoCompletionSession() state.SendTypeChars("x, vari") Await state.AssertSelectedCompletionItem(displayText:="Variable", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(Variable x, Variable ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertSelectedCompletionItem(displayText:="Variable", isHardSelected:=False) Await state.AssertCompletionItemsContainAll("variable") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedDeconstructionDeclarationWithInt(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Integer { public void Goo() { ($$) = (1, 2); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("int") Await state.AssertSelectedCompletionItem(displayText:="int", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(int ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertNoCompletionSession() state.SendTypeChars("x, int") Await state.AssertSelectedCompletionItem(displayText:="int", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(int x, int ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestIncompleteParenthesizedDeconstructionDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { ($$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(", va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(")") Assert.Contains("(var a, var a)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestIncompleteParenthesizedDeconstructionDeclaration2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { ($$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(", va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendReturn() Dim caretLine = state.GetLineFromCurrentCaretPosition() Assert.Contains(" )", caretLine.GetText(), StringComparison.Ordinal) Dim previousLine = caretLine.Snapshot.Lines(caretLine.LineNumber - 1) Assert.Contains("(var a, var a", previousLine.GetText(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceInIncompleteParenthesizedDeconstructionDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var as$$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(", var as") state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(")") Await state.AssertNoCompletionSession() Assert.Contains("(var a, var a)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceInParenthesizedDeconstructionDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var as$$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(", var as") state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendReturn() Await state.AssertNoCompletionSession() Dim caretLine = state.GetLineFromCurrentCaretPosition() Assert.Contains(" )", caretLine.GetText(), StringComparison.Ordinal) Dim previousLine = caretLine.Snapshot.Lines(caretLine.LineNumber - 1) Assert.Contains("(var a, var a", previousLine.GetText(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(17256, "https://github.com/dotnet/roslyn/issues/17256")> Public Async Function TestThrowExpression(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public object Goo() { return null ?? throw new$$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Exception", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(17256, "https://github.com/dotnet/roslyn/issues/17256")> Public Async Function TestThrowStatement(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public object Goo() { throw new$$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Exception", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNonTrailingNamedArgumentInCSharp7_1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" LanguageVersion="7.1" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> class C { public void M() { int better = 2; M(a: 1, $$) } public void M(int a, int bar, int c) { } } </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("b") Await state.AssertSelectedCompletionItem(displayText:="bar", displayTextSuffix:=":", isHardSelected:=True) state.SendTypeChars("e") Await state.AssertSelectedCompletionItem(displayText:="bar", displayTextSuffix:=":", isSoftSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNonTrailingNamedArgumentInCSharp7_2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" LanguageVersion="7.2" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> class C { public void M() { int better = 2; M(a: 1, $$) } public void M(int a, int bar, int c) { } } </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("b") Await state.AssertSelectedCompletionItem(displayText:="better", isHardSelected:=True) state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="bar", displayTextSuffix:=":", isHardSelected:=True) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="better", isHardSelected:=True) state.SendTypeChars(", ") Assert.Contains("M(a: 1, better,", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestDefaultSwitchLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { switch (o) { default: goto $$ } } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="default", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestGotoOrdinaryLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { label1: goto $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("l") Await state.AssertSelectedCompletionItem(displayText:="label1", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto label1;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestEscapedDefaultLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { @default: goto $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="@default", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto @default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestEscapedDefaultLabel2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { switch (o) { default: @default: goto $$ } } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="default", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestEscapedDefaultLabelWithoutSwitch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { @default: goto $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="@default", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto @default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestArrayInitialization(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { Class[] x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("new ") Await state.AssertSelectedCompletionItem(displayText:="Class", isSoftSelected:=True) state.SendTypeChars("C") Await state.AssertSelectedCompletionItem(displayText:="Class", isHardSelected:=True) state.SendTypeChars("[") Assert.Contains("Class[] x = new Class[", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars("] {") Assert.Contains("Class[] x = new Class[] {", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestImplicitArrayInitialization(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { Class[] x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("n") Await state.AssertSelectedCompletionItem(displayText:="nameof", isHardSelected:=True) state.SendTypeChars("e") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Class", isSoftSelected:=True) state.SendTypeChars("[") Assert.Contains("Class[] x = new [", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars("] {") Assert.Contains("Class[] x = new [] {", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestImplicitArrayInitialization2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { Class[] x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ne") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars("[") Assert.Contains("Class[] x = new[", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestImplicitArrayInitialization3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { Class[] x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ne") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Class", isSoftSelected:=True) Assert.Contains("Class[] x = new ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars("[") Assert.Contains("Class[] x = new [", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestImplicitArrayInitialization4(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { Class[] x =$$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("{") Assert.Contains("Class[] x = {", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestImplicitArrayInitialization_WithTab(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { Class[] x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ne") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Class", isSoftSelected:=True) Assert.Contains("Class[] x = new ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTab() Assert.Contains("Class[] x = new Class", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestTypelessImplicitArrayInitialization(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { var x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ne") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("[") Assert.Contains("var x = new [", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars("] {") Assert.Contains("var x = new [] {", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestTypelessImplicitArrayInitialization2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { var x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ne") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars("[") Assert.Contains("var x = new[", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestTypelessImplicitArrayInitialization3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { var x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ne") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("var x = new ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars("[") Assert.Contains("var x = new [", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestPropertyInPropertySubpattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { int Prop { get; set; } int OtherProp { get; set; } public void M() { _ = this is $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendTypeChars("C") Await state.AssertSelectedCompletionItem(displayText:="Class", isHardSelected:=True) state.SendTypeChars(" { P") Await state.AssertSelectedCompletionItem(displayText:="Prop", displayTextSuffix:=":", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("{ Prop:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars(" 0, ") Await state.AssertSelectedCompletionItem(displayText:="OtherProp", displayTextSuffix:=":", isSoftSelected:=True) state.SendTypeChars("O") Await state.AssertSelectedCompletionItem(displayText:="OtherProp", displayTextSuffix:=":", isHardSelected:=True) state.SendTypeChars(": 1 }") Assert.Contains("is Class { Prop: 0, OtherProp: 1 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestPropertyInPropertySubpattern_TriggerWithSpace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { int Prop { get; set; } int OtherProp { get; set; } public void M() { _ = this is $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendTypeChars("C") Await state.AssertSelectedCompletionItem(displayText:="Class", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("is Class", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars("{ P") Await state.AssertSelectedCompletionItem(displayText:="Prop", displayTextSuffix:=":", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("is Class { Prop ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars(":") Assert.Contains("is Class { Prop :", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars(" 0, ") Await state.AssertSelectedCompletionItem(displayText:="OtherProp", displayTextSuffix:=":", isSoftSelected:=True) state.SendTypeChars("O") Await state.AssertSelectedCompletionItem(displayText:="OtherProp", displayTextSuffix:=":", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("is Class { Prop : 0, OtherProp", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars(": 1 }") Assert.Contains("is Class { Prop : 0, OtherProp : 1 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestSymbolInTupleLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Fo() { ($$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("F") Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("(F:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestSymbolInTupleLiteralAfterComma(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Fo() { (x, $$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("F") Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("(x, F:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function ColonInTupleNameInTupleLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = ($$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("fi") Await state.AssertSelectedCompletionItem(displayText:="first", displayTextSuffix:=":", isHardSelected:=True) Assert.Equal("first", state.GetSelectedItem().FilterText) state.SendTypeChars(":") Assert.Contains("(first:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function ColonInExactTupleNameInTupleLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = ($$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("first") Await state.AssertSelectedCompletionItem(displayText:="first", displayTextSuffix:=":", isHardSelected:=True) Assert.Equal("first", state.GetSelectedItem().FilterText) state.SendTypeChars(":") Assert.Contains("(first:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function ColonInTupleNameInTupleLiteralAfterComma(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = (0, $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("se") Await state.AssertSelectedCompletionItem(displayText:="second", displayTextSuffix:=":", isHardSelected:=True) Assert.Equal("second", state.GetSelectedItem().FilterText) state.SendTypeChars(":") Assert.Contains("(0, second:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function TabInTupleNameInTupleLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = ($$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("fi") Await state.AssertSelectedCompletionItem(displayText:="first", displayTextSuffix:=":", isHardSelected:=True) Assert.Equal("first", state.GetSelectedItem().FilterText) state.SendTab() state.SendTypeChars(":") state.SendTypeChars("0") Assert.Contains("(first:0", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function TabInExactTupleNameInTupleLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = ($$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("first") Await state.AssertSelectedCompletionItem(displayText:="first", displayTextSuffix:=":", isHardSelected:=True) Assert.Equal("first", state.GetSelectedItem().FilterText) state.SendTab() state.SendTypeChars(":") state.SendTypeChars("0") Assert.Contains("(first:0", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function TabInTupleNameInTupleLiteralAfterComma(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = (0, $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("se") Await state.AssertSelectedCompletionItem(displayText:="second", displayTextSuffix:=":", isHardSelected:=True) Assert.Equal("second", state.GetSelectedItem().FilterText) state.SendTab() state.SendTypeChars(":") state.SendTypeChars("1") Assert.Contains("(0, second:1", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestKeywordInTupleLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { ($$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="decimal", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("(d:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestTupleType(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { ($$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="decimal", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(decimal ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestDefaultKeyword(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { switch(true) { $$ } } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("def") Await state.AssertSelectedCompletionItem(displayText:="default", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("default:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestInvocationExpression(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo(int Alice) { Goo($$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("A") Await state.AssertSelectedCompletionItem(displayText:="Alice", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("Goo(Alice:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestImplicitObjectCreationExpression(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ public class C { public C(int Alice, int Bob) { } public C(string ignored) { } public void M() { C c = new($$ } }]]></Document>, languageVersion:=LanguageVersion.CSharp9, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("A") Await state.AssertSelectedCompletionItem(displayText:="Alice:", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("new(Alice:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestImplicitObjectCreationExpression_WithSpace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ public class C { public C(int Alice, int Bob) { } public C(string ignored) { } public void M() { C c = new$$ } }]]></Document>, languageVersion:=LanguageVersion.CSharp9, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="C", isHardSelected:=True) state.SendTypeChars("(") If showCompletionInArgumentLists Then Await state.AssertSignatureHelpSession() Else Await state.AssertNoCompletionSession() End If state.SendTypeChars("A") Await state.AssertSelectedCompletionItem(displayText:="Alice:", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("new C(Alice:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestInvocationExpressionAfterComma(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo(int Alice, int Bob) { Goo(1, $$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("B") Await state.AssertSelectedCompletionItem(displayText:="Bob", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("Goo(1, Bob:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestCaseLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Fo() { switch (1) { case $$ } } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("F") Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("case Fo:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(543268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543268")> Public Async Function TestTypePreselection1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ partial class C { } partial class C { $$ }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("C") Await state.AssertSelectedCompletionItem(displayText:="C", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertCompletionSession() End Using End Function <WorkItem(543519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543519")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNewPreselectionAfterVar(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { var c = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("new ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(543559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543559")> <WorkItem(543561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543561")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEscapedIdentifiers(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class @return { void goo() { $$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("@") Await state.AssertNoCompletionSession() state.SendTypeChars("r") Await state.AssertSelectedCompletionItem(displayText:="@return", isHardSelected:=True) state.SendTab() Assert.Contains("@return", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(543771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543771")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitUniqueItem1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main(string[] args) { Console.WriteL$$(); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("WriteLine()", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(543771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543771")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitUniqueItem2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main(string[] args) { Console.WriteL$$ine(); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("using Sys") Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars("(") Await state.AssertNoCompletionSession() Assert.Contains("using Sys(", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("using Sys") Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.Contains("using System.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("using Sys") Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars(";") Await state.AssertNoCompletionSession() state.AssertMatchesTextStartingAtLine(1, "using System;") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective4(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("using Sys") Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() Assert.Contains("using Sys ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function KeywordsIncludedInObjectCreationCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo() { string s = new$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="string", isHardSelected:=True) Await state.AssertCompletionItemsContainAll("int") End Using End Function <WorkItem(544293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544293")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoKeywordsOrSymbolsAfterNamedParameterWithCSharp7(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class Goo { void Test() { object m = null; Method(obj:m, $$ } void Method(object obj, int num = 23, string str = "") { } } </Document>, languageVersion:=LanguageVersion.CSharp7, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("a") Await state.AssertCompletionItemsDoNotContainAny("System", "int") Await state.AssertCompletionItemsContain("num", ":") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function KeywordsOrSymbolsAfterNamedParameter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class Goo { void Test() { object m = null; Method(obj:m, $$ } void Method(object obj, int num = 23, string str = "") { } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("a") Await state.AssertCompletionItemsContainAll("System", "int") Await state.AssertCompletionItemsContain("num", ":") End Using End Function <WorkItem(544017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544017")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionTriggeredOnSpace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Goo { void Bar(int a, Numeros n) { } void Baz() { Bar(0$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(", ") Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True) Assert.Equal(1, state.GetCompletionItems().Where(Function(c) c.DisplayText = "Numeros").Count()) End Using End Function <WorkItem(479078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/479078")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionTriggeredOnSpaceForNullables(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Goo { void Bar(int a, Numeros? n) { } void Baz() { Bar(0$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(", ") Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True) Assert.Equal(1, state.GetCompletionItems().Where(Function(c) c.DisplayText = "Numeros").Count()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub EnumCompletionTriggeredOnDot(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Goo { void Bar() { Numeros num = $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Nu.") Assert.Contains("Numeros num = Numeros.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionNotTriggeredOnPlusCommitCharacter(showCompletionInArgumentLists As Boolean) As Task Await EnumCompletionNotTriggeredOn("+"c, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionNotTriggeredOnLeftBraceCommitCharacter(showCompletionInArgumentLists As Boolean) As Task Await EnumCompletionNotTriggeredOn("{"c, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionNotTriggeredOnSpaceCommitCharacter(showCompletionInArgumentLists As Boolean) As Task Await EnumCompletionNotTriggeredOn(" "c, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionNotTriggeredOnSemicolonCommitCharacter(showCompletionInArgumentLists As Boolean) As Task Await EnumCompletionNotTriggeredOn(";"c, showCompletionInArgumentLists) End Function Private Shared Async Function EnumCompletionNotTriggeredOn(c As Char, showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Goo { void Bar() { Numeros num = $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Nu") Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True) state.SendTypeChars(c.ToString()) Await state.AssertSessionIsNothingOrNoCompletionItemLike("Numberos") Assert.Contains(String.Format("Numeros num = Nu{0}", c), state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(49632, "https://github.com/dotnet/roslyn/pull/49632")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionEnumTypeAndValues() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace A { public enum Colors { Red, Green } } namespace B { class Program { static void Main() { var color = A.Colors.Red; switch (color) { case $$ } } } </Document>) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain(Function(i) i.DisplayText = "A.Colors" AndAlso i.FilterText = "Colors") Await state.AssertCompletionItemsContain(Function(i) i.DisplayText = "A.Colors.Green" AndAlso i.FilterText = "A.Colors.Green") Await state.AssertCompletionItemsContain(Function(i) i.DisplayText = "A.Colors.Red" AndAlso i.FilterText = "A.Colors.Red") Await state.AssertSelectedCompletionItem("A.Colors", isHardSelected:=True) End Using End Function <WorkItem(49632, "https://github.com/dotnet/roslyn/pull/49632")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionEnumTypeSelectionSequenceTest() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public enum Colors { Red, Green } class Program { void M(Colors color) { } static void Main() { M$$ } } </Document>) state.SendTypeChars("(") Await state.AssertCompletionSession Await state.AssertCompletionItemsContain("Colors", "") Await state.AssertCompletionItemsContain("Colors.Green", "") Await state.AssertCompletionItemsContain("Colors.Red", "") Await state.AssertSelectedCompletionItem("Colors", isHardSelected:=True) state.SendDownKey() 'Select "Colors.Red" state.SendTab() ' Insert "Colors.Red" state.SendUndo() 'Undo insert state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Colors", isHardSelected:=True) End Using End Function <WorkItem(49632, "https://github.com/dotnet/roslyn/pull/49632")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionEnumTypeAndValuesWithAlias() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using AT = System.AttributeTargets; public class Program { static void M(AT attributeTargets) { } public static void Main() { M($$ } } </Document>) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain(Function(i) i.DisplayText = "AT" AndAlso i.SortText = "AT" AndAlso i.FilterText = "AT") Await state.AssertCompletionItemsContain(Function(i) i.DisplayText = "AT.All" AndAlso i.FilterText = "AT.All") Await state.AssertSelectedCompletionItem("AT", isHardSelected:=True) End Using End Function <WorkItem(544296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544296")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestVerbatimNamedIdentifierFiltering(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class Program { void Goo(int @int) { Goo($$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("i") Await state.AssertCompletionSession() Await state.AssertCompletionItemsContain("@int", ":") state.SendTypeChars("n") Await state.AssertCompletionItemsContain("@int", ":") state.SendTypeChars("t") Await state.AssertCompletionItemsContain("@int", ":") End Using End Function <WorkItem(543687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543687")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoPreselectInInvalidObjectCreationLocation(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { void Test() { $$ } } class Bar { } class Goo<T> : IGoo<T> { } interface IGoo<T> { }]]> </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("IGoo<Bar> a = new ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(544925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544925")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestQualifiedEnumSelection(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class Program { void Main() { Environment.GetFolderPath$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") state.SendTab() Assert.Contains("Environment.SpecialFolder", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Sub <WorkItem(545070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545070")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTextChangeSpanWithAtCharacter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class @event { $$@event() { } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("public ") Await state.AssertNoCompletionSession() Assert.Contains("public @event", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDoNotInsertColonSoThatUserCanCompleteOutAVariableNameThatDoesNotCurrentlyExist_IE_TheCyrusCase(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System.Threading; class Program { static void Main(string[] args) { Goo($$) } void Goo(CancellationToken cancellationToken) { } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("can") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("Goo(cancellationToken)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function #If False Then <Scenario Name="Verify correct intellisense selection on ENTER"> <SetEditorText> <![CDATA[class Class1 { void Main(string[] args) { // } }]]> </SetEditorText> <PlaceCursor Marker="//"/> <SendKeys>var a = System.TimeSpan.FromMin{ENTER}{(}</SendKeys> <VerifyEditorContainsText> <![CDATA[class Class1 { void Main(string[] args) { var a = System.TimeSpan.FromMinutes( } }]]> </VerifyEditorContainsText> </Scenario> #End If <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedPropertyCompletionCommitWithTab(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } [MyAttribute($$ public class Goo { } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Nam") state.SendTab() Await state.AssertNoCompletionSession() Assert.Equal("[MyAttribute(Name =", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function LocalFunctionAttributeNamedPropertyCompletionCommitWithTab(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } public class Goo { void M() { [MyAttribute($$ void local1() { } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Nam") state.SendTab() Await state.AssertNoCompletionSession() Assert.Equal(" [MyAttribute(Name =", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeOnLocalFunctionCompletionCommitWithTab(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyGoodAttribute : System.Attribute { public string Name { get; set; } } public class Goo { void M() { [$$ void local1() { } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("MyG") state.SendTab() Await state.AssertNoCompletionSession() Assert.Equal(" [MyGood", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeOnMissingStatementCompletionCommitWithTab(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyGoodAttribute : System.Attribute { public string Name { get; set; } } public class Goo { void M() { [$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("MyG") state.SendTab() Await state.AssertNoCompletionSession() Assert.Equal(" [MyGood", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeAfterAttributeListOnStatement(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyGoodAttribute : System.Attribute { public string Name { get; set; } } public class Goo { void M() { [MyGood] $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Equal(" [MyGood] Goo", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedPropertyCompletionCommitWithEquals(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } [MyAttribute($$ public class Goo { } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Nam=") Await state.AssertNoCompletionSession() Assert.Equal("[MyAttribute(Name =", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedPropertyCompletionCommitWithSpace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } [MyAttribute($$ public class Goo { } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Nam ") Await state.AssertNoCompletionSession() Assert.Equal("[MyAttribute(Name ", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(545590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545590")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOverrideDefaultParameter_CSharp7(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public virtual void Goo<S>(S x = default(S)) { } } class D : C { override $$ } ]]></Document>, languageVersion:=LanguageVersion.CSharp7, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" Goo") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("public override void Goo<S>(S x = default(S))", state.SubjectBuffer.CurrentSnapshot.GetText(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOverrideDefaultParameter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public virtual void Goo<S>(S x = default(S)) { } } class D : C { override $$ } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" Goo") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("public override void Goo<S>(S x = default)", state.SubjectBuffer.CurrentSnapshot.GetText(), StringComparison.Ordinal) End Using End Function <WorkItem(545664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545664")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestArrayAfterOptionalParameter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class A { public virtual void Goo(int x = 0, int[] y = null) { } } class B : A { public override void Goo(int x = 0, params int[] y) { } } class C : B { override$$ } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" Goo") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains(" public override void Goo(int x = 0, int[] y = null)", state.SubjectBuffer.CurrentSnapshot.GetText(), StringComparison.Ordinal) End Using End Function <WorkItem(545967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545967")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestVirtualSpaces(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public string P { get; set; } void M() { var v = new C {$$ }; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendReturn() Assert.True(state.TextView.Caret.InVirtualSpace) Assert.Equal(12, state.TextView.Caret.Position.VirtualSpaces) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("P", isSoftSelected:=True) state.SendDownKey() Await state.AssertSelectedCompletionItem("P", isHardSelected:=True) state.SendTab() Assert.Equal(" P", state.GetLineFromCurrentCaretPosition().GetText()) Dim bufferPosition = state.TextView.Caret.Position.BufferPosition Assert.Equal(13, bufferPosition.Position - bufferPosition.GetContainingLine().Start.Position) Assert.False(state.TextView.Caret.InVirtualSpace) End Using End Function <WorkItem(546561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546561")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNamedParameterAgainstMRU(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { void Goo(string s) { } static void Main() { $$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' prime the MRU state.SendTypeChars("string") state.SendTab() Await state.AssertNoCompletionSession() ' Delete what we just wrote. state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendEscape() Await state.AssertNoCompletionSession() ' ensure we still select the named param even though 'string' is in the MRU. state.SendTypeChars("Goo(s") Await state.AssertSelectedCompletionItem("s", displayTextSuffix:=":") End Using End Function <WorkItem(546403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546403")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMissingOnObjectCreationAfterVar1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class A { void Goo() { var v = new$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(546403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546403")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMissingOnObjectCreationAfterVar2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class A { void Goo() { var v = new $$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("X") Await state.AssertCompletionItemsDoNotContainAny("X") End Using End Function <WorkItem(546917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546917")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEnumInSwitch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ enum Numeros { } class C { void M() { Numeros n; switch (n) { case$$ } } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Numeros") End Using End Function <WorkItem(547016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547016")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAmbiguityInLocalDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public int W; public C() { $$ W = 0; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("w") Await state.AssertSelectedCompletionItem(displayText:="W") End Using End Function <WorkItem(530835, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530835")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompletionFilterSpanCaretBoundary(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Method() { $$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Met") Await state.AssertSelectedCompletionItem(displayText:="Method") state.SendLeftKey() state.SendLeftKey() state.SendLeftKey() state.SendTypeChars("new") Await state.AssertSelectedCompletionItem(displayText:="Method", isSoftSelected:=True) End Using End Function <WorkItem(5487, "https://github.com/dotnet/roslyn/issues/5487")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitCharTypedAtTheBeginingOfTheFilterSpan(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public bool Method() { if ($$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Met") Await state.AssertCompletionSession() state.SendLeftKey() state.SendLeftKey() state.SendLeftKey() Await state.AssertSelectedCompletionItem(isSoftSelected:=True) state.SendTypeChars("!") Await state.AssertNoCompletionSession() Assert.Equal("if (!Met", state.GetLineTextFromCaretPosition().Trim()) Assert.Equal("M", state.GetCaretPoint().BufferPosition.GetChar()) End Using End Function <WorkItem(622957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622957")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBangFiltersInDocComment(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; /// $$ /// TestDocComment /// </summary> class TestException : Exception { } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("<") Await state.AssertCompletionSession() state.SendTypeChars("!") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("!--") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function InvokeCompletionDoesNotFilter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { string$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("string") Await state.AssertCompletionItemsContainAll("int", "Method") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function InvokeBeforeWordDoesNotSelect(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { $$string } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("AccessViolationException") Await state.AssertCompletionItemsContainAll("int", "Method") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function InvokeCompletionSelectsWithoutRegardToCaretPosition(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { s$$tring } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("string") Await state.AssertCompletionItemsContainAll("int", "Method") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TabAfterQuestionMark(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { ?$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTab() Assert.Equal(state.GetLineTextFromCaretPosition(), " ?" + vbTab) End Using End Sub <WorkItem(657658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657658")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PreselectionIgnoresBrackets(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { $$ static void Main(string[] args) { } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("static void F<T>(int a, Func<T, int> b) { }") state.SendEscape() state.TextView.Caret.MoveTo(New VisualStudio.Text.SnapshotPoint(state.SubjectBuffer.CurrentSnapshot, 220)) state.SendTypeChars("F") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("F", displayTextSuffix:="<>") End Using End Function <WorkItem(672474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672474")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvokeSnippetCommandDismissesCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document>$$</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("us") Await state.AssertCompletionSession() state.SendInsertSnippetCommand() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(672474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672474")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSurroundWithCommandDismissesCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document>$$</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("us") Await state.AssertCompletionSession() state.SendSurroundWithCommand() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(737239, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737239")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function LetEditorHandleOpenParen(showCompletionInArgumentLists As Boolean) As Task Dim expected = <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { List<int> x = new List<int>( } }]]></Document>.Value.Replace(vbLf, vbCrLf) Using state = TestStateFactory.CreateCSharpTestState(<Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { List<int> x = new$$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("List<int>") state.SendTypeChars("(") Assert.Equal(expected, state.GetDocumentText()) End Using End Function <WorkItem(785637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/785637")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitMovesCaretToWordEnd(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Main() { M$$ain } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.SendCommitUniqueCompletionListItemAsync() Assert.Equal(state.GetLineFromCurrentCaretPosition().End, state.GetCaretPoint().BufferPosition) End Using End Function <WorkItem(775370, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775370")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function MatchingConsidersAtSign(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Main() { $$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("var @this = ""goo"";") state.SendReturn() state.SendTypeChars("string str = this.ToString();") state.SendReturn() state.SendTypeChars("str = @th") Await state.AssertSelectedCompletionItem("@this") End Using End Function <WorkItem(865089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/865089")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeFilterTextRemovesAttributeSuffix(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ [$$] class AtAttribute : System.Attribute { }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("At") Await state.AssertSelectedCompletionItem("At") Assert.Equal("At", state.GetSelectedItem().FilterText) End Using End Function <WorkItem(852578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/852578")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PreselectExceptionOverSnippet(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { Exception goo() { return new $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem("Exception") End Using End Function <WorkItem(868286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868286")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub CommitNameAfterAlias(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using goo = System$$]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".act<") state.AssertMatchesTextStartingAtLine(1, "using goo = System.Action<") End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompletionInLinkedFiles(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Thing2"> <Document FilePath="C.cs"> class C { void M() { $$ } #if Thing1 void Thing1() { } #elif Thing2 void Thing2() { } #endif } </Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Thing1"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim documents = state.Workspace.Documents Dim linkDocument = documents.Single(Function(d) d.IsLinkFile) state.SendTypeChars("Thing1") Await state.AssertSelectedCompletionItem("Thing1") state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendEscape() state.Workspace.SetDocumentContext(linkDocument.Id) state.SendTypeChars("Thing1") Await state.AssertSelectedCompletionItem("Thing1") Assert.True(state.GetSelectedItem().Tags.Contains(WellKnownTags.Warning)) state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendTypeChars("M") Await state.AssertSelectedCompletionItem("M") Assert.False(state.GetSelectedItem().Tags.Contains(WellKnownTags.Warning)) End Using End Function <WorkItem(951726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951726")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function DismissUponSave(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { $$ }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("voi") Await state.AssertSelectedCompletionItem("void") state.SendSave() Await state.AssertNoCompletionSession() state.AssertMatchesTextStartingAtLine(3, " voi") End Using End Function <WorkItem(930254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930254")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoCompletionWithBoxSelection(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { {|Selection:$$int x;|} {|Selection:int y;|} }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertNoCompletionSession() state.SendTypeChars("goo") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(839555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839555")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TriggeredOnHash(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ $$]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("#") Await state.AssertCompletionSession() End Using End Function <WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function RegionCompletionCommitTriggersFormatting_1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { $$ }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("#reg") Await state.AssertSelectedCompletionItem("region") state.SendReturn() state.AssertMatchesTextStartingAtLine(3, " #region") End Using End Function <WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function RegionCompletionCommitTriggersFormatting_2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { $$ }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("#reg") Await state.AssertSelectedCompletionItem("region") state.SendTypeChars(" ") state.AssertMatchesTextStartingAtLine(3, " #region ") End Using End Function <WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EndRegionCompletionCommitTriggersFormatting_2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { #region NameIt $$ }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("#endreg") Await state.AssertSelectedCompletionItem("endregion") state.SendReturn() state.AssertMatchesTextStartingAtLine(4, " #endregion ") End Using End Function <ExportCompletionProvider(NameOf(SlowProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class SlowProvider Inherits CommonCompletionProvider Public checkpoint As Checkpoint = New Checkpoint() <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Async Function ProvideCompletionsAsync(context As CompletionContext) As Task Await checkpoint.Task.ConfigureAwait(False) End Function Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return True End Function End Class <WorkItem(1015893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1015893")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function BackspaceDismissesIfComputationIsIncomplete(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void goo() { goo($$ } }]]></Document>, extraExportedTypes:={GetType(SlowProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") state.SendBackspace() ' Send a backspace that goes beyond the session's applicable span ' before the model computation has finished. Then, allow the ' computation to complete. There should still be no session. state.SendBackspace() Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim slowProvider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of SlowProvider)().Single() slowProvider.checkpoint.Release() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(31135, "https://github.com/dotnet/roslyn/issues/31135")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypingWithoutMatchAfterBackspaceDismissesCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class$$ C { }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertCompletionSession() state.SendTypeChars("w") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36513")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypingBackspaceShouldPreserveCase(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { void M() { Structure structure; structure.$$ } struct Structure { public int A; } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("structure") state.SendTypeChars(".") Await state.AssertCompletionItemsContainAll("A") End Using End Function <WorkItem(1594, "https://github.com/dotnet/roslyn/issues/1594")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoPreselectionOnSpaceWhenAbuttingWord(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { void Main() { Program p = new $$Program(); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(1594, "https://github.com/dotnet/roslyn/issues/1594")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SpacePreselectionAtEndOfFile(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { void Main() { Program p = new $$]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertCompletionSession() End Using End Function <WorkItem(1659, "https://github.com/dotnet/roslyn/issues/1659")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function DismissOnSelectAllCommand(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) { $$]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' Note: the caret is at the file, so the Select All command's movement ' of the caret to the end of the selection isn't responsible for ' dismissing the session. state.SendInvokeCompletionList() Await state.AssertCompletionSession() state.SendSelectAll() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub CompletionCommitAndFormatAreSeparateUndoTransactions(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) { int doodle; $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("doo;") state.AssertMatchesTextStartingAtLine(6, " doodle;") state.SendUndo() state.AssertMatchesTextStartingAtLine(6, "doo;") End Using End Sub <WorkItem(4978, "https://github.com/dotnet/roslyn/issues/4978")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SessionNotStartedWhenCaretNotMappableIntoSubjectBuffer(showCompletionInArgumentLists As Boolean) As Task ' In inline diff view, typing delete next to a "deletion", ' can cause our CommandChain to be called with a subjectbuffer ' and TextView such that the textView's caret can't be mapped ' into our subject buffer. ' ' To test this, we create a projection buffer with 2 source ' spans: one of "text" content type and one based on a C# ' buffer. We create a TextView with that projection as ' its buffer, setting the caret such that it maps only ' into the "text" buffer. We then call the completionImplementation ' command handlers with commandargs based on that TextView ' but with the C# buffer as the SubjectBuffer. Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) {$$ /********/ int doodle; } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim textBufferFactoryService = state.GetExportedValue(Of ITextBufferFactoryService)() Dim contentTypeService = state.GetExportedValue(Of VisualStudio.Utilities.IContentTypeRegistryService)() Dim contentType = contentTypeService.GetContentType(ContentTypeNames.CSharpContentType) Dim textViewFactory = state.GetExportedValue(Of ITextEditorFactoryService)() Dim editorOperationsFactory = state.GetExportedValue(Of IEditorOperationsFactoryService)() Dim otherBuffer = textBufferFactoryService.CreateTextBuffer("text", contentType) Dim otherExposedSpan = otherBuffer.CurrentSnapshot.CreateTrackingSpan(0, 4, SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward) Dim subjectBufferExposedSpan = state.SubjectBuffer.CurrentSnapshot.CreateTrackingSpan(0, state.SubjectBuffer.CurrentSnapshot.Length, SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward) Dim projectionBufferFactory = state.GetExportedValue(Of IProjectionBufferFactoryService)() Dim projection = projectionBufferFactory.CreateProjectionBuffer(Nothing, New Object() {otherExposedSpan, subjectBufferExposedSpan}.ToList(), ProjectionBufferOptions.None) Using disposableView As DisposableTextView = textViewFactory.CreateDisposableTextView(projection) disposableView.TextView.Caret.MoveTo(New SnapshotPoint(disposableView.TextView.TextBuffer.CurrentSnapshot, 0)) Dim editorOperations = editorOperationsFactory.GetEditorOperations(disposableView.TextView) state.SendDeleteToSpecificViewAndBuffer(disposableView.TextView, state.SubjectBuffer) Await state.AssertNoCompletionSession() End Using End Using End Function <WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround1(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) { string.$$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("is") Await state.AssertSelectedCompletionItem("IsInterned") End Using End Using End Function <WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround2(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) { string.$$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ı") Await state.AssertSelectedCompletionItem() End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround3(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class TARIFE { } class C { void goo(int x) { var t = new $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("tarif") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("TARIFE") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround4(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class IFADE {} class ifTest {} class C { void goo(int x) { IFADE ifade = null; $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("if") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("if") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround5(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class İFADE {} class ifTest {} class C { void goo(int x) { İFADE ifade = null; $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("if") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("if") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround6(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class TARİFE { } class C { void goo(int x) { var obj = new $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("tarif") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("TARİFE") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround7(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class İFADE {} class ifTest {} class C { void goo(int x) { var obj = new $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ifad") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("İFADE") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround8(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class IFADE {} class ifTest {} class C { void goo(int x) { var obj = new $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ifad") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("IFADE") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround9(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class IFADE {} class ifTest {} class C { void goo(int x) { IFADE ifade = null; $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("IF") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("if") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround10(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class İFADE {} class ifTest {} class C { void goo(int x) { İFADE ifade = null; $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("IF") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("if") End Using End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Threading; class Program { void Cancel(int x, CancellationToken cancellationToken) { Cancel(x + 1, cancellationToken: $$) } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("cancellationToken", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { static void Main(string[] args) { int aaz = 0; args = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("a") Await state.AssertSelectedCompletionItem("args", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection_DoesNotOverrideEnumPreselection(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ enum E { } class Program { static void Main(string[] args) { E e; e = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("E", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection_DoesNotOverrideEnumPreselection2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ enum E { A } class Program { static void Main(string[] args) { E e = E.A; if (e == $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("E", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class D {} class Program { static void Main(string[] args) { int cw = 7; D cx = new D(); D cx2 = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("c") Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionLocalsOverType(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class A {} class Program { static void Main(string[] args) { A cx = new A(); A cx2 = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("c") Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionParameterOverMethod(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { bool f; void goo(bool x) { } void Main(string[] args) { goo($$) // Not "Equals" } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("f", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/6942"), CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionConvertibility1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ abstract class C {} class D : C {} class Program { static void Main(string[] args) { D cx = new D(); C cx2 = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("c") Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionLocalOverProperty(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { public int aaa { get; } void Main(string[] args) { int aaq; int y = a$$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("aaq", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(12254, "https://github.com/dotnet/roslyn/issues/12254")> Public Sub TestGenericCallOnTypeContainingAnonymousType(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Linq; class Program { static void Main(string[] args) { new[] { new { x = 1 } }.ToArr$$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("(") state.AssertMatchesTextStartingAtLine(7, "new[] { new { x = 1 } }.ToArray(") End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionSetterValuey(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { int _x; int X { set { _x = $$ } } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("value", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(12530, "https://github.com/dotnet/roslyn/issues/12530")> Public Async Function TestAnonymousTypeDescription(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Linq; class Program { static void Main(string[] args) { new[] { new { x = 1 } }.ToArr$$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem(description:= $"({ CSharpFeaturesResources.extension }) 'a[] System.Collections.Generic.IEnumerable<'a>.ToArray<'a>() { FeaturesResources.Anonymous_Types_colon } 'a { FeaturesResources.is_ } new {{ int x }}") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRecursiveGenericSymbolKey(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections.Generic; class Program { static void ReplaceInList<T>(List<T> list, T oldItem, T newItem) { $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("list") state.SendTypeChars(".") Await state.AssertCompletionSession() state.SendTypeChars("Add") Await state.AssertSelectedCompletionItem("Add", description:="void List<T>.Add(T item)") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitNamedParameterWithColon(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections.Generic; class Program { static void Main(int args) { Main(args$$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars(":") Await state.AssertNoCompletionSession() Assert.Contains("args:", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(13481, "https://github.com/dotnet/roslyn/issues/13481")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceSelection1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main() { DateTimeOffset$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) For Each c In "Offset" state.SendBackspace() Await state.WaitForAsynchronousOperationsAsync() Next Await state.AssertSelectedCompletionItem("DateTime") End Using End Function <WorkItem(13481, "https://github.com/dotnet/roslyn/issues/13481")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceSelection2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main() { DateTimeOffset.$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) For Each c In "Offset." state.SendBackspace() Await state.WaitForAsynchronousOperationsAsync() Next Await state.AssertSelectedCompletionItem("DateTime") End Using End Function <WorkItem(14465, "https://github.com/dotnet/roslyn/issues/14465")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypingNumberShouldNotDismiss1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void Moo1() { new C()$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionSession() state.SendTypeChars("1") Await state.AssertSelectedCompletionItem("Moo1") End Using End Function <WorkItem(14085, "https://github.com/dotnet/roslyn/issues/14085")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypingDoesNotOverrideExactMatch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.IO; class C { void Moo1() { string path = $$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Path") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("Path") End Using End Function <WorkItem(14085, "https://github.com/dotnet/roslyn/issues/14085")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function MRUOverTargetTyping(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { await Moo().$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Configure") state.SendTab() For i = 1 To "ConfigureAwait".Length state.SendBackspace() Next state.SendInvokeCompletionList() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("ConfigureAwait") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function MovingCaretToStartSoftSelects(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void M() { $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Conso") Await state.AssertSelectedCompletionItem(displayText:="Console", isHardSelected:=True) For Each ch In "Conso" state.SendLeftKey() Next Await state.AssertSelectedCompletionItem(displayText:="Console", isHardSelected:=False) state.SendRightKey() Await state.AssertSelectedCompletionItem(displayText:="Console", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoBlockOnCompletionItems1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using $$ </Document>, extraExportedTypes:={GetType(BooleanTaskControlledCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of BooleanTaskControlledCompletionProvider)().Single() Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.BlockForCompletionItems2, LanguageNames.CSharp, False))) state.SendTypeChars("Sys.") Await state.AssertNoCompletionSession() Assert.Contains("Sys.", state.GetLineTextFromCaretPosition()) provider.completionSource.SetResult(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoBlockOnCompletionItems2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using $$ </Document>, extraExportedTypes:={GetType(CompletedTaskControlledCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.BlockForCompletionItems2, LanguageNames.CSharp, False))) state.SendTypeChars("Sys") Await state.AssertSelectedCompletionItem(displayText:="System") state.SendTypeChars(".") Assert.Contains("System.", state.GetLineTextFromCaretPosition()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoBlockOnCompletionItems4(showCompletionInArgumentLists As Boolean) As Task ' This test verifies a scenario with the following conditions: ' a. A slow completion provider ' b. The block option set to false. ' Scenario: ' 1. Type 'Sys' ' 2. Send CommitIfUnique (Ctrl + space) ' 3. Wait for 250ms. ' 4. Verify that there is no completion window shown. In the new completion, we can just start the verification and check that the verification is still running. ' 5. Check that the commit is not yet provided: there is 'Sys' but no 'System' ' 6. Simulate unblocking the provider. ' 7. Verify that the completion completes CommitIfUnique. Using state = TestStateFactory.CreateCSharpTestState( <Document> using $$ </Document>, extraExportedTypes:={GetType(BooleanTaskControlledCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of BooleanTaskControlledCompletionProvider)().Single() Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.BlockForCompletionItems2, LanguageNames.CSharp, False))) state.SendTypeChars("Sys") Dim task1 As Task = Nothing Dim task2 As Task = Nothing Dim providerCalledHandler = Sub() task2 = New Task( Sub() Thread.Sleep(250) Try ' 3. Check that the other task is running/deadlocked. Assert.Equal(TaskStatus.Running, task1.Status) Assert.Contains("Sys", state.GetLineTextFromCaretPosition()) Assert.DoesNotContain("System", state.GetLineTextFromCaretPosition()) ' Need the Finally to avoid deadlocks if any of Asserts failed, the task will never complete and Task.WhenAll will wait forever. Finally ' 4. Unblock the first task and the main thread. provider.completionSource.SetResult(True) End Try End Sub) task1 = Task.Run( Sub() task2.Start() ' 2. Deadlock here as well: getting items is waiting provider to respond. state.CalculateItemsIfSessionExists() End Sub) End Sub AddHandler provider.ProviderCalled, providerCalledHandler ' SendCommitUniqueCompletionListItem is a asynchronous operation. ' It guarantees that ProviderCalled will be triggered and after that the completion will deadlock waiting for a task to be resolved. ' In the new completion, when pressed <ctrl>-<space>, we have to wait for the aggregate operation to complete. ' 1. Deadlock here. Await state.SendCommitUniqueCompletionListItemAsync() Assert.NotNull(task1) Assert.NotNull(task2) Await Task.WhenAll(task1, task2) Await state.AssertNoCompletionSession() Assert.Contains("System", state.GetLineTextFromCaretPosition()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoBlockOnCompletionItems3(showCompletionInArgumentLists As Boolean) As Task ' This test verifies a scenario with the following conditions: ' a. A slow completion provider ' b. The block option set to false. ' Scenario: ' 1. Type 'Sys' ' 2. Send CommitIfUnique (Ctrl + space) ' 3. Wait for 250ms. ' 4. Verify that there is no completion window shown. In the new completion, we can just start the verification and check that the verification is still running. ' 5. Check that the commit is not yet provided: there is 'Sys' but no 'System' ' 6. The next statement in the UI thread after CommitIfUnique is typing 'a'. ' 7. Simulate unblocking the provider. ' 8. Verify that ' 8.a. The old completion adds 'a' to 'Sys' and displays 'Sysa'. CommitIfUnique is canceled because it was interrupted by typing 'a'. ' 8.b. The new completion completes CommitIfUnique and then adds 'a'. Using state = TestStateFactory.CreateCSharpTestState( <Document> using $$ </Document>, extraExportedTypes:={GetType(BooleanTaskControlledCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of BooleanTaskControlledCompletionProvider)().Single() Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.BlockForCompletionItems2, LanguageNames.CSharp, False))) state.SendTypeChars("Sys") Dim task1 As Task = Nothing Dim task2 As Task = Nothing Dim providerCalledHandler = Sub() task2 = New Task( Sub() Thread.Sleep(250) Try ' 3. Check that the other task is running/deadlocked. Assert.Equal(TaskStatus.Running, task1.Status) Assert.Contains("Sys", state.GetLineTextFromCaretPosition()) Assert.DoesNotContain("System", state.GetLineTextFromCaretPosition()) ' Need the Finally to avoid deadlocks if any of Asserts failed, the task will never complete and Task.WhenAll will wait forever. Finally ' 4. Unblock the first task and the main thread. provider.completionSource.SetResult(True) End Try End Sub) task1 = Task.Run( Sub() task2.Start() ' 2. Deadlock here as well: getting items is waiting provider to respond. state.CalculateItemsIfSessionExists() End Sub) End Sub AddHandler provider.ProviderCalled, providerCalledHandler ' SendCommitUniqueCompletionListItem is an asynchronous operation. ' It guarantees that ProviderCalled will be triggered and after that the completion will deadlock waiting for a task to be resolved. ' In the new completion, when pressed <ctrl>-<space>, we have to wait for the aggregate operation to complete. ' 1. Deadlock here. Await state.SendCommitUniqueCompletionListItemAsync() ' 5. Put insertion of 'a' into the edtior queue. It can be executed in the foreground thread only state.SendTypeChars("a") Assert.NotNull(task1) Assert.NotNull(task2) Await Task.WhenAll(task1, task2) Await state.AssertNoCompletionSession() ' Here is a difference between the old and the new completions: ' The old completion adds 'a' to 'Sys' and displays 'Sysa'. CommitIfUnique is canceled because it was interrupted by typing 'a'. ' The new completion completes CommitIfUnique and then adds 'a'. Assert.Contains("Systema", state.GetLineTextFromCaretPosition()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSwitchBetweenBlockingAndNoBlockOnCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using $$ </Document>, extraExportedTypes:={GetType(BooleanTaskControlledCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of BooleanTaskControlledCompletionProvider)().Single() #Disable Warning BC42358 ' Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(Function() Task.Delay(TimeSpan.FromSeconds(10)) provider.completionSource.SetResult(True) Return True End Function) #Enable Warning BC42358 ' Because this call is not awaited, execution of the current method continues before the call is completed state.SendTypeChars("Sys.") Assert.Contains("System.", state.GetLineTextFromCaretPosition()) ' reset the input For i As Integer = 1 To "System.".Length state.SendBackspace() Next state.SendEscape() Await state.WaitForAsynchronousOperationsAsync() ' reset the task provider.Reset() ' Switch to the non-blocking mode Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.BlockForCompletionItems2, LanguageNames.CSharp, False))) ' re-use of TestNoBlockOnCompletionItems1 state.SendTypeChars("Sys.") Await state.AssertNoCompletionSession() Assert.Contains("Sys.", state.GetLineTextFromCaretPosition()) provider.completionSource.SetResult(True) For i As Integer = 1 To "Sys.".Length state.SendBackspace() Next state.SendEscape() Await state.WaitForAsynchronousOperationsAsync() ' reset the task provider.Reset() ' Switch to the blocking mode workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.BlockForCompletionItems2, LanguageNames.CSharp, True))) #Disable Warning BC42358 ' Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(Function() Task.Delay(TimeSpan.FromSeconds(10)) provider.completionSource.SetResult(True) Return True End Function) #Enable Warning BC42358 ' Because this call is not awaited, execution of the current method continues before the call is completed state.SendTypeChars("Sys.") Await state.AssertCompletionSession() Assert.Contains("System.", state.GetLineTextFromCaretPosition()) End Using End Function Private MustInherit Class TaskControlledCompletionProvider Inherits CompletionProvider Private _task As Task Public Event ProviderCalled() Public Sub New(task As Task) _task = task End Sub Public Sub UpdateTask(task As Task) _task = task End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task RaiseEvent ProviderCalled() Return _task End Function End Class <ExportCompletionProvider(NameOf(CompletedTaskControlledCompletionProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class CompletedTaskControlledCompletionProvider Inherits TaskControlledCompletionProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New(Task.FromResult(True)) End Sub End Class <ExportCompletionProvider(NameOf(BooleanTaskControlledCompletionProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class BooleanTaskControlledCompletionProvider Inherits TaskControlledCompletionProvider Public completionSource As TaskCompletionSource(Of Boolean) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New(Task.CompletedTask) Reset() End Sub Public Sub Reset() completionSource = New TaskCompletionSource(Of Boolean) UpdateTask(completionSource.Task) End Sub End Class <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Filters_EmptyList1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { var x = asd$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() Dim oldFilters = state.GetCompletionItemFilters() Dim newFilters = ArrayBuilder(Of Data.CompletionFilterWithState).GetInstance() For Each f In oldFilters Assert.NotEqual(FilterSet.InterfaceFilter.DisplayText, f.Filter.DisplayText) newFilters.Add(f.WithSelected(False)) Next newFilters.Add(New Data.CompletionFilterWithState(FilterSet.InterfaceFilter, isAvailable:=True, isSelected:=True)) state.RaiseFiltersChanged(newFilters.ToImmutableAndFree()) Await state.WaitForUIRenderedAsync() Assert.Null(state.GetSelectedItem()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Filters_EmptyList2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { var x = asd$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() Dim oldFilters = state.GetCompletionItemFilters() Dim newFilters = ArrayBuilder(Of Data.CompletionFilterWithState).GetInstance() For Each f In oldFilters Assert.NotEqual(FilterSet.InterfaceFilter.DisplayText, f.Filter.DisplayText) newFilters.Add(f.WithSelected(False)) Next newFilters.Add(New Data.CompletionFilterWithState(FilterSet.InterfaceFilter, isAvailable:=True, isSelected:=True)) state.RaiseFiltersChanged(newFilters.ToImmutableAndFree()) Await state.WaitForUIRenderedAsync() Assert.Null(state.GetSelectedItem()) state.SendTab() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Filters_EmptyList3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { var x = asd$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() Dim oldFilters = state.GetCompletionItemFilters() Dim newFilters = ArrayBuilder(Of Data.CompletionFilterWithState).GetInstance() For Each f In oldFilters Assert.NotEqual(FilterSet.InterfaceFilter.DisplayText, f.Filter.DisplayText) newFilters.Add(f.WithSelected(False)) Next newFilters.Add(New Data.CompletionFilterWithState(FilterSet.InterfaceFilter, isAvailable:=True, isSelected:=True)) state.RaiseFiltersChanged(newFilters.ToImmutableAndFree()) Await state.WaitForUIRenderedAsync() Assert.Null(state.GetSelectedItem()) state.SendReturn() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Filters_EmptyList4(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { var x = asd$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() Dim oldFilters = state.GetCompletionItemFilters() Dim newFilters = ArrayBuilder(Of Data.CompletionFilterWithState).GetInstance() For Each f In oldFilters Assert.NotEqual(FilterSet.InterfaceFilter.DisplayText, f.Filter.DisplayText) newFilters.Add(f.WithSelected(False)) Next newFilters.Add(New Data.CompletionFilterWithState(FilterSet.InterfaceFilter, isAvailable:=True, isSelected:=True)) state.RaiseFiltersChanged(newFilters.ToImmutableAndFree()) Await state.WaitForUIRenderedAsync() Assert.Null(state.GetSelectedItem()) state.SendTypeChars(".") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(15881, "https://github.com/dotnet/roslyn/issues/15881")> Public Async Function CompletionAfterDotBeforeAwaitTask(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Threading.Tasks; class C { async Task Moo() { Task.$$ await Task.Delay(50); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionSession() End Using End Function <WorkItem(14704, "https://github.com/dotnet/roslyn/issues/14704")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function BackspaceTriggerSubstringMatching(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class Program { static void Main(string[] args) { if (Environment$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim key = New OptionKey(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(key, True))) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="Environment", isHardSelected:=True) End Using End Function <WorkItem(16236, "https://github.com/dotnet/roslyn/issues/16236")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedParameterEqualsItemCommittedOnSpace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> [A($$)] class AAttribute: Attribute { public string Skip { get; set; } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Skip") Await state.AssertCompletionSession() state.SendTypeChars(" ") Await state.AssertNoCompletionSession() Assert.Equal("[A(Skip )]", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(362890, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=362890")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFilteringAfterSimpleInvokeShowsAllItemsMatchingFilter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ static class Color { public const uint Red = 1; public const uint Green = 2; public const uint Blue = 3; } class C { void M() { Color.Re$$d } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem("Red") Await state.AssertCompletionItemsContainAll("Red", "Green", "Blue", "Equals") Dim oldFilters = state.GetCompletionItemFilters() Dim newFiltersBuilder = ArrayBuilder(Of Data.CompletionFilterWithState).GetInstance() For Each f In oldFilters newFiltersBuilder.Add(f.WithSelected(f.Filter.DisplayText = FilterSet.ConstantFilter.DisplayText)) Next state.RaiseFiltersChanged(newFiltersBuilder.ToImmutableAndFree()) Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem("Red") Await state.AssertCompletionItemsContainAll("Red", "Green", "Blue") Await state.AssertCompletionItemsDoNotContainAny("Equals") oldFilters = state.GetCompletionItemFilters() newFiltersBuilder = ArrayBuilder(Of Data.CompletionFilterWithState).GetInstance() For Each f In oldFilters newFiltersBuilder.Add(f.WithSelected(False)) Next state.RaiseFiltersChanged(newFiltersBuilder.ToImmutableAndFree()) Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem("Red") Await state.AssertCompletionItemsContainAll({"Red", "Green", "Blue", "Equals"}) End Using End Function <WorkItem(16236, "https://github.com/dotnet/roslyn/issues/16236")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NameCompletionSorting(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> interface ISyntaxFactsService {} class C { void M() { ISyntaxFactsService $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Dim expectedOrder = { "syntaxFactsService", "syntaxFacts", "factsService", "syntax", "service" } state.AssertItemsInOrder(expectedOrder) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestLargeChangeBrokenUpIntoSmallTextChanges(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { void goo() { return $$ } }]]></Document>, extraExportedTypes:={GetType(MultipleChangeCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of MultipleChangeCompletionProvider)().Single() Dim testDocument = state.Workspace.Documents(0) Dim textBuffer = testDocument.GetTextBuffer() Dim snapshotBeforeCommit = textBuffer.CurrentSnapshot provider.SetInfo(snapshotBeforeCommit.GetText(), testDocument.CursorPosition.Value) ' First send a space to trigger out special completionImplementation provider. state.SendInvokeCompletionList() state.SendTab() ' Verify that we see the entire change Dim finalText = textBuffer.CurrentSnapshot.GetText() Assert.Equal( "using NewUsing; using System; class C { void goo() { return InsertedItem } }", finalText) Dim changes = snapshotBeforeCommit.Version.Changes ' This should have happened as two text changes to the buffer. Assert.Equal(2, changes.Count) Dim actualChanges = changes.ToArray() Dim firstChange = actualChanges(0) Assert.Equal(New Span(0, 0), firstChange.OldSpan) Assert.Equal("using NewUsing;", firstChange.NewText) Dim secondChange = actualChanges(1) Assert.Equal(New Span(testDocument.CursorPosition.Value, 0), secondChange.OldSpan) Assert.Equal("InsertedItem", secondChange.NewText) ' Make sure new edits happen after the text that was inserted. state.SendTypeChars("1") finalText = textBuffer.CurrentSnapshot.GetText() Assert.Equal( "using NewUsing; using System; class C { void goo() { return InsertedItem1 } }", finalText) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestLargeChangeBrokenUpIntoSmallTextChanges2(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { void goo() { return Custom$$ } }]]></Document>, extraExportedTypes:={GetType(MultipleChangeCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of MultipleChangeCompletionProvider)().Single() Dim testDocument = state.Workspace.Documents(0) Dim textBuffer = testDocument.GetTextBuffer() Dim snapshotBeforeCommit = textBuffer.CurrentSnapshot provider.SetInfo(snapshotBeforeCommit.GetText(), testDocument.CursorPosition.Value) ' First send a space to trigger out special completionImplementation provider. state.SendInvokeCompletionList() state.SendTab() ' Verify that we see the entire change Dim finalText = textBuffer.CurrentSnapshot.GetText() Assert.Equal( "using NewUsing; using System; class C { void goo() { return InsertedItem } }", finalText) Dim changes = snapshotBeforeCommit.Version.Changes ' This should have happened as two text changes to the buffer. Assert.Equal(2, changes.Count) Dim actualChanges = changes.ToArray() Dim firstChange = actualChanges(0) Assert.Equal(New Span(0, 0), firstChange.OldSpan) Assert.Equal("using NewUsing;", firstChange.NewText) Dim secondChange = actualChanges(1) Assert.Equal(New Span(testDocument.CursorPosition.Value - "Custom".Length, "Custom".Length), secondChange.OldSpan) Assert.Equal("InsertedItem", secondChange.NewText) ' Make sure new edits happen after the text that was inserted. state.SendTypeChars("1") finalText = textBuffer.CurrentSnapshot.GetText() Assert.Equal( "using NewUsing; using System; class C { void goo() { return InsertedItem1 } }", finalText) End Using End Sub <WorkItem(296512, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=296512")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRegionDirectiveIndentation(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { $$ } </Document>, includeFormatCommandHandler:=True, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("#") Assert.Equal("#", state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertCompletionSession() state.SendTypeChars("reg") Await state.AssertSelectedCompletionItem(displayText:="region") state.SendReturn() Await state.AssertNoCompletionSession() Assert.Equal(" #region", state.GetLineFromCurrentCaretPosition().GetText()) Assert.Equal(state.GetLineFromCurrentCaretPosition().End, state.GetCaretPoint().BufferPosition) state.SendReturn() Assert.Equal("", state.GetLineFromCurrentCaretPosition().GetText()) state.SendTypeChars("#") Assert.Equal("#", state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertCompletionSession() state.SendTypeChars("endr") Await state.AssertSelectedCompletionItem(displayText:="endregion") state.SendReturn() Assert.Equal(" #endregion", state.GetLineFromCurrentCaretPosition().GetText()) Assert.Equal(state.GetLineFromCurrentCaretPosition().End, state.GetCaretPoint().BufferPosition) End Using End Function <WpfTheory> <InlineData("r")> <InlineData("load")> <WorkItem(49861, "https://github.com/dotnet/roslyn/issues/49861")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PathDirective(directive As String) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { # <%= directive %> $$ } </Document>) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendTypeChars("""") Assert.Equal($" # {directive} """, state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertCompletionSession() state.SendTypeChars("x") Assert.Equal($" # {directive} ""x", state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertCompletionSession() state.SendBackspace() Assert.Equal($" # {directive} """, state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertCompletionSession() state.SendBackspace() Assert.Equal($" # {directive} ", state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AfterIdentifierInCaseLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M() { switch (true) { case identifier $$ } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("w") Await state.AssertSelectedCompletionItem(displayText:="when", isHardSelected:=False) state.SendBackspace() state.SendTypeChars("i") Await state.AssertSelectedCompletionItem(displayText:="identifier", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AfterIdentifierInCaseLabel_ColorColor(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class identifier { } class C { const identifier identifier = null; void M() { switch (true) { case identifier $$ } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("w") Await state.AssertSelectedCompletionItem(displayText:="when", isHardSelected:=False) state.SendBackspace() state.SendTypeChars("i") Await state.AssertSelectedCompletionItem(displayText:="identifier", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AfterIdentifierInCaseLabel_ClassNameOnly(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class identifier { } class C { void M() { switch (true) { case identifier $$ } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("z") Await state.AssertSelectedCompletionItem(displayText:="identifier", isHardSelected:=False) state.SendBackspace() state.SendTypeChars("i") Await state.AssertSelectedCompletionItem(displayText:="identifier", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AfterIdentifierInCaseLabel_ClassNameOnly_WithMiscLetters(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class identifier { } class C { void M() { switch (true) { case identifier $$ } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="and", isHardSelected:=False) state.SendBackspace() state.SendTypeChars("w") Await state.AssertSelectedCompletionItem(displayText:="when", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AfterDoubleIdentifierInCaseLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M() { switch (true) { case identifier identifier $$ } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("w") Await state.AssertSelectedCompletionItem(displayText:="when", isHardSelected:=True) End Using End Function <WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGenericAsyncTaskDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace A.B { class TestClass { } } namespace A { class C { async Task&lt;A$$ Method() { } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem(displayText:="B", isSoftSelected:=True) End Using End Function <WorkItem(15348, "https://github.com/dotnet/roslyn/issues/15348")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterCasePatternSwitchLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M() { object o = 1; switch(o) { case int i: $$ break; } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("this") Await state.AssertSelectedCompletionItem(displayText:="this", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceInMiddleOfSelection(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public enum foo { aaa } public class Program { public static void Main(string[] args) { foo.a$$a } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="aaa", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceWithMultipleCharactersSelected(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; public class Program { public static void Main(string[] args) { Console.WriteLine$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() state.SelectAndMoveCaret(-6) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="Write", isHardSelected:=True) End Using End Function <WorkItem(30097, "https://github.com/dotnet/roslyn/issues/30097")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMRUKeepsTwoRecentlyUsedItems(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public double Ma(double m) => m; public void Test() { $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("M(M(M(M(") Await state.AssertNoCompletionSession() Assert.Equal(" Ma(m:(Ma(m:(", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(36546, "https://github.com/dotnet/roslyn/issues/36546")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDoNotDismissIfEmptyOnBackspaceIfStartedWithBackspace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { public void M() { Console.W$$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertCompletionItemsContainAll("WriteLine") End Using End Function <WorkItem(36546, "https://github.com/dotnet/roslyn/issues/36546")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDoNotDismissIfEmptyOnMultipleBackspaceIfStartedInvoke(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { public void M() { Console.Wr$$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionSession() state.SendBackspace() state.SendBackspace() Await state.AssertCompletionSession() End Using End Function <WorkItem(30097, "https://github.com/dotnet/roslyn/issues/30097")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNamedParameterDoesNotAddExtraColon(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public double M(double some) => m; public void Test() { $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("M(some:M(some:") Await state.AssertNoCompletionSession() Assert.Equal(" M(some:M(some:", state.GetLineTextFromCaretPosition()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSuggestionMode(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M() { $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendToggleCompletionMode() Await state.WaitForAsynchronousOperationsAsync() state.SendTypeChars("s") Await state.AssertCompletionSession() Assert.True(state.HasSuggestedItem()) Await state.AssertSelectedCompletionItem(displayText:="sbyte", isSoftSelected:=True) state.SendToggleCompletionMode() Await state.AssertCompletionSession() Assert.False(state.HasSuggestedItem()) ' We want to soft select if we were already in soft select mode. Await state.AssertSelectedCompletionItem(displayText:="sbyte", isSoftSelected:=True) state.SendToggleCompletionMode() Await state.AssertCompletionSession() Assert.True(state.HasSuggestedItem()) Await state.AssertSelectedCompletionItem(displayText:="sbyte", isSoftSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTabAfterOverride(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { override $$ public static void M() { } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("gethashcod") state.SendTab() Await state.AssertNoCompletionSession() state.AssertMatchesTextStartingAtLine(3, " public override int GetHashCode()") state.AssertMatchesTextStartingAtLine(4, " {") state.AssertMatchesTextStartingAtLine(5, " return base.GetHashCode();") state.AssertMatchesTextStartingAtLine(6, " }") state.AssertMatchesTextStartingAtLine(7, " public static void M() { }") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSuppressNullableWarningExpression(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M() { var s = ""; s$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("!") Await state.AssertNoCompletionSession() state.SendTypeChars(".") Await state.AssertCompletionItemsContainAll("ToString", "GetHashCode") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitIfUniqueFiltersIfNotUnique(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { Me$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertCompletionItemsContainAll("MemberwiseClone", "Method") Await state.AssertCompletionItemsDoNotContainAny("int", "ToString()", "Microsoft", "Math") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDismissCompletionOnBacktick(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void Method() { Con$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionSession() state.SendTypeChars("`") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUnique(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void Method() { var s=""; s.Len$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Length", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueInInsertionSession(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".len") Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Length", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueInDeletionSession1(showCompletionInArgumentLists As Boolean) As Task ' We explicitly use a weak matching on Delete. ' It matches by the first letter. Therefore, if backspace in s.Length, it matches s.Length and s.LastIndexOf. ' In this case, CommitIfUnique is not applied. Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s.Normalize$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertCompletionSession() Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Normalize", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(37231, "https://github.com/dotnet/roslyn/issues/37231")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueInDeletionSession2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void Method() { AccessViolationException$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertCompletionSession() Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("AccessViolationException", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueWithIntelliCode(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s.Len$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockProvider)().Single() Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Length", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueInInsertionSessionWithIntelliCode(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockProvider)().Single() state.SendTypeChars(".len") Await state.AssertCompletionItemsContainAll("Length", "★ Length") Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Length", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueInDeletionSessionWithIntelliCode(showCompletionInArgumentLists As Boolean) As Task ' We explicitly use a weak matching on Delete. ' It matches by the first letter. Therefore, if backspace in s.Length, it matches s.Length and s.LastIndexOf. ' In this case, CommitIfUnique is not applied. Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s.Normalize$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockProvider)().Single() Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertCompletionItemsContainAll("Normalize", "★ Normalize") Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Normalize", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAutomationTextPassedToEditor(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s.Len$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockProvider)().Single() state.SendInvokeCompletionList() state.SendSelectCompletionItem("★ Length") Await state.AssertSelectedCompletionItem(displayText:="★ Length", automationText:=provider.AutomationTextString) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueWithIntelliCodeAndDuplicateItemsFromIntelliCode(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s.Len$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockWeirdProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockWeirdProvider)().Single() Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Length", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueInInsertionSessionWithIntelliCodeAndDuplicateItemsFromIntelliCode(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockWeirdProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockWeirdProvider)().Single() state.SendTypeChars(".len") Await state.AssertCompletionItemsContainAll("Length", "★ Length", "★ Length2") Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Length", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function IntelliCodeItemPreferredAfterCommitingIntelliCodeItem(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockProvider)().Single() Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendTypeChars(".nor") Await state.AssertCompletionItemsContainAll("Normalize", "★ Normalize") Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("s.Normalize", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) For i = 1 To "ze".Length state.SendBackspace() Next Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") state.SendEscape() For i = 1 To "Normali".Length state.SendBackspace() Next state.SendEscape() Assert.Contains("s.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") state.SendEscape() state.SendTypeChars("n") Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function IntelliCodeItemPreferredAfterCommitingNonIntelliCodeItem(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockProvider)().Single() Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendTypeChars(".nor") Await state.AssertCompletionItemsContainAll("Normalize", "★ Normalize") Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") state.NavigateToDisplayText("Normalize") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("s.Normalize", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) For i = 1 To "ze".Length state.SendBackspace() Next Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") state.SendEscape() For i = 1 To "Normali".Length state.SendBackspace() Next state.SendEscape() Assert.Contains("s.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") state.SendEscape() state.SendTypeChars("n") Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExpanderWithImportCompletionDisabled(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { Bar$$ } } } namespace NS2 { public class Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, False))) ' trigger completion with import completion disabled state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) ' unselect expander state.SetCompletionItemExpanderState(isSelected:=False) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertCompletionItemsDoNotContainAny("Bar") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=False) ' select expander again state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) ' dismiss completion state.SendEscape() Await state.AssertNoCompletionSession() ' trigger completion again state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' should not show unimported item even with cache populated Await state.AssertCompletionItemsDoNotContainAny({"Bar"}) state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExpanderWithImportCompletionEnabled(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { Bar$$ } } } namespace NS2 { public class Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) ' trigger completion with import completion enabled state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) ' dismiss completion state.SendEscape() Await state.AssertNoCompletionSession() ' trigger completion again state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' now cache is populated Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoExpanderAvailableWhenNotInTypeContext(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { $$ } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) ' trigger completion with import completion enabled state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() state.AssertCompletionItemExpander(isAvailable:=False, isSelected:=False) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterInt(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { int first = 3; int[] array = new int[100]; var range = array[first$$]; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var range = array[first..];", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterClassAndAfterIntProperty(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { var d = new D(); int[] array = new int[100]; var range = array[d$$]; } } class D { public int A; } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem("A", isHardSelected:=True) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var range = array[d.A..];", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterClassAndAfterIntMethod(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { var d = new D(); int[] array = new int[100]; var range = array[d$$]; } } class D { public int A() => 0; } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem("A", isHardSelected:=True) state.SendTypeChars("().") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var range = array[d.A()..];", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterClassAndAfterDecimalProperty(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { var d = new D(); int[] array = new int[100]; var range = array[d$$]; } } class D { public decimal A; } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem("GetHashCode", isHardSelected:=True) state.SendTypeChars("A.") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var range = array[d.A..];", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterClassAndAfterDoubleMethod(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { var d = new D(); int[] array = new int[100]; var range = array[d$$]; } } class D { public double A() => 0; } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem("GetHashCode", isHardSelected:=True) state.SendTypeChars("A().") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var range = array[d.A()..];", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterIntWithinArrayDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { int d = 1; var array = new int[d$$]; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var array = new int[d..];", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterIntInVariableDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { int d = 1; var e = d$$; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var e = d..;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingToStringAfterIntInVariableDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { int d = 1; var e = d$$; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars("ToStr(") Assert.Contains("var e = d.ToString(", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(36187, "https://github.com/dotnet/roslyn/issues/36187")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function CompletionWithTwoOverloadsOneOfThemIsEmpty(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { private enum A { A, B, } private void Get(string a) { } private void Get(A a) { } private void Test() { Get$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSelectedCompletionItem(displayText:="A", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24960, "https://github.com/dotnet/roslyn/issues/24960")> Public Async Function TypeParameterTOnType(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C<T> { $$ }]]> </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("T") Await state.AssertSelectedCompletionItem("T") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24960, "https://github.com/dotnet/roslyn/issues/24960")> Public Async Function TypeParameterTOnMethod(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M<T>() { $$ } }]]> </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("T") Await state.AssertSelectedCompletionItem("T") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionBeforeVarWithEnableNullableReferenceAnalysisIDEFeatures(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" LanguageVersion="8" CommonReferences="true" AssemblyName="CSProj" Features="run-nullable-analysis=always"> <Document><![CDATA[ class C { void M(string s) { s$$ var o = new object(); } }]]></Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionItemsContainAll("Length") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletingWithColonInMethodParametersWithNoInstanceToInsert(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[class C { void M(string s) { N(10, $$); } void N(int id, string serviceName) {} }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("serviceN") Await state.AssertCompletionSession() state.SendTypeChars(":") Assert.Contains("N(10, serviceName:);", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletingWithSpaceInMethodParametersWithNoInstanceToInsert(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[class C { void M(string s) { N(10, $$); } void N(int id, string serviceName) {} }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("serviceN") Await state.AssertCompletionSession() state.SendTypeChars(" ") Assert.Contains("N(10, serviceName );", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(35163, "https://github.com/dotnet/roslyn/issues/35163")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NonExpandedItemShouldBePreferred_SameDisplayText(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { Bar$$ } } public class Bar<T> { } } namespace NS2 { public class Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = " namespace NS1 { class C { public void Foo() { Bar } } public class Bar<T> { } } namespace NS2 { public class Bar { } } " Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) Await state.AssertSelectedCompletionItem(displayText:="Bar", displayTextSuffix:="<>") state.SendTab() Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WorkItem(35163, "https://github.com/dotnet/roslyn/issues/35163")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NonExpandedItemShouldBePreferred_SameFullDisplayText(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { Bar$$ } } public class Bar { } } namespace NS2 { public class Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = " namespace NS1 { class C { public void Foo() { Bar } } public class Bar { } } namespace NS2 { public class Bar { } } " Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) Await state.AssertSelectedCompletionItem(displayText:="Bar") state.SendTab() Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WorkItem(35163, "https://github.com/dotnet/roslyn/issues/35163")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NonExpandedItemShouldBePreferred_ExpandedItemHasBetterButNotCompleteMatch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { bar$$ } } public class ABar { } } namespace NS2 { public class Bar1 { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = " namespace NS1 { class C { public void Foo() { ABar } } public class ABar { } } namespace NS2 { public class Bar1 { } } " Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) Await state.AssertSelectedCompletionItem(displayText:="ABar") state.SendTab() Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WorkItem(38253, "https://github.com/dotnet/roslyn/issues/38253")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NonExpandedItemShouldBePreferred_BothExpandedAndNonExpandedItemsHaveCompleteMatch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { bar$$ } } public class Bar { } } namespace NS2 { public class Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = " namespace NS1 { class C { public void Foo() { Bar } } public class Bar { } } namespace NS2 { public class Bar { } } " Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="") state.SendTab() Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WorkItem(38253, "https://github.com/dotnet/roslyn/issues/38253")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletelyMatchedExpandedItemAndWorseThanPrefixMatchedNonExpandedItem(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { bar$$ } } public class ABar { } } namespace NS2 { public class Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = " using NS2; namespace NS1 { class C { public void Foo() { Bar } } public class ABar { } } namespace NS2 { public class Bar { } } " Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) state.SendTab() Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletelyMatchedExpandedItemAndPrefixMatchedNonExpandedItem(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace NS { class C { void M() { object designer = null; des$$ } } } namespace OtherNS { public class DES { } } </Document>, extraExportedTypes:={GetType(TestExperimentationService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected so all unimported items are in the list state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem(displayText:="designer") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) End Using End Function <WorkItem(38253, "https://github.com/dotnet/roslyn/issues/38253")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SortItemsByPatternMatch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace NS { class C { void M() { $$ } } class Task { } class BTask1 { } class BTask2 { } class BTask3 { } class Task1 { } class Task2 { } class Task3 { } class ATaAaSaKa { } } </Document>, extraExportedTypes:={GetType(TestExperimentationService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, False))) state.SendTypeChars("task") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Task") Dim expectedOrder = { "Task", "Task1", "Task2", "Task3", "BTask1", "BTask2", "BTask3", "ATaAaSaKa" } state.AssertItemsInOrder(expectedOrder) End Using End Function <WorkItem(41601, "https://github.com/dotnet/roslyn/issues/41601")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SortItemsByExpandedFlag(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace NS1 { class C { void M() { $$ } } class MyTask1 { } class MyTask2 { } class MyTask3 { } } namespace NS2 { class MyTask1 { } class MyTask2 { } class MyTask3 { } } </Document>, extraExportedTypes:={GetType(TestExperimentationService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, False))) ' trigger completion with import completion disabled state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.SendEscape() Await state.AssertNoCompletionSession() workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendTypeChars("mytask") Await state.WaitForAsynchronousOperationsAsync() ' make sure expander is selected state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) Await state.AssertSelectedCompletionItem(displayText:="MyTask1", inlineDescription:="") Dim expectedOrder As (String, String)() = { ("MyTask1", ""), ("MyTask2", ""), ("MyTask3", ""), ("MyTask1", "NS2"), ("MyTask2", "NS2"), ("MyTask3", "NS2") } state.AssertItemsInOrder(expectedOrder) End Using End Function <WorkItem(39519, "https://github.com/dotnet/roslyn/issues/39519")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSuggestedNamesDontStartWithDigit_DigitsInTheMiddle(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS { class C { public void Foo(Foo123Bar $$) { } } public class Foo123Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.ShowNameSuggestions, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("foo123Bar", "foo123", "foo", "bar") Await state.AssertCompletionItemsDoNotContainAny("123Bar") End Using End Function <WorkItem(39519, "https://github.com/dotnet/roslyn/issues/39519")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSuggestedNamesDontStartWithDigit_DigitsOnTheRight(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS { class C { public void Foo(Foo123 $$) { } } public class Foo123 { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.ShowNameSuggestions, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("foo123", "foo") Await state.AssertCompletionItemsDoNotContainAny("123") End Using End Function <ExportCompletionProvider(NameOf(MultipleChangeCompletionProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class MultipleChangeCompletionProvider Inherits CompletionProvider Private _text As String Private _caretPosition As Integer <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Sub SetInfo(text As String, caretPosition As Integer) _text = text _caretPosition = caretPosition End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task context.AddItem(CompletionItem.Create( "CustomItem", rules:=CompletionItemRules.Default.WithMatchPriority(1000))) Return Task.CompletedTask End Function Public Overrides Function ShouldTriggerCompletion(text As SourceText, caretPosition As Integer, trigger As CompletionTrigger, options As OptionSet) As Boolean Return True End Function Public Overrides Function GetChangeAsync(document As Document, item As CompletionItem, commitKey As Char?, cancellationToken As CancellationToken) As Task(Of CompletionChange) Dim newText = "using NewUsing; using System; class C { void goo() { return InsertedItem" Dim change = CompletionChange.Create( New TextChange(New TextSpan(0, _caretPosition), newText)) Return Task.FromResult(change) End Function End Class <ExportCompletionProvider(NameOf(IntelliCodeMockProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class IntelliCodeMockProvider Inherits CompletionProvider Public AutomationTextString As String = "Hello from IntelliCode: Length" <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task Dim intelliCodeItem = CompletionItem.Create(displayText:="★ Length", filterText:="Length") intelliCodeItem.AutomationText = AutomationTextString context.AddItem(intelliCodeItem) context.AddItem(CompletionItem.Create(displayText:="★ Normalize", filterText:="Normalize", displayTextSuffix:="()")) context.AddItem(CompletionItem.Create(displayText:="Normalize", filterText:="Normalize")) context.AddItem(CompletionItem.Create(displayText:="Length", filterText:="Length")) context.AddItem(CompletionItem.Create(displayText:="ToString", filterText:="ToString", displayTextSuffix:="()")) context.AddItem(CompletionItem.Create(displayText:="First", filterText:="First", displayTextSuffix:="()")) Return Task.CompletedTask End Function Public Overrides Function ShouldTriggerCompletion(text As SourceText, caretPosition As Integer, trigger As CompletionTrigger, options As OptionSet) As Boolean Return True End Function Public Overrides Function GetChangeAsync(document As Document, item As CompletionItem, commitKey As Char?, cancellationToken As CancellationToken) As Task(Of CompletionChange) Dim commitText = item.DisplayText If commitText.StartsWith("★") Then ' remove the star and the following space commitText = commitText.Substring(2) End If Return Task.FromResult(CompletionChange.Create(New TextChange(item.Span, commitText))) End Function End Class <WorkItem(43439, "https://github.com/dotnet/roslyn/issues/43439")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectNullOverNuint(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public static void Main() { object o = $$ } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' 'nu' should select 'null' instead of 'nuint' (even though 'nuint' sorts higher in the list textually). state.SendTypeChars("nu") Await state.AssertSelectedCompletionItem(displayText:="null", isHardSelected:=True) Await state.AssertCompletionItemsContain("nuint", "") ' even after 'nuint' is selected, deleting the 'i' should still take us back to 'null'. state.SendTypeChars("i") Await state.AssertSelectedCompletionItem(displayText:="nuint", isHardSelected:=True) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="null", isHardSelected:=True) End Using End Function <WorkItem(43439, "https://github.com/dotnet/roslyn/issues/43439")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectNuintOverNullOnceInMRU(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public static void Main() { object o = $$ } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("nui") Await state.AssertCompletionItemsContain("nuint", "") state.SendTab() Assert.Contains("nuint", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendDeleteWordToLeft() ' nuint should be in the mru now. so typing 'nu' should select it instead of null. state.SendTypeChars("nu") Await state.AssertSelectedCompletionItem(displayText:="nuint", isHardSelected:=True) End Using End Function <WorkItem(944031, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/944031")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLambdaParameterInferenceInJoin1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System.Collections.Generic; using System.Linq; class Program { public class Book { public int Id { get; set; } public int OwnerId { get; set; } public string Name { get; set; } } public class Person { public int Id { get; set; } public string Nickname { get; set; } } static void Main() { var books = new List&lt;Book&gt;(); var persons = new List&lt;Person&gt;(); var join = persons.Join(books, person => person.Id, book => book.$$, (person, book) => new { person.Id, person.Nickname, book.Name }); </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain("OwnerId", "") End Using End Function <WorkItem(944031, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/944031")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLambdaParameterInferenceInJoin2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System.Collections.Generic; using System.Linq; class Program { public class Book { public int Id { get; set; } public int OwnerId { get; set; } public string Name { get; set; } } public class Person { public int Id { get; set; } public string Nickname { get; set; } } static void Main() { var books = new List&lt;Book&gt;(); var persons = new List&lt;Person&gt;(); var join = persons.Join(books, person => person.Id, book => book.OwnerId, (person, book) => new { person.Id, person.Nickname, book.$$ }); </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain("Name", "") End Using End Function <WorkItem(944031, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/944031")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLambdaParameterInferenceInGroupJoin1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System.Collections.Generic; using System.Linq; class Program { public class Book { public int Id { get; set; } public int OwnerId { get; set; } public string Name { get; set; } } public class Person { public int Id { get; set; } public string Nickname { get; set; } } static void Main() { var books = new List&lt;Book&gt;(); var persons = new List&lt;Person&gt;(); var join = persons.GroupJoin(books, person => person.Id, book => book.$$, (person, books1) => new { person.Id, person.Nickname, books1.Select(s => s.Name) }); </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain("OwnerId", "") End Using End Function <WorkItem(944031, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/944031")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLambdaParameterInferenceInGroupJoin2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System.Collections.Generic; using System.Linq; class Program { public class Book { public int Id { get; set; } public int OwnerId { get; set; } public string Name { get; set; } } public class Person { public int Id { get; set; } public string Nickname { get; set; } } static void Main() { var books = new List&lt;Book&gt;(); var persons = new List&lt;Person&gt;(); var join = persons.GroupJoin(books, person => person.Id, book => book.OwnerId, (person, books1) => new { person.Id, person.Nickname, books1.$$ }); </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain("Select", "<>") End Using End Function <WorkItem(944031, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/944031")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLambdaParameterInferenceInGroupJoin3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System.Collections.Generic; using System.Linq; class Program { public class Book { public int Id { get; set; } public int OwnerId { get; set; } public string Name { get; set; } } public class Person { public int Id { get; set; } public string Nickname { get; set; } } static void Main() { var books = new List&lt;Book&gt;(); var persons = new List&lt;Person&gt;(); var join = persons.GroupJoin(books, person => person.Id, book => book.OwnerId, (person, books1) => new { person.Id, person.Nickname, books1.Select(s => s.$$) }); </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain("Name", "") End Using End Function <WorkItem(1128749, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1128749")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFallingBackToItemWithLongestCommonPrefixWhenNoMatch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class SomePrefixAndName {} class C { void Method() { SomePrefixOrName$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() state.SendEscape() Await state.WaitForAsynchronousOperationsAsync() state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem(displayText:="SomePrefixAndName", isHardSelected:=False) End Using End Function <WorkItem(47511, "https://github.com/dotnet/roslyn/pull/47511")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ConversionsOperatorsAndIndexerAreShownBelowMethodsAndPropertiesAndBeforeUnimportedItems() Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace A { using B; public static class CExtensions{ public static void ExtensionUnimported(this C c) { } } } namespace B { public static class CExtensions{ public static void ExtensionImported(this C c) { } } public class C { public int A { get; } = default; public int Z { get; } = default; public void AM() { } public void ZM() { } public int this[int _] => default; public static explicit operator int(C _) => default; public static C operator +(C a, C b) => default; } class Program { static void Main() { var c = new C(); c.$$ } } } </Document>) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption( CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() state.AssertItemsInOrder(New String() { "A", ' Method, properties, and imported extension methods alphabetical ordered "AM", "Equals", "ExtensionImported", "GetHashCode", "GetType", "this[]", ' Indexer "ToString", "Z", "ZM", "(int)", ' Conversions "+", ' Operators "ExtensionUnimported" 'Unimported extension methods }) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestCompleteMethodParenthesisForSymbolCompletionProvider(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) Using state = TestStateFactory.CreateCSharpTestState( <Document> public class B { private void C11() { $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" public class B {{ private void C11() {{ C11(){commitChar} }} }}" state.SendTypeChars("C") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("C11")) Assert.True(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("C11") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> Public Sub TestNestedMethodCallWhenCommitUsingSemicolon(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> public class B { private void C11() { AAA($$) } private int DDD() => 1; private int AAA(int i) => 1; }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" public class B {{ private void C11() {{ AAA(DDD()); }} private int DDD() => 1; private int AAA(int i) => 1; }}" state.SendTypeChars("D") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("DDD")) Assert.True(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("DDD") state.SendTypeChars(";"c) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> Public Sub TestNestedMethodCallUnderDelegateContextWhenCommitUsingSemicolon(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; public class B { private void C11() { AAA($$) } private void DDD() {} private int AAA(Action c) => 1; }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" using System; public class B {{ private void C11() {{ AAA(DDD); }} private void DDD() {{}} private int AAA(Action c) => 1; }}" state.SendTypeChars("D") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("DDD")) Assert.False(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("DDD") state.SendTypeChars(";"c) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> Public Sub TestNestedMethodCallWhenCommitUsingDot(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> public class B { private void C11() { AAA($$) } private int DDD() => 1; private int AAA(int i) => 1; }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" public class B {{ private void C11() {{ AAA(DDD().) }} private int DDD() => 1; private int AAA(int i) => 1; }}" state.SendTypeChars("D") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("DDD")) Assert.True(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("DDD") state.SendTypeChars("."c) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestCompleteMethodParenthesisForSymbolCompletionProviderUnderDelegateContext(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; public class B { private void C11() { Action t = $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" using System; public class B {{ private void C11() {{ Action t = C11{commitChar} }} }}" state.SendTypeChars("C") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("C11")) Assert.False(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("C11") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestCompleteObjectCreationParenthesisForSymbolCreationCompletionProvider(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) Using state = TestStateFactory.CreateCSharpTestState( <Document> using Bar = System.String public class AA { private static void CC() { var a = new $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" using Bar = System.String public class AA {{ private static void CC() {{ var a = new Bar(){commitChar} }} }}" state.SendTypeChars("B") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("AA")) Assert.True(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("Bar") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestCompleteObjectCreationParenthesisForSymbolCreationCompletionProviderUnderNonObjectCreationContext(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) Using state = TestStateFactory.CreateCSharpTestState( <Document> using Bar = System.String public class AA { private static void CC() { $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" using Bar = System.String public class AA {{ private static void CC() {{ Bar{commitChar} }} }}" state.SendTypeChars("B") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("AA")) Assert.False(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("Bar") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestCompleteParenthesisForObjectCreationCompletionProvider(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) Using state = TestStateFactory.CreateCSharpTestState( <Document> public class AA { private static void CC() { AA a = new $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" public class AA {{ private static void CC() {{ AA a = new AA(){commitChar} }} }}" state.SendTypeChars("A") state.SendSelectCompletionItem("AA") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestCompleteParenthesisForExtensionMethodImportCompletionProvider(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace CC { public static class DD { public static int ToInt(this AA a) => 1; } } public class AA { private static void CC() { AA a = new AA(); var value = a.$$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True) _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1)) Dim expectedText = $" using CC; namespace CC {{ public static class DD {{ public static int ToInt(this AA a) => 1; }} }} public class AA {{ private static void CC() {{ AA a = new AA(); var value = a.ToInt(){commitChar} }} }}" state.SendTypeChars("To") state.SendSelectCompletionItem("ToInt") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompleteParenthesisForTypeImportCompletionProvider(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace CC { public class Bar { } } public class AA { private static void CC() { var a = new $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() ' Make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Dim expectedText = $" using CC; namespace CC {{ public class Bar {{ }} }} public class AA {{ private static void CC() {{ var a = new Bar(){commitChar} }} }}" state.SendTypeChars("Ba") state.SendSelectCompletionItem("Bar") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompleteParenthesisForTypeImportCompletionProviderUnderNonObjectCreationContext(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace CC { public class Bar { } } public class AA { private static void CC() { $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() ' Make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Dim expectedText = $" using CC; namespace CC {{ public class Bar {{ }} }} public class AA {{ private static void CC() {{ Bar{commitChar} }} }}" state.SendTypeChars("Ba") state.SendSelectCompletionItem("Bar") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompleteParenthesisForMethodUnderNameofContext(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class AA { private static void CC() { var x = nameof($$) } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Dim expectedText = " public class AA { private static void CC() { var x = nameof(CC); } }" state.SendTypeChars("CC") state.SendSelectCompletionItem("CC") state.SendTypeChars(";") Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompleteParenthesisForGenericMethodUnderNameofContext(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; public class AA { private static void CC() { var x = nameof($$) } private static T GetSomething&lt;T&gt;() => (T)Activator.GetInstance(typeof(T)); }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Dim expectedText = " using System; public class AA { private static void CC() { var x = nameof(GetSomething); } private static T GetSomething<T>() => (T)Activator.GetInstance(typeof(T)); }" state.SendTypeChars("Get") state.SendSelectCompletionItem("GetSomething<>") state.SendTypeChars(";") Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompleteParenthesisForFullMethodUnderNameofContext(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class AA { private static void CC() { var x = nameof($$) } } namespace Bar1 { public class Bar2 { public void Bar3() { } } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Dim expectedText = " public class AA { private static void CC() { var x = nameof(Bar1.Bar2.Bar3); } } namespace Bar1 { public class Bar2 { public void Bar3() { } } }" state.SendTypeChars("Bar1.Bar2.Ba") state.SendSelectCompletionItem("Bar3") state.SendTypeChars(";") Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompleteParenthesisForFunctionPointer(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; public unsafe class AA { private static void CC() { delegate*&lt;void&gt; p = $$ } public static void Bar() {} }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Dim expectedText = " using System; public unsafe class AA { private static void CC() { delegate*<void> p = Bar; } public static void Bar() {} }" state.SendTypeChars("Ba") state.SendSelectCompletionItem("Bar") state.SendTypeChars(";") Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorIf(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if $$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#if Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorElif(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if false #elif $$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#elif Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionNotInPreprocessorElse(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if false #elif false #else $$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorParenthesized(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if ($$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#if (Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorNot(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if !$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#if !Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorAnd(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if true &amp;&amp; $$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#if true && Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorOr(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if true || $$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#if true || Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorCasingDifference(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,BAR,Baz"> <Document> #if $$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "BAR", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#if Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSuggestionModeWithDeletionTrigger(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections.Generic; using System.Linq; class C { public static void Baz(List<int> list) { var xml = 0; list.FirstOrDefault(xx$$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertSelectedCompletionItem("xml", isSoftSelected:=True).ConfigureAwait(True) End Using End Function ' Simulates a situation where IntelliCode provides items not included into the Rolsyn original list. ' We want to ignore these items in CommitIfUnique. ' This situation should not happen. Tests with this provider were added to cover protective scenarios. <ExportCompletionProvider(NameOf(IntelliCodeMockWeirdProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class IntelliCodeMockWeirdProvider Inherits IntelliCodeMockProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New() End Sub Public Overrides Async Function ProvideCompletionsAsync(context As CompletionContext) As Task Await MyBase.ProvideCompletionsAsync(context).ConfigureAwait(False) context.AddItem(CompletionItem.Create(displayText:="★ Length2", filterText:="Length")) End Function End Class <WorkItem(49813, "https://github.com/dotnet/roslyn/issues/49813")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCaseSensitiveMatchWithLowerMatchPriority(showCompletionInArgumentLists As Boolean) As Task ' PreselectionProvider will provide an item "★ length" with filter text "length", ' which is a case-insentive match to typed text "Length", but with higher match priority. ' In this case, we need to make sure the case-sensitive match "Length" is selected. Using state = TestStateFactory.CreateCSharpTestState( <Document> struct Range { public (int Offset, int Length) GetOffsetAndLength(int length) => (0, 0); } class Repro { public int Length { get; } public void Test(Range x) { var (offset, length) = x.GetOffsetAndLength(Length$$); } } </Document>, extraExportedTypes:={GetType(PreselectionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"★ length", "length", "Length"}) Await state.AssertSelectedCompletionItem("Length", isHardSelected:=True) state.SendEscape() Await state.AssertNoCompletionSession() state.SendBackspace() Await state.AssertCompletionSession() Await state.AssertCompletionItemsContainAll({"★ length", "length", "Length"}) Await state.AssertSelectedCompletionItem("Length", isHardSelected:=True) End Using End Function ' Simulate the situation that some provider (e.g. IntelliCode) provides items with higher match priority that only match case-insensitively. <ExportCompletionProvider(NameOf(PreselectionProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class PreselectionProvider Inherits CommonCompletionProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task Dim rules = CompletionItemRules.Default.WithSelectionBehavior(CompletionItemSelectionBehavior.HardSelection).WithMatchPriority(MatchPriority.Preselect) context.AddItem(CompletionItem.Create(displayText:="★ length", filterText:="length", rules:=rules)) Return Task.CompletedTask End Function Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return True End Function End Class <WorkItem(53712, "https://github.com/dotnet/roslyn/issues/53712")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotifyCommittingItemCompletionProvider(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public void M() { ItemFromNotifyCommittingItemCompletion$$ } } </Document>, extraExportedTypes:={GetType(NotifyCommittingItemCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim notifyProvider As NotifyCommittingItemCompletionProvider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of NotifyCommittingItemCompletionProvider)().Single() notifyProvider.Reset() state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain(NotifyCommittingItemCompletionProvider.DisplayText, "") Await state.AssertSelectedCompletionItem(NotifyCommittingItemCompletionProvider.DisplayText, isHardSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains(NotifyCommittingItemCompletionProvider.DisplayText, state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await notifyProvider.checkpoint.Task Assert.False(notifyProvider.CalledOnMainThread) End Using End Function <ExportCompletionProvider(NameOf(NotifyCommittingItemCompletionProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class NotifyCommittingItemCompletionProvider Inherits CommonCompletionProvider Implements INotifyCommittingItemCompletionProvider Private ReadOnly _threadingContext As IThreadingContext Public Const DisplayText As String = "ItemFromNotifyCommittingItemCompletionProvider" Public Checkpoint As Checkpoint = New Checkpoint() Public CalledOnMainThread As Boolean? Public Sub Reset() Checkpoint = New Checkpoint() CalledOnMainThread = Nothing End Sub <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(threadingContext As IThreadingContext) _threadingContext = threadingContext End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task context.AddItem(CompletionItem.Create(displayText:=DisplayText, filterText:=DisplayText)) Return Task.CompletedTask End Function Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return True End Function #Disable Warning IDE0060 ' Remove unused parameter Public Function NotifyCommittingItemAsync(document As Document, item As CompletionItem, commitKey As Char?, cancellationToken As CancellationToken) As Task Implements INotifyCommittingItemCompletionProvider.NotifyCommittingItemAsync #Enable Warning IDE0060 ' Remove unused parameter CalledOnMainThread = _threadingContext.HasMainThread AndAlso _threadingContext.JoinableTaskContext.IsOnMainThread Checkpoint.Release() Return Task.CompletedTask End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.CSharp Imports Microsoft.CodeAnalysis.CSharp.Formatting Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Tags Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Text.Projection Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class CSharpCompletionCommandHandlerTests <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_FirstNested(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 CProperty { get; set; } } public class C2 { public int IntProperty { get; set; } void M(C c) { _ = c is { CProperty$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=False) state.SendTypeChars("IP") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 2 }") Await state.AssertNoCompletionSession() Assert.Contains("c is { CProperty.IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnListPattern_FirstNested(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { } public class C2 { public C2 CProperty { get; set; } public int IntProperty { get; set; } void M(C c) { _ = c is { $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) ' This is the expected behavior until we implement support for list-patterns. state.SendTypeChars("CP") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_Hidden(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" LanguageVersion="Preview" CommonReferences="true"> <ProjectReference>VBAssembly1</ProjectReference> <Document FilePath="C.cs"> public class C3 { void M(C c) { _ = c is { CProperty$$ } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true"> <Document><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Property CProperty As C2 End Class Public Class C2 Public Property IntProperty As Integer End Class ]]></Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=False) state.SendTypeChars("IP") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 2 }") Await state.AssertNoCompletionSession() Assert.Contains("c is { CProperty.IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_SecondNested(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 C2Property { get; set; } } public class C2 { public C3 C3Property { get; set; } } public class C3 { public int IntProperty { get; set; } void M(C c) { _ = c is { C2Property.C3Property$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=False) state.SendTypeChars("IP") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 2 }") Await state.AssertNoCompletionSession() Assert.Contains("c is { C2Property.C3Property.IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_SecondNested_Fields(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 C2Field; } public class C2 { public C3 C3Field; } public class C3 { public int IntField; void M(C c) { _ = c is { C2Field$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem(displayText:="C3Field:", isHardSelected:=False) state.SendTypeChars("CF") Await state.AssertSelectedCompletionItem(displayText:="C3Field:", isHardSelected:=True) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem(displayText:="IntField:", isHardSelected:=False) state.SendTypeChars("IF") Await state.AssertSelectedCompletionItem(displayText:="IntField:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 2 }") Await state.AssertNoCompletionSession() Assert.Contains("c is { C2Field.C3Field.IntField: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_ErrorProperty(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public int IntProperty { get; set; } void M(C c) { _ = c is { Error$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(".") Await state.AssertNoCompletionSession() state.SendTypeChars("IP") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 CProperty { get; set; } } public class C2 { public int IntProperty { get; set; } void M(C c) { _ = c is $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars("{ ") Await state.AssertSelectedCompletionItem(displayText:="CProperty:", isHardSelected:=False) state.SendTypeChars("CP") Await state.AssertSelectedCompletionItem(displayText:="CProperty:", isHardSelected:=True) state.SendTypeChars(".") Assert.Contains("c is { CProperty.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=False) state.SendTypeChars("IP") Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 2 }") Await state.AssertNoCompletionSession() Assert.Contains("c is { CProperty.IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_AlreadyTestedBySimplePattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 CProperty { get; set; } } public class C2 { public int IntProperty { get; set; } void M(C c) { _ = c is { CProperty: 2$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) ' No second completion since already tested at top-level state.SendTypeChars(", ") Await state.AssertNoCompletionSession() state.SendTypeChars("CP") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_AlreadyTestedByExtendedPattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 CProperty { get; set; } } public class C2 { public int IntProperty { get; set; } public short ShortProperty { get; set; } void M(C c) { _ = c is { CProperty.IntProperty: 2$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(", ") Await state.AssertSelectedCompletionItem(displayText:="CProperty:", isHardSelected:=False) state.SendTypeChars("CP") Await state.AssertSelectedCompletionItem(displayText:="CProperty:", isHardSelected:=True) state.SendTypeChars(".") Assert.Contains("is { CProperty.IntProperty: 2, CProperty.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) ' Note: same completion is offered a second time Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=False) state.SendTypeChars("SP") Await state.AssertSelectedCompletionItem(displayText:="ShortProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 3") Await state.AssertNoCompletionSession() Assert.Contains("is { CProperty.IntProperty: 2, CProperty.ShortProperty: 3", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_AlreadyTestedByNestedPattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 CProperty { get; set; } } public class C2 { public int IntProperty { get; set; } public short ShortProperty { get; set; } void M(C c) { _ = c is { CProperty: { IntProperty: 2 }$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(", ") Await state.AssertNoCompletionSession() state.SendTypeChars("CProperty") Await state.AssertNoCompletionSession() state.SendTypeChars(".") Assert.Contains("is { CProperty: { IntProperty: 2 }, CProperty.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) ' Note: same completion is offered a second time Await state.AssertSelectedCompletionItem(displayText:="IntProperty:", isHardSelected:=False) state.SendTypeChars("SP") Await state.AssertSelectedCompletionItem(displayText:="ShortProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 3") Await state.AssertNoCompletionSession() Assert.Contains("is { CProperty: { IntProperty: 2 }, CProperty.ShortProperty: 3", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnExtendedPropertyPattern_BeforeAnotherPattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public C2 CProperty { get; set; } } public class C2 { public int IntProperty { get; set; } public short ShortProperty { get; set; } void M(C c) { _ = c is {$$ CProperty.IntProperty: 2 } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="CProperty:", isHardSelected:=False) state.SendTypeChars("CP") Await state.AssertSelectedCompletionItem(displayText:="CProperty:", isHardSelected:=True) state.SendTypeChars(".") Assert.Contains("is { CProperty. CProperty.IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertSelectedCompletionItem(displayText:="Equals", isHardSelected:=False) state.SendTypeChars("SP") Await state.AssertSelectedCompletionItem(displayText:="ShortProperty", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 3,") Await state.AssertNoCompletionSession() Assert.Contains("is { CProperty.ShortProperty: 3, CProperty.IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnPropertyPattern_BeforeAnotherPattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class C { public int IntProperty { get; set; } public short ShortProperty { get; set; } } public class C2 { void M(C c) { _ = c is {$$ IntProperty: 2 } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="ShortProperty:", isHardSelected:=False) state.SendTypeChars("SP") Await state.AssertSelectedCompletionItem(displayText:="ShortProperty:", isHardSelected:=True) state.SendTab() state.SendTypeChars(": 3,") Await state.AssertNoCompletionSession() Assert.Contains("is { ShortProperty: 3, IntProperty: 2 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnRecordBaseType(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> record Base(int Alice, int Bob); record Derived(int Other) : [|Base$$|] </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp9) state.SendTypeChars("(") If showCompletionInArgumentLists Then Await state.AssertSelectedCompletionItem(displayText:="Alice:", isHardSelected:=False) End If state.SendTypeChars("A") If showCompletionInArgumentLists Then Await state.AssertSelectedCompletionItem(displayText:="Alice:", isHardSelected:=True) End If state.SendTypeChars(": 1, B") If showCompletionInArgumentLists Then Await state.AssertSelectedCompletionItem(displayText:="Bob:", isHardSelected:=True) End If state.SendTab() state.SendTypeChars(": 2)") Await state.AssertNoCompletionSession() Assert.Contains(": Base(Alice: 1, Bob: 2)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(46397, "https://github.com/dotnet/roslyn/issues/46397")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnImplicitObjectCreationExpressionInitializer(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public int Alice; public int Bob; void M(int value) { C c = new() $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp9) state.SendTypeChars("{ ") Await state.AssertSelectedCompletionItem(displayText:="Alice", isHardSelected:=False) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("new() { Alice", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars(" = va") Await state.AssertSelectedCompletionItem(displayText:="value", isHardSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("new() { Alice = value", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(44921, "https://github.com/dotnet/roslyn/issues/44921")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnWithExpressionInitializer(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> record Base(int Alice, int Bob) { void M(int value) { _ = this with $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp9) state.SendTypeChars("{ ") Await state.AssertSelectedCompletionItem(displayText:="Alice", isHardSelected:=False) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("with { Alice", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars(" = va") Await state.AssertSelectedCompletionItem(displayText:="value", isHardSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("with { Alice = value", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(44921, "https://github.com/dotnet/roslyn/issues/44921")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnWithExpressionInitializer_AfterComma(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> record Base(int Alice, int Bob) { void M(int value) { _ = this with { Alice = value$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp9) state.SendTypeChars(", ") Await state.AssertSelectedCompletionItem(displayText:="Bob", isHardSelected:=False) state.SendTab() Await state.AssertNoCompletionSession() state.SendTypeChars(" = va") Await state.AssertSelectedCompletionItem(displayText:="value", isHardSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("with { Alice = value, Bob = value", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(47430, "https://github.com/dotnet/roslyn/issues/47430")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnWithExpressionForTypeParameter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public abstract record MyRecord { public string Name { get; init; } } public static class Test { public static TRecord WithNameSuffix&lt;TRecord&gt;(this TRecord record, string nameSuffix) where TRecord : MyRecord => record with { $$ }; } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.CSharp9) state.SendTypeChars("N") Await state.AssertSelectedCompletionItem(displayText:="Name", isHardSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("Name", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnWithExpressionInitializer_AnonymousType(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M() { var a = new { Property = 1 }; _ = a $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists, languageVersion:=LanguageVersion.Preview) state.SendTypeChars("w") Await state.AssertSelectedCompletionItem(displayText:="with", isHardSelected:=False) state.SendTab() state.SendTypeChars(" { ") Await state.AssertSelectedCompletionItem(displayText:="Property", isHardSelected:=False) state.SendTypeChars("P") Await state.AssertSelectedCompletionItem(displayText:="Property", isHardSelected:=True) state.SendTypeChars(" = 2") Await state.AssertNoCompletionSession() Assert.Contains("with { Property = 2", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(44921, "https://github.com/dotnet/roslyn/issues/44921")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionOnObjectCreation(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { int Alice { get; set; } void M() { _ = new C() $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("{ ") Await state.AssertSelectedCompletionItem(displayText:="Alice", isHardSelected:=False) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("new C() { Alice", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(541201, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541201")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TabCommitsWithoutAUniqueMatch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("using System.Ne") Await state.AssertSelectedCompletionItem(displayText:="Net", isHardSelected:=True) state.SendTypeChars("x") Await state.AssertSelectedCompletionItem(displayText:="Net", isSoftSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("using System.Net", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBetweenTwoDotsInNamespaceName(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace N.O.P { } namespace N$$.P { } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem(displayText:="O", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAtEndOfFile(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document>$$</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("usi") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("using", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(44459, "https://github.com/dotnet/roslyn/issues/44459")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectUsingOverUshort(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' 'us' should select 'using' instead of 'ushort' (even though 'ushort' sorts higher in the list textually). state.SendTypeChars("us") Await state.AssertSelectedCompletionItem(displayText:="using", isHardSelected:=True) Await state.AssertCompletionItemsContain("ushort", "") ' even after 'ushort' is selected, deleting the 'h' should still take us back to 'using'. state.SendTypeChars("h") Await state.AssertSelectedCompletionItem(displayText:="ushort", isHardSelected:=True) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="using", isHardSelected:=True) End Using End Function <WorkItem(44459, "https://github.com/dotnet/roslyn/issues/44459")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectUshortOverUsingOnceInMRU(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ush") Await state.AssertCompletionItemsContain("ushort", "") state.SendTab() Assert.Contains("ushort", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendDeleteWordToLeft() ' 'ushort' should be in the MRU now. so typing 'us' should select it instead of 'using'. state.SendTypeChars("us") Await state.AssertSelectedCompletionItem(displayText:="ushort", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDeletingWholeWordResetCompletionToTheDefaultItem(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void M() { var replyUri = new Uri(""); $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendTypeChars("repl") state.SendTab() For i = 1 To 7 state.SendBackspace() Await state.WaitForAsynchronousOperationsAsync() Next Await state.AssertCompletionSession() state.SendBackspace() Await state.AssertSelectedCompletionItem("AccessViolationException") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestTabsDoNotTriggerCompletion(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void M() { var replyUri = new Uri(""); replyUri$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTab() state.SendTab() Assert.Equal(" replyUri" & vbTab & vbTab, state.GetLineTextFromCaretPosition()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEnterDoesNotTriggerCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void M() { String.Equals("foo", "bar", $$StringComparison.CurrentCulture) } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendReturn() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotAtStartOfExistingWord(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document>$$using</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("u") Await state.AssertNoCompletionSession() Assert.Contains("using", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMSCorLibTypes(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class c : $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("A") Await state.AssertCompletionItemsContainAll("Attribute", "Exception", "IDisposable") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFiltering1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class c { $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Sy") Await state.AssertCompletionItemsContainAll("OperatingSystem", "System", "SystemException") Await state.AssertCompletionItemsDoNotContainAny("Exception", "Activator") End Using End Function ' NOTE(cyrusn): This should just be a unit test for SymbolCompletionProvider. However, I'm ' just porting the integration tests to here for now. <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMultipleTypes(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { $$ } struct S { } enum E { } interface I { } delegate void D(); </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("C") Await state.AssertCompletionItemsContainAll("C", "S", "E", "I", "D") End Using End Function ' NOTE(cyrusn): This should just be a unit test for KeywordCompletionProvider. However, I'm ' just porting the integration tests to here for now. <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInEmptyFile(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("abstract", "class", "namespace") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotAfterTypingDotAfterIntegerLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class c { void M() { 3$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterExplicitInvokeAfterDotAfterIntegerLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class c { void M() { 3.$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("ToString") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TestTypingDotBeforeExistingDot(showCompletionInArgumentLists As Boolean) As Task ' Starting C# 8.0 two dots are considered as a DotDotToken of a Range expression. ' However, typing dot before a single dot (and adding the second one) should lead to a completion ' in the context of the previous token if this completion exists. Using state = TestStateFactory.CreateCSharpTestState( <Document> class c { void M() { this$$.ToString() } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionItemsContainAll("ToString") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypingDotAfterExistingDot(showCompletionInArgumentLists As Boolean) As Task ' Starting C# 8.0 two dots are considered as a DotDotToken of a Range expression. ' A test above (TestTypingDotBeforeExistingDot) verifies that the completion happens ' if we type dot before a single dot. ' However, we should not have a completion if typing dot after a dot. Using state = TestStateFactory.CreateCSharpTestState( <Document> class c { void M() { this.$$ToString() } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TestInvokingCompletionBetweenTwoDots(showCompletionInArgumentLists As Boolean) As Task ' Starting C# 8.0 two dots are considered as a DotDotToken of a Range expression. ' However, we may want to have a completion when invoking it aqfter the first dot. Using state = TestStateFactory.CreateCSharpTestState( <Document> class c { void M() { this.$$.ToString() } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("ToString") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestEnterIsConsumed(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> class Class1 { void Main(string[] args) { $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("System.TimeSpan.FromMin") state.SendReturn() Assert.Equal(<text> class Class1 { void Main(string[] args) { System.TimeSpan.FromMinutes } }</text>.NormalizedValue, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestEnterIsConsumedWithAfterFullyTypedWordOption_NotFullyTyped(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> class Class1 { void Main(string[] args) { $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.EnterKeyBehavior, LanguageNames.CSharp, EnterKeyRule.AfterFullyTypedWord))) state.SendTypeChars("System.TimeSpan.FromMin") state.SendReturn() Assert.Equal(<text> class Class1 { void Main(string[] args) { System.TimeSpan.FromMinutes } }</text>.NormalizedValue, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestEnterIsConsumedWithAfterFullyTypedWordOption_FullyTyped(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> class Class1 { void Main(string[] args) { $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.EnterKeyBehavior, LanguageNames.CSharp, EnterKeyRule.AfterFullyTypedWord))) state.SendTypeChars("System.TimeSpan.FromMinutes") state.SendReturn() Assert.Equal(<text> class Class1 { void Main(string[] args) { System.TimeSpan.FromMinutes } }</text>.NormalizedValue, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDescription1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; /// <summary> /// TestDocComment /// </summary> class TestException : Exception { } class MyException : $$]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Test") Await state.AssertSelectedCompletionItem(description:="class TestException" & vbCrLf & "TestDocComment") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestObjectCreationPreselection1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections.Generic; class C { public void Goo() { List<int> list = new$$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True) Await state.AssertCompletionItemsContainAll("LinkedList", "List", "System") state.SendTypeChars("Li") Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True) Await state.AssertCompletionItemsContainAll("LinkedList", "List") Await state.AssertCompletionItemsDoNotContainAny("System") state.SendTypeChars("n") Await state.AssertSelectedCompletionItem(displayText:="LinkedList", displayTextSuffix:="<>", isHardSelected:=True) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True) state.SendTab() Assert.Contains("new List<int>", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDeconstructionDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { var ($$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("i") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDeconstructionDeclaration2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { var (a, $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("i") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDeconstructionDeclaration3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { var ($$) = (1, 2); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("i") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedDeconstructionDeclarationWithVar(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var a$$) = (1, 2); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem(displayText:="as", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedDeconstructionDeclarationWithVarAfterComma(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var a, var a$$) = (1, 2); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem(displayText:="as", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedVarDeconstructionDeclarationWithVar(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var a, var ($$)) = (1, 2); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("a") Await state.AssertNoCompletionSession() state.SendTypeChars(", a") Await state.AssertNoCompletionSession() Assert.Contains("(var a, var (a, a)) = ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestVarDeconstructionDeclarationWithVar(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" (a") Await state.AssertNoCompletionSession() state.SendTypeChars(", a") Await state.AssertNoCompletionSession() Assert.Contains("var (a, a", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedDeconstructionDeclarationWithSymbol(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { ($$) = (1, 2); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("vari") Await state.AssertSelectedCompletionItem(displayText:="Variable", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(Variable ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertNoCompletionSession() state.SendTypeChars("x, vari") Await state.AssertSelectedCompletionItem(displayText:="Variable", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(Variable x, Variable ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertSelectedCompletionItem(displayText:="Variable", isHardSelected:=False) Await state.AssertCompletionItemsContainAll("variable") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedDeconstructionDeclarationWithInt(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Integer { public void Goo() { ($$) = (1, 2); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("int") Await state.AssertSelectedCompletionItem(displayText:="int", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(int ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertNoCompletionSession() state.SendTypeChars("x, int") Await state.AssertSelectedCompletionItem(displayText:="int", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(int x, int ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestIncompleteParenthesizedDeconstructionDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { ($$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(", va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(")") Assert.Contains("(var a, var a)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestIncompleteParenthesizedDeconstructionDeclaration2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { ($$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(", va") Await state.AssertSelectedCompletionItem(displayText:="var", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendReturn() Dim caretLine = state.GetLineFromCurrentCaretPosition() Assert.Contains(" )", caretLine.GetText(), StringComparison.Ordinal) Dim previousLine = caretLine.Snapshot.Lines(caretLine.LineNumber - 1) Assert.Contains("(var a, var a", previousLine.GetText(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceInIncompleteParenthesizedDeconstructionDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var as$$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(", var as") state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(")") Await state.AssertNoCompletionSession() Assert.Contains("(var a, var a)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceInParenthesizedDeconstructionDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Variable { public void Goo() { (var as$$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendTypeChars(", var as") state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="as", isSoftSelected:=True) state.SendReturn() Await state.AssertNoCompletionSession() Dim caretLine = state.GetLineFromCurrentCaretPosition() Assert.Contains(" )", caretLine.GetText(), StringComparison.Ordinal) Dim previousLine = caretLine.Snapshot.Lines(caretLine.LineNumber - 1) Assert.Contains("(var a, var a", previousLine.GetText(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(17256, "https://github.com/dotnet/roslyn/issues/17256")> Public Async Function TestThrowExpression(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public object Goo() { return null ?? throw new$$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Exception", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(17256, "https://github.com/dotnet/roslyn/issues/17256")> Public Async Function TestThrowStatement(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public object Goo() { throw new$$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Exception", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNonTrailingNamedArgumentInCSharp7_1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" LanguageVersion="7.1" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> class C { public void M() { int better = 2; M(a: 1, $$) } public void M(int a, int bar, int c) { } } </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("b") Await state.AssertSelectedCompletionItem(displayText:="bar", displayTextSuffix:=":", isHardSelected:=True) state.SendTypeChars("e") Await state.AssertSelectedCompletionItem(displayText:="bar", displayTextSuffix:=":", isSoftSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNonTrailingNamedArgumentInCSharp7_2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" LanguageVersion="7.2" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> class C { public void M() { int better = 2; M(a: 1, $$) } public void M(int a, int bar, int c) { } } </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("b") Await state.AssertSelectedCompletionItem(displayText:="better", isHardSelected:=True) state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="bar", displayTextSuffix:=":", isHardSelected:=True) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="better", isHardSelected:=True) state.SendTypeChars(", ") Assert.Contains("M(a: 1, better,", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestDefaultSwitchLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { switch (o) { default: goto $$ } } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="default", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestGotoOrdinaryLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { label1: goto $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("l") Await state.AssertSelectedCompletionItem(displayText:="label1", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto label1;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestEscapedDefaultLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { @default: goto $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="@default", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto @default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestEscapedDefaultLabel2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { switch (o) { default: @default: goto $$ } } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="default", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(4677, "https://github.com/dotnet/roslyn/issues/4677")> Public Async Function TestEscapedDefaultLabelWithoutSwitch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M(object o) { @default: goto $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="@default", isHardSelected:=True) state.SendTypeChars(";") Assert.Contains("goto @default;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestArrayInitialization(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { Class[] x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("new ") Await state.AssertSelectedCompletionItem(displayText:="Class", isSoftSelected:=True) state.SendTypeChars("C") Await state.AssertSelectedCompletionItem(displayText:="Class", isHardSelected:=True) state.SendTypeChars("[") Assert.Contains("Class[] x = new Class[", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars("] {") Assert.Contains("Class[] x = new Class[] {", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestImplicitArrayInitialization(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { Class[] x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("n") Await state.AssertSelectedCompletionItem(displayText:="nameof", isHardSelected:=True) state.SendTypeChars("e") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Class", isSoftSelected:=True) state.SendTypeChars("[") Assert.Contains("Class[] x = new [", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars("] {") Assert.Contains("Class[] x = new [] {", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestImplicitArrayInitialization2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { Class[] x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ne") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars("[") Assert.Contains("Class[] x = new[", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestImplicitArrayInitialization3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { Class[] x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ne") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Class", isSoftSelected:=True) Assert.Contains("Class[] x = new ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars("[") Assert.Contains("Class[] x = new [", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestImplicitArrayInitialization4(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { Class[] x =$$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("{") Assert.Contains("Class[] x = {", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestImplicitArrayInitialization_WithTab(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { Class[] x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ne") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Class", isSoftSelected:=True) Assert.Contains("Class[] x = new ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTab() Assert.Contains("Class[] x = new Class", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestTypelessImplicitArrayInitialization(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { var x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ne") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() state.SendTypeChars("[") Assert.Contains("var x = new [", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars("] {") Assert.Contains("var x = new [] {", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestTypelessImplicitArrayInitialization2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { var x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ne") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars("[") Assert.Contains("var x = new[", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")> Public Async Function TestTypelessImplicitArrayInitialization3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { public void M() { var x = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ne") Await state.AssertSelectedCompletionItem(displayText:="new", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("var x = new ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars("[") Assert.Contains("var x = new [", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestPropertyInPropertySubpattern(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { int Prop { get; set; } int OtherProp { get; set; } public void M() { _ = this is $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendTypeChars("C") Await state.AssertSelectedCompletionItem(displayText:="Class", isHardSelected:=True) state.SendTypeChars(" { P") Await state.AssertSelectedCompletionItem(displayText:="Prop", displayTextSuffix:=":", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("{ Prop:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars(" 0, ") Await state.AssertSelectedCompletionItem(displayText:="OtherProp", displayTextSuffix:=":", isSoftSelected:=True) state.SendTypeChars("O") Await state.AssertSelectedCompletionItem(displayText:="OtherProp", displayTextSuffix:=":", isHardSelected:=True) state.SendTypeChars(": 1 }") Assert.Contains("is Class { Prop: 0, OtherProp: 1 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestPropertyInPropertySubpattern_TriggerWithSpace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Class { int Prop { get; set; } int OtherProp { get; set; } public void M() { _ = this is $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendTypeChars("C") Await state.AssertSelectedCompletionItem(displayText:="Class", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("is Class", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars("{ P") Await state.AssertSelectedCompletionItem(displayText:="Prop", displayTextSuffix:=":", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("is Class { Prop ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars(":") Assert.Contains("is Class { Prop :", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars(" 0, ") Await state.AssertSelectedCompletionItem(displayText:="OtherProp", displayTextSuffix:=":", isSoftSelected:=True) state.SendTypeChars("O") Await state.AssertSelectedCompletionItem(displayText:="OtherProp", displayTextSuffix:=":", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("is Class { Prop : 0, OtherProp", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendTypeChars(": 1 }") Assert.Contains("is Class { Prop : 0, OtherProp : 1 }", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestSymbolInTupleLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Fo() { ($$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("F") Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("(F:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestSymbolInTupleLiteralAfterComma(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Fo() { (x, $$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("F") Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("(x, F:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function ColonInTupleNameInTupleLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = ($$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("fi") Await state.AssertSelectedCompletionItem(displayText:="first", displayTextSuffix:=":", isHardSelected:=True) Assert.Equal("first", state.GetSelectedItem().FilterText) state.SendTypeChars(":") Assert.Contains("(first:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function ColonInExactTupleNameInTupleLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = ($$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("first") Await state.AssertSelectedCompletionItem(displayText:="first", displayTextSuffix:=":", isHardSelected:=True) Assert.Equal("first", state.GetSelectedItem().FilterText) state.SendTypeChars(":") Assert.Contains("(first:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function ColonInTupleNameInTupleLiteralAfterComma(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = (0, $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("se") Await state.AssertSelectedCompletionItem(displayText:="second", displayTextSuffix:=":", isHardSelected:=True) Assert.Equal("second", state.GetSelectedItem().FilterText) state.SendTypeChars(":") Assert.Contains("(0, second:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function TabInTupleNameInTupleLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = ($$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("fi") Await state.AssertSelectedCompletionItem(displayText:="first", displayTextSuffix:=":", isHardSelected:=True) Assert.Equal("first", state.GetSelectedItem().FilterText) state.SendTab() state.SendTypeChars(":") state.SendTypeChars("0") Assert.Contains("(first:0", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function TabInExactTupleNameInTupleLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = ($$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("first") Await state.AssertSelectedCompletionItem(displayText:="first", displayTextSuffix:=":", isHardSelected:=True) Assert.Equal("first", state.GetSelectedItem().FilterText) state.SendTab() state.SendTypeChars(":") state.SendTypeChars("0") Assert.Contains("(first:0", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(19335, "https://github.com/dotnet/roslyn/issues/19335")> Public Async Function TabInTupleNameInTupleLiteralAfterComma(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void M() { (int first, int second) t = (0, $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("se") Await state.AssertSelectedCompletionItem(displayText:="second", displayTextSuffix:=":", isHardSelected:=True) Assert.Equal("second", state.GetSelectedItem().FilterText) state.SendTab() state.SendTypeChars(":") state.SendTypeChars("1") Assert.Contains("(0, second:1", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestKeywordInTupleLiteral(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { ($$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="decimal", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("(d:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestTupleType(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { ($$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("d") Await state.AssertSelectedCompletionItem(displayText:="decimal", isHardSelected:=True) state.SendTypeChars(" ") Assert.Contains("(decimal ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestDefaultKeyword(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo() { switch(true) { $$ } } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("def") Await state.AssertSelectedCompletionItem(displayText:="default", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("default:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestInvocationExpression(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo(int Alice) { Goo($$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("A") Await state.AssertSelectedCompletionItem(displayText:="Alice", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("Goo(Alice:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestImplicitObjectCreationExpression(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ public class C { public C(int Alice, int Bob) { } public C(string ignored) { } public void M() { C c = new($$ } }]]></Document>, languageVersion:=LanguageVersion.CSharp9, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("A") Await state.AssertSelectedCompletionItem(displayText:="Alice:", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("new(Alice:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestImplicitObjectCreationExpression_WithSpace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ public class C { public C(int Alice, int Bob) { } public C(string ignored) { } public void M() { C c = new$$ } }]]></Document>, languageVersion:=LanguageVersion.CSharp9, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="C", isHardSelected:=True) state.SendTypeChars("(") If showCompletionInArgumentLists Then Await state.AssertSignatureHelpSession() Else Await state.AssertNoCompletionSession() End If state.SendTypeChars("A") Await state.AssertSelectedCompletionItem(displayText:="Alice:", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("new C(Alice:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestInvocationExpressionAfterComma(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Goo(int Alice, int Bob) { Goo(1, $$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("B") Await state.AssertSelectedCompletionItem(displayText:="Bob", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("Goo(1, Bob:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(13527, "https://github.com/dotnet/roslyn/issues/13527")> Public Async Function TestCaseLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Fo() { switch (1) { case $$ } } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("F") Await state.AssertSelectedCompletionItem(displayText:="Fo", isHardSelected:=True) state.SendTypeChars(":") Assert.Contains("case Fo:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(543268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543268")> Public Async Function TestTypePreselection1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ partial class C { } partial class C { $$ }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("C") Await state.AssertSelectedCompletionItem(displayText:="C", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertCompletionSession() End Using End Function <WorkItem(543519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543519")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNewPreselectionAfterVar(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { var c = $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("new ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(543559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543559")> <WorkItem(543561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543561")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEscapedIdentifiers(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class @return { void goo() { $$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("@") Await state.AssertNoCompletionSession() state.SendTypeChars("r") Await state.AssertSelectedCompletionItem(displayText:="@return", isHardSelected:=True) state.SendTab() Assert.Contains("@return", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(543771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543771")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitUniqueItem1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main(string[] args) { Console.WriteL$$(); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("WriteLine()", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(543771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543771")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitUniqueItem2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main(string[] args) { Console.WriteL$$ine(); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("using Sys") Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars("(") Await state.AssertNoCompletionSession() Assert.Contains("using Sys(", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("using Sys") Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.Contains("using System.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("using Sys") Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars(";") Await state.AssertNoCompletionSession() state.AssertMatchesTextStartingAtLine(1, "using System;") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective4(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> $$ </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("using Sys") Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() Assert.Contains("using Sys ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function KeywordsIncludedInObjectCreationCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Goo() { string s = new$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="string", isHardSelected:=True) Await state.AssertCompletionItemsContainAll("int") End Using End Function <WorkItem(544293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544293")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoKeywordsOrSymbolsAfterNamedParameterWithCSharp7(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class Goo { void Test() { object m = null; Method(obj:m, $$ } void Method(object obj, int num = 23, string str = "") { } } </Document>, languageVersion:=LanguageVersion.CSharp7, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("a") Await state.AssertCompletionItemsDoNotContainAny("System", "int") Await state.AssertCompletionItemsContain("num", ":") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function KeywordsOrSymbolsAfterNamedParameter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class Goo { void Test() { object m = null; Method(obj:m, $$ } void Method(object obj, int num = 23, string str = "") { } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("a") Await state.AssertCompletionItemsContainAll("System", "int") Await state.AssertCompletionItemsContain("num", ":") End Using End Function <WorkItem(544017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544017")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionTriggeredOnSpace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Goo { void Bar(int a, Numeros n) { } void Baz() { Bar(0$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(", ") Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True) Assert.Equal(1, state.GetCompletionItems().Where(Function(c) c.DisplayText = "Numeros").Count()) End Using End Function <WorkItem(479078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/479078")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionTriggeredOnSpaceForNullables(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Goo { void Bar(int a, Numeros? n) { } void Baz() { Bar(0$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(", ") Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True) Assert.Equal(1, state.GetCompletionItems().Where(Function(c) c.DisplayText = "Numeros").Count()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub EnumCompletionTriggeredOnDot(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Goo { void Bar() { Numeros num = $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Nu.") Assert.Contains("Numeros num = Numeros.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionNotTriggeredOnPlusCommitCharacter(showCompletionInArgumentLists As Boolean) As Task Await EnumCompletionNotTriggeredOn("+"c, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionNotTriggeredOnLeftBraceCommitCharacter(showCompletionInArgumentLists As Boolean) As Task Await EnumCompletionNotTriggeredOn("{"c, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionNotTriggeredOnSpaceCommitCharacter(showCompletionInArgumentLists As Boolean) As Task Await EnumCompletionNotTriggeredOn(" "c, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionNotTriggeredOnSemicolonCommitCharacter(showCompletionInArgumentLists As Boolean) As Task Await EnumCompletionNotTriggeredOn(";"c, showCompletionInArgumentLists) End Function Private Shared Async Function EnumCompletionNotTriggeredOn(c As Char, showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Goo { void Bar() { Numeros num = $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Nu") Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True) state.SendTypeChars(c.ToString()) Await state.AssertSessionIsNothingOrNoCompletionItemLike("Numberos") Assert.Contains(String.Format("Numeros num = Nu{0}", c), state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(49632, "https://github.com/dotnet/roslyn/pull/49632")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionEnumTypeAndValues() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace A { public enum Colors { Red, Green } } namespace B { class Program { static void Main() { var color = A.Colors.Red; switch (color) { case $$ } } } </Document>) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain(Function(i) i.DisplayText = "A.Colors" AndAlso i.FilterText = "Colors") Await state.AssertCompletionItemsContain(Function(i) i.DisplayText = "A.Colors.Green" AndAlso i.FilterText = "A.Colors.Green") Await state.AssertCompletionItemsContain(Function(i) i.DisplayText = "A.Colors.Red" AndAlso i.FilterText = "A.Colors.Red") Await state.AssertSelectedCompletionItem("A.Colors", isHardSelected:=True) End Using End Function <WorkItem(49632, "https://github.com/dotnet/roslyn/pull/49632")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionEnumTypeSelectionSequenceTest() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public enum Colors { Red, Green } class Program { void M(Colors color) { } static void Main() { M$$ } } </Document>) state.SendTypeChars("(") Await state.AssertCompletionSession Await state.AssertCompletionItemsContain("Colors", "") Await state.AssertCompletionItemsContain("Colors.Green", "") Await state.AssertCompletionItemsContain("Colors.Red", "") Await state.AssertSelectedCompletionItem("Colors", isHardSelected:=True) state.SendDownKey() 'Select "Colors.Red" state.SendTab() ' Insert "Colors.Red" state.SendUndo() 'Undo insert state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Colors", isHardSelected:=True) End Using End Function <WorkItem(49632, "https://github.com/dotnet/roslyn/pull/49632")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionEnumTypeAndValuesWithAlias() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using AT = System.AttributeTargets; public class Program { static void M(AT attributeTargets) { } public static void Main() { M($$ } } </Document>) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain(Function(i) i.DisplayText = "AT" AndAlso i.SortText = "AT" AndAlso i.FilterText = "AT") Await state.AssertCompletionItemsContain(Function(i) i.DisplayText = "AT.All" AndAlso i.FilterText = "AT.All") Await state.AssertSelectedCompletionItem("AT", isHardSelected:=True) End Using End Function <WorkItem(544296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544296")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestVerbatimNamedIdentifierFiltering(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class Program { void Goo(int @int) { Goo($$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("i") Await state.AssertCompletionSession() Await state.AssertCompletionItemsContain("@int", ":") state.SendTypeChars("n") Await state.AssertCompletionItemsContain("@int", ":") state.SendTypeChars("t") Await state.AssertCompletionItemsContain("@int", ":") End Using End Function <WorkItem(543687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543687")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoPreselectInInvalidObjectCreationLocation(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { void Test() { $$ } } class Bar { } class Goo<T> : IGoo<T> { } interface IGoo<T> { }]]> </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("IGoo<Bar> a = new ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(544925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544925")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestQualifiedEnumSelection(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class Program { void Main() { Environment.GetFolderPath$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") state.SendTab() Assert.Contains("Environment.SpecialFolder", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Sub <WorkItem(545070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545070")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTextChangeSpanWithAtCharacter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class @event { $$@event() { } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("public ") Await state.AssertNoCompletionSession() Assert.Contains("public @event", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDoNotInsertColonSoThatUserCanCompleteOutAVariableNameThatDoesNotCurrentlyExist_IE_TheCyrusCase(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System.Threading; class Program { static void Main(string[] args) { Goo($$) } void Goo(CancellationToken cancellationToken) { } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("can") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("Goo(cancellationToken)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function #If False Then <Scenario Name="Verify correct intellisense selection on ENTER"> <SetEditorText> <![CDATA[class Class1 { void Main(string[] args) { // } }]]> </SetEditorText> <PlaceCursor Marker="//"/> <SendKeys>var a = System.TimeSpan.FromMin{ENTER}{(}</SendKeys> <VerifyEditorContainsText> <![CDATA[class Class1 { void Main(string[] args) { var a = System.TimeSpan.FromMinutes( } }]]> </VerifyEditorContainsText> </Scenario> #End If <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedPropertyCompletionCommitWithTab(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } [MyAttribute($$ public class Goo { } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Nam") state.SendTab() Await state.AssertNoCompletionSession() Assert.Equal("[MyAttribute(Name =", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function LocalFunctionAttributeNamedPropertyCompletionCommitWithTab(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } public class Goo { void M() { [MyAttribute($$ void local1() { } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Nam") state.SendTab() Await state.AssertNoCompletionSession() Assert.Equal(" [MyAttribute(Name =", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeOnLocalFunctionCompletionCommitWithTab(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyGoodAttribute : System.Attribute { public string Name { get; set; } } public class Goo { void M() { [$$ void local1() { } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("MyG") state.SendTab() Await state.AssertNoCompletionSession() Assert.Equal(" [MyGood", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeOnMissingStatementCompletionCommitWithTab(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyGoodAttribute : System.Attribute { public string Name { get; set; } } public class Goo { void M() { [$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("MyG") state.SendTab() Await state.AssertNoCompletionSession() Assert.Equal(" [MyGood", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeAfterAttributeListOnStatement(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyGoodAttribute : System.Attribute { public string Name { get; set; } } public class Goo { void M() { [MyGood] $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Equal(" [MyGood] Goo", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedPropertyCompletionCommitWithEquals(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } [MyAttribute($$ public class Goo { } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Nam=") Await state.AssertNoCompletionSession() Assert.Equal("[MyAttribute(Name =", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedPropertyCompletionCommitWithSpace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } [MyAttribute($$ public class Goo { } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Nam ") Await state.AssertNoCompletionSession() Assert.Equal("[MyAttribute(Name ", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(545590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545590")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOverrideDefaultParameter_CSharp7(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public virtual void Goo<S>(S x = default(S)) { } } class D : C { override $$ } ]]></Document>, languageVersion:=LanguageVersion.CSharp7, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" Goo") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("public override void Goo<S>(S x = default(S))", state.SubjectBuffer.CurrentSnapshot.GetText(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOverrideDefaultParameter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public virtual void Goo<S>(S x = default(S)) { } } class D : C { override $$ } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" Goo") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("public override void Goo<S>(S x = default)", state.SubjectBuffer.CurrentSnapshot.GetText(), StringComparison.Ordinal) End Using End Function <WorkItem(545664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545664")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestArrayAfterOptionalParameter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class A { public virtual void Goo(int x = 0, int[] y = null) { } } class B : A { public override void Goo(int x = 0, params int[] y) { } } class C : B { override$$ } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" Goo") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains(" public override void Goo(int x = 0, int[] y = null)", state.SubjectBuffer.CurrentSnapshot.GetText(), StringComparison.Ordinal) End Using End Function <WorkItem(545967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545967")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestVirtualSpaces(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public string P { get; set; } void M() { var v = new C {$$ }; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendReturn() Assert.True(state.TextView.Caret.InVirtualSpace) Assert.Equal(12, state.TextView.Caret.Position.VirtualSpaces) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("P", isSoftSelected:=True) state.SendDownKey() Await state.AssertSelectedCompletionItem("P", isHardSelected:=True) state.SendTab() Assert.Equal(" P", state.GetLineFromCurrentCaretPosition().GetText()) Dim bufferPosition = state.TextView.Caret.Position.BufferPosition Assert.Equal(13, bufferPosition.Position - bufferPosition.GetContainingLine().Start.Position) Assert.False(state.TextView.Caret.InVirtualSpace) End Using End Function <WorkItem(546561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546561")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNamedParameterAgainstMRU(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { void Goo(string s) { } static void Main() { $$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' prime the MRU state.SendTypeChars("string") state.SendTab() Await state.AssertNoCompletionSession() ' Delete what we just wrote. state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendEscape() Await state.AssertNoCompletionSession() ' ensure we still select the named param even though 'string' is in the MRU. state.SendTypeChars("Goo(s") Await state.AssertSelectedCompletionItem("s", displayTextSuffix:=":") End Using End Function <WorkItem(546403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546403")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMissingOnObjectCreationAfterVar1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class A { void Goo() { var v = new$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(546403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546403")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMissingOnObjectCreationAfterVar2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class A { void Goo() { var v = new $$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("X") Await state.AssertCompletionItemsDoNotContainAny("X") End Using End Function <WorkItem(546917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546917")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEnumInSwitch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ enum Numeros { } class C { void M() { Numeros n; switch (n) { case$$ } } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem(displayText:="Numeros") End Using End Function <WorkItem(547016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547016")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAmbiguityInLocalDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public int W; public C() { $$ W = 0; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("w") Await state.AssertSelectedCompletionItem(displayText:="W") End Using End Function <WorkItem(530835, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530835")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompletionFilterSpanCaretBoundary(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public void Method() { $$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Met") Await state.AssertSelectedCompletionItem(displayText:="Method") state.SendLeftKey() state.SendLeftKey() state.SendLeftKey() state.SendTypeChars("new") Await state.AssertSelectedCompletionItem(displayText:="Method", isSoftSelected:=True) End Using End Function <WorkItem(5487, "https://github.com/dotnet/roslyn/issues/5487")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitCharTypedAtTheBeginingOfTheFilterSpan(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { public bool Method() { if ($$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Met") Await state.AssertCompletionSession() state.SendLeftKey() state.SendLeftKey() state.SendLeftKey() Await state.AssertSelectedCompletionItem(isSoftSelected:=True) state.SendTypeChars("!") Await state.AssertNoCompletionSession() Assert.Equal("if (!Met", state.GetLineTextFromCaretPosition().Trim()) Assert.Equal("M", state.GetCaretPoint().BufferPosition.GetChar()) End Using End Function <WorkItem(622957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622957")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBangFiltersInDocComment(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; /// $$ /// TestDocComment /// </summary> class TestException : Exception { } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("<") Await state.AssertCompletionSession() state.SendTypeChars("!") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("!--") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function InvokeCompletionDoesNotFilter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { string$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("string") Await state.AssertCompletionItemsContainAll("int", "Method") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function InvokeBeforeWordDoesNotSelect(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { $$string } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("AccessViolationException") Await state.AssertCompletionItemsContainAll("int", "Method") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function InvokeCompletionSelectsWithoutRegardToCaretPosition(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { s$$tring } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("string") Await state.AssertCompletionItemsContainAll("int", "Method") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TabAfterQuestionMark(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { ?$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTab() Assert.Equal(state.GetLineTextFromCaretPosition(), " ?" + vbTab) End Using End Sub <WorkItem(657658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657658")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PreselectionIgnoresBrackets(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { $$ static void Main(string[] args) { } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("static void F<T>(int a, Func<T, int> b) { }") state.SendEscape() state.TextView.Caret.MoveTo(New VisualStudio.Text.SnapshotPoint(state.SubjectBuffer.CurrentSnapshot, 220)) state.SendTypeChars("F") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("F", displayTextSuffix:="<>") End Using End Function <WorkItem(672474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672474")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvokeSnippetCommandDismissesCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document>$$</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("us") Await state.AssertCompletionSession() state.SendInsertSnippetCommand() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(672474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672474")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSurroundWithCommandDismissesCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document>$$</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("us") Await state.AssertCompletionSession() state.SendSurroundWithCommand() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(737239, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737239")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function LetEditorHandleOpenParen(showCompletionInArgumentLists As Boolean) As Task Dim expected = <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { List<int> x = new List<int>( } }]]></Document>.Value.Replace(vbLf, vbCrLf) Using state = TestStateFactory.CreateCSharpTestState(<Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { List<int> x = new$$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("List<int>") state.SendTypeChars("(") Assert.Equal(expected, state.GetDocumentText()) End Using End Function <WorkItem(785637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/785637")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitMovesCaretToWordEnd(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Main() { M$$ain } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.SendCommitUniqueCompletionListItemAsync() Assert.Equal(state.GetLineFromCurrentCaretPosition().End, state.GetCaretPoint().BufferPosition) End Using End Function <WorkItem(775370, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775370")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function MatchingConsidersAtSign(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Main() { $$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("var @this = ""goo"";") state.SendReturn() state.SendTypeChars("string str = this.ToString();") state.SendReturn() state.SendTypeChars("str = @th") Await state.AssertSelectedCompletionItem("@this") End Using End Function <WorkItem(865089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/865089")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeFilterTextRemovesAttributeSuffix(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ [$$] class AtAttribute : System.Attribute { }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("At") Await state.AssertSelectedCompletionItem("At") Assert.Equal("At", state.GetSelectedItem().FilterText) End Using End Function <WorkItem(852578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/852578")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PreselectExceptionOverSnippet(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { Exception goo() { return new $$ } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertSelectedCompletionItem("Exception") End Using End Function <WorkItem(868286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868286")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub CommitNameAfterAlias(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using goo = System$$]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".act<") state.AssertMatchesTextStartingAtLine(1, "using goo = System.Action<") End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompletionInLinkedFiles(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Thing2"> <Document FilePath="C.cs"> class C { void M() { $$ } #if Thing1 void Thing1() { } #elif Thing2 void Thing2() { } #endif } </Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Thing1"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim documents = state.Workspace.Documents Dim linkDocument = documents.Single(Function(d) d.IsLinkFile) state.SendTypeChars("Thing1") Await state.AssertSelectedCompletionItem("Thing1") state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendEscape() state.Workspace.SetDocumentContext(linkDocument.Id) state.SendTypeChars("Thing1") Await state.AssertSelectedCompletionItem("Thing1") Assert.True(state.GetSelectedItem().Tags.Contains(WellKnownTags.Warning)) state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendTypeChars("M") Await state.AssertSelectedCompletionItem("M") Assert.False(state.GetSelectedItem().Tags.Contains(WellKnownTags.Warning)) End Using End Function <WorkItem(951726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951726")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function DismissUponSave(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { $$ }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("voi") Await state.AssertSelectedCompletionItem("void") state.SendSave() Await state.AssertNoCompletionSession() state.AssertMatchesTextStartingAtLine(3, " voi") End Using End Function <WorkItem(930254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930254")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoCompletionWithBoxSelection(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { {|Selection:$$int x;|} {|Selection:int y;|} }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertNoCompletionSession() state.SendTypeChars("goo") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(839555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839555")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TriggeredOnHash(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ $$]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("#") Await state.AssertCompletionSession() End Using End Function <WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function RegionCompletionCommitTriggersFormatting_1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { $$ }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("#reg") Await state.AssertSelectedCompletionItem("region") state.SendReturn() state.AssertMatchesTextStartingAtLine(3, " #region") End Using End Function <WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function RegionCompletionCommitTriggersFormatting_2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { $$ }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("#reg") Await state.AssertSelectedCompletionItem("region") state.SendTypeChars(" ") state.AssertMatchesTextStartingAtLine(3, " #region ") End Using End Function <WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EndRegionCompletionCommitTriggersFormatting_2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { #region NameIt $$ }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("#endreg") Await state.AssertSelectedCompletionItem("endregion") state.SendReturn() state.AssertMatchesTextStartingAtLine(4, " #endregion ") End Using End Function <ExportCompletionProvider(NameOf(SlowProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class SlowProvider Inherits CommonCompletionProvider Public checkpoint As Checkpoint = New Checkpoint() <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Async Function ProvideCompletionsAsync(context As CompletionContext) As Task Await checkpoint.Task.ConfigureAwait(False) End Function Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return True End Function End Class <WorkItem(1015893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1015893")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function BackspaceDismissesIfComputationIsIncomplete(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void goo() { goo($$ } }]]></Document>, extraExportedTypes:={GetType(SlowProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") state.SendBackspace() ' Send a backspace that goes beyond the session's applicable span ' before the model computation has finished. Then, allow the ' computation to complete. There should still be no session. state.SendBackspace() Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim slowProvider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of SlowProvider)().Single() slowProvider.checkpoint.Release() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(31135, "https://github.com/dotnet/roslyn/issues/31135")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypingWithoutMatchAfterBackspaceDismissesCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class$$ C { }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertCompletionSession() state.SendTypeChars("w") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36513")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypingBackspaceShouldPreserveCase(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { void M() { Structure structure; structure.$$ } struct Structure { public int A; } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("structure") state.SendTypeChars(".") Await state.AssertCompletionItemsContainAll("A") End Using End Function <WorkItem(1594, "https://github.com/dotnet/roslyn/issues/1594")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoPreselectionOnSpaceWhenAbuttingWord(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { void Main() { Program p = new $$Program(); } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(1594, "https://github.com/dotnet/roslyn/issues/1594")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SpacePreselectionAtEndOfFile(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { void Main() { Program p = new $$]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(" ") Await state.AssertCompletionSession() End Using End Function <WorkItem(1659, "https://github.com/dotnet/roslyn/issues/1659")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function DismissOnSelectAllCommand(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) { $$]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' Note: the caret is at the file, so the Select All command's movement ' of the caret to the end of the selection isn't responsible for ' dismissing the session. state.SendInvokeCompletionList() Await state.AssertCompletionSession() state.SendSelectAll() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub CompletionCommitAndFormatAreSeparateUndoTransactions(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) { int doodle; $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("doo;") state.AssertMatchesTextStartingAtLine(6, " doodle;") state.SendUndo() state.AssertMatchesTextStartingAtLine(6, "doo;") End Using End Sub <WorkItem(4978, "https://github.com/dotnet/roslyn/issues/4978")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SessionNotStartedWhenCaretNotMappableIntoSubjectBuffer(showCompletionInArgumentLists As Boolean) As Task ' In inline diff view, typing delete next to a "deletion", ' can cause our CommandChain to be called with a subjectbuffer ' and TextView such that the textView's caret can't be mapped ' into our subject buffer. ' ' To test this, we create a projection buffer with 2 source ' spans: one of "text" content type and one based on a C# ' buffer. We create a TextView with that projection as ' its buffer, setting the caret such that it maps only ' into the "text" buffer. We then call the completionImplementation ' command handlers with commandargs based on that TextView ' but with the C# buffer as the SubjectBuffer. Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) {$$ /********/ int doodle; } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim textBufferFactoryService = state.GetExportedValue(Of ITextBufferFactoryService)() Dim contentTypeService = state.GetExportedValue(Of VisualStudio.Utilities.IContentTypeRegistryService)() Dim contentType = contentTypeService.GetContentType(ContentTypeNames.CSharpContentType) Dim textViewFactory = state.GetExportedValue(Of ITextEditorFactoryService)() Dim editorOperationsFactory = state.GetExportedValue(Of IEditorOperationsFactoryService)() Dim otherBuffer = textBufferFactoryService.CreateTextBuffer("text", contentType) Dim otherExposedSpan = otherBuffer.CurrentSnapshot.CreateTrackingSpan(0, 4, SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward) Dim subjectBufferExposedSpan = state.SubjectBuffer.CurrentSnapshot.CreateTrackingSpan(0, state.SubjectBuffer.CurrentSnapshot.Length, SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward) Dim projectionBufferFactory = state.GetExportedValue(Of IProjectionBufferFactoryService)() Dim projection = projectionBufferFactory.CreateProjectionBuffer(Nothing, New Object() {otherExposedSpan, subjectBufferExposedSpan}.ToList(), ProjectionBufferOptions.None) Using disposableView As DisposableTextView = textViewFactory.CreateDisposableTextView(projection) disposableView.TextView.Caret.MoveTo(New SnapshotPoint(disposableView.TextView.TextBuffer.CurrentSnapshot, 0)) Dim editorOperations = editorOperationsFactory.GetEditorOperations(disposableView.TextView) state.SendDeleteToSpecificViewAndBuffer(disposableView.TextView, state.SubjectBuffer) Await state.AssertNoCompletionSession() End Using End Using End Function <WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround1(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) { string.$$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("is") Await state.AssertSelectedCompletionItem("IsInterned") End Using End Using End Function <WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround2(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void goo(int x) { string.$$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ı") Await state.AssertSelectedCompletionItem() End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround3(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class TARIFE { } class C { void goo(int x) { var t = new $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("tarif") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("TARIFE") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround4(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class IFADE {} class ifTest {} class C { void goo(int x) { IFADE ifade = null; $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("if") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("if") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround5(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class İFADE {} class ifTest {} class C { void goo(int x) { İFADE ifade = null; $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("if") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("if") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround6(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class TARİFE { } class C { void goo(int x) { var obj = new $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("tarif") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("TARİFE") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround7(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class İFADE {} class ifTest {} class C { void goo(int x) { var obj = new $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ifad") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("İFADE") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround8(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class IFADE {} class ifTest {} class C { void goo(int x) { var obj = new $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("ifad") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("IFADE") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround9(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class IFADE {} class ifTest {} class C { void goo(int x) { IFADE ifade = null; $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("IF") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("if") End Using End Using End Function <WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround10(showCompletionInArgumentLists As Boolean) As Task Using New CultureContext(New CultureInfo("tr-TR", useUserOverride:=False)) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class İFADE {} class ifTest {} class C { void goo(int x) { İFADE ifade = null; $$]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("IF") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("if") End Using End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Threading; class Program { void Cancel(int x, CancellationToken cancellationToken) { Cancel(x + 1, cancellationToken: $$) } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("cancellationToken", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { static void Main(string[] args) { int aaz = 0; args = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("a") Await state.AssertSelectedCompletionItem("args", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection_DoesNotOverrideEnumPreselection(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ enum E { } class Program { static void Main(string[] args) { E e; e = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("E", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection_DoesNotOverrideEnumPreselection2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ enum E { A } class Program { static void Main(string[] args) { E e = E.A; if (e == $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("E", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselection3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class D {} class Program { static void Main(string[] args) { int cw = 7; D cx = new D(); D cx2 = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("c") Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionLocalsOverType(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class A {} class Program { static void Main(string[] args) { A cx = new A(); A cx2 = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("c") Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionParameterOverMethod(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { bool f; void goo(bool x) { } void Main(string[] args) { goo($$) // Not "Equals" } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("f", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/6942"), CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionConvertibility1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ abstract class C {} class D : C {} class Program { static void Main(string[] args) { D cx = new D(); C cx2 = $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("c") Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionLocalOverProperty(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { public int aaa { get; } void Main(string[] args) { int aaq; int y = a$$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("aaq", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(12254, "https://github.com/dotnet/roslyn/issues/12254")> Public Sub TestGenericCallOnTypeContainingAnonymousType(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Linq; class Program { static void Main(string[] args) { new[] { new { x = 1 } }.ToArr$$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("(") state.AssertMatchesTextStartingAtLine(7, "new[] { new { x = 1 } }.ToArray(") End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypePreselectionSetterValuey(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class Program { int _x; int X { set { _x = $$ } } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("value", isHardSelected:=True).ConfigureAwait(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(12530, "https://github.com/dotnet/roslyn/issues/12530")> Public Async Function TestAnonymousTypeDescription(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Linq; class Program { static void Main(string[] args) { new[] { new { x = 1 } }.ToArr$$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem(description:= $"({ CSharpFeaturesResources.extension }) 'a[] System.Collections.Generic.IEnumerable<'a>.ToArray<'a>() { FeaturesResources.Anonymous_Types_colon } 'a { FeaturesResources.is_ } new {{ int x }}") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRecursiveGenericSymbolKey(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections.Generic; class Program { static void ReplaceInList<T>(List<T> list, T oldItem, T newItem) { $$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("list") state.SendTypeChars(".") Await state.AssertCompletionSession() state.SendTypeChars("Add") Await state.AssertSelectedCompletionItem("Add", description:="void List<T>.Add(T item)") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitNamedParameterWithColon(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections.Generic; class Program { static void Main(int args) { Main(args$$ } }]]></Document>, extraExportedTypes:={GetType(CSharpFormattingInteractionService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars(":") Await state.AssertNoCompletionSession() Assert.Contains("args:", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(13481, "https://github.com/dotnet/roslyn/issues/13481")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceSelection1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main() { DateTimeOffset$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) For Each c In "Offset" state.SendBackspace() Await state.WaitForAsynchronousOperationsAsync() Next Await state.AssertSelectedCompletionItem("DateTime") End Using End Function <WorkItem(13481, "https://github.com/dotnet/roslyn/issues/13481")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceSelection2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main() { DateTimeOffset.$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) For Each c In "Offset." state.SendBackspace() Await state.WaitForAsynchronousOperationsAsync() Next Await state.AssertSelectedCompletionItem("DateTime") End Using End Function <WorkItem(14465, "https://github.com/dotnet/roslyn/issues/14465")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypingNumberShouldNotDismiss1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void Moo1() { new C()$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionSession() state.SendTypeChars("1") Await state.AssertSelectedCompletionItem("Moo1") End Using End Function <WorkItem(14085, "https://github.com/dotnet/roslyn/issues/14085")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TargetTypingDoesNotOverrideExactMatch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.IO; class C { void Moo1() { string path = $$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Path") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("Path") End Using End Function <WorkItem(14085, "https://github.com/dotnet/roslyn/issues/14085")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function MRUOverTargetTyping(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { await Moo().$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Configure") state.SendTab() For i = 1 To "ConfigureAwait".Length state.SendBackspace() Next state.SendInvokeCompletionList() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("ConfigureAwait") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function MovingCaretToStartSoftSelects(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void M() { $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Conso") Await state.AssertSelectedCompletionItem(displayText:="Console", isHardSelected:=True) For Each ch In "Conso" state.SendLeftKey() Next Await state.AssertSelectedCompletionItem(displayText:="Console", isHardSelected:=False) state.SendRightKey() Await state.AssertSelectedCompletionItem(displayText:="Console", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoBlockOnCompletionItems1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using $$ </Document>, extraExportedTypes:={GetType(BooleanTaskControlledCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of BooleanTaskControlledCompletionProvider)().Single() Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.BlockForCompletionItems2, LanguageNames.CSharp, False))) state.SendTypeChars("Sys.") Await state.AssertNoCompletionSession() Assert.Contains("Sys.", state.GetLineTextFromCaretPosition()) provider.completionSource.SetResult(True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoBlockOnCompletionItems2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using $$ </Document>, extraExportedTypes:={GetType(CompletedTaskControlledCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.BlockForCompletionItems2, LanguageNames.CSharp, False))) state.SendTypeChars("Sys") Await state.AssertSelectedCompletionItem(displayText:="System") state.SendTypeChars(".") Assert.Contains("System.", state.GetLineTextFromCaretPosition()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoBlockOnCompletionItems4(showCompletionInArgumentLists As Boolean) As Task ' This test verifies a scenario with the following conditions: ' a. A slow completion provider ' b. The block option set to false. ' Scenario: ' 1. Type 'Sys' ' 2. Send CommitIfUnique (Ctrl + space) ' 3. Wait for 250ms. ' 4. Verify that there is no completion window shown. In the new completion, we can just start the verification and check that the verification is still running. ' 5. Check that the commit is not yet provided: there is 'Sys' but no 'System' ' 6. Simulate unblocking the provider. ' 7. Verify that the completion completes CommitIfUnique. Using state = TestStateFactory.CreateCSharpTestState( <Document> using $$ </Document>, extraExportedTypes:={GetType(BooleanTaskControlledCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of BooleanTaskControlledCompletionProvider)().Single() Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.BlockForCompletionItems2, LanguageNames.CSharp, False))) state.SendTypeChars("Sys") Dim task1 As Task = Nothing Dim task2 As Task = Nothing Dim providerCalledHandler = Sub() task2 = New Task( Sub() Thread.Sleep(250) Try ' 3. Check that the other task is running/deadlocked. Assert.Equal(TaskStatus.Running, task1.Status) Assert.Contains("Sys", state.GetLineTextFromCaretPosition()) Assert.DoesNotContain("System", state.GetLineTextFromCaretPosition()) ' Need the Finally to avoid deadlocks if any of Asserts failed, the task will never complete and Task.WhenAll will wait forever. Finally ' 4. Unblock the first task and the main thread. provider.completionSource.SetResult(True) End Try End Sub) task1 = Task.Run( Sub() task2.Start() ' 2. Deadlock here as well: getting items is waiting provider to respond. state.CalculateItemsIfSessionExists() End Sub) End Sub AddHandler provider.ProviderCalled, providerCalledHandler ' SendCommitUniqueCompletionListItem is a asynchronous operation. ' It guarantees that ProviderCalled will be triggered and after that the completion will deadlock waiting for a task to be resolved. ' In the new completion, when pressed <ctrl>-<space>, we have to wait for the aggregate operation to complete. ' 1. Deadlock here. Await state.SendCommitUniqueCompletionListItemAsync() Assert.NotNull(task1) Assert.NotNull(task2) Await Task.WhenAll(task1, task2) Await state.AssertNoCompletionSession() Assert.Contains("System", state.GetLineTextFromCaretPosition()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoBlockOnCompletionItems3(showCompletionInArgumentLists As Boolean) As Task ' This test verifies a scenario with the following conditions: ' a. A slow completion provider ' b. The block option set to false. ' Scenario: ' 1. Type 'Sys' ' 2. Send CommitIfUnique (Ctrl + space) ' 3. Wait for 250ms. ' 4. Verify that there is no completion window shown. In the new completion, we can just start the verification and check that the verification is still running. ' 5. Check that the commit is not yet provided: there is 'Sys' but no 'System' ' 6. The next statement in the UI thread after CommitIfUnique is typing 'a'. ' 7. Simulate unblocking the provider. ' 8. Verify that ' 8.a. The old completion adds 'a' to 'Sys' and displays 'Sysa'. CommitIfUnique is canceled because it was interrupted by typing 'a'. ' 8.b. The new completion completes CommitIfUnique and then adds 'a'. Using state = TestStateFactory.CreateCSharpTestState( <Document> using $$ </Document>, extraExportedTypes:={GetType(BooleanTaskControlledCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of BooleanTaskControlledCompletionProvider)().Single() Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.BlockForCompletionItems2, LanguageNames.CSharp, False))) state.SendTypeChars("Sys") Dim task1 As Task = Nothing Dim task2 As Task = Nothing Dim providerCalledHandler = Sub() task2 = New Task( Sub() Thread.Sleep(250) Try ' 3. Check that the other task is running/deadlocked. Assert.Equal(TaskStatus.Running, task1.Status) Assert.Contains("Sys", state.GetLineTextFromCaretPosition()) Assert.DoesNotContain("System", state.GetLineTextFromCaretPosition()) ' Need the Finally to avoid deadlocks if any of Asserts failed, the task will never complete and Task.WhenAll will wait forever. Finally ' 4. Unblock the first task and the main thread. provider.completionSource.SetResult(True) End Try End Sub) task1 = Task.Run( Sub() task2.Start() ' 2. Deadlock here as well: getting items is waiting provider to respond. state.CalculateItemsIfSessionExists() End Sub) End Sub AddHandler provider.ProviderCalled, providerCalledHandler ' SendCommitUniqueCompletionListItem is an asynchronous operation. ' It guarantees that ProviderCalled will be triggered and after that the completion will deadlock waiting for a task to be resolved. ' In the new completion, when pressed <ctrl>-<space>, we have to wait for the aggregate operation to complete. ' 1. Deadlock here. Await state.SendCommitUniqueCompletionListItemAsync() ' 5. Put insertion of 'a' into the edtior queue. It can be executed in the foreground thread only state.SendTypeChars("a") Assert.NotNull(task1) Assert.NotNull(task2) Await Task.WhenAll(task1, task2) Await state.AssertNoCompletionSession() ' Here is a difference between the old and the new completions: ' The old completion adds 'a' to 'Sys' and displays 'Sysa'. CommitIfUnique is canceled because it was interrupted by typing 'a'. ' The new completion completes CommitIfUnique and then adds 'a'. Assert.Contains("Systema", state.GetLineTextFromCaretPosition()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSwitchBetweenBlockingAndNoBlockOnCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using $$ </Document>, extraExportedTypes:={GetType(BooleanTaskControlledCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of BooleanTaskControlledCompletionProvider)().Single() #Disable Warning BC42358 ' Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(Function() Task.Delay(TimeSpan.FromSeconds(10)) provider.completionSource.SetResult(True) Return True End Function) #Enable Warning BC42358 ' Because this call is not awaited, execution of the current method continues before the call is completed state.SendTypeChars("Sys.") Assert.Contains("System.", state.GetLineTextFromCaretPosition()) ' reset the input For i As Integer = 1 To "System.".Length state.SendBackspace() Next state.SendEscape() Await state.WaitForAsynchronousOperationsAsync() ' reset the task provider.Reset() ' Switch to the non-blocking mode Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.BlockForCompletionItems2, LanguageNames.CSharp, False))) ' re-use of TestNoBlockOnCompletionItems1 state.SendTypeChars("Sys.") Await state.AssertNoCompletionSession() Assert.Contains("Sys.", state.GetLineTextFromCaretPosition()) provider.completionSource.SetResult(True) For i As Integer = 1 To "Sys.".Length state.SendBackspace() Next state.SendEscape() Await state.WaitForAsynchronousOperationsAsync() ' reset the task provider.Reset() ' Switch to the blocking mode workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.BlockForCompletionItems2, LanguageNames.CSharp, True))) #Disable Warning BC42358 ' Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(Function() Task.Delay(TimeSpan.FromSeconds(10)) provider.completionSource.SetResult(True) Return True End Function) #Enable Warning BC42358 ' Because this call is not awaited, execution of the current method continues before the call is completed state.SendTypeChars("Sys.") Await state.AssertCompletionSession() Assert.Contains("System.", state.GetLineTextFromCaretPosition()) End Using End Function Private MustInherit Class TaskControlledCompletionProvider Inherits CompletionProvider Private _task As Task Public Event ProviderCalled() Public Sub New(task As Task) _task = task End Sub Public Sub UpdateTask(task As Task) _task = task End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task RaiseEvent ProviderCalled() Return _task End Function End Class <ExportCompletionProvider(NameOf(CompletedTaskControlledCompletionProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class CompletedTaskControlledCompletionProvider Inherits TaskControlledCompletionProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New(Task.FromResult(True)) End Sub End Class <ExportCompletionProvider(NameOf(BooleanTaskControlledCompletionProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class BooleanTaskControlledCompletionProvider Inherits TaskControlledCompletionProvider Public completionSource As TaskCompletionSource(Of Boolean) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New(Task.CompletedTask) Reset() End Sub Public Sub Reset() completionSource = New TaskCompletionSource(Of Boolean) UpdateTask(completionSource.Task) End Sub End Class <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Filters_EmptyList1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { var x = asd$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() Dim oldFilters = state.GetCompletionItemFilters() Dim newFilters = ArrayBuilder(Of Data.CompletionFilterWithState).GetInstance() For Each f In oldFilters Assert.NotEqual(FilterSet.InterfaceFilter.DisplayText, f.Filter.DisplayText) newFilters.Add(f.WithSelected(False)) Next newFilters.Add(New Data.CompletionFilterWithState(FilterSet.InterfaceFilter, isAvailable:=True, isSelected:=True)) state.RaiseFiltersChanged(newFilters.ToImmutableAndFree()) Await state.WaitForUIRenderedAsync() Assert.Null(state.GetSelectedItem()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Filters_EmptyList2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { var x = asd$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() Dim oldFilters = state.GetCompletionItemFilters() Dim newFilters = ArrayBuilder(Of Data.CompletionFilterWithState).GetInstance() For Each f In oldFilters Assert.NotEqual(FilterSet.InterfaceFilter.DisplayText, f.Filter.DisplayText) newFilters.Add(f.WithSelected(False)) Next newFilters.Add(New Data.CompletionFilterWithState(FilterSet.InterfaceFilter, isAvailable:=True, isSelected:=True)) state.RaiseFiltersChanged(newFilters.ToImmutableAndFree()) Await state.WaitForUIRenderedAsync() Assert.Null(state.GetSelectedItem()) state.SendTab() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Filters_EmptyList3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { var x = asd$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() Dim oldFilters = state.GetCompletionItemFilters() Dim newFilters = ArrayBuilder(Of Data.CompletionFilterWithState).GetInstance() For Each f In oldFilters Assert.NotEqual(FilterSet.InterfaceFilter.DisplayText, f.Filter.DisplayText) newFilters.Add(f.WithSelected(False)) Next newFilters.Add(New Data.CompletionFilterWithState(FilterSet.InterfaceFilter, isAvailable:=True, isSelected:=True)) state.RaiseFiltersChanged(newFilters.ToImmutableAndFree()) Await state.WaitForUIRenderedAsync() Assert.Null(state.GetSelectedItem()) state.SendReturn() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Filters_EmptyList4(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.IO; using System.Threading.Tasks; class C { async Task Moo() { var x = asd$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() Dim oldFilters = state.GetCompletionItemFilters() Dim newFilters = ArrayBuilder(Of Data.CompletionFilterWithState).GetInstance() For Each f In oldFilters Assert.NotEqual(FilterSet.InterfaceFilter.DisplayText, f.Filter.DisplayText) newFilters.Add(f.WithSelected(False)) Next newFilters.Add(New Data.CompletionFilterWithState(FilterSet.InterfaceFilter, isAvailable:=True, isSelected:=True)) state.RaiseFiltersChanged(newFilters.ToImmutableAndFree()) Await state.WaitForUIRenderedAsync() Assert.Null(state.GetSelectedItem()) state.SendTypeChars(".") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(15881, "https://github.com/dotnet/roslyn/issues/15881")> Public Async Function CompletionAfterDotBeforeAwaitTask(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Threading.Tasks; class C { async Task Moo() { Task.$$ await Task.Delay(50); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionSession() End Using End Function <WorkItem(14704, "https://github.com/dotnet/roslyn/issues/14704")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function BackspaceTriggerSubstringMatching(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class Program { static void Main(string[] args) { if (Environment$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim key = New OptionKey(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(key, True))) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="Environment", isHardSelected:=True) End Using End Function <WorkItem(16236, "https://github.com/dotnet/roslyn/issues/16236")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedParameterEqualsItemCommittedOnSpace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> [A($$)] class AAttribute: Attribute { public string Skip { get; set; } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("Skip") Await state.AssertCompletionSession() state.SendTypeChars(" ") Await state.AssertNoCompletionSession() Assert.Equal("[A(Skip )]", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(362890, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=362890")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFilteringAfterSimpleInvokeShowsAllItemsMatchingFilter(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ static class Color { public const uint Red = 1; public const uint Green = 2; public const uint Blue = 3; } class C { void M() { Color.Re$$d } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem("Red") Await state.AssertCompletionItemsContainAll("Red", "Green", "Blue", "Equals") Dim oldFilters = state.GetCompletionItemFilters() Dim newFiltersBuilder = ArrayBuilder(Of Data.CompletionFilterWithState).GetInstance() For Each f In oldFilters newFiltersBuilder.Add(f.WithSelected(f.Filter.DisplayText = FilterSet.ConstantFilter.DisplayText)) Next state.RaiseFiltersChanged(newFiltersBuilder.ToImmutableAndFree()) Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem("Red") Await state.AssertCompletionItemsContainAll("Red", "Green", "Blue") Await state.AssertCompletionItemsDoNotContainAny("Equals") oldFilters = state.GetCompletionItemFilters() newFiltersBuilder = ArrayBuilder(Of Data.CompletionFilterWithState).GetInstance() For Each f In oldFilters newFiltersBuilder.Add(f.WithSelected(False)) Next state.RaiseFiltersChanged(newFiltersBuilder.ToImmutableAndFree()) Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem("Red") Await state.AssertCompletionItemsContainAll({"Red", "Green", "Blue", "Equals"}) End Using End Function <WorkItem(16236, "https://github.com/dotnet/roslyn/issues/16236")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NameCompletionSorting(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> interface ISyntaxFactsService {} class C { void M() { ISyntaxFactsService $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Dim expectedOrder = { "syntaxFactsService", "syntaxFacts", "factsService", "syntax", "service" } state.AssertItemsInOrder(expectedOrder) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestLargeChangeBrokenUpIntoSmallTextChanges(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { void goo() { return $$ } }]]></Document>, extraExportedTypes:={GetType(MultipleChangeCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of MultipleChangeCompletionProvider)().Single() Dim testDocument = state.Workspace.Documents(0) Dim textBuffer = testDocument.GetTextBuffer() Dim snapshotBeforeCommit = textBuffer.CurrentSnapshot provider.SetInfo(snapshotBeforeCommit.GetText(), testDocument.CursorPosition.Value) ' First send a space to trigger out special completionImplementation provider. state.SendInvokeCompletionList() state.SendTab() ' Verify that we see the entire change Dim finalText = textBuffer.CurrentSnapshot.GetText() Assert.Equal( "using NewUsing; using System; class C { void goo() { return InsertedItem } }", finalText) Dim changes = snapshotBeforeCommit.Version.Changes ' This should have happened as two text changes to the buffer. Assert.Equal(2, changes.Count) Dim actualChanges = changes.ToArray() Dim firstChange = actualChanges(0) Assert.Equal(New Span(0, 0), firstChange.OldSpan) Assert.Equal("using NewUsing;", firstChange.NewText) Dim secondChange = actualChanges(1) Assert.Equal(New Span(testDocument.CursorPosition.Value, 0), secondChange.OldSpan) Assert.Equal("InsertedItem", secondChange.NewText) ' Make sure new edits happen after the text that was inserted. state.SendTypeChars("1") finalText = textBuffer.CurrentSnapshot.GetText() Assert.Equal( "using NewUsing; using System; class C { void goo() { return InsertedItem1 } }", finalText) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestLargeChangeBrokenUpIntoSmallTextChanges2(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class C { void goo() { return Custom$$ } }]]></Document>, extraExportedTypes:={GetType(MultipleChangeCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of MultipleChangeCompletionProvider)().Single() Dim testDocument = state.Workspace.Documents(0) Dim textBuffer = testDocument.GetTextBuffer() Dim snapshotBeforeCommit = textBuffer.CurrentSnapshot provider.SetInfo(snapshotBeforeCommit.GetText(), testDocument.CursorPosition.Value) ' First send a space to trigger out special completionImplementation provider. state.SendInvokeCompletionList() state.SendTab() ' Verify that we see the entire change Dim finalText = textBuffer.CurrentSnapshot.GetText() Assert.Equal( "using NewUsing; using System; class C { void goo() { return InsertedItem } }", finalText) Dim changes = snapshotBeforeCommit.Version.Changes ' This should have happened as two text changes to the buffer. Assert.Equal(2, changes.Count) Dim actualChanges = changes.ToArray() Dim firstChange = actualChanges(0) Assert.Equal(New Span(0, 0), firstChange.OldSpan) Assert.Equal("using NewUsing;", firstChange.NewText) Dim secondChange = actualChanges(1) Assert.Equal(New Span(testDocument.CursorPosition.Value - "Custom".Length, "Custom".Length), secondChange.OldSpan) Assert.Equal("InsertedItem", secondChange.NewText) ' Make sure new edits happen after the text that was inserted. state.SendTypeChars("1") finalText = textBuffer.CurrentSnapshot.GetText() Assert.Equal( "using NewUsing; using System; class C { void goo() { return InsertedItem1 } }", finalText) End Using End Sub <WorkItem(296512, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=296512")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRegionDirectiveIndentation(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { $$ } </Document>, includeFormatCommandHandler:=True, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("#") Assert.Equal("#", state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertCompletionSession() state.SendTypeChars("reg") Await state.AssertSelectedCompletionItem(displayText:="region") state.SendReturn() Await state.AssertNoCompletionSession() Assert.Equal(" #region", state.GetLineFromCurrentCaretPosition().GetText()) Assert.Equal(state.GetLineFromCurrentCaretPosition().End, state.GetCaretPoint().BufferPosition) state.SendReturn() Assert.Equal("", state.GetLineFromCurrentCaretPosition().GetText()) state.SendTypeChars("#") Assert.Equal("#", state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertCompletionSession() state.SendTypeChars("endr") Await state.AssertSelectedCompletionItem(displayText:="endregion") state.SendReturn() Assert.Equal(" #endregion", state.GetLineFromCurrentCaretPosition().GetText()) Assert.Equal(state.GetLineFromCurrentCaretPosition().End, state.GetCaretPoint().BufferPosition) End Using End Function <WpfTheory> <InlineData("r")> <InlineData("load")> <WorkItem(49861, "https://github.com/dotnet/roslyn/issues/49861")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PathDirective(directive As String) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { # <%= directive %> $$ } </Document>) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendTypeChars("""") Assert.Equal($" # {directive} """, state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertCompletionSession() state.SendTypeChars("x") Assert.Equal($" # {directive} ""x", state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertCompletionSession() state.SendBackspace() Assert.Equal($" # {directive} """, state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertCompletionSession() state.SendBackspace() Assert.Equal($" # {directive} ", state.GetLineFromCurrentCaretPosition().GetText()) Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AfterIdentifierInCaseLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M() { switch (true) { case identifier $$ } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("w") Await state.AssertSelectedCompletionItem(displayText:="when", isHardSelected:=False) state.SendBackspace() state.SendTypeChars("i") Await state.AssertSelectedCompletionItem(displayText:="identifier", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AfterIdentifierInCaseLabel_ColorColor(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class identifier { } class C { const identifier identifier = null; void M() { switch (true) { case identifier $$ } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("w") Await state.AssertSelectedCompletionItem(displayText:="when", isHardSelected:=False) state.SendBackspace() state.SendTypeChars("i") Await state.AssertSelectedCompletionItem(displayText:="identifier", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AfterIdentifierInCaseLabel_ClassNameOnly(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class identifier { } class C { void M() { switch (true) { case identifier $$ } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("z") Await state.AssertSelectedCompletionItem(displayText:="identifier", isHardSelected:=False) state.SendBackspace() state.SendTypeChars("i") Await state.AssertSelectedCompletionItem(displayText:="identifier", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AfterIdentifierInCaseLabel_ClassNameOnly_WithMiscLetters(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class identifier { } class C { void M() { switch (true) { case identifier $$ } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("a") Await state.AssertSelectedCompletionItem(displayText:="and", isHardSelected:=False) state.SendBackspace() state.SendTypeChars("w") Await state.AssertSelectedCompletionItem(displayText:="when", isHardSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AfterDoubleIdentifierInCaseLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M() { switch (true) { case identifier identifier $$ } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("w") Await state.AssertSelectedCompletionItem(displayText:="when", isHardSelected:=True) End Using End Function <WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGenericAsyncTaskDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace A.B { class TestClass { } } namespace A { class C { async Task&lt;A$$ Method() { } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem(displayText:="B", isSoftSelected:=True) End Using End Function <WorkItem(15348, "https://github.com/dotnet/roslyn/issues/15348")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterCasePatternSwitchLabel(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M() { object o = 1; switch(o) { case int i: $$ break; } } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("this") Await state.AssertSelectedCompletionItem(displayText:="this", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceInMiddleOfSelection(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public enum foo { aaa } public class Program { public static void Main(string[] args) { foo.a$$a } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="aaa", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBackspaceWithMultipleCharactersSelected(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; public class Program { public static void Main(string[] args) { Console.WriteLine$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() state.SelectAndMoveCaret(-6) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="Write", isHardSelected:=True) End Using End Function <WorkItem(30097, "https://github.com/dotnet/roslyn/issues/30097")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMRUKeepsTwoRecentlyUsedItems(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public double Ma(double m) => m; public void Test() { $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("M(M(M(M(") Await state.AssertNoCompletionSession() Assert.Equal(" Ma(m:(Ma(m:(", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(36546, "https://github.com/dotnet/roslyn/issues/36546")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDoNotDismissIfEmptyOnBackspaceIfStartedWithBackspace(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { public void M() { Console.W$$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertCompletionItemsContainAll("WriteLine") End Using End Function <WorkItem(36546, "https://github.com/dotnet/roslyn/issues/36546")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDoNotDismissIfEmptyOnMultipleBackspaceIfStartedInvoke(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { public void M() { Console.Wr$$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionSession() state.SendBackspace() state.SendBackspace() Await state.AssertCompletionSession() End Using End Function <WorkItem(30097, "https://github.com/dotnet/roslyn/issues/30097")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNamedParameterDoesNotAddExtraColon(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public double M(double some) => m; public void Test() { $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("M(some:M(some:") Await state.AssertNoCompletionSession() Assert.Equal(" M(some:M(some:", state.GetLineTextFromCaretPosition()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSuggestionMode(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M() { $$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendToggleCompletionMode() Await state.WaitForAsynchronousOperationsAsync() state.SendTypeChars("s") Await state.AssertCompletionSession() Assert.True(state.HasSuggestedItem()) Await state.AssertSelectedCompletionItem(displayText:="sbyte", isSoftSelected:=True) state.SendToggleCompletionMode() Await state.AssertCompletionSession() Assert.False(state.HasSuggestedItem()) ' We want to soft select if we were already in soft select mode. Await state.AssertSelectedCompletionItem(displayText:="sbyte", isSoftSelected:=True) state.SendToggleCompletionMode() Await state.AssertCompletionSession() Assert.True(state.HasSuggestedItem()) Await state.AssertSelectedCompletionItem(displayText:="sbyte", isSoftSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTabAfterOverride(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { override $$ public static void M() { } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("gethashcod") state.SendTab() Await state.AssertNoCompletionSession() state.AssertMatchesTextStartingAtLine(3, " public override int GetHashCode()") state.AssertMatchesTextStartingAtLine(4, " {") state.AssertMatchesTextStartingAtLine(5, " return base.GetHashCode();") state.AssertMatchesTextStartingAtLine(6, " }") state.AssertMatchesTextStartingAtLine(7, " public static void M() { }") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSuppressNullableWarningExpression(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void M() { var s = ""; s$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("!") Await state.AssertNoCompletionSession() state.SendTypeChars(".") Await state.AssertCompletionItemsContainAll("ToString", "GetHashCode") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitIfUniqueFiltersIfNotUnique(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { Me$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertCompletionItemsContainAll("MemberwiseClone", "Method") Await state.AssertCompletionItemsDoNotContainAny("int", "ToString()", "Microsoft", "Math") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDismissCompletionOnBacktick(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void Method() { Con$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionSession() state.SendTypeChars("`") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUnique(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void Method() { var s=""; s.Len$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Length", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueInInsertionSession(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".len") Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Length", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueInDeletionSession1(showCompletionInArgumentLists As Boolean) As Task ' We explicitly use a weak matching on Delete. ' It matches by the first letter. Therefore, if backspace in s.Length, it matches s.Length and s.LastIndexOf. ' In this case, CommitIfUnique is not applied. Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s.Normalize$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertCompletionSession() Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Normalize", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(37231, "https://github.com/dotnet/roslyn/issues/37231")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueInDeletionSession2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; class C { void Method() { AccessViolationException$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertCompletionSession() Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("AccessViolationException", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueWithIntelliCode(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s.Len$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockProvider)().Single() Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Length", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueInInsertionSessionWithIntelliCode(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockProvider)().Single() state.SendTypeChars(".len") Await state.AssertCompletionItemsContainAll("Length", "★ Length") Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Length", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueInDeletionSessionWithIntelliCode(showCompletionInArgumentLists As Boolean) As Task ' We explicitly use a weak matching on Delete. ' It matches by the first letter. Therefore, if backspace in s.Length, it matches s.Length and s.LastIndexOf. ' In this case, CommitIfUnique is not applied. Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s.Normalize$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockProvider)().Single() Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertCompletionItemsContainAll("Normalize", "★ Normalize") Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Normalize", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAutomationTextPassedToEditor(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s.Len$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockProvider)().Single() state.SendInvokeCompletionList() state.SendSelectCompletionItem("★ Length") Await state.AssertSelectedCompletionItem(displayText:="★ Length", automationText:=provider.AutomationTextString) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueWithIntelliCodeAndDuplicateItemsFromIntelliCode(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s.Len$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockWeirdProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockWeirdProvider)().Single() Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Length", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSendCommitIfUniqueInInsertionSessionWithIntelliCodeAndDuplicateItemsFromIntelliCode(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockWeirdProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockWeirdProvider)().Single() state.SendTypeChars(".len") Await state.AssertCompletionItemsContainAll("Length", "★ Length", "★ Length2") Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() Assert.Contains("s.Length", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function IntelliCodeItemPreferredAfterCommitingIntelliCodeItem(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockProvider)().Single() Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendTypeChars(".nor") Await state.AssertCompletionItemsContainAll("Normalize", "★ Normalize") Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("s.Normalize", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) For i = 1 To "ze".Length state.SendBackspace() Next Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") state.SendEscape() For i = 1 To "Normali".Length state.SendBackspace() Next state.SendEscape() Assert.Contains("s.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") state.SendEscape() state.SendTypeChars("n") Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function IntelliCodeItemPreferredAfterCommitingNonIntelliCodeItem(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { void Method() { var s = ""; s$$ } } </Document>, extraExportedTypes:={GetType(IntelliCodeMockProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of IntelliCodeMockProvider)().Single() Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendTypeChars(".nor") Await state.AssertCompletionItemsContainAll("Normalize", "★ Normalize") Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") state.NavigateToDisplayText("Normalize") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("s.Normalize", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) For i = 1 To "ze".Length state.SendBackspace() Next Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") state.SendEscape() For i = 1 To "Normali".Length state.SendBackspace() Next state.SendEscape() Assert.Contains("s.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") state.SendEscape() state.SendTypeChars("n") Await state.AssertSelectedCompletionItem("★ Normalize", displayTextSuffix:="()") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExpanderWithImportCompletionDisabled(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { Bar$$ } } } namespace NS2 { public class Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, False))) ' trigger completion with import completion disabled state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) ' unselect expander state.SetCompletionItemExpanderState(isSelected:=False) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertCompletionItemsDoNotContainAny("Bar") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=False) ' select expander again state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) ' dismiss completion state.SendEscape() Await state.AssertNoCompletionSession() ' trigger completion again state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' should not show unimported item even with cache populated Await state.AssertCompletionItemsDoNotContainAny({"Bar"}) state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=False) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExpanderWithImportCompletionEnabled(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { Bar$$ } } } namespace NS2 { public class Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) ' trigger completion with import completion enabled state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) ' dismiss completion state.SendEscape() Await state.AssertNoCompletionSession() ' trigger completion again state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' now cache is populated Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoExpanderAvailableWhenNotInTypeContext(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { $$ } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) ' trigger completion with import completion enabled state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() state.AssertCompletionItemExpander(isAvailable:=False, isSelected:=False) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterInt(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { int first = 3; int[] array = new int[100]; var range = array[first$$]; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var range = array[first..];", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterClassAndAfterIntProperty(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { var d = new D(); int[] array = new int[100]; var range = array[d$$]; } } class D { public int A; } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem("A", isHardSelected:=True) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var range = array[d.A..];", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterClassAndAfterIntMethod(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { var d = new D(); int[] array = new int[100]; var range = array[d$$]; } } class D { public int A() => 0; } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem("A", isHardSelected:=True) state.SendTypeChars("().") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var range = array[d.A()..];", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterClassAndAfterDecimalProperty(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { var d = new D(); int[] array = new int[100]; var range = array[d$$]; } } class D { public decimal A; } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem("GetHashCode", isHardSelected:=True) state.SendTypeChars("A.") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var range = array[d.A..];", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterClassAndAfterDoubleMethod(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { var d = new D(); int[] array = new int[100]; var range = array[d$$]; } } class D { public double A() => 0; } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertSelectedCompletionItem("GetHashCode", isHardSelected:=True) state.SendTypeChars("A().") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var range = array[d.A()..];", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterIntWithinArrayDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { int d = 1; var array = new int[d$$]; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var array = new int[d..];", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingDotsAfterIntInVariableDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { int d = 1; var e = d$$; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars(".") Assert.Contains("var e = d..;", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(34943, "https://github.com/dotnet/roslyn/issues/34943")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function TypingToStringAfterIntInVariableDeclaration(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { int d = 1; var e = d$$; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.True(state.IsSoftSelected()) state.SendTypeChars("ToStr(") Assert.Contains("var e = d.ToString(", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(36187, "https://github.com/dotnet/roslyn/issues/36187")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)> Public Async Function CompletionWithTwoOverloadsOneOfThemIsEmpty(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { private enum A { A, B, } private void Get(string a) { } private void Get(A a) { } private void Test() { Get$$ } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("(") Await state.AssertSelectedCompletionItem(displayText:="A", isHardSelected:=True) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24960, "https://github.com/dotnet/roslyn/issues/24960")> Public Async Function TypeParameterTOnType(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C<T> { $$ }]]> </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("T") Await state.AssertSelectedCompletionItem("T") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(24960, "https://github.com/dotnet/roslyn/issues/24960")> Public Async Function TypeParameterTOnMethod(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ class C { void M<T>() { $$ } }]]> </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("T") Await state.AssertSelectedCompletionItem("T") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionBeforeVarWithEnableNullableReferenceAnalysisIDEFeatures(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" LanguageVersion="8" CommonReferences="true" AssemblyName="CSProj" Features="run-nullable-analysis=always"> <Document><![CDATA[ class C { void M(string s) { s$$ var o = new object(); } }]]></Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(".") Await state.AssertCompletionItemsContainAll("Length") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletingWithColonInMethodParametersWithNoInstanceToInsert(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[class C { void M(string s) { N(10, $$); } void N(int id, string serviceName) {} }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("serviceN") Await state.AssertCompletionSession() state.SendTypeChars(":") Assert.Contains("N(10, serviceName:);", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletingWithSpaceInMethodParametersWithNoInstanceToInsert(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[class C { void M(string s) { N(10, $$); } void N(int id, string serviceName) {} }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("serviceN") Await state.AssertCompletionSession() state.SendTypeChars(" ") Assert.Contains("N(10, serviceName );", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(35163, "https://github.com/dotnet/roslyn/issues/35163")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NonExpandedItemShouldBePreferred_SameDisplayText(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { Bar$$ } } public class Bar<T> { } } namespace NS2 { public class Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = " namespace NS1 { class C { public void Foo() { Bar } } public class Bar<T> { } } namespace NS2 { public class Bar { } } " Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) Await state.AssertSelectedCompletionItem(displayText:="Bar", displayTextSuffix:="<>") state.SendTab() Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WorkItem(35163, "https://github.com/dotnet/roslyn/issues/35163")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NonExpandedItemShouldBePreferred_SameFullDisplayText(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { Bar$$ } } public class Bar { } } namespace NS2 { public class Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = " namespace NS1 { class C { public void Foo() { Bar } } public class Bar { } } namespace NS2 { public class Bar { } } " Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) Await state.AssertSelectedCompletionItem(displayText:="Bar") state.SendTab() Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WorkItem(35163, "https://github.com/dotnet/roslyn/issues/35163")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NonExpandedItemShouldBePreferred_ExpandedItemHasBetterButNotCompleteMatch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { bar$$ } } public class ABar { } } namespace NS2 { public class Bar1 { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = " namespace NS1 { class C { public void Foo() { ABar } } public class ABar { } } namespace NS2 { public class Bar1 { } } " Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) Await state.AssertSelectedCompletionItem(displayText:="ABar") state.SendTab() Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WorkItem(38253, "https://github.com/dotnet/roslyn/issues/38253")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NonExpandedItemShouldBePreferred_BothExpandedAndNonExpandedItemsHaveCompleteMatch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { bar$$ } } public class Bar { } } namespace NS2 { public class Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = " namespace NS1 { class C { public void Foo() { Bar } } public class Bar { } } namespace NS2 { public class Bar { } } " Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="") state.SendTab() Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WorkItem(38253, "https://github.com/dotnet/roslyn/issues/38253")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletelyMatchedExpandedItemAndWorseThanPrefixMatchedNonExpandedItem(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS1 { class C { public void Foo() { bar$$ } } public class ABar { } } namespace NS2 { public class Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = " using NS2; namespace NS1 { class C { public void Foo() { Bar } } public class ABar { } } namespace NS2 { public class Bar { } } " Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) state.SendTab() Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletelyMatchedExpandedItemAndPrefixMatchedNonExpandedItem(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace NS { class C { void M() { object designer = null; des$$ } } } namespace OtherNS { public class DES { } } </Document>, extraExportedTypes:={GetType(TestExperimentationService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected so all unimported items are in the list state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem(displayText:="designer") state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) End Using End Function <WorkItem(38253, "https://github.com/dotnet/roslyn/issues/38253")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SortItemsByPatternMatch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace NS { class C { void M() { $$ } } class Task { } class BTask1 { } class BTask2 { } class BTask3 { } class Task1 { } class Task2 { } class Task3 { } class ATaAaSaKa { } } </Document>, extraExportedTypes:={GetType(TestExperimentationService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, False))) state.SendTypeChars("task") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Task") Dim expectedOrder = { "Task", "Task1", "Task2", "Task3", "BTask1", "BTask2", "BTask3", "ATaAaSaKa" } state.AssertItemsInOrder(expectedOrder) End Using End Function <WorkItem(41601, "https://github.com/dotnet/roslyn/issues/41601")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SortItemsByExpandedFlag(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace NS1 { class C { void M() { $$ } } class MyTask1 { } class MyTask2 { } class MyTask3 { } } namespace NS2 { class MyTask1 { } class MyTask2 { } class MyTask3 { } } </Document>, extraExportedTypes:={GetType(TestExperimentationService)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, False))) ' trigger completion with import completion disabled state.SendInvokeCompletionList() Await state.WaitForUIRenderedAsync() ' make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.SendEscape() Await state.AssertNoCompletionSession() workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1) _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True))) state.SendTypeChars("mytask") Await state.WaitForAsynchronousOperationsAsync() ' make sure expander is selected state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) Await state.AssertSelectedCompletionItem(displayText:="MyTask1", inlineDescription:="") Dim expectedOrder As (String, String)() = { ("MyTask1", ""), ("MyTask2", ""), ("MyTask3", ""), ("MyTask1", "NS2"), ("MyTask2", "NS2"), ("MyTask3", "NS2") } state.AssertItemsInOrder(expectedOrder) End Using End Function <WorkItem(39519, "https://github.com/dotnet/roslyn/issues/39519")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSuggestedNamesDontStartWithDigit_DigitsInTheMiddle(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS { class C { public void Foo(Foo123Bar $$) { } } public class Foo123Bar { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.ShowNameSuggestions, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("foo123Bar", "foo123", "foo", "bar") Await state.AssertCompletionItemsDoNotContainAny("123Bar") End Using End Function <WorkItem(39519, "https://github.com/dotnet/roslyn/issues/39519")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSuggestedNamesDontStartWithDigit_DigitsOnTheRight(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ namespace NS { class C { public void Foo(Foo123 $$) { } } public class Foo123 { } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.ShowNameSuggestions, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("foo123", "foo") Await state.AssertCompletionItemsDoNotContainAny("123") End Using End Function <ExportCompletionProvider(NameOf(MultipleChangeCompletionProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class MultipleChangeCompletionProvider Inherits CompletionProvider Private _text As String Private _caretPosition As Integer <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Sub SetInfo(text As String, caretPosition As Integer) _text = text _caretPosition = caretPosition End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task context.AddItem(CompletionItem.Create( "CustomItem", rules:=CompletionItemRules.Default.WithMatchPriority(1000))) Return Task.CompletedTask End Function Public Overrides Function ShouldTriggerCompletion(text As SourceText, caretPosition As Integer, trigger As CompletionTrigger, options As OptionSet) As Boolean Return True End Function Public Overrides Function GetChangeAsync(document As Document, item As CompletionItem, commitKey As Char?, cancellationToken As CancellationToken) As Task(Of CompletionChange) Dim newText = "using NewUsing; using System; class C { void goo() { return InsertedItem" Dim change = CompletionChange.Create( New TextChange(New TextSpan(0, _caretPosition), newText)) Return Task.FromResult(change) End Function End Class <ExportCompletionProvider(NameOf(IntelliCodeMockProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class IntelliCodeMockProvider Inherits CompletionProvider Public AutomationTextString As String = "Hello from IntelliCode: Length" <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task Dim intelliCodeItem = CompletionItem.Create(displayText:="★ Length", filterText:="Length") intelliCodeItem.AutomationText = AutomationTextString context.AddItem(intelliCodeItem) context.AddItem(CompletionItem.Create(displayText:="★ Normalize", filterText:="Normalize", displayTextSuffix:="()")) context.AddItem(CompletionItem.Create(displayText:="Normalize", filterText:="Normalize")) context.AddItem(CompletionItem.Create(displayText:="Length", filterText:="Length")) context.AddItem(CompletionItem.Create(displayText:="ToString", filterText:="ToString", displayTextSuffix:="()")) context.AddItem(CompletionItem.Create(displayText:="First", filterText:="First", displayTextSuffix:="()")) Return Task.CompletedTask End Function Public Overrides Function ShouldTriggerCompletion(text As SourceText, caretPosition As Integer, trigger As CompletionTrigger, options As OptionSet) As Boolean Return True End Function Public Overrides Function GetChangeAsync(document As Document, item As CompletionItem, commitKey As Char?, cancellationToken As CancellationToken) As Task(Of CompletionChange) Dim commitText = item.DisplayText If commitText.StartsWith("★") Then ' remove the star and the following space commitText = commitText.Substring(2) End If Return Task.FromResult(CompletionChange.Create(New TextChange(item.Span, commitText))) End Function End Class <WorkItem(43439, "https://github.com/dotnet/roslyn/issues/43439")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectNullOverNuint(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public static void Main() { object o = $$ } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) ' 'nu' should select 'null' instead of 'nuint' (even though 'nuint' sorts higher in the list textually). state.SendTypeChars("nu") Await state.AssertSelectedCompletionItem(displayText:="null", isHardSelected:=True) Await state.AssertCompletionItemsContain("nuint", "") ' even after 'nuint' is selected, deleting the 'i' should still take us back to 'null'. state.SendTypeChars("i") Await state.AssertSelectedCompletionItem(displayText:="nuint", isHardSelected:=True) state.SendBackspace() Await state.AssertSelectedCompletionItem(displayText:="null", isHardSelected:=True) End Using End Function <WorkItem(43439, "https://github.com/dotnet/roslyn/issues/43439")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectNuintOverNullOnceInMRU(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public static void Main() { object o = $$ } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("nui") Await state.AssertCompletionItemsContain("nuint", "") state.SendTab() Assert.Contains("nuint", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) state.SendDeleteWordToLeft() ' nuint should be in the mru now. so typing 'nu' should select it instead of null. state.SendTypeChars("nu") Await state.AssertSelectedCompletionItem(displayText:="nuint", isHardSelected:=True) End Using End Function <WorkItem(944031, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/944031")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLambdaParameterInferenceInJoin1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System.Collections.Generic; using System.Linq; class Program { public class Book { public int Id { get; set; } public int OwnerId { get; set; } public string Name { get; set; } } public class Person { public int Id { get; set; } public string Nickname { get; set; } } static void Main() { var books = new List&lt;Book&gt;(); var persons = new List&lt;Person&gt;(); var join = persons.Join(books, person => person.Id, book => book.$$, (person, book) => new { person.Id, person.Nickname, book.Name }); </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain("OwnerId", "") End Using End Function <WorkItem(944031, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/944031")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLambdaParameterInferenceInJoin2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System.Collections.Generic; using System.Linq; class Program { public class Book { public int Id { get; set; } public int OwnerId { get; set; } public string Name { get; set; } } public class Person { public int Id { get; set; } public string Nickname { get; set; } } static void Main() { var books = new List&lt;Book&gt;(); var persons = new List&lt;Person&gt;(); var join = persons.Join(books, person => person.Id, book => book.OwnerId, (person, book) => new { person.Id, person.Nickname, book.$$ }); </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain("Name", "") End Using End Function <WorkItem(944031, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/944031")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLambdaParameterInferenceInGroupJoin1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System.Collections.Generic; using System.Linq; class Program { public class Book { public int Id { get; set; } public int OwnerId { get; set; } public string Name { get; set; } } public class Person { public int Id { get; set; } public string Nickname { get; set; } } static void Main() { var books = new List&lt;Book&gt;(); var persons = new List&lt;Person&gt;(); var join = persons.GroupJoin(books, person => person.Id, book => book.$$, (person, books1) => new { person.Id, person.Nickname, books1.Select(s => s.Name) }); </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain("OwnerId", "") End Using End Function <WorkItem(944031, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/944031")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLambdaParameterInferenceInGroupJoin2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System.Collections.Generic; using System.Linq; class Program { public class Book { public int Id { get; set; } public int OwnerId { get; set; } public string Name { get; set; } } public class Person { public int Id { get; set; } public string Nickname { get; set; } } static void Main() { var books = new List&lt;Book&gt;(); var persons = new List&lt;Person&gt;(); var join = persons.GroupJoin(books, person => person.Id, book => book.OwnerId, (person, books1) => new { person.Id, person.Nickname, books1.$$ }); </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain("Select", "<>") End Using End Function <WorkItem(944031, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/944031")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLambdaParameterInferenceInGroupJoin3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System.Collections.Generic; using System.Linq; class Program { public class Book { public int Id { get; set; } public int OwnerId { get; set; } public string Name { get; set; } } public class Person { public int Id { get; set; } public string Nickname { get; set; } } static void Main() { var books = new List&lt;Book&gt;(); var persons = new List&lt;Person&gt;(); var join = persons.GroupJoin(books, person => person.Id, book => book.OwnerId, (person, books1) => new { person.Id, person.Nickname, books1.Select(s => s.$$) }); </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain("Name", "") End Using End Function <WorkItem(1128749, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1128749")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFallingBackToItemWithLongestCommonPrefixWhenNoMatch(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class SomePrefixAndName {} class C { void Method() { SomePrefixOrName$$ } } </Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.SendCommitUniqueCompletionListItemAsync() Await state.AssertNoCompletionSession() state.SendEscape() Await state.WaitForAsynchronousOperationsAsync() state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem(displayText:="SomePrefixAndName", isHardSelected:=False) End Using End Function <WorkItem(47511, "https://github.com/dotnet/roslyn/pull/47511")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub ConversionsOperatorsAndIndexerAreShownBelowMethodsAndPropertiesAndBeforeUnimportedItems() Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace A { using B; public static class CExtensions{ public static void ExtensionUnimported(this C c) { } } } namespace B { public static class CExtensions{ public static void ExtensionImported(this C c) { } } public class C { public int A { get; } = default; public int Z { get; } = default; public void AM() { } public void ZM() { } public int this[int _] => default; public static explicit operator int(C _) => default; public static C operator +(C a, C b) => default; } class Program { static void Main() { var c = new C(); c.$$ } } } </Document>) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption( CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() state.AssertItemsInOrder(New String() { "A", ' Method, properties, and imported extension methods alphabetical ordered "AM", "Equals", "ExtensionImported", "GetHashCode", "GetType", "this[]", ' Indexer "ToString", "Z", "ZM", "(int)", ' Conversions "+", ' Operators "ExtensionUnimported" 'Unimported extension methods }) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestCompleteMethodParenthesisForSymbolCompletionProvider(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) Using state = TestStateFactory.CreateCSharpTestState( <Document> public class B { private void C11() { $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" public class B {{ private void C11() {{ C11(){commitChar} }} }}" state.SendTypeChars("C") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("C11")) Assert.True(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("C11") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> Public Sub TestNestedMethodCallWhenCommitUsingSemicolon(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> public class B { private void C11() { AAA($$) } private int DDD() => 1; private int AAA(int i) => 1; }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" public class B {{ private void C11() {{ AAA(DDD()); }} private int DDD() => 1; private int AAA(int i) => 1; }}" state.SendTypeChars("D") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("DDD")) Assert.True(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("DDD") state.SendTypeChars(";"c) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> Public Sub TestNestedMethodCallUnderDelegateContextWhenCommitUsingSemicolon(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; public class B { private void C11() { AAA($$) } private void DDD() {} private int AAA(Action c) => 1; }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" using System; public class B {{ private void C11() {{ AAA(DDD); }} private void DDD() {{}} private int AAA(Action c) => 1; }}" state.SendTypeChars("D") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("DDD")) Assert.False(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("DDD") state.SendTypeChars(";"c) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> Public Sub TestNestedMethodCallWhenCommitUsingDot(showCompletionInArgumentLists As Boolean) Using state = TestStateFactory.CreateCSharpTestState( <Document> public class B { private void C11() { AAA($$) } private int DDD() => 1; private int AAA(int i) => 1; }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" public class B {{ private void C11() {{ AAA(DDD().) }} private int DDD() => 1; private int AAA(int i) => 1; }}" state.SendTypeChars("D") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("DDD")) Assert.True(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("DDD") state.SendTypeChars("."c) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestCompleteMethodParenthesisForSymbolCompletionProviderUnderDelegateContext(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; public class B { private void C11() { Action t = $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" using System; public class B {{ private void C11() {{ Action t = C11{commitChar} }} }}" state.SendTypeChars("C") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("C11")) Assert.False(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("C11") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestCompleteObjectCreationParenthesisForSymbolCreationCompletionProvider(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) Using state = TestStateFactory.CreateCSharpTestState( <Document> using Bar = System.String public class AA { private static void CC() { var a = new $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" using Bar = System.String public class AA {{ private static void CC() {{ var a = new Bar(){commitChar} }} }}" state.SendTypeChars("B") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("AA")) Assert.True(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("Bar") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestCompleteObjectCreationParenthesisForSymbolCreationCompletionProviderUnderNonObjectCreationContext(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) Using state = TestStateFactory.CreateCSharpTestState( <Document> using Bar = System.String public class AA { private static void CC() { $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" using Bar = System.String public class AA {{ private static void CC() {{ Bar{commitChar} }} }}" state.SendTypeChars("B") Dim expectingItem = state.GetCompletionItems().First(Function(item) item.DisplayText.Equals("AA")) Assert.False(SymbolCompletionItem.GetShouldProvideParenthesisCompletion(expectingItem)) state.SendSelectCompletionItem("Bar") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestCompleteParenthesisForObjectCreationCompletionProvider(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) Using state = TestStateFactory.CreateCSharpTestState( <Document> public class AA { private static void CC() { AA a = new $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim expectedText = $" public class AA {{ private static void CC() {{ AA a = new AA(){commitChar} }} }}" state.SendTypeChars("A") state.SendSelectCompletionItem("AA") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Sub TestCompleteParenthesisForExtensionMethodImportCompletionProvider(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace CC { public static class DD { public static int ToInt(this AA a) => 1; } } public class AA { private static void CC() { AA a = new AA(); var value = a.$$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True) _ .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion, -1)) Dim expectedText = $" using CC; namespace CC {{ public static class DD {{ public static int ToInt(this AA a) => 1; }} }} public class AA {{ private static void CC() {{ AA a = new AA(); var value = a.ToInt(){commitChar} }} }}" state.SendTypeChars("To") state.SendSelectCompletionItem("ToInt") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Sub <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompleteParenthesisForTypeImportCompletionProvider(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace CC { public class Bar { } } public class AA { private static void CC() { var a = new $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() ' Make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Dim expectedText = $" using CC; namespace CC {{ public class Bar {{ }} }} public class AA {{ private static void CC() {{ var a = new Bar(){commitChar} }} }}" state.SendTypeChars("Ba") state.SendSelectCompletionItem("Bar") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompleteParenthesisForTypeImportCompletionProviderUnderNonObjectCreationContext(showCompletionInArgumentLists As Boolean, <CombinatorialValues(";"c, "."c)> commitChar As Char) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> namespace CC { public class Bar { } } public class AA { private static void CC() { $$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() ' Make sure expander is selected state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Dim expectedText = $" using CC; namespace CC {{ public class Bar {{ }} }} public class AA {{ private static void CC() {{ Bar{commitChar} }} }}" state.SendTypeChars("Ba") state.SendSelectCompletionItem("Bar") state.SendTypeChars(commitChar) Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompleteParenthesisForMethodUnderNameofContext(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class AA { private static void CC() { var x = nameof($$) } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Dim expectedText = " public class AA { private static void CC() { var x = nameof(CC); } }" state.SendTypeChars("CC") state.SendSelectCompletionItem("CC") state.SendTypeChars(";") Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompleteParenthesisForGenericMethodUnderNameofContext(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; public class AA { private static void CC() { var x = nameof($$) } private static T GetSomething&lt;T&gt;() => (T)Activator.GetInstance(typeof(T)); }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Dim expectedText = " using System; public class AA { private static void CC() { var x = nameof(GetSomething); } private static T GetSomething<T>() => (T)Activator.GetInstance(typeof(T)); }" state.SendTypeChars("Get") state.SendSelectCompletionItem("GetSomething<>") state.SendTypeChars(";") Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompleteParenthesisForFullMethodUnderNameofContext(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class AA { private static void CC() { var x = nameof($$) } } namespace Bar1 { public class Bar2 { public void Bar3() { } } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Dim expectedText = " public class AA { private static void CC() { var x = nameof(Bar1.Bar2.Bar3); } } namespace Bar1 { public class Bar2 { public void Bar3() { } } }" state.SendTypeChars("Bar1.Bar2.Ba") state.SendSelectCompletionItem("Bar3") state.SendTypeChars(";") Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompleteParenthesisForFunctionPointer(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; public unsafe class AA { private static void CC() { delegate*&lt;void&gt; p = $$ } public static void Bar() {} }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.Workspace.SetOptions(state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True)) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.SetCompletionItemExpanderState(isSelected:=True) Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Dim expectedText = " using System; public unsafe class AA { private static void CC() { delegate*<void> p = Bar; } public static void Bar() {} }" state.SendTypeChars("Ba") state.SendSelectCompletionItem("Bar") state.SendTypeChars(";") Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorIf(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if $$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#if Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorElif(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if false #elif $$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#elif Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionNotInPreprocessorElse(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if false #elif false #else $$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorParenthesized(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if ($$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#if (Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorNot(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if !$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#if !Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorAnd(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if true &amp;&amp; $$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#if true && Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorOr(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,Baz"> <Document> #if true || $$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#if true || Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInPreprocessorCasingDifference(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Goo,Bar,BAR,Baz"> <Document> #if $$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "BAR", "Baz", "true", "false"}) state.SendTypeChars("Go") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("#if Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(55546, "https://github.com/dotnet/roslyn/issues/55546")> Public Async Function PreferHigherMatchPriorityOverCaseSensitiveWithOnlyLowercaseTyped(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> using System; public static class Ext { public static bool Should(this int x) => false; } public class AA { private static void CC(int x) { var y = x.$$ } }</Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.SendTypeChars("sh") Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem("Should") End Using End Function <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(55546, "https://github.com/dotnet/roslyn/issues/55546")> Public Async Function PreferBestMatchPriorityAndCaseSensitiveWithOnlyLowercaseTyped(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class AA { private static void CC) { $$ } }</Document>, extraExportedTypes:={GetType(MultipleLowercaseItemsWithNoHigherMatchPriorityProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.SendTypeChars("item") Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() ' We have multiple items have "item" prefix but with different MatchPriority, ' need to ensure we select the one with best casing AND MatchPriority. Await state.AssertSelectedCompletionItem("item2") End Using End Function <ExportCompletionProvider(NameOf(MultipleLowercaseItemsWithNoHigherMatchPriorityProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class MultipleLowercaseItemsWithNoHigherMatchPriorityProvider Inherits CompletionProvider Private ReadOnly highPriorityRule As CompletionItemRules = CompletionItemRules.Default.WithMatchPriority(MatchPriority.Default + 1) Private ReadOnly lowPriorityRule As CompletionItemRules = CompletionItemRules.Default.WithMatchPriority(MatchPriority.Default - 1) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub ' All lowercase items have lower MatchPriority than uppercase item, except one with equal value. Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task context.AddItem(CompletionItem.Create(displayText:="item1", rules:=lowPriorityRule)) context.AddItem(CompletionItem.Create(displayText:="item2", rules:=highPriorityRule)) context.AddItem(CompletionItem.Create(displayText:="item3", rules:=CompletionItemRules.Default)) context.AddItem(CompletionItem.Create(displayText:="Item4", rules:=highPriorityRule)) Return Task.CompletedTask End Function Public Overrides Function ShouldTriggerCompletion(text As SourceText, caretPosition As Integer, trigger As CompletionTrigger, options As OptionSet) As Boolean Return True End Function End Class <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(55546, "https://github.com/dotnet/roslyn/issues/55546")> Public Async Function PreferBestCaseSensitiveWithUppercaseTyped(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> public class AA { private static void CC) { $$ } }</Document>, extraExportedTypes:={GetType(UppercaseItemWithLowerPriorityProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() state.SendTypeChars("Item") Await state.WaitForAsynchronousOperationsAsync() Await state.WaitForUIRenderedAsync() Await state.AssertSelectedCompletionItem("Item3") ' ensure we prefer casing over match priority if uppercase is typed End Using End Function <ExportCompletionProvider(NameOf(UppercaseItemWithLowerPriorityProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class UppercaseItemWithLowerPriorityProvider Inherits CompletionProvider Private ReadOnly highPriorityRule As CompletionItemRules = CompletionItemRules.Default.WithMatchPriority(MatchPriority.Default + 1) Private ReadOnly lowPriorityRule As CompletionItemRules = CompletionItemRules.Default.WithMatchPriority(MatchPriority.Default - 1) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task context.AddItem(CompletionItem.Create(displayText:="item1", rules:=highPriorityRule)) context.AddItem(CompletionItem.Create(displayText:="item2", rules:=highPriorityRule)) context.AddItem(CompletionItem.Create(displayText:="Item3", rules:=lowPriorityRule)) Return Task.CompletedTask End Function Public Overrides Function ShouldTriggerCompletion(text As SourceText, caretPosition As Integer, trigger As CompletionTrigger, options As OptionSet) As Boolean Return True End Function End Class <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSuggestionModeWithDeletionTrigger(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Collections.Generic; using System.Linq; class C { public static void Baz(List<int> list) { var xml = 0; list.FirstOrDefault(xx$$) } }]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendBackspace() Await state.AssertSelectedCompletionItem("xml", isSoftSelected:=True).ConfigureAwait(True) End Using End Function ' Simulates a situation where IntelliCode provides items not included into the Rolsyn original list. ' We want to ignore these items in CommitIfUnique. ' This situation should not happen. Tests with this provider were added to cover protective scenarios. <ExportCompletionProvider(NameOf(IntelliCodeMockWeirdProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class IntelliCodeMockWeirdProvider Inherits IntelliCodeMockProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New() End Sub Public Overrides Async Function ProvideCompletionsAsync(context As CompletionContext) As Task Await MyBase.ProvideCompletionsAsync(context).ConfigureAwait(False) context.AddItem(CompletionItem.Create(displayText:="★ Length2", filterText:="Length")) End Function End Class <WorkItem(49813, "https://github.com/dotnet/roslyn/issues/49813")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCaseSensitiveMatchWithLowerMatchPriority(showCompletionInArgumentLists As Boolean) As Task ' PreselectionProvider will provide an item "★ length" with filter text "length", ' which is a case-insentive match to typed text "Length", but with higher match priority. ' In this case, we need to make sure the case-sensitive match "Length" is selected. Using state = TestStateFactory.CreateCSharpTestState( <Document> struct Range { public (int Offset, int Length) GetOffsetAndLength(int length) => (0, 0); } class Repro { public int Length { get; } public void Test(Range x) { var (offset, length) = x.GetOffsetAndLength(Length$$); } } </Document>, extraExportedTypes:={GetType(PreselectionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim workspace = state.Workspace workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(CompletionOptions.TriggerOnDeletion, LanguageNames.CSharp, True))) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll({"★ length", "length", "Length"}) Await state.AssertSelectedCompletionItem("Length", isHardSelected:=True) state.SendEscape() Await state.AssertNoCompletionSession() state.SendBackspace() Await state.AssertCompletionSession() Await state.AssertCompletionItemsContainAll({"★ length", "length", "Length"}) Await state.AssertSelectedCompletionItem("Length", isHardSelected:=True) End Using End Function ' Simulate the situation that some provider (e.g. IntelliCode) provides items with higher match priority that only match case-insensitively. <ExportCompletionProvider(NameOf(PreselectionProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class PreselectionProvider Inherits CommonCompletionProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task Dim rules = CompletionItemRules.Default.WithSelectionBehavior(CompletionItemSelectionBehavior.HardSelection).WithMatchPriority(MatchPriority.Preselect) context.AddItem(CompletionItem.Create(displayText:="★ length", filterText:="length", rules:=rules)) Return Task.CompletedTask End Function Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return True End Function End Class <WorkItem(53712, "https://github.com/dotnet/roslyn/issues/53712")> <WpfTheory, CombinatorialData> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotifyCommittingItemCompletionProvider(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document> class C { public void M() { ItemFromNotifyCommittingItemCompletion$$ } } </Document>, extraExportedTypes:={GetType(NotifyCommittingItemCompletionProvider)}.ToList(), showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders) Dim notifyProvider As NotifyCommittingItemCompletionProvider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of NotifyCommittingItemCompletionProvider)().Single() notifyProvider.Reset() state.SendInvokeCompletionList() Await state.AssertCompletionItemsContain(NotifyCommittingItemCompletionProvider.DisplayText, "") Await state.AssertSelectedCompletionItem(NotifyCommittingItemCompletionProvider.DisplayText, isHardSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains(NotifyCommittingItemCompletionProvider.DisplayText, state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) Await notifyProvider.checkpoint.Task Assert.False(notifyProvider.CalledOnMainThread) End Using End Function <ExportCompletionProvider(NameOf(NotifyCommittingItemCompletionProvider), LanguageNames.CSharp)> <[Shared]> <PartNotDiscoverable> Private Class NotifyCommittingItemCompletionProvider Inherits CommonCompletionProvider Implements INotifyCommittingItemCompletionProvider Private ReadOnly _threadingContext As IThreadingContext Public Const DisplayText As String = "ItemFromNotifyCommittingItemCompletionProvider" Public Checkpoint As Checkpoint = New Checkpoint() Public CalledOnMainThread As Boolean? Public Sub Reset() Checkpoint = New Checkpoint() CalledOnMainThread = Nothing End Sub <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(threadingContext As IThreadingContext) _threadingContext = threadingContext End Sub Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task context.AddItem(CompletionItem.Create(displayText:=DisplayText, filterText:=DisplayText)) Return Task.CompletedTask End Function Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return True End Function #Disable Warning IDE0060 ' Remove unused parameter Public Function NotifyCommittingItemAsync(document As Document, item As CompletionItem, commitKey As Char?, cancellationToken As CancellationToken) As Task Implements INotifyCommittingItemCompletionProvider.NotifyCommittingItemAsync #Enable Warning IDE0060 ' Remove unused parameter CalledOnMainThread = _threadingContext.HasMainThread AndAlso _threadingContext.JoinableTaskContext.IsOnMainThread Checkpoint.Release() Return Task.CompletedTask End Function End Class End Class End Namespace
1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/CSharp/Portable/Completion/CompletionProviders/OperatorsAndIndexer/UnnamedSymbolCompletionProvider_Conversions.cs
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal partial class UnnamedSymbolCompletionProvider { // Place conversions before operators. private readonly int ConversionSortingGroupIndex = 1; /// <summary> /// Tag to let us know we need to rehydrate the conversion from the parameter and return type. /// </summary> private const string RehydrateName = "Rehydrate"; private static readonly ImmutableDictionary<string, string> ConversionProperties = ImmutableDictionary<string, string>.Empty.Add(KindName, ConversionKindName); private void AddConversion(CompletionContext context, SemanticModel semanticModel, int position, IMethodSymbol conversion) { var (symbols, properties) = GetConversionSymbolsAndProperties(context, conversion); var targetTypeName = conversion.ReturnType.ToMinimalDisplayString(semanticModel, position); context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayTextPrefix: "(", displayText: targetTypeName, displayTextSuffix: ")", filterText: targetTypeName, sortText: SortText(ConversionSortingGroupIndex, targetTypeName), glyph: Glyph.Operator, symbols: symbols, rules: CompletionItemRules.Default, contextPosition: position, properties: properties)); } private static (ImmutableArray<ISymbol> symbols, ImmutableDictionary<string, string> properties) GetConversionSymbolsAndProperties( CompletionContext context, IMethodSymbol conversion) { // If it's a non-synthesized method, then we can just encode it as is. if (conversion is not CodeGenerationSymbol) return (ImmutableArray.Create<ISymbol>(conversion), ConversionProperties); // Otherwise, encode the constituent parts so we can recover it in GetConversionDescriptionAsync; var properties = ConversionProperties .Add(RehydrateName, RehydrateName) .Add(DocumentationCommentXmlName, conversion.GetDocumentationCommentXml(cancellationToken: context.CancellationToken) ?? ""); var symbols = ImmutableArray.Create<ISymbol>(conversion.ContainingType, conversion.Parameters.First().Type, conversion.ReturnType); return (symbols, properties); } private static async Task<CompletionChange> GetConversionChangeAsync( Document document, CompletionItem item, CancellationToken cancellationToken) { var position = SymbolCompletionItem.GetContextPosition(item); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var (dotToken, _) = GetDotAndExpressionStart(root, position); var questionToken = dotToken.GetPreviousToken().Kind() == SyntaxKind.QuestionToken ? dotToken.GetPreviousToken() : (SyntaxToken?)null; var expression = (ExpressionSyntax)dotToken.GetRequiredParent(); expression = expression.GetRootConditionalAccessExpression() ?? expression; var replacement = questionToken != null ? $"(({item.DisplayText}){text.ToString(TextSpan.FromBounds(expression.SpanStart, questionToken.Value.FullSpan.Start))}){questionToken.Value}" : $"(({item.DisplayText}){text.ToString(TextSpan.FromBounds(expression.SpanStart, dotToken.SpanStart))})"; // If we're at `x.$$.y` then we only want to replace up through the first dot. var tokenOnLeft = root.FindTokenOnLeftOfPosition(position, includeSkipped: true); var fullTextChange = new TextChange( TextSpan.FromBounds( expression.SpanStart, tokenOnLeft.Kind() == SyntaxKind.DotDotToken ? tokenOnLeft.SpanStart + 1 : tokenOnLeft.Span.End), replacement); var newPosition = expression.SpanStart + replacement.Length; return CompletionChange.Create(fullTextChange, newPosition); } private static async Task<CompletionDescription?> GetConversionDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) { var conversion = await TryRehydrateAsync(document, item, cancellationToken).ConfigureAwait(false); if (conversion == null) return null; return await SymbolCompletionItem.GetDescriptionForSymbolsAsync( item, document, ImmutableArray.Create(conversion), cancellationToken).ConfigureAwait(false); } private static async Task<ISymbol?> TryRehydrateAsync(Document document, CompletionItem item, CancellationToken cancellationToken) { // If we're need to rehydrate the conversion, pull out the necessary parts. if (item.Properties.ContainsKey(RehydrateName)) { var symbols = await SymbolCompletionItem.GetSymbolsAsync(item, document, cancellationToken).ConfigureAwait(false); if (symbols.Length == 3 && symbols[0] is INamedTypeSymbol containingType && symbols[1] is ITypeSymbol fromType && symbols[2] is ITypeSymbol toType) { return CodeGenerationSymbolFactory.CreateConversionSymbol( toType: toType, fromType: CodeGenerationSymbolFactory.CreateParameterSymbol(fromType, "value"), containingType: containingType, documentationCommentXml: item.Properties[DocumentationCommentXmlName]); } return null; } else { // Otherwise, just go retrieve the conversion directly. var symbols = await SymbolCompletionItem.GetSymbolsAsync(item, document, cancellationToken).ConfigureAwait(false); return symbols.Length == 1 ? symbols.Single() : null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal partial class UnnamedSymbolCompletionProvider { // Place conversions before operators. private const int ConversionSortingGroupIndex = 1; /// <summary> /// Tag to let us know we need to rehydrate the conversion from the parameter and return type. /// </summary> private const string RehydrateName = "Rehydrate"; private static readonly ImmutableDictionary<string, string> s_conversionProperties = ImmutableDictionary<string, string>.Empty.Add(KindName, ConversionKindName); // We set conversion items' match priority to lower than default so completion selects other symbols over it when user starts typing. // e.g. method symbol `Should` should be selected over `(short)` when "sh" is typed. private static readonly CompletionItemRules s_conversionRules = CompletionItemRules.Default.WithMatchPriority(MatchPriority.Default - 1); private static void AddConversion(CompletionContext context, SemanticModel semanticModel, int position, IMethodSymbol conversion) { var (symbols, properties) = GetConversionSymbolsAndProperties(context, conversion); var targetTypeName = conversion.ReturnType.ToMinimalDisplayString(semanticModel, position); context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayTextPrefix: "(", displayText: targetTypeName, displayTextSuffix: ")", filterText: targetTypeName, sortText: SortText(ConversionSortingGroupIndex, targetTypeName), glyph: Glyph.Operator, symbols: symbols, rules: s_conversionRules, contextPosition: position, properties: properties)); } private static (ImmutableArray<ISymbol> symbols, ImmutableDictionary<string, string> properties) GetConversionSymbolsAndProperties( CompletionContext context, IMethodSymbol conversion) { // If it's a non-synthesized method, then we can just encode it as is. if (conversion is not CodeGenerationSymbol) return (ImmutableArray.Create<ISymbol>(conversion), s_conversionProperties); // Otherwise, encode the constituent parts so we can recover it in GetConversionDescriptionAsync; var properties = s_conversionProperties .Add(RehydrateName, RehydrateName) .Add(DocumentationCommentXmlName, conversion.GetDocumentationCommentXml(cancellationToken: context.CancellationToken) ?? ""); var symbols = ImmutableArray.Create<ISymbol>(conversion.ContainingType, conversion.Parameters.First().Type, conversion.ReturnType); return (symbols, properties); } private static async Task<CompletionChange> GetConversionChangeAsync( Document document, CompletionItem item, CancellationToken cancellationToken) { var position = SymbolCompletionItem.GetContextPosition(item); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var (dotToken, _) = GetDotAndExpressionStart(root, position); var questionToken = dotToken.GetPreviousToken().Kind() == SyntaxKind.QuestionToken ? dotToken.GetPreviousToken() : (SyntaxToken?)null; var expression = (ExpressionSyntax)dotToken.GetRequiredParent(); expression = expression.GetRootConditionalAccessExpression() ?? expression; var replacement = questionToken != null ? $"(({item.DisplayText}){text.ToString(TextSpan.FromBounds(expression.SpanStart, questionToken.Value.FullSpan.Start))}){questionToken.Value}" : $"(({item.DisplayText}){text.ToString(TextSpan.FromBounds(expression.SpanStart, dotToken.SpanStart))})"; // If we're at `x.$$.y` then we only want to replace up through the first dot. var tokenOnLeft = root.FindTokenOnLeftOfPosition(position, includeSkipped: true); var fullTextChange = new TextChange( TextSpan.FromBounds( expression.SpanStart, tokenOnLeft.Kind() == SyntaxKind.DotDotToken ? tokenOnLeft.SpanStart + 1 : tokenOnLeft.Span.End), replacement); var newPosition = expression.SpanStart + replacement.Length; return CompletionChange.Create(fullTextChange, newPosition); } private static async Task<CompletionDescription?> GetConversionDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken) { var conversion = await TryRehydrateAsync(document, item, cancellationToken).ConfigureAwait(false); if (conversion == null) return null; return await SymbolCompletionItem.GetDescriptionForSymbolsAsync( item, document, ImmutableArray.Create(conversion), cancellationToken).ConfigureAwait(false); } private static async Task<ISymbol?> TryRehydrateAsync(Document document, CompletionItem item, CancellationToken cancellationToken) { // If we're need to rehydrate the conversion, pull out the necessary parts. if (item.Properties.ContainsKey(RehydrateName)) { var symbols = await SymbolCompletionItem.GetSymbolsAsync(item, document, cancellationToken).ConfigureAwait(false); if (symbols.Length == 3 && symbols[0] is INamedTypeSymbol containingType && symbols[1] is ITypeSymbol fromType && symbols[2] is ITypeSymbol toType) { return CodeGenerationSymbolFactory.CreateConversionSymbol( toType: toType, fromType: CodeGenerationSymbolFactory.CreateParameterSymbol(fromType, "value"), containingType: containingType, documentationCommentXml: item.Properties[DocumentationCommentXmlName]); } return null; } else { // Otherwise, just go retrieve the conversion directly. var symbols = await SymbolCompletionItem.GetSymbolsAsync(item, document, cancellationToken).ConfigureAwait(false); return symbols.Length == 1 ? symbols.Single() : null; } } } }
1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/Core/Portable/Completion/CommonCompletionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Options; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.Tags; namespace Microsoft.CodeAnalysis.Completion { internal abstract partial class CommonCompletionService : CompletionServiceWithProviders { protected CommonCompletionService(Workspace workspace) : base(workspace) { } protected override CompletionItem GetBetterItem(CompletionItem item, CompletionItem existingItem) { // We've constructed the export order of completion providers so // that snippets are exported after everything else. That way, // when we choose a single item per display text, snippet // glyphs appear by snippets. This breaks preselection of items // whose display text is also a snippet (workitem 852578), // the snippet item doesn't have its preselect bit set. // We'll special case this by not preferring later items // if they are snippets and the other candidate is preselected. if (existingItem.Rules.MatchPriority != MatchPriority.Default && IsSnippetItem(item)) { return existingItem; } return base.GetBetterItem(item, existingItem); } internal override Task<(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsInternalAsync( Document document, int caretPosition, CompletionTrigger trigger, ImmutableHashSet<string> roles, OptionSet options, CancellationToken cancellationToken) { return GetCompletionsWithAvailabilityOfExpandedItemsAsync(document, caretPosition, trigger, roles, options, cancellationToken); } protected static bool IsKeywordItem(CompletionItem item) => item.Tags.Contains(WellKnownTags.Keyword); protected static bool IsSnippetItem(CompletionItem item) => item.Tags.Contains(WellKnownTags.Snippet); internal override ImmutableArray<CompletionItem> FilterItems(Document document, ImmutableArray<(CompletionItem, PatternMatch?)> itemsWithPatternMatch, string filterText) { var helper = CompletionHelper.GetHelper(document); return CompletionService.FilterItems(helper, itemsWithPatternMatch); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Options; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.Tags; namespace Microsoft.CodeAnalysis.Completion { internal abstract partial class CommonCompletionService : CompletionServiceWithProviders { protected CommonCompletionService(Workspace workspace) : base(workspace) { } protected override CompletionItem GetBetterItem(CompletionItem item, CompletionItem existingItem) { // We've constructed the export order of completion providers so // that snippets are exported after everything else. That way, // when we choose a single item per display text, snippet // glyphs appear by snippets. This breaks preselection of items // whose display text is also a snippet (workitem 852578), // the snippet item doesn't have its preselect bit set. // We'll special case this by not preferring later items // if they are snippets and the other candidate is preselected. if (existingItem.Rules.MatchPriority != MatchPriority.Default && IsSnippetItem(item)) { return existingItem; } return base.GetBetterItem(item, existingItem); } internal override Task<(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsInternalAsync( Document document, int caretPosition, CompletionTrigger trigger, ImmutableHashSet<string> roles, OptionSet options, CancellationToken cancellationToken) { return GetCompletionsWithAvailabilityOfExpandedItemsAsync(document, caretPosition, trigger, roles, options, cancellationToken); } protected static bool IsKeywordItem(CompletionItem item) => item.Tags.Contains(WellKnownTags.Keyword); protected static bool IsSnippetItem(CompletionItem item) => item.Tags.Contains(WellKnownTags.Snippet); internal override ImmutableArray<CompletionItem> FilterItems(Document document, ImmutableArray<(CompletionItem, PatternMatch?)> itemsWithPatternMatch, string filterText) { var helper = CompletionHelper.GetHelper(document); return CompletionService.FilterItems(helper, itemsWithPatternMatch, filterText); } } }
1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/Core/Portable/Completion/CompletionHelper.cs
// Licensed to the .NET Foundation under one or more 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.Globalization; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion { internal sealed class CompletionHelper { private readonly object _gate = new(); private readonly Dictionary<(string pattern, CultureInfo, bool includeMatchedSpans), PatternMatcher> _patternMatcherMap = new(); private static readonly CultureInfo EnUSCultureInfo = new("en-US"); private readonly bool _isCaseSensitive; public CompletionHelper(bool isCaseSensitive) => _isCaseSensitive = isCaseSensitive; public static CompletionHelper GetHelper(Document document) { return document.Project.Solution.Workspace.Services.GetRequiredService<ICompletionHelperService>() .GetCompletionHelper(document); } public ImmutableArray<TextSpan> GetHighlightedSpans( string text, string pattern, CultureInfo culture) { var match = GetMatch(text, pattern, includeMatchSpans: true, culture: culture); return match == null ? ImmutableArray<TextSpan>.Empty : match.Value.MatchedSpans; } /// <summary> /// Returns true if the completion item matches the pattern so far. Returns 'true' /// if and only if the completion item matches and should be included in the filtered completion /// results, or false if it should not be. /// </summary> public bool MatchesPattern(string text, string pattern, CultureInfo culture) => GetMatch(text, pattern, includeMatchSpans: false, culture) != null; public PatternMatch? GetMatch( string completionItemText, string pattern, bool includeMatchSpans, CultureInfo culture) { // If the item has a dot in it (i.e. for something like enum completion), then attempt // to match what the user wrote against the last portion of the name. That way if they // write "Bl" and we have "Blub" and "Color.Black", we'll consider the latter to be a // better match as they'll both be prefix matches, and the latter will have a higher // priority. var lastDotIndex = completionItemText.LastIndexOf('.'); if (lastDotIndex >= 0) { var afterDotPosition = lastDotIndex + 1; var textAfterLastDot = completionItemText[afterDotPosition..]; var match = GetMatchWorker(textAfterLastDot, pattern, culture, includeMatchSpans); if (match != null) { return AdjustMatchedSpans(match.Value, afterDotPosition); } } // Didn't have a dot, or the user text didn't match the portion after the dot. // Just do a normal check against the entire completion item. return GetMatchWorker(completionItemText, pattern, culture, includeMatchSpans); } private static PatternMatch? AdjustMatchedSpans(PatternMatch value, int offset) => value.MatchedSpans.IsDefaultOrEmpty ? value : value.WithMatchedSpans(value.MatchedSpans.SelectAsArray(s => new TextSpan(s.Start + offset, s.Length))); private PatternMatch? GetMatchWorker( string completionItemText, string pattern, CultureInfo culture, bool includeMatchSpans) { var patternMatcher = GetPatternMatcher(pattern, culture, includeMatchSpans); var match = patternMatcher.GetFirstMatch(completionItemText); // We still have making checks for language having different to English capitalization, // for example, for Turkish with dotted and dotless i capitalization totally diferent from English. // Now we escaping from the second check for English languages. // Maybe we can escape as well for more similar languages in case if we meet performance issues. if (culture.ThreeLetterWindowsLanguageName.Equals(EnUSCultureInfo.ThreeLetterWindowsLanguageName)) { return match; } // Keywords in .NET are always in En-US. // Identifiers can be in user language. // Try to get matches for both and return the best of them. patternMatcher = GetPatternMatcher(pattern, EnUSCultureInfo, includeMatchSpans); var enUSCultureMatch = patternMatcher.GetFirstMatch(completionItemText); if (match == null) { return enUSCultureMatch; } if (enUSCultureMatch == null) { return match; } return match.Value.CompareTo(enUSCultureMatch.Value) < 0 ? match.Value : enUSCultureMatch.Value; } private PatternMatcher GetPatternMatcher( string pattern, CultureInfo culture, bool includeMatchedSpans, Dictionary<(string, CultureInfo, bool), PatternMatcher> map) { lock (_gate) { var key = (pattern, culture, includeMatchedSpans); if (!map.TryGetValue(key, out var patternMatcher)) { patternMatcher = PatternMatcher.CreatePatternMatcher( pattern, culture, includeMatchedSpans, allowFuzzyMatching: false); map.Add(key, patternMatcher); } return patternMatcher; } } private PatternMatcher GetPatternMatcher(string pattern, CultureInfo culture, bool includeMatchedSpans) => GetPatternMatcher(pattern, culture, includeMatchedSpans, _patternMatcherMap); /// <summary> /// Returns true if item1 is a better completion item than item2 given the provided filter /// text, or false if it is not better. /// </summary> public int CompareItems(CompletionItem item1, CompletionItem item2, string pattern, CultureInfo culture) { var match1 = GetMatch(item1.FilterText, pattern, includeMatchSpans: false, culture); var match2 = GetMatch(item2.FilterText, pattern, includeMatchSpans: false, culture); return CompareItems(item1, match1, item2, match2); } public int CompareItems(CompletionItem item1, PatternMatch? match1, CompletionItem item2, PatternMatch? match2) { if (match1 != null && match2 != null) { var result = CompareMatches(match1.Value, match2.Value, item1, item2); if (result != 0) { return result; } } else if (match1 != null) { return -1; } else if (match2 != null) { return 1; } var preselectionDiff = ComparePreselection(item1, item2); if (preselectionDiff != 0) { return preselectionDiff; } // Prefer things with a keyword tag, if the filter texts are the same. if (!TagsEqual(item1, item2) && item1.FilterText == item2.FilterText) { return (!IsKeywordItem(item1)).CompareTo(!IsKeywordItem(item2)); } return 0; } private static bool TagsEqual(CompletionItem item1, CompletionItem item2) => TagsEqual(item1.Tags, item2.Tags); private static bool TagsEqual(ImmutableArray<string> tags1, ImmutableArray<string> tags2) => tags1 == tags2 || System.Linq.Enumerable.SequenceEqual(tags1, tags2); private static bool IsKeywordItem(CompletionItem item) => item.Tags.Contains(WellKnownTags.Keyword); private int CompareMatches(PatternMatch match1, PatternMatch match2, CompletionItem item1, CompletionItem item2) { // *Almost* always prefer non-expanded item regardless of the pattern matching result. // Except when all non-expanded items are worse than prefix matching and there's // a complete match from expanded ones. // // For example, In the scenarios below, `NS2.Designer` would be selected over `System.Security.Cryptography.DES` // // namespace System.Security.Cryptography // { // class DES {} // } // namespace NS2 // { // class Designer {} // class C // { // des$$ // } // } // // But in this case, `System.Security.Cryptography.DES` would be selected over `NS2.MyDesigner` // // namespace System.Security.Cryptography // { // class DES {} // } // namespace NS2 // { // class MyDesigner {} // class C // { // des$$ // } // } // // This currently means items from unimported namespaces (those are the only expanded items now) // are treated as "2nd tier" results, which forces users to be more explicit about selecting them. var expandedDiff = CompareExpandedItem(item1, match1, item2, match2); if (expandedDiff != 0) { return expandedDiff; } // Then see how the two items compare in a case insensitive fashion. Matches that // are strictly better (ignoring case) should prioritize the item. i.e. if we have // a prefix match, that should always be better than a substring match. // // The reason we ignore case is that it's very common for people to type expecting // completion to fix up their casing. i.e. 'false' will be written with the // expectation that it will get fixed by the completion list to 'False'. var diff = match1.CompareTo(match2, ignoreCase: true); if (diff != 0) { return diff; } // If two items match in case-insensitive manner, and we are in a case-insensitive language, // then the preselected one is considered better, otherwise we will prefer the one matches // case-sensitively. This is to make sure common items in VB like `True` and `False` are prioritized // for selection when user types `t` and `f`. // More details can be found in comments of https://github.com/dotnet/roslyn/issues/4892 if (!_isCaseSensitive) { var preselectionDiff = ComparePreselection(item1, item2); if (preselectionDiff != 0) { return preselectionDiff; } } // At this point we have two items which we're matching in a rather similar fashion. // If one is a prefix of the other, prefer the prefix. i.e. if we have // "Table" and "table:=" and the user types 't' and we are in a case insensitive // language, then we prefer the former. if (item1.GetEntireDisplayText().Length != item2.GetEntireDisplayText().Length) { var comparison = _isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; if (item2.GetEntireDisplayText().StartsWith(item1.GetEntireDisplayText(), comparison)) { return -1; } else if (item1.GetEntireDisplayText().StartsWith(item2.GetEntireDisplayText(), comparison)) { return 1; } } // Now compare the matches again in a case sensitive manner. If everything was // equal up to this point, we prefer the item that better matches based on case. return match1.CompareTo(match2, ignoreCase: false); } // If they both seemed just as good, but they differ on preselection, then // item1 is better if it is preselected, otherwise it is worse. private static int ComparePreselection(CompletionItem item1, CompletionItem item2) => (item1.Rules.MatchPriority != MatchPriority.Preselect).CompareTo(item2.Rules.MatchPriority != MatchPriority.Preselect); private static int CompareExpandedItem(CompletionItem item1, PatternMatch match1, CompletionItem item2, PatternMatch match2) { var isItem1Expanded = item1.Flags.IsExpanded(); var isItem2Expanded = item2.Flags.IsExpanded(); // Consider them equal if both items are of the same kind (i.e. both expanded or non-expanded) if (isItem1Expanded == isItem2Expanded) { return 0; } // Now we have two items of different kind. // If neither item is exact match, we always prefer non-expanded one. // For example, `NS2.MyTask` would be selected over `NS1.Tasks` // // namespace NS1 // { // class Tasks {} // } // namespace NS2 // { // class MyTask {} // class C // { // task$$ // } // } if (match1.Kind != PatternMatchKind.Exact && match2.Kind != PatternMatchKind.Exact) { return isItem1Expanded ? 1 : -1; } // Now we have two items of different kind and at least one is exact match. // Prefer non-expanded item if it is prefix match or better. // In the scenarios below, `NS2.Designer` would be selected over `System.Security.Cryptography.DES` // // namespace System.Security.Cryptography // { // class DES {} // } // namespace NS2 // { // class Designer {} // class C // { // des$$ // } // } if (!isItem1Expanded && match1.Kind <= PatternMatchKind.Prefix) { return -1; } if (!isItem2Expanded && match2.Kind <= PatternMatchKind.Prefix) { return 1; } // Now we are left with an expanded item with exact match and a non-expanded item with worse than prefix match. // Prefer non-expanded item with exact match. Debug.Assert(isItem1Expanded && match1.Kind == PatternMatchKind.Exact && !isItem2Expanded && match2.Kind > PatternMatchKind.Prefix || isItem2Expanded && match2.Kind == PatternMatchKind.Exact && !isItem1Expanded && match1.Kind > PatternMatchKind.Prefix); return isItem1Expanded ? -1 : 1; } public static string ConcatNamespace(string? containingNamespace, string name) => string.IsNullOrEmpty(containingNamespace) ? name : containingNamespace + "." + name; internal static bool TryCreateMatchResult<T>( CompletionHelper completionHelper, CompletionItem item, T editorCompletionItem, string filterText, CompletionTriggerKind initialTriggerKind, CompletionFilterReason filterReason, ImmutableArray<string> recentItems, bool includeMatchSpans, int currentIndex, out MatchResult<T> matchResult) { // Get the match of the given completion item for the pattern provided so far. // A completion item is checked against the pattern by see if it's // CompletionItem.FilterText matches the item. That way, the pattern it checked // against terms like "IList" and not IList<>. // Note that the check on filter text length is purely for efficiency, we should // get the same result with or without it. var patternMatch = filterText.Length > 0 ? completionHelper.GetMatch(item.FilterText, filterText, includeMatchSpans, CultureInfo.CurrentCulture) : null; var matchedFilterText = MatchesFilterText( item, filterText, initialTriggerKind, filterReason, recentItems, patternMatch); if (matchedFilterText || KeepAllItemsInTheList(initialTriggerKind, filterText)) { matchResult = new MatchResult<T>( item, editorCompletionItem, matchedFilterText: matchedFilterText, patternMatch: patternMatch, currentIndex); return true; } matchResult = default; return false; static bool MatchesFilterText( CompletionItem item, string filterText, CompletionTriggerKind initialTriggerKind, CompletionFilterReason filterReason, ImmutableArray<string> recentItems, PatternMatch? patternMatch) { // For the deletion we bake in the core logic for how matching should work. // This way deletion feels the same across all languages that opt into deletion // as a completion trigger. // Specifically, to avoid being too aggressive when matching an item during // completion, we require that the current filter text be a prefix of the // item in the list. if (filterReason == CompletionFilterReason.Deletion && initialTriggerKind == CompletionTriggerKind.Deletion) { return item.FilterText.GetCaseInsensitivePrefixLength(filterText) > 0; } // If the user hasn't typed anything, and this item was preselected, or was in the // MRU list, then we definitely want to include it. if (filterText.Length == 0) { if (item.Rules.MatchPriority > MatchPriority.Default) { return true; } if (!recentItems.IsDefault && GetRecentItemIndex(recentItems, item) <= 0) { return true; } } // Otherwise, the item matches filter text if a pattern match is returned. return patternMatch != null; } static int GetRecentItemIndex(ImmutableArray<string> recentItems, CompletionItem item) { var index = recentItems.IndexOf(item.FilterText); return -index; } // If the item didn't match the filter text, we still keep it in the list // if one of two things is true: // 1. The user has typed nothing or only typed a single character. In this case they might // have just typed the character to get completion. Filtering out items // here is not desirable. // // 2. They brought up completion with ctrl-j or through deletion. In these // cases we just always keep all the items in the list. static bool KeepAllItemsInTheList(CompletionTriggerKind initialTriggerKind, string filterText) { return filterText.Length <= 1 || initialTriggerKind == CompletionTriggerKind.Invoke || initialTriggerKind == CompletionTriggerKind.Deletion; } } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion { internal sealed class CompletionHelper { private readonly object _gate = new(); private readonly Dictionary<(string pattern, CultureInfo, bool includeMatchedSpans), PatternMatcher> _patternMatcherMap = new(); private static readonly CultureInfo EnUSCultureInfo = new("en-US"); private readonly bool _isCaseSensitive; public CompletionHelper(bool isCaseSensitive) => _isCaseSensitive = isCaseSensitive; public static CompletionHelper GetHelper(Document document) { return document.Project.Solution.Workspace.Services.GetRequiredService<ICompletionHelperService>() .GetCompletionHelper(document); } public ImmutableArray<TextSpan> GetHighlightedSpans( string text, string pattern, CultureInfo culture) { var match = GetMatch(text, pattern, includeMatchSpans: true, culture: culture); return match == null ? ImmutableArray<TextSpan>.Empty : match.Value.MatchedSpans; } /// <summary> /// Returns true if the completion item matches the pattern so far. Returns 'true' /// if and only if the completion item matches and should be included in the filtered completion /// results, or false if it should not be. /// </summary> public bool MatchesPattern(string text, string pattern, CultureInfo culture) => GetMatch(text, pattern, includeMatchSpans: false, culture) != null; public PatternMatch? GetMatch( string completionItemText, string pattern, bool includeMatchSpans, CultureInfo culture) { // If the item has a dot in it (i.e. for something like enum completion), then attempt // to match what the user wrote against the last portion of the name. That way if they // write "Bl" and we have "Blub" and "Color.Black", we'll consider the latter to be a // better match as they'll both be prefix matches, and the latter will have a higher // priority. var lastDotIndex = completionItemText.LastIndexOf('.'); if (lastDotIndex >= 0) { var afterDotPosition = lastDotIndex + 1; var textAfterLastDot = completionItemText[afterDotPosition..]; var match = GetMatchWorker(textAfterLastDot, pattern, culture, includeMatchSpans); if (match != null) { return AdjustMatchedSpans(match.Value, afterDotPosition); } } // Didn't have a dot, or the user text didn't match the portion after the dot. // Just do a normal check against the entire completion item. return GetMatchWorker(completionItemText, pattern, culture, includeMatchSpans); } private static PatternMatch? AdjustMatchedSpans(PatternMatch value, int offset) => value.MatchedSpans.IsDefaultOrEmpty ? value : value.WithMatchedSpans(value.MatchedSpans.SelectAsArray(s => new TextSpan(s.Start + offset, s.Length))); private PatternMatch? GetMatchWorker( string completionItemText, string pattern, CultureInfo culture, bool includeMatchSpans) { var patternMatcher = GetPatternMatcher(pattern, culture, includeMatchSpans); var match = patternMatcher.GetFirstMatch(completionItemText); // We still have making checks for language having different to English capitalization, // for example, for Turkish with dotted and dotless i capitalization totally diferent from English. // Now we escaping from the second check for English languages. // Maybe we can escape as well for more similar languages in case if we meet performance issues. if (culture.ThreeLetterWindowsLanguageName.Equals(EnUSCultureInfo.ThreeLetterWindowsLanguageName)) { return match; } // Keywords in .NET are always in En-US. // Identifiers can be in user language. // Try to get matches for both and return the best of them. patternMatcher = GetPatternMatcher(pattern, EnUSCultureInfo, includeMatchSpans); var enUSCultureMatch = patternMatcher.GetFirstMatch(completionItemText); if (match == null) { return enUSCultureMatch; } if (enUSCultureMatch == null) { return match; } return match.Value.CompareTo(enUSCultureMatch.Value) < 0 ? match.Value : enUSCultureMatch.Value; } private PatternMatcher GetPatternMatcher( string pattern, CultureInfo culture, bool includeMatchedSpans, Dictionary<(string, CultureInfo, bool), PatternMatcher> map) { lock (_gate) { var key = (pattern, culture, includeMatchedSpans); if (!map.TryGetValue(key, out var patternMatcher)) { patternMatcher = PatternMatcher.CreatePatternMatcher( pattern, culture, includeMatchedSpans, allowFuzzyMatching: false); map.Add(key, patternMatcher); } return patternMatcher; } } private PatternMatcher GetPatternMatcher(string pattern, CultureInfo culture, bool includeMatchedSpans) => GetPatternMatcher(pattern, culture, includeMatchedSpans, _patternMatcherMap); /// <summary> /// Returns true if item1 is a better completion item than item2 given the provided filter /// text, or false if it is not better. /// </summary> public int CompareItems(CompletionItem item1, CompletionItem item2, string pattern, CultureInfo culture) { var match1 = GetMatch(item1.FilterText, pattern, includeMatchSpans: false, culture); var match2 = GetMatch(item2.FilterText, pattern, includeMatchSpans: false, culture); return CompareItems(item1, match1, item2, match2, out _); } public int CompareItems(CompletionItem item1, PatternMatch? match1, CompletionItem item2, PatternMatch? match2, out bool onlyDifferInCaseSensitivity) { onlyDifferInCaseSensitivity = false; if (match1 != null && match2 != null) { var result = CompareMatches(match1.Value, match2.Value, item1, item2, out onlyDifferInCaseSensitivity); if (result != 0) { return result; } Debug.Assert(!onlyDifferInCaseSensitivity); } else if (match1 != null) { return -1; } else if (match2 != null) { return 1; } var preselectionDiff = ComparePreselection(item1, item2); if (preselectionDiff != 0) { return preselectionDiff; } // Prefer things with a keyword tag, if the filter texts are the same. if (!TagsEqual(item1, item2) && item1.FilterText == item2.FilterText) { return (!IsKeywordItem(item1)).CompareTo(!IsKeywordItem(item2)); } return 0; } private static bool TagsEqual(CompletionItem item1, CompletionItem item2) => TagsEqual(item1.Tags, item2.Tags); private static bool TagsEqual(ImmutableArray<string> tags1, ImmutableArray<string> tags2) => tags1 == tags2 || System.Linq.Enumerable.SequenceEqual(tags1, tags2); private static bool IsKeywordItem(CompletionItem item) => item.Tags.Contains(WellKnownTags.Keyword); private int CompareMatches( PatternMatch match1, PatternMatch match2, CompletionItem item1, CompletionItem item2, out bool onlyDifferInCaseSensitivity) { onlyDifferInCaseSensitivity = false; // *Almost* always prefer non-expanded item regardless of the pattern matching result. // Except when all non-expanded items are worse than prefix matching and there's // a complete match from expanded ones. // // For example, In the scenarios below, `NS2.Designer` would be selected over `System.Security.Cryptography.DES` // // namespace System.Security.Cryptography // { // class DES {} // } // namespace NS2 // { // class Designer {} // class C // { // des$$ // } // } // // But in this case, `System.Security.Cryptography.DES` would be selected over `NS2.MyDesigner` // // namespace System.Security.Cryptography // { // class DES {} // } // namespace NS2 // { // class MyDesigner {} // class C // { // des$$ // } // } // // This currently means items from unimported namespaces (those are the only expanded items now) // are treated as "2nd tier" results, which forces users to be more explicit about selecting them. var expandedDiff = CompareExpandedItem(item1, match1, item2, match2); if (expandedDiff != 0) { return expandedDiff; } // Then see how the two items compare in a case insensitive fashion. Matches that // are strictly better (ignoring case) should prioritize the item. i.e. if we have // a prefix match, that should always be better than a substring match. // // The reason we ignore case is that it's very common for people to type expecting // completion to fix up their casing. i.e. 'false' will be written with the // expectation that it will get fixed by the completion list to 'False'. var diff = match1.CompareTo(match2, ignoreCase: true); if (diff != 0) { return diff; } // If two items match in case-insensitive manner, and we are in a case-insensitive language, // then the preselected one is considered better, otherwise we will prefer the one matches // case-sensitively. This is to make sure common items in VB like `True` and `False` are prioritized // for selection when user types `t` and `f`. // More details can be found in comments of https://github.com/dotnet/roslyn/issues/4892 if (!_isCaseSensitive) { var preselectionDiff = ComparePreselection(item1, item2); if (preselectionDiff != 0) { return preselectionDiff; } } // At this point we have two items which we're matching in a rather similar fashion. // If one is a prefix of the other, prefer the prefix. i.e. if we have // "Table" and "table:=" and the user types 't' and we are in a case insensitive // language, then we prefer the former. if (item1.GetEntireDisplayText().Length != item2.GetEntireDisplayText().Length) { var comparison = _isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; if (item2.GetEntireDisplayText().StartsWith(item1.GetEntireDisplayText(), comparison)) { return -1; } else if (item1.GetEntireDisplayText().StartsWith(item2.GetEntireDisplayText(), comparison)) { return 1; } } // Now compare the matches again in a case sensitive manner. If everything was // equal up to this point, we prefer the item that better matches based on case. diff = match1.CompareTo(match2, ignoreCase: false); onlyDifferInCaseSensitivity = diff != 0; return diff; } // If they both seemed just as good, but they differ on preselection, then // item1 is better if it is preselected, otherwise it is worse. private static int ComparePreselection(CompletionItem item1, CompletionItem item2) => (item1.Rules.MatchPriority != MatchPriority.Preselect).CompareTo(item2.Rules.MatchPriority != MatchPriority.Preselect); private static int CompareExpandedItem(CompletionItem item1, PatternMatch match1, CompletionItem item2, PatternMatch match2) { var isItem1Expanded = item1.Flags.IsExpanded(); var isItem2Expanded = item2.Flags.IsExpanded(); // Consider them equal if both items are of the same kind (i.e. both expanded or non-expanded) if (isItem1Expanded == isItem2Expanded) { return 0; } // Now we have two items of different kind. // If neither item is exact match, we always prefer non-expanded one. // For example, `NS2.MyTask` would be selected over `NS1.Tasks` // // namespace NS1 // { // class Tasks {} // } // namespace NS2 // { // class MyTask {} // class C // { // task$$ // } // } if (match1.Kind != PatternMatchKind.Exact && match2.Kind != PatternMatchKind.Exact) { return isItem1Expanded ? 1 : -1; } // Now we have two items of different kind and at least one is exact match. // Prefer non-expanded item if it is prefix match or better. // In the scenarios below, `NS2.Designer` would be selected over `System.Security.Cryptography.DES` // // namespace System.Security.Cryptography // { // class DES {} // } // namespace NS2 // { // class Designer {} // class C // { // des$$ // } // } if (!isItem1Expanded && match1.Kind <= PatternMatchKind.Prefix) { return -1; } if (!isItem2Expanded && match2.Kind <= PatternMatchKind.Prefix) { return 1; } // Now we are left with an expanded item with exact match and a non-expanded item with worse than prefix match. // Prefer non-expanded item with exact match. Debug.Assert(isItem1Expanded && match1.Kind == PatternMatchKind.Exact && !isItem2Expanded && match2.Kind > PatternMatchKind.Prefix || isItem2Expanded && match2.Kind == PatternMatchKind.Exact && !isItem1Expanded && match1.Kind > PatternMatchKind.Prefix); return isItem1Expanded ? -1 : 1; } public static string ConcatNamespace(string? containingNamespace, string name) => string.IsNullOrEmpty(containingNamespace) ? name : containingNamespace + "." + name; internal static bool TryCreateMatchResult<T>( CompletionHelper completionHelper, CompletionItem item, T editorCompletionItem, string filterText, CompletionTriggerKind initialTriggerKind, CompletionFilterReason filterReason, ImmutableArray<string> recentItems, bool includeMatchSpans, int currentIndex, out MatchResult<T> matchResult) { // Get the match of the given completion item for the pattern provided so far. // A completion item is checked against the pattern by see if it's // CompletionItem.FilterText matches the item. That way, the pattern it checked // against terms like "IList" and not IList<>. // Note that the check on filter text length is purely for efficiency, we should // get the same result with or without it. var patternMatch = filterText.Length > 0 ? completionHelper.GetMatch(item.FilterText, filterText, includeMatchSpans, CultureInfo.CurrentCulture) : null; var matchedFilterText = MatchesFilterText( item, filterText, initialTriggerKind, filterReason, recentItems, patternMatch); if (matchedFilterText || KeepAllItemsInTheList(initialTriggerKind, filterText)) { matchResult = new MatchResult<T>( item, editorCompletionItem, matchedFilterText: matchedFilterText, patternMatch: patternMatch, currentIndex); return true; } matchResult = default; return false; static bool MatchesFilterText( CompletionItem item, string filterText, CompletionTriggerKind initialTriggerKind, CompletionFilterReason filterReason, ImmutableArray<string> recentItems, PatternMatch? patternMatch) { // For the deletion we bake in the core logic for how matching should work. // This way deletion feels the same across all languages that opt into deletion // as a completion trigger. // Specifically, to avoid being too aggressive when matching an item during // completion, we require that the current filter text be a prefix of the // item in the list. if (filterReason == CompletionFilterReason.Deletion && initialTriggerKind == CompletionTriggerKind.Deletion) { return item.FilterText.GetCaseInsensitivePrefixLength(filterText) > 0; } // If the user hasn't typed anything, and this item was preselected, or was in the // MRU list, then we definitely want to include it. if (filterText.Length == 0) { if (item.Rules.MatchPriority > MatchPriority.Default) { return true; } if (!recentItems.IsDefault && GetRecentItemIndex(recentItems, item) <= 0) { return true; } } // Otherwise, the item matches filter text if a pattern match is returned. return patternMatch != null; } static int GetRecentItemIndex(ImmutableArray<string> recentItems, CompletionItem item) { var index = recentItems.IndexOf(item.FilterText); return -index; } // If the item didn't match the filter text, we still keep it in the list // if one of two things is true: // 1. The user has typed nothing or only typed a single character. In this case they might // have just typed the character to get completion. Filtering out items // here is not desirable. // // 2. They brought up completion with ctrl-j or through deletion. In these // cases we just always keep all the items in the list. static bool KeepAllItemsInTheList(CompletionTriggerKind initialTriggerKind, string filterText) { return filterText.Length <= 1 || initialTriggerKind == CompletionTriggerKind.Invoke || initialTriggerKind == CompletionTriggerKind.Deletion; } } } }
1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/Core/Portable/Completion/CompletionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// A per language service for constructing context dependent list of completions that /// can be presented to a user during typing in an editor. /// </summary> public abstract class CompletionService : ILanguageService { /// <summary> /// Gets the service corresponding to the specified document. /// </summary> public static CompletionService GetService(Document document) => document?.GetLanguageService<CompletionService>(); /// <summary> /// The language from <see cref="LanguageNames"/> this service corresponds to. /// </summary> public abstract string Language { get; } /// <summary> /// Gets the current presentation and behavior rules. /// </summary> public virtual CompletionRules GetRules() => CompletionRules.Default; /// <summary> /// Returns true if the character recently inserted or deleted in the text should trigger completion. /// </summary> /// <param name="text">The document text to trigger completion within </param> /// <param name="caretPosition">The position of the caret after the triggering action.</param> /// <param name="trigger">The potential triggering action.</param> /// <param name="roles">Optional set of roles associated with the editor state.</param> /// <param name="options">Optional options that override the default options.</param> /// <remarks> /// This API uses SourceText instead of Document so implementations can only be based on text, not syntax or semantics. /// </remarks> public virtual bool ShouldTriggerCompletion( SourceText text, int caretPosition, CompletionTrigger trigger, ImmutableHashSet<string> roles = null, OptionSet options = null) { return false; } /// <summary> /// Returns true if the character recently inserted or deleted in the text should trigger completion. /// </summary> /// <param name="project">The project containing the document and text</param> /// <param name="text">The document text to trigger completion within </param> /// <param name="caretPosition">The position of the caret after the triggering action.</param> /// <param name="trigger">The potential triggering action.</param> /// <param name="roles">Optional set of roles associated with the editor state.</param> /// <param name="options">Optional options that override the default options.</param> /// <remarks> /// We pass the project here to retrieve information about the <see cref="Project.AnalyzerReferences"/>, /// <see cref="WorkspaceKind"/> and <see cref="Project.Language"/> which are fast operations. /// It should not be used for syntactic or semantic operations. /// </remarks> internal virtual bool ShouldTriggerCompletion( Project project, SourceText text, int caretPosition, CompletionTrigger trigger, ImmutableHashSet<string> roles = null, OptionSet options = null) { return ShouldTriggerCompletion(text, caretPosition, trigger, roles, options); } /// <summary> /// Gets the span of the syntax element at the caret position. /// This is the most common value used for <see cref="CompletionItem.Span"/>. /// </summary> /// <param name="text">The document text that completion is occurring within.</param> /// <param name="caretPosition">The position of the caret within the text.</param> [Obsolete("Not used anymore. CompletionService.GetDefaultCompletionListSpan is used instead.", error: true)] public virtual TextSpan GetDefaultItemSpan(SourceText text, int caretPosition) => GetDefaultCompletionListSpan(text, caretPosition); public virtual TextSpan GetDefaultCompletionListSpan(SourceText text, int caretPosition) { return CommonCompletionUtilities.GetWordSpan( text, caretPosition, c => char.IsLetter(c), c => char.IsLetterOrDigit(c)); } /// <summary> /// Gets the completions available at the caret position. /// </summary> /// <param name="document">The document that completion is occurring within.</param> /// <param name="caretPosition">The position of the caret after the triggering action.</param> /// <param name="trigger">The triggering action.</param> /// <param name="roles">Optional set of roles associated with the editor state.</param> /// <param name="options">Optional options that override the default options.</param> /// <param name="cancellationToken"></param> public abstract Task<CompletionList> GetCompletionsAsync( Document document, int caretPosition, CompletionTrigger trigger = default, ImmutableHashSet<string> roles = null, OptionSet options = null, CancellationToken cancellationToken = default); /// <summary> /// Gets the completions available at the caret position, with additional info indicates /// whether expander items are available. /// </summary> /// <remarks> /// expandItemsAvailable is true when expanded items are returned or can be provided upon request. /// </remarks> internal virtual async Task<(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsInternalAsync( Document document, int caretPosition, CompletionTrigger trigger = default, ImmutableHashSet<string> roles = null, OptionSet options = null, CancellationToken cancellationToken = default) { var completionList = await GetCompletionsAsync(document, caretPosition, trigger, roles, options, cancellationToken).ConfigureAwait(false); return (completionList, false); } /// <summary> /// Gets the description of the item. /// </summary> /// <param name="document">This will be the original document that /// <paramref name="item"/> was created against.</param> /// <param name="item">The item to get the description for.</param> /// <param name="cancellationToken"></param> public virtual Task<CompletionDescription> GetDescriptionAsync( Document document, CompletionItem item, CancellationToken cancellationToken = default) { return Task.FromResult(CompletionDescription.Empty); } /// <summary> /// Gets the change to be applied when the item is committed. /// </summary> /// <param name="document">The document that completion is occurring within.</param> /// <param name="item">The item to get the change for.</param> /// <param name="commitCharacter">The typed character that caused the item to be committed. /// This character may be used as part of the change. /// This value is null when the commit was caused by the [TAB] or [ENTER] keys.</param> /// <param name="cancellationToken"></param> public virtual Task<CompletionChange> GetChangeAsync( Document document, CompletionItem item, char? commitCharacter = null, CancellationToken cancellationToken = default) { return Task.FromResult(CompletionChange.Create(new TextChange(item.Span, item.DisplayText))); } /// <summary> /// Given a list of completion items that match the current code typed by the user, /// returns the item that is considered the best match, and whether or not that /// item should be selected or not. /// /// itemToFilterText provides the values that each individual completion item should /// be filtered against. /// </summary> public virtual ImmutableArray<CompletionItem> FilterItems( Document document, ImmutableArray<CompletionItem> items, string filterText) { var helper = CompletionHelper.GetHelper(document); return FilterItems(helper, items, filterText); } internal virtual ImmutableArray<CompletionItem> FilterItems( Document document, ImmutableArray<(CompletionItem, PatternMatch?)> itemsWithPatternMatch, string filterText) { // Default implementation just drops the pattern matches and // calls the public overload of FilterItems for compatibility. return FilterItems(document, itemsWithPatternMatch.SelectAsArray(item => item.Item1), filterText); } internal static ImmutableArray<CompletionItem> FilterItems( CompletionHelper completionHelper, ImmutableArray<CompletionItem> items, string filterText) { var itemsWithPatternMatch = items.SelectAsArray( item => (item, completionHelper.GetMatch(item.FilterText, filterText, includeMatchSpans: false, CultureInfo.CurrentCulture))); return FilterItems(completionHelper, itemsWithPatternMatch); } internal static ImmutableArray<CompletionItem> FilterItems( CompletionHelper completionHelper, ImmutableArray<(CompletionItem item, PatternMatch? match)> itemsWithPatternMatch) { var bestItems = ArrayBuilder<(CompletionItem, PatternMatch?)>.GetInstance(); foreach (var pair in itemsWithPatternMatch) { if (bestItems.Count == 0) { // We've found no good items yet. So this is the best item currently. bestItems.Add(pair); } else { var (bestItem, bestItemMatch) = bestItems.First(); var comparison = completionHelper.CompareItems(pair.item, pair.match, bestItem, bestItemMatch); if (comparison < 0) { // This item is strictly better than the best items we've found so far. bestItems.Clear(); bestItems.Add(pair); } else if (comparison == 0) { // This item is as good as the items we've been collecting. We'll return // it and let the controller decide what to do. (For example, it will // pick the one that has the best MRU index). bestItems.Add(pair); } // otherwise, this item is strictly worse than the ones we've been collecting. // We can just ignore it. } } return bestItems.ToImmutableAndFree().SelectAsArray(itemWithPatternMatch => itemWithPatternMatch.Item1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// A per language service for constructing context dependent list of completions that /// can be presented to a user during typing in an editor. /// </summary> public abstract class CompletionService : ILanguageService { /// <summary> /// Gets the service corresponding to the specified document. /// </summary> public static CompletionService GetService(Document document) => document?.GetLanguageService<CompletionService>(); /// <summary> /// The language from <see cref="LanguageNames"/> this service corresponds to. /// </summary> public abstract string Language { get; } /// <summary> /// Gets the current presentation and behavior rules. /// </summary> public virtual CompletionRules GetRules() => CompletionRules.Default; /// <summary> /// Returns true if the character recently inserted or deleted in the text should trigger completion. /// </summary> /// <param name="text">The document text to trigger completion within </param> /// <param name="caretPosition">The position of the caret after the triggering action.</param> /// <param name="trigger">The potential triggering action.</param> /// <param name="roles">Optional set of roles associated with the editor state.</param> /// <param name="options">Optional options that override the default options.</param> /// <remarks> /// This API uses SourceText instead of Document so implementations can only be based on text, not syntax or semantics. /// </remarks> public virtual bool ShouldTriggerCompletion( SourceText text, int caretPosition, CompletionTrigger trigger, ImmutableHashSet<string> roles = null, OptionSet options = null) { return false; } /// <summary> /// Returns true if the character recently inserted or deleted in the text should trigger completion. /// </summary> /// <param name="project">The project containing the document and text</param> /// <param name="text">The document text to trigger completion within </param> /// <param name="caretPosition">The position of the caret after the triggering action.</param> /// <param name="trigger">The potential triggering action.</param> /// <param name="roles">Optional set of roles associated with the editor state.</param> /// <param name="options">Optional options that override the default options.</param> /// <remarks> /// We pass the project here to retrieve information about the <see cref="Project.AnalyzerReferences"/>, /// <see cref="WorkspaceKind"/> and <see cref="Project.Language"/> which are fast operations. /// It should not be used for syntactic or semantic operations. /// </remarks> internal virtual bool ShouldTriggerCompletion( Project project, SourceText text, int caretPosition, CompletionTrigger trigger, ImmutableHashSet<string> roles = null, OptionSet options = null) { return ShouldTriggerCompletion(text, caretPosition, trigger, roles, options); } /// <summary> /// Gets the span of the syntax element at the caret position. /// This is the most common value used for <see cref="CompletionItem.Span"/>. /// </summary> /// <param name="text">The document text that completion is occurring within.</param> /// <param name="caretPosition">The position of the caret within the text.</param> [Obsolete("Not used anymore. CompletionService.GetDefaultCompletionListSpan is used instead.", error: true)] public virtual TextSpan GetDefaultItemSpan(SourceText text, int caretPosition) => GetDefaultCompletionListSpan(text, caretPosition); public virtual TextSpan GetDefaultCompletionListSpan(SourceText text, int caretPosition) { return CommonCompletionUtilities.GetWordSpan( text, caretPosition, c => char.IsLetter(c), c => char.IsLetterOrDigit(c)); } /// <summary> /// Gets the completions available at the caret position. /// </summary> /// <param name="document">The document that completion is occurring within.</param> /// <param name="caretPosition">The position of the caret after the triggering action.</param> /// <param name="trigger">The triggering action.</param> /// <param name="roles">Optional set of roles associated with the editor state.</param> /// <param name="options">Optional options that override the default options.</param> /// <param name="cancellationToken"></param> public abstract Task<CompletionList> GetCompletionsAsync( Document document, int caretPosition, CompletionTrigger trigger = default, ImmutableHashSet<string> roles = null, OptionSet options = null, CancellationToken cancellationToken = default); /// <summary> /// Gets the completions available at the caret position, with additional info indicates /// whether expander items are available. /// </summary> /// <remarks> /// expandItemsAvailable is true when expanded items are returned or can be provided upon request. /// </remarks> internal virtual async Task<(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsInternalAsync( Document document, int caretPosition, CompletionTrigger trigger = default, ImmutableHashSet<string> roles = null, OptionSet options = null, CancellationToken cancellationToken = default) { var completionList = await GetCompletionsAsync(document, caretPosition, trigger, roles, options, cancellationToken).ConfigureAwait(false); return (completionList, false); } /// <summary> /// Gets the description of the item. /// </summary> /// <param name="document">This will be the original document that /// <paramref name="item"/> was created against.</param> /// <param name="item">The item to get the description for.</param> /// <param name="cancellationToken"></param> public virtual Task<CompletionDescription> GetDescriptionAsync( Document document, CompletionItem item, CancellationToken cancellationToken = default) { return Task.FromResult(CompletionDescription.Empty); } /// <summary> /// Gets the change to be applied when the item is committed. /// </summary> /// <param name="document">The document that completion is occurring within.</param> /// <param name="item">The item to get the change for.</param> /// <param name="commitCharacter">The typed character that caused the item to be committed. /// This character may be used as part of the change. /// This value is null when the commit was caused by the [TAB] or [ENTER] keys.</param> /// <param name="cancellationToken"></param> public virtual Task<CompletionChange> GetChangeAsync( Document document, CompletionItem item, char? commitCharacter = null, CancellationToken cancellationToken = default) { return Task.FromResult(CompletionChange.Create(new TextChange(item.Span, item.DisplayText))); } /// <summary> /// Given a list of completion items that match the current code typed by the user, /// returns the item that is considered the best match, and whether or not that /// item should be selected or not. /// /// itemToFilterText provides the values that each individual completion item should /// be filtered against. /// </summary> public virtual ImmutableArray<CompletionItem> FilterItems( Document document, ImmutableArray<CompletionItem> items, string filterText) { var helper = CompletionHelper.GetHelper(document); return FilterItems(helper, items, filterText); } internal virtual ImmutableArray<CompletionItem> FilterItems( Document document, ImmutableArray<(CompletionItem, PatternMatch?)> itemsWithPatternMatch, string filterText) { // Default implementation just drops the pattern matches and // calls the public overload of FilterItems for compatibility. return FilterItems(document, itemsWithPatternMatch.SelectAsArray(item => item.Item1), filterText); } internal static ImmutableArray<CompletionItem> FilterItems( CompletionHelper completionHelper, ImmutableArray<CompletionItem> items, string filterText) { var itemsWithPatternMatch = items.SelectAsArray( item => (item, completionHelper.GetMatch(item.FilterText, filterText, includeMatchSpans: false, CultureInfo.CurrentCulture))); return FilterItems(completionHelper, itemsWithPatternMatch, filterText); } /// <summary> /// Determine among the provided items the best match w.r.t. the given filter text, /// those returned would be considered equally good candidates for selection by controller. /// </summary> internal static ImmutableArray<CompletionItem> FilterItems( CompletionHelper completionHelper, ImmutableArray<(CompletionItem item, PatternMatch? match)> itemsWithPatternMatch, string filterText) { // It's very common for people to type expecting completion to fix up their casing, // so if no uppercase characters were typed so far, we'd loosen our standard on comparing items // in case-sensitive manner and take into consideration the MatchPriority as well. // i.e. when everything else is equal, then if item1 is a better case-sensitive match but item2 has higher // MatchPriority, we consider them equally good match, so the controller will later have a chance to // decide which is the best one to select. var filterTextContainsNoUpperLetters = true; for (var i = 0; i < filterText.Length; ++i) { if (char.IsUpper(filterText[i])) { filterTextContainsNoUpperLetters = false; break; } } // Keep track the highest MatchPriority of all items in the best list. var highestMatchPriorityInBest = int.MinValue; using var _1 = ArrayBuilder<(CompletionItem item, PatternMatch? match)>.GetInstance(out var bestItems); // This contains a list of items that are considered equally good match as bestItems except casing, // and they have higher MatchPriority than the ones in bestItems (although as a perf optimization we don't // actually guarantee this during the process, instead we check the MatchPriority again after the loop.) using var _2 = ArrayBuilder<(CompletionItem item, PatternMatch? match)>.GetInstance(out var itemsWithCasingMismatchButHigherMatchPriority); foreach (var pair in itemsWithPatternMatch) { if (bestItems.Count == 0) { // We've found no good items yet. So this is the best item currently. bestItems.Add(pair); highestMatchPriorityInBest = pair.item.Rules.MatchPriority; continue; } var (bestItem, bestItemMatch) = bestItems.First(); var comparison = completionHelper.CompareItems( pair.item, pair.match, bestItem, bestItemMatch, out var onlyDifferInCaseSensitivity); if (comparison == 0) { // This item is as good as the items we've been collecting. We'll return it and let the controller // decide what to do. (For example, it will pick the one that has the best MRU index). // Also there's no need to remove items with lower MatchPriority from similarItemsWithHigerMatchPriority // list, we will only add ones with higher value at the end. bestItems.Add(pair); highestMatchPriorityInBest = Math.Max(highestMatchPriorityInBest, pair.item.Rules.MatchPriority); } else if (comparison < 0) { // This item is strictly better than the best items we've found so far. // However, if it's only better in terms of case-sensitivity, we'd like // to save the prior best items and consider their MatchPriority later. itemsWithCasingMismatchButHigherMatchPriority.Clear(); if (filterTextContainsNoUpperLetters && onlyDifferInCaseSensitivity && highestMatchPriorityInBest > pair.item.Rules.MatchPriority) // don't add if this item has higher MatchPriority than all prior best items { itemsWithCasingMismatchButHigherMatchPriority.AddRange(bestItems); } bestItems.Clear(); bestItems.Add(pair); highestMatchPriorityInBest = pair.item.Rules.MatchPriority; } else { // otherwise, this item is strictly worse than the ones we've been collecting. // However, if it's only worse in terms of case-sensitivity, we'd like // to save it and consider its MatchPriority later. if (filterTextContainsNoUpperLetters && onlyDifferInCaseSensitivity && pair.item.Rules.MatchPriority > highestMatchPriorityInBest) // don't add if this item doesn't have higher MatchPriority { itemsWithCasingMismatchButHigherMatchPriority.Add(pair); } } } // Include those similar items (only worse in terms of case-sensitivity) that have better MatchPriority. foreach (var pair in itemsWithCasingMismatchButHigherMatchPriority) { if (pair.item.Rules.MatchPriority > highestMatchPriorityInBest) { bestItems.Add(pair); } } return bestItems.ToImmutable().SelectAsArray(itemWithPatternMatch => itemWithPatternMatch.item); } } }
1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/TypedConstantTests.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 Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Public Class TypedConstantTests Inherits BasicTestBase Private ReadOnly _compilation As VisualBasicCompilation Private ReadOnly _namedType As NamedTypeSymbol Private ReadOnly _systemType As NamedTypeSymbol Private ReadOnly _arrayType As ArrayTypeSymbol Public Sub New() _compilation = VisualBasicCompilation.Create("goo") _namedType = _compilation.GetSpecialType(SpecialType.System_Byte) _systemType = _compilation.GetWellKnownType(WellKnownType.System_Type) _arrayType = _compilation.CreateArrayTypeSymbol(_compilation.GetSpecialType(SpecialType.System_Object)) End Sub <Fact()> Public Sub Conversions() Dim common As TypedConstant = New TypedConstant(_systemType, TypedConstantKind.Type, _namedType) Dim lang As TypedConstant = CType(common, TypedConstant) Dim common2 As TypedConstant = lang Assert.Equal(common.Value, lang.Value) Assert.Equal(common.Kind, lang.Kind) Assert.Equal(Of Object)(common.Type, lang.Type) Assert.Equal(common.Value, common2.Value) Assert.Equal(common.Kind, common2.Kind) Assert.Equal(common.Type, common2.Type) Dim commonArray As TypedConstant = New TypedConstant(_arrayType, {New TypedConstant(_systemType, TypedConstantKind.Type, _namedType)}.AsImmutableOrNull()) Dim langArray As TypedConstant = CType(commonArray, TypedConstant) Dim commonArray2 As TypedConstant = langArray Assert.Equal(commonArray.Values.Single(), langArray.Values.Single()) Assert.Equal(commonArray.Kind, langArray.Kind) Assert.Equal(Of Object)(commonArray.Type, langArray.Type) Assert.Equal(commonArray.Values, commonArray2.Values) Assert.Equal(commonArray.Kind, commonArray2.Kind) Assert.Equal(commonArray.Type, commonArray2.Type) Assert.Equal(common2, CType(lang, TypedConstant)) Assert.IsType(Of Microsoft.CodeAnalysis.TypedConstant)(common2) 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 Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Public Class TypedConstantTests Inherits BasicTestBase Private ReadOnly _compilation As VisualBasicCompilation Private ReadOnly _namedType As NamedTypeSymbol Private ReadOnly _systemType As NamedTypeSymbol Private ReadOnly _arrayType As ArrayTypeSymbol Public Sub New() _compilation = VisualBasicCompilation.Create("goo") _namedType = _compilation.GetSpecialType(SpecialType.System_Byte) _systemType = _compilation.GetWellKnownType(WellKnownType.System_Type) _arrayType = _compilation.CreateArrayTypeSymbol(_compilation.GetSpecialType(SpecialType.System_Object)) End Sub <Fact()> Public Sub Conversions() Dim common As TypedConstant = New TypedConstant(_systemType, TypedConstantKind.Type, _namedType) Dim lang As TypedConstant = CType(common, TypedConstant) Dim common2 As TypedConstant = lang Assert.Equal(common.Value, lang.Value) Assert.Equal(common.Kind, lang.Kind) Assert.Equal(Of Object)(common.Type, lang.Type) Assert.Equal(common.Value, common2.Value) Assert.Equal(common.Kind, common2.Kind) Assert.Equal(common.Type, common2.Type) Dim commonArray As TypedConstant = New TypedConstant(_arrayType, {New TypedConstant(_systemType, TypedConstantKind.Type, _namedType)}.AsImmutableOrNull()) Dim langArray As TypedConstant = CType(commonArray, TypedConstant) Dim commonArray2 As TypedConstant = langArray Assert.Equal(commonArray.Values.Single(), langArray.Values.Single()) Assert.Equal(commonArray.Kind, langArray.Kind) Assert.Equal(Of Object)(commonArray.Type, langArray.Type) Assert.Equal(commonArray.Values, commonArray2.Values) Assert.Equal(commonArray.Kind, commonArray2.Kind) Assert.Equal(commonArray.Type, commonArray2.Type) Assert.Equal(common2, CType(lang, TypedConstant)) Assert.IsType(Of Microsoft.CodeAnalysis.TypedConstant)(common2) End Sub End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/EditorFeatures/Core/Undo/IGlobalUndoService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; namespace Microsoft.CodeAnalysis.Editor.Undo { /// <summary> /// This provides a way to do global undo. but semantic of the global undo is defined by the workspace host. /// </summary> internal interface IGlobalUndoService : IWorkspaceService { /// <summary> /// Queries whether a global transaction is currently active. /// </summary> bool IsGlobalTransactionOpen(Workspace workspace); /// <summary> /// query method that can answer whether global undo is supported by the workspace /// </summary> bool CanUndo(Workspace workspace); /// <summary> /// open global undo transaction for the workspace /// </summary> IWorkspaceGlobalUndoTransaction OpenGlobalUndoTransaction(Workspace workspace, string description); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; namespace Microsoft.CodeAnalysis.Editor.Undo { /// <summary> /// This provides a way to do global undo. but semantic of the global undo is defined by the workspace host. /// </summary> internal interface IGlobalUndoService : IWorkspaceService { /// <summary> /// Queries whether a global transaction is currently active. /// </summary> bool IsGlobalTransactionOpen(Workspace workspace); /// <summary> /// query method that can answer whether global undo is supported by the workspace /// </summary> bool CanUndo(Workspace workspace); /// <summary> /// open global undo transaction for the workspace /// </summary> IWorkspaceGlobalUndoTransaction OpenGlobalUndoTransaction(Workspace workspace, string description); } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/CSharp/Portable/Symbols/PublicModel/ModuleSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class ModuleSymbol : Symbol, IModuleSymbol { private readonly Symbols.ModuleSymbol _underlying; public ModuleSymbol(Symbols.ModuleSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; INamespaceSymbol IModuleSymbol.GlobalNamespace { get { return _underlying.GlobalNamespace.GetPublicSymbol(); } } INamespaceSymbol IModuleSymbol.GetModuleNamespace(INamespaceSymbol namespaceSymbol) { return _underlying.GetModuleNamespace(namespaceSymbol).GetPublicSymbol(); } ImmutableArray<IAssemblySymbol> IModuleSymbol.ReferencedAssemblySymbols { get { return _underlying.ReferencedAssemblySymbols.GetPublicSymbols(); } } ImmutableArray<AssemblyIdentity> IModuleSymbol.ReferencedAssemblies => _underlying.ReferencedAssemblies; ModuleMetadata IModuleSymbol.GetMetadata() => _underlying.GetMetadata(); #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitModule(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitModule(this); } #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.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class ModuleSymbol : Symbol, IModuleSymbol { private readonly Symbols.ModuleSymbol _underlying; public ModuleSymbol(Symbols.ModuleSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; INamespaceSymbol IModuleSymbol.GlobalNamespace { get { return _underlying.GlobalNamespace.GetPublicSymbol(); } } INamespaceSymbol IModuleSymbol.GetModuleNamespace(INamespaceSymbol namespaceSymbol) { return _underlying.GetModuleNamespace(namespaceSymbol).GetPublicSymbol(); } ImmutableArray<IAssemblySymbol> IModuleSymbol.ReferencedAssemblySymbols { get { return _underlying.ReferencedAssemblySymbols.GetPublicSymbols(); } } ImmutableArray<AssemblyIdentity> IModuleSymbol.ReferencedAssemblies => _underlying.ReferencedAssemblies; ModuleMetadata IModuleSymbol.GetMetadata() => _underlying.GetMetadata(); #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitModule(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitModule(this); } #endregion } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/PersistentStorageOptionsProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Host { [ExportOptionProvider, Shared] internal class PersistentStorageOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PersistentStorageOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(PersistentStorageOptions.Enabled); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Host { [ExportOptionProvider, Shared] internal class PersistentStorageOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PersistentStorageOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(PersistentStorageOptions.Enabled); } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Workspaces/Core/Portable/CodeStyle/NotificationOption.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CodeStyle { /// <inheritdoc cref="NotificationOption2"/> public class NotificationOption { private readonly NotificationOption2 _notificationOptionImpl; /// <inheritdoc cref="NotificationOption2.Name"/> public string Name { get => _notificationOptionImpl.Name; set => _notificationOptionImpl.Name = value; } /// <inheritdoc cref="NotificationOption2.Severity"/> public ReportDiagnostic Severity { get => _notificationOptionImpl.Severity; set => _notificationOptionImpl.Severity = value; } [Obsolete("Use " + nameof(Severity) + " instead.")] public DiagnosticSeverity Value { get => Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden; set => Severity = value.ToReportDiagnostic(); } /// <inheritdoc cref="NotificationOption2.None"/> public static readonly NotificationOption None = new(NotificationOption2.None); /// <inheritdoc cref="NotificationOption2.Silent"/> public static readonly NotificationOption Silent = new(NotificationOption2.Silent); /// <inheritdoc cref="NotificationOption2.Suggestion"/> public static readonly NotificationOption Suggestion = new(NotificationOption2.Suggestion); /// <inheritdoc cref="NotificationOption2.Warning"/> public static readonly NotificationOption Warning = new(NotificationOption2.Warning); /// <inheritdoc cref="NotificationOption2.Error"/> public static readonly NotificationOption Error = new(NotificationOption2.Error); private NotificationOption(NotificationOption2 notificationOptionImpl) => _notificationOptionImpl = notificationOptionImpl; public override string ToString() => _notificationOptionImpl.ToString(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CodeStyle { /// <inheritdoc cref="NotificationOption2"/> public class NotificationOption { private readonly NotificationOption2 _notificationOptionImpl; /// <inheritdoc cref="NotificationOption2.Name"/> public string Name { get => _notificationOptionImpl.Name; set => _notificationOptionImpl.Name = value; } /// <inheritdoc cref="NotificationOption2.Severity"/> public ReportDiagnostic Severity { get => _notificationOptionImpl.Severity; set => _notificationOptionImpl.Severity = value; } [Obsolete("Use " + nameof(Severity) + " instead.")] public DiagnosticSeverity Value { get => Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden; set => Severity = value.ToReportDiagnostic(); } /// <inheritdoc cref="NotificationOption2.None"/> public static readonly NotificationOption None = new(NotificationOption2.None); /// <inheritdoc cref="NotificationOption2.Silent"/> public static readonly NotificationOption Silent = new(NotificationOption2.Silent); /// <inheritdoc cref="NotificationOption2.Suggestion"/> public static readonly NotificationOption Suggestion = new(NotificationOption2.Suggestion); /// <inheritdoc cref="NotificationOption2.Warning"/> public static readonly NotificationOption Warning = new(NotificationOption2.Warning); /// <inheritdoc cref="NotificationOption2.Error"/> public static readonly NotificationOption Error = new(NotificationOption2.Error); private NotificationOption(NotificationOption2 notificationOptionImpl) => _notificationOptionImpl = notificationOptionImpl; public override string ToString() => _notificationOptionImpl.ToString(); } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/Test/Resources/Core/SymbolsTests/TypeForwarders/TypeForwarder2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. public class Base { }; public class GenericBase<T> { public class NestedGenericBase<T1> { }; };
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. public class Base { }; public class GenericBase<T> { public class NestedGenericBase<T1> { }; };
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCommandLineParser.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.IO Imports System.Runtime.InteropServices Imports System.Security.Cryptography Imports System.Text Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' The VisualBasicCommandLineParser class contains members used to perform various Visual Basic command line parsing operations. ''' </summary> Public Class VisualBasicCommandLineParser Inherits CommandLineParser ''' <summary> ''' Gets the current command line parser. ''' </summary> Public Shared ReadOnly Property [Default] As New VisualBasicCommandLineParser() ''' <summary> ''' Gets the current interactive command line parser. ''' </summary> Public Shared ReadOnly Property Script As New VisualBasicCommandLineParser(isScriptCommandLineParser:=True) ''' <summary> ''' Creates a new command line parser. ''' </summary> ''' <param name="isScriptCommandLineParser">An optional parameter indicating whether to create a interactive command line parser.</param> Friend Sub New(Optional isScriptCommandLineParser As Boolean = False) MyBase.New(VisualBasic.MessageProvider.Instance, isScriptCommandLineParser) End Sub Private Const s_win32Manifest As String = "win32manifest" Private Const s_win32Icon As String = "win32icon" Private Const s_win32Res As String = "win32resource" ''' <summary> ''' Gets the standard Visual Basic source file extension ''' </summary> ''' <returns>A string representing the standard Visual Basic source file extension.</returns> Protected Overrides ReadOnly Property RegularFileExtension As String Get Return ".vb" End Get End Property ''' <summary> ''' Gets the standard Visual Basic script file extension. ''' </summary> ''' <returns>A string representing the standard Visual Basic script file extension.</returns> Protected Overrides ReadOnly Property ScriptFileExtension As String Get Return ".vbx" End Get End Property Friend NotOverridable Overrides Function CommonParse(args As IEnumerable(Of String), baseDirectory As String, sdkDirectoryOpt As String, additionalReferenceDirectories As String) As CommandLineArguments Return Parse(args, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories) End Function ''' <summary> ''' Parses a command line. ''' </summary> ''' <param name="args">A collection of strings representing the command line arguments.</param> ''' <param name="baseDirectory">The base directory used for qualifying file locations.</param> ''' <param name="sdkDirectory">The directory to search for mscorlib, or Nothing if not available.</param> ''' <param name="additionalReferenceDirectories">A string representing additional reference paths.</param> ''' <returns>A CommandLineArguments object representing the parsed command line.</returns> Public Shadows Function Parse(args As IEnumerable(Of String), baseDirectory As String, sdkDirectory As String, Optional additionalReferenceDirectories As String = Nothing) As VisualBasicCommandLineArguments Debug.Assert(baseDirectory Is Nothing OrElse PathUtilities.IsAbsolute(baseDirectory)) Const GenerateFileNameForDocComment As String = "USE-OUTPUT-NAME" Dim diagnostics As List(Of Diagnostic) = New List(Of Diagnostic)() Dim flattenedArgs = ArrayBuilder(Of String).GetInstance() Dim scriptArgs As List(Of String) = If(IsScriptCommandLineParser, New List(Of String)(), Nothing) ' normalized paths to directories containing response files: Dim responsePaths As New List(Of String) FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory, responsePaths) Dim displayLogo As Boolean = True Dim displayHelp As Boolean = False Dim displayVersion As Boolean = False Dim displayLangVersions As Boolean = False Dim outputLevel As OutputLevel = OutputLevel.Normal Dim optimize As Boolean = False Dim checkOverflow As Boolean = True Dim concurrentBuild As Boolean = True Dim deterministic As Boolean = False Dim emitPdb As Boolean Dim debugInformationFormat As DebugInformationFormat = If(PathUtilities.IsUnixLikePlatform, DebugInformationFormat.PortablePdb, DebugInformationFormat.Pdb) Dim noStdLib As Boolean = False Dim utf8output As Boolean = False Dim outputFileName As String = Nothing Dim outputRefFileName As String = Nothing Dim refOnly As Boolean = False Dim outputDirectory As String = baseDirectory Dim documentationPath As String = Nothing Dim errorLogOptions As ErrorLogOptions = Nothing Dim parseDocumentationComments As Boolean = False ' Don't just null check documentationFileName because we want to do this even if the file name is invalid. Dim outputKind As OutputKind = OutputKind.ConsoleApplication Dim ssVersion As SubsystemVersion = SubsystemVersion.None Dim languageVersion As LanguageVersion = LanguageVersion.Default Dim mainTypeName As String = Nothing Dim win32ManifestFile As String = Nothing Dim win32ResourceFile As String = Nothing Dim win32IconFile As String = Nothing Dim noWin32Manifest As Boolean = False Dim managedResources = New List(Of ResourceDescription)() Dim sourceFiles = New List(Of CommandLineSourceFile)() Dim hasSourceFiles = False Dim additionalFiles = New List(Of CommandLineSourceFile)() Dim analyzerConfigPaths = ArrayBuilder(Of String).GetInstance() Dim embeddedFiles = New List(Of CommandLineSourceFile)() Dim embedAllSourceFiles = False Dim codepage As Encoding = Nothing Dim checksumAlgorithm = SourceHashAlgorithmUtils.DefaultContentHashAlgorithm Dim defines As IReadOnlyDictionary(Of String, Object) = Nothing Dim metadataReferences = New List(Of CommandLineReference)() Dim analyzers = New List(Of CommandLineAnalyzerReference)() Dim sdkPaths As New List(Of String)() Dim libPaths As New List(Of String)() Dim sourcePaths As New List(Of String)() Dim keyFileSearchPaths = New List(Of String)() Dim globalImports = New List(Of GlobalImport) Dim rootNamespace As String = "" Dim optionStrict As OptionStrict = OptionStrict.Off Dim optionInfer As Boolean = False ' MSDN says: ...The compiler default for this option is /optioninfer-. Dim optionExplicit As Boolean = True Dim optionCompareText As Boolean = False Dim embedVbCoreRuntime As Boolean = False Dim platform As Platform = Platform.AnyCpu Dim preferredUILang As CultureInfo = Nothing Dim fileAlignment As Integer = 0 Dim baseAddress As ULong = 0 Dim highEntropyVA As Boolean = False Dim vbRuntimePath As String = Nothing Dim includeVbRuntimeReference As Boolean = True Dim generalDiagnosticOption As ReportDiagnostic = ReportDiagnostic.Default Dim pathMap As ImmutableArray(Of KeyValuePair(Of String, String)) = ImmutableArray(Of KeyValuePair(Of String, String)).Empty ' Diagnostic ids specified via /nowarn /warnaserror must be processed in case-insensitive fashion. Dim specificDiagnosticOptionsFromRuleSet = New Dictionary(Of String, ReportDiagnostic)(CaseInsensitiveComparison.Comparer) Dim specificDiagnosticOptionsFromGeneralArguments = New Dictionary(Of String, ReportDiagnostic)(CaseInsensitiveComparison.Comparer) Dim specificDiagnosticOptionsFromSpecificArguments = New Dictionary(Of String, ReportDiagnostic)(CaseInsensitiveComparison.Comparer) Dim specificDiagnosticOptionsFromNoWarnArguments = New Dictionary(Of String, ReportDiagnostic)(CaseInsensitiveComparison.Comparer) Dim keyFileSetting As String = Nothing Dim keyContainerSetting As String = Nothing Dim delaySignSetting As Boolean? = Nothing Dim moduleAssemblyName As String = Nothing Dim moduleName As String = Nothing Dim touchedFilesPath As String = Nothing Dim features = New List(Of String)() Dim reportAnalyzer As Boolean = False Dim skipAnalyzers As Boolean = False Dim publicSign As Boolean = False Dim interactiveMode As Boolean = False Dim instrumentationKinds As ArrayBuilder(Of InstrumentationKind) = ArrayBuilder(Of InstrumentationKind).GetInstance() Dim sourceLink As String = Nothing Dim ruleSetPath As String = Nothing ' Process ruleset files first so that diagnostic severity settings specified on the command line via ' /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file. If Not IsScriptCommandLineParser Then For Each arg In flattenedArgs Dim name As String = Nothing Dim value As String = Nothing If TryParseOption(arg, name, value) AndAlso (name = "ruleset") Then Dim unquoted = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(unquoted) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file>") Continue For End If ruleSetPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory) generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(ruleSetPath, specificDiagnosticOptionsFromRuleSet, diagnostics) End If Next End If For Each arg In flattenedArgs Debug.Assert(Not arg.StartsWith("@", StringComparison.Ordinal)) Dim name As String = Nothing Dim value As String = Nothing If Not TryParseOption(arg, name, value) Then Dim builder = ArrayBuilder(Of String).GetInstance() ParseFileArgument(arg.AsMemory(), baseDirectory, builder, diagnostics) For Each path In builder sourceFiles.Add(ToCommandLineSourceFile(path)) Next builder.Free() hasSourceFiles = True Continue For End If Select Case name Case "?", "help" If value IsNot Nothing Then Exit Select End If displayHelp = True Continue For Case "version" If value IsNot Nothing Then Exit Select End If displayVersion = True Continue For Case "r", "reference" metadataReferences.AddRange(ParseAssemblyReferences(name, value, diagnostics, embedInteropTypes:=False)) Continue For Case "a", "analyzer" analyzers.AddRange(ParseAnalyzers(name, value, diagnostics)) Continue For Case "d", "define" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<symbol_list>") Continue For End If Dim conditionalCompilationDiagnostics As IEnumerable(Of Diagnostic) = Nothing defines = ParseConditionalCompilationSymbols(value, conditionalCompilationDiagnostics, defines) diagnostics.AddRange(conditionalCompilationDiagnostics) Continue For Case "imports", "import" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, If(name = "import", ":<str>", ":<import_list>")) Continue For End If ParseGlobalImports(value, globalImports, diagnostics) Continue For Case "optionstrict" value = RemoveQuotesAndSlashes(value) If value Is Nothing Then optionStrict = VisualBasic.OptionStrict.On ElseIf String.Equals(value, "custom", StringComparison.OrdinalIgnoreCase) Then optionStrict = VisualBasic.OptionStrict.Custom Else AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "optionstrict", ":custom") End If Continue For Case "optionstrict+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optionstrict") Continue For End If optionStrict = VisualBasic.OptionStrict.On Continue For Case "optionstrict-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optionstrict") Continue For End If optionStrict = VisualBasic.OptionStrict.Off Continue For Case "optioncompare" value = RemoveQuotesAndSlashes(value) If value Is Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "optioncompare", ":binary|text") ElseIf String.Equals(value, "text", StringComparison.OrdinalIgnoreCase) Then optionCompareText = True ElseIf String.Equals(value, "binary", StringComparison.OrdinalIgnoreCase) Then optionCompareText = False Else AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, "optioncompare", value) End If Continue For Case "optionexplicit", "optionexplicit+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optionexplicit") Continue For End If optionExplicit = True Continue For Case "optionexplicit-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optionexplicit") Continue For End If optionExplicit = False Continue For Case "optioninfer", "optioninfer+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optioninfer") Continue For End If optionInfer = True Continue For Case "optioninfer-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optioninfer") Continue For End If optionInfer = False Continue For Case "codepage" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "codepage", ":<number>") Continue For End If Dim encoding = TryParseEncodingName(value) If encoding Is Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_BadCodepage, value) Continue For End If codepage = encoding Continue For Case "checksumalgorithm" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "checksumalgorithm", ":<algorithm>") Continue For End If Dim newChecksumAlgorithm = TryParseHashAlgorithmName(value) If newChecksumAlgorithm = SourceHashAlgorithm.None Then AddDiagnostic(diagnostics, ERRID.ERR_BadChecksumAlgorithm, value) Continue For End If checksumAlgorithm = newChecksumAlgorithm Continue For Case "removeintchecks", "removeintchecks+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "removeintchecks") Continue For End If checkOverflow = False Continue For Case "removeintchecks-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "removeintchecks") Continue For End If checkOverflow = True Continue For Case "sqmsessionguid" ' The use of SQM is deprecated in the compiler but we still support the command line parsing for ' back compat reasons. value = RemoveQuotesAndSlashes(value) If String.IsNullOrWhiteSpace(value) = True Then AddDiagnostic(diagnostics, ERRID.ERR_MissingGuidForOption, value, name) Else Dim sqmsessionguid As Guid If Not Guid.TryParse(value, sqmsessionguid) Then AddDiagnostic(diagnostics, ERRID.ERR_InvalidFormatForGuidForOption, value, name) End If End If Continue For Case "preferreduilang" value = RemoveQuotesAndSlashes(value) If (String.IsNullOrEmpty(value)) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<string>") Continue For End If Try preferredUILang = New CultureInfo(value) If (preferredUILang.CultureTypes And CultureTypes.UserCustomCulture) <> 0 Then ' Do not use user custom cultures. preferredUILang = Nothing End If Catch ex As CultureNotFoundException End Try If preferredUILang Is Nothing Then AddDiagnostic(diagnostics, ERRID.WRN_BadUILang, value) End If Continue For Case "lib", "libpath", "libpaths" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<path_list>") Continue For End If libPaths.AddRange(ParseSeparatedPaths(value)) Continue For #If DEBUG Then Case "attachdebugger" Debugger.Launch() Continue For #End If End Select If IsScriptCommandLineParser Then Select Case name Case "-" If Console.IsInputRedirected Then sourceFiles.Add(New CommandLineSourceFile("-", isScript:=True, isInputRedirected:=True)) hasSourceFiles = True Else AddDiagnostic(diagnostics, ERRID.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected) End If Continue For Case "i", "i+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "i") End If interactiveMode = True Continue For Case "i-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "i") End If interactiveMode = False Continue For Case "loadpath", "loadpaths" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<path_list>") Continue For End If sourcePaths.AddRange(ParseSeparatedPaths(value)) Continue For End Select Else Select Case name Case "out" If String.IsNullOrWhiteSpace(value) Then ' When the value has " " (e.g., "/out: ") ' the Roslyn VB compiler reports "BC 2006 : option 'out' requires ':<file>', ' While the Dev11 VB compiler reports "BC2012 : can't open ' ' for writing, AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file>") Else ' Even when value is neither null or whitespace, the output file name still could be invalid. (e.g., "/out:sub\ ") ' While the Dev11 VB compiler reports "BC2012: can't open 'sub\ ' for writing, ' the Roslyn VB compiler reports "BC2032: File name 'sub\ ' is empty, contains invalid characters, ..." ' which is generated by the following ParseOutputFile. ParseOutputFile(value, diagnostics, baseDirectory, outputFileName, outputDirectory) End If Continue For Case "refout" Dim unquoted = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(unquoted) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file>") Else outputRefFileName = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory) End If Continue For Case "refonly", "refonly+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "refonly") End If refOnly = True Continue For Case "t", "target" value = RemoveQuotesAndSlashes(value) outputKind = ParseTarget(name, value, diagnostics) Continue For Case "moduleassemblyname" value = RemoveQuotesAndSlashes(value) Dim identity As AssemblyIdentity = Nothing ' Note that native compiler also extracts public key, but Roslyn doesn't use it. If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "moduleassemblyname", ":<string>") ElseIf Not AssemblyIdentity.TryParseDisplayName(value, identity) OrElse Not MetadataHelpers.IsValidAssemblyOrModuleName(identity.Name) Then AddDiagnostic(diagnostics, ERRID.ERR_InvalidAssemblyName, value, arg) Else moduleAssemblyName = identity.Name End If Continue For Case "rootnamespace" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "rootnamespace", ":<string>") Continue For End If rootNamespace = value Continue For Case "doc" value = RemoveQuotesAndSlashes(value) parseDocumentationComments = True If value Is Nothing Then ' Illegal in C#, but works in VB documentationPath = GenerateFileNameForDocComment Continue For End If Dim unquoted = RemoveQuotesAndSlashes(value) If unquoted.Length = 0 Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "doc", ":<file>") Else documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory, generateDiagnostic:=False) If String.IsNullOrWhiteSpace(documentationPath) Then AddDiagnostic(diagnostics, ERRID.WRN_XMLCannotWriteToXMLDocFile2, unquoted, New LocalizableErrorArgument(ERRID.IDS_TheSystemCannotFindThePathSpecified)) documentationPath = Nothing End If End If Continue For Case "doc+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "doc") End If ' Seems redundant with default values, but we need to clobber any preceding /doc switches documentationPath = GenerateFileNameForDocComment parseDocumentationComments = True Continue For Case "doc-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "doc") End If ' Seems redundant with default values, but we need to clobber any preceding /doc switches documentationPath = Nothing parseDocumentationComments = False Continue For Case "errorlog" Dim unquoted = RemoveQuotesAndSlashes(value) If (String.IsNullOrWhiteSpace(unquoted)) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "errorlog", ErrorLogOptionFormat) Else Dim diagnosticAlreadyReported As Boolean errorLogOptions = ParseErrorLogOptions(unquoted.AsMemory(), diagnostics, baseDirectory, diagnosticAlreadyReported) If errorLogOptions Is Nothing And Not diagnosticAlreadyReported Then AddDiagnostic(diagnostics, ERRID.ERR_BadSwitchValue, unquoted, "errorlog", ErrorLogOptionFormat) Continue For End If End If Continue For Case "netcf" ' Do nothing as we no longer have any use for implementing this switch and ' want to avoid failing with any warnings/errors Continue For Case "sdkpath" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "sdkpath", ":<path>") Continue For End If sdkPaths.Clear() sdkPaths.AddRange(ParseSeparatedPaths(value)) Continue For Case "nosdkpath" sdkDirectory = Nothing sdkPaths.Clear() Continue For Case "instrument" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "instrument", ":<string>") Continue For End If For Each instrumentationKind As InstrumentationKind In ParseInstrumentationKinds(value, diagnostics) If Not instrumentationKinds.Contains(instrumentationKind) Then instrumentationKinds.Add(instrumentationKind) End If Next Continue For Case "recurse" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "recurse", ":<wildcard>") Continue For End If Dim before As Integer = sourceFiles.Count sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics)) If sourceFiles.Count > before Then hasSourceFiles = True End If Continue For Case "addmodule" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "addmodule", ":<file_list>") Continue For End If ' NOTE(tomat): Dev10 reports "Command line error BC2017 : could not find library." ' Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. ' An error will be reported by the assembly manager anyways. metadataReferences.AddRange( ParseSeparatedPaths(value).Select( Function(path) New CommandLineReference(path, New MetadataReferenceProperties(MetadataImageKind.Module)))) Continue For Case "l", "link" metadataReferences.AddRange(ParseAssemblyReferences(name, value, diagnostics, embedInteropTypes:=True)) Continue For Case "win32resource" win32ResourceFile = GetWin32Setting(s_win32Res, RemoveQuotesAndSlashes(value), diagnostics) Continue For Case "win32icon" win32IconFile = GetWin32Setting(s_win32Icon, RemoveQuotesAndSlashes(value), diagnostics) Continue For Case "win32manifest" win32ManifestFile = GetWin32Setting(s_win32Manifest, RemoveQuotesAndSlashes(value), diagnostics) Continue For Case "nowin32manifest" If value IsNot Nothing Then Exit Select End If noWin32Manifest = True Continue For Case "res", "resource" Dim embeddedResource = ParseResourceDescription(name, value, baseDirectory, diagnostics, embedded:=True) If embeddedResource IsNot Nothing Then managedResources.Add(embeddedResource) End If Continue For Case "linkres", "linkresource" Dim linkedResource = ParseResourceDescription(name, value, baseDirectory, diagnostics, embedded:=False) If linkedResource IsNot Nothing Then managedResources.Add(linkedResource) End If Continue For Case "sourcelink" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "sourcelink", ":<file>") Else sourceLink = ParseGenericPathToFile(value, diagnostics, baseDirectory) End If Continue For Case "debug" ' parse only for backwards compat value = RemoveQuotesAndSlashes(value) If value IsNot Nothing Then Select Case value.ToLower() Case "full", "pdbonly" debugInformationFormat = If(PathUtilities.IsUnixLikePlatform, DebugInformationFormat.PortablePdb, DebugInformationFormat.Pdb) Case "portable" debugInformationFormat = DebugInformationFormat.PortablePdb Case "embedded" debugInformationFormat = DebugInformationFormat.Embedded Case Else AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, "debug", value) End Select End If emitPdb = True Continue For Case "debug+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "debug") End If emitPdb = True Continue For Case "debug-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "debug") End If emitPdb = False Continue For Case "optimize", "optimize+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optimize") Continue For End If optimize = True Continue For Case "optimize-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optimize") Continue For End If optimize = False Continue For Case "parallel", "p" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name) Continue For End If concurrentBuild = True Continue For Case "deterministic", "deterministic+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name) Continue For End If deterministic = True Continue For Case "deterministic-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name) Continue For End If deterministic = False Continue For Case "parallel+", "p+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name.Substring(0, name.Length - 1)) Continue For End If concurrentBuild = True Continue For Case "parallel-", "p-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name.Substring(0, name.Length - 1)) Continue For End If concurrentBuild = False Continue For Case "warnaserror", "warnaserror+" If value Is Nothing Then generalDiagnosticOption = ReportDiagnostic.Error specificDiagnosticOptionsFromGeneralArguments.Clear() For Each pair In specificDiagnosticOptionsFromRuleSet If pair.Value = ReportDiagnostic.Warn Then specificDiagnosticOptionsFromGeneralArguments.Add(pair.Key, ReportDiagnostic.Error) End If Next Continue For End If AddWarnings(specificDiagnosticOptionsFromSpecificArguments, ReportDiagnostic.Error, ParseWarnings(value)) Continue For Case "warnaserror-" If value Is Nothing Then If generalDiagnosticOption <> ReportDiagnostic.Suppress Then generalDiagnosticOption = ReportDiagnostic.Default End If specificDiagnosticOptionsFromGeneralArguments.Clear() Continue For End If For Each id In ParseWarnings(value) Dim ruleSetValue As ReportDiagnostic If specificDiagnosticOptionsFromRuleSet.TryGetValue(id, ruleSetValue) Then specificDiagnosticOptionsFromSpecificArguments(id) = ruleSetValue Else specificDiagnosticOptionsFromSpecificArguments(id) = ReportDiagnostic.Default End If Next Continue For Case "nowarn" If value Is Nothing Then generalDiagnosticOption = ReportDiagnostic.Suppress specificDiagnosticOptionsFromGeneralArguments.Clear() For Each pair In specificDiagnosticOptionsFromRuleSet If pair.Value <> ReportDiagnostic.Error Then specificDiagnosticOptionsFromGeneralArguments.Add(pair.Key, ReportDiagnostic.Suppress) End If Next Continue For End If AddWarnings(specificDiagnosticOptionsFromNoWarnArguments, ReportDiagnostic.Suppress, ParseWarnings(value)) Continue For Case "langversion" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "langversion", ":<number>") ElseIf value = "?" Then displayLangVersions = True Else If Not TryParse(value, languageVersion) Then AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, "langversion", value) End If End If Continue For Case "delaysign", "delaysign+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "delaysign") Continue For End If delaySignSetting = True Continue For Case "delaysign-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "delaysign") Continue For End If delaySignSetting = False Continue For Case "publicsign", "publicsign+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "publicsign") Continue For End If publicSign = True Continue For Case "publicsign-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "publicsign") Continue For End If publicSign = False Continue For Case "keycontainer" ' NOTE: despite what MSDN says, Dev11 resets '/keyfile' in this case: ' ' MSDN: In case both /keyfile and /keycontainer are specified (either by command-line ' MSDN: option or by custom attribute) in the same compilation, the compiler first tries ' MSDN: the key container. If that succeeds, then the assembly is signed with the ' MSDN: information in the key container. If the compiler does not find the key container, ' MSDN: it tries the file specified with /keyfile. If this succeeds, the assembly is ' MSDN: signed with the information in the key file, and the key information is installed ' MSDN: in the key container (similar to sn -i) so that on the next compilation, ' MSDN: the key container will be valid. value = RemoveQuotesAndSlashes(value) keyFileSetting = Nothing If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "keycontainer", ":<string>") Else keyContainerSetting = value End If Continue For Case "keyfile" ' NOTE: despite what MSDN says, Dev11 resets '/keycontainer' in this case: ' ' MSDN: In case both /keyfile and /keycontainer are specified (either by command-line ' MSDN: option or by custom attribute) in the same compilation, the compiler first tries ' MSDN: the key container. If that succeeds, then the assembly is signed with the ' MSDN: information in the key container. If the compiler does not find the key container, ' MSDN: it tries the file specified with /keyfile. If this succeeds, the assembly is ' MSDN: signed with the information in the key file, and the key information is installed ' MSDN: in the key container (similar to sn -i) so that on the next compilation, ' MSDN: the key container will be valid. value = RemoveQuotesAndSlashes(value) keyContainerSetting = Nothing If String.IsNullOrWhiteSpace(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "keyfile", ":<file>") Else keyFileSetting = value End If Continue For Case "highentropyva", "highentropyva+" If value IsNot Nothing Then Exit Select End If highEntropyVA = True Continue For Case "highentropyva-" If value IsNot Nothing Then Exit Select End If highEntropyVA = False Continue For Case "nologo", "nologo+" If value IsNot Nothing Then Exit Select End If displayLogo = False Continue For Case "nologo-" If value IsNot Nothing Then Exit Select End If displayLogo = True Continue For Case "quiet+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "quiet") Continue For End If outputLevel = VisualBasic.OutputLevel.Quiet Continue For Case "quiet" If value IsNot Nothing Then Exit Select End If outputLevel = VisualBasic.OutputLevel.Quiet Continue For Case "verbose" If value IsNot Nothing Then Exit Select End If outputLevel = VisualBasic.OutputLevel.Verbose Continue For Case "verbose+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "verbose") Continue For End If outputLevel = VisualBasic.OutputLevel.Verbose Continue For Case "quiet-", "verbose-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name.Substring(0, name.Length - 1)) Continue For End If outputLevel = VisualBasic.OutputLevel.Normal Continue For Case "utf8output", "utf8output+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "utf8output") End If utf8output = True Continue For Case "utf8output-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "utf8output") End If utf8output = False Continue For Case "noconfig" ' It is already handled (see CommonCommandLineCompiler.cs). Continue For Case "bugreport" ' Do nothing as we no longer have any use for implementing this switch and ' want to avoid failing with any warnings/errors ' We do no further checking as to a value provided or not and ' ' this will cause no diagnostics for invalid values. Continue For Case "errorreport" ' Allows any value to be entered and will just silently do nothing ' previously we would validate value for prompt, send Or Queue ' This will cause no diagnostics for invalid values. Continue For Case "novbruntimeref" ' The switch is no longer supported and for backwards compat ignored. Continue For Case "m", "main" ' MSBuild can result in maintypename being passed in quoted when Cyrillic namespace was being used resulting ' in ERRID.ERR_StartupCodeNotFound1 diagnostic. The additional quotes cause problems and quotes are not a ' valid character in typename. value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<class>") Continue For End If mainTypeName = value Continue For Case "subsystemversion" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<version>") Continue For End If Dim version As SubsystemVersion = Nothing If SubsystemVersion.TryParse(value, version) Then ssVersion = version Else AddDiagnostic(diagnostics, ERRID.ERR_InvalidSubsystemVersion, value) End If Continue For Case "touchedfiles" Dim unquoted = RemoveQuotesAndSlashes(value) If (String.IsNullOrEmpty(unquoted)) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<touchedfiles>") Continue For Else touchedFilesPath = unquoted End If Continue For Case "fullpaths", "errorendlocation" UnimplementedSwitch(diagnostics, name) Continue For Case "pathmap" ' "/pathmap:K1=V1,K2=V2..." Dim unquoted = RemoveQuotesAndSlashes(value) If unquoted = Nothing Then Exit Select End If pathMap = pathMap.Concat(ParsePathMap(unquoted, diagnostics)) Continue For Case "reportanalyzer" reportAnalyzer = True Continue For Case "skipanalyzers", "skipanalyzers+" If value IsNot Nothing Then Exit Select End If skipAnalyzers = True Continue For Case "skipanalyzers-" If value IsNot Nothing Then Exit Select End If skipAnalyzers = False Continue For Case "nostdlib" If value IsNot Nothing Then Exit Select End If noStdLib = True Continue For Case "vbruntime" If value Is Nothing Then GoTo lVbRuntimePlus End If ' NOTE: that Dev11 does not report errors on empty or invalid file specified vbRuntimePath = RemoveQuotesAndSlashes(value) includeVbRuntimeReference = True embedVbCoreRuntime = False Continue For Case "vbruntime+" If value IsNot Nothing Then Exit Select End If lVbRuntimePlus: vbRuntimePath = Nothing includeVbRuntimeReference = True embedVbCoreRuntime = False Continue For Case "vbruntime-" If value IsNot Nothing Then Exit Select End If vbRuntimePath = Nothing includeVbRuntimeReference = False embedVbCoreRuntime = False Continue For Case "vbruntime*" If value IsNot Nothing Then Exit Select End If vbRuntimePath = Nothing includeVbRuntimeReference = False embedVbCoreRuntime = True Continue For Case "platform" value = RemoveQuotesAndSlashes(value) If value IsNot Nothing Then platform = ParsePlatform(name, value, diagnostics) Else AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "platform", ":<string>") End If Continue For Case "filealign" fileAlignment = ParseFileAlignment(name, RemoveQuotesAndSlashes(value), diagnostics) Continue For Case "baseaddress" baseAddress = ParseBaseAddress(name, RemoveQuotesAndSlashes(value), diagnostics) Continue For Case "ruleset" ' The ruleset arg has already been processed in a separate pass above. Continue For Case "features" If value Is Nothing Then features.Clear() Else features.Add(RemoveQuotesAndSlashes(value)) End If Continue For Case "additionalfile" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file_list>") Continue For End If For Each path In ParseSeparatedFileArgument(value, baseDirectory, diagnostics) additionalFiles.Add(ToCommandLineSourceFile(path)) Next Continue For Case "analyzerconfig" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file_list>") Continue For End If analyzerConfigPaths.AddRange(ParseSeparatedFileArgument(value, baseDirectory, diagnostics)) Continue For Case "embed" If String.IsNullOrEmpty(value) Then embedAllSourceFiles = True Continue For End If For Each path In ParseSeparatedFileArgument(value, baseDirectory, diagnostics) embeddedFiles.Add(ToCommandLineSourceFile(path)) Next Continue For Case "-" If Console.IsInputRedirected Then sourceFiles.Add(New CommandLineSourceFile("-", isScript:=False, isInputRedirected:=True)) hasSourceFiles = True Else AddDiagnostic(diagnostics, ERRID.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected) End If Continue For End Select End If AddDiagnostic(diagnostics, ERRID.WRN_BadSwitch, arg) Next Dim specificDiagnosticOptions = New Dictionary(Of String, ReportDiagnostic)(specificDiagnosticOptionsFromRuleSet, CaseInsensitiveComparison.Comparer) For Each item In specificDiagnosticOptionsFromGeneralArguments specificDiagnosticOptions(item.Key) = item.Value Next For Each item In specificDiagnosticOptionsFromSpecificArguments specificDiagnosticOptions(item.Key) = item.Value Next For Each item In specificDiagnosticOptionsFromNoWarnArguments specificDiagnosticOptions(item.Key) = item.Value Next If refOnly AndAlso outputRefFileName IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_NoRefOutWhenRefOnly) End If If outputKind = OutputKind.NetModule AndAlso (refOnly OrElse outputRefFileName IsNot Nothing) Then AddDiagnostic(diagnostics, ERRID.ERR_NoNetModuleOutputWhenRefOutOrRefOnly) End If If Not IsScriptCommandLineParser AndAlso Not hasSourceFiles AndAlso managedResources.IsEmpty() Then ' VB displays help when there is nothing specified on the command line If flattenedArgs.Any Then AddDiagnostic(diagnostics, ERRID.ERR_NoSources) Else displayHelp = True End If End If ' Prepare SDK PATH If sdkDirectory IsNot Nothing AndAlso sdkPaths.Count = 0 Then sdkPaths.Add(sdkDirectory) End If ' Locate default 'mscorlib.dll' or 'System.Runtime.dll', if any. Dim defaultCoreLibraryReference As CommandLineReference? = LoadCoreLibraryReference(sdkPaths, baseDirectory) ' If /nostdlib is not specified, load System.dll ' Dev12 does it through combination of CompilerHost::InitStandardLibraryList and CompilerProject::AddStandardLibraries. If Not noStdLib Then Dim systemDllPath As String = FindFileInSdkPath(sdkPaths, "System.dll", baseDirectory) If systemDllPath Is Nothing Then AddDiagnostic(diagnostics, ERRID.WRN_CannotFindStandardLibrary1, "System.dll") Else metadataReferences.Add( New CommandLineReference(systemDllPath, New MetadataReferenceProperties(MetadataImageKind.Assembly))) End If ' Dev11 also adds System.Core.dll in VbHostedCompiler::CreateCompilerProject() End If ' Add reference to 'Microsoft.VisualBasic.dll' if needed If includeVbRuntimeReference Then If vbRuntimePath Is Nothing Then Dim msVbDllPath As String = FindFileInSdkPath(sdkPaths, "Microsoft.VisualBasic.dll", baseDirectory) If msVbDllPath Is Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_LibNotFound, "Microsoft.VisualBasic.dll") Else metadataReferences.Add( New CommandLineReference(msVbDllPath, New MetadataReferenceProperties(MetadataImageKind.Assembly))) End If Else metadataReferences.Add(New CommandLineReference(vbRuntimePath, New MetadataReferenceProperties(MetadataImageKind.Assembly))) End If End If ' add additional reference paths if specified If Not String.IsNullOrEmpty(additionalReferenceDirectories) Then libPaths.AddRange(ParseSeparatedPaths(additionalReferenceDirectories)) End If ' Build search path Dim searchPaths As ImmutableArray(Of String) = BuildSearchPaths(baseDirectory, sdkPaths, responsePaths, libPaths) ' Public sign doesn't use legacy search path settings If publicSign AndAlso Not String.IsNullOrEmpty(keyFileSetting) Then keyFileSetting = ParseGenericPathToFile(keyFileSetting, diagnostics, baseDirectory) End If ValidateWin32Settings(noWin32Manifest, win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics) If sourceLink IsNot Nothing And Not emitPdb Then AddDiagnostic(diagnostics, ERRID.ERR_SourceLinkRequiresPdb) End If If embedAllSourceFiles Then embeddedFiles.AddRange(sourceFiles) End If If embeddedFiles.Count > 0 And Not emitPdb Then AddDiagnostic(diagnostics, ERRID.ERR_CannotEmbedWithoutPdb) End If ' Validate root namespace if specified Debug.Assert(rootNamespace IsNot Nothing) ' NOTE: empty namespace is a valid option If Not String.Empty.Equals(rootNamespace) Then rootNamespace = rootNamespace.Unquote() If String.IsNullOrWhiteSpace(rootNamespace) OrElse Not OptionsValidator.IsValidNamespaceName(rootNamespace) Then AddDiagnostic(diagnostics, ERRID.ERR_BadNamespaceName1, rootNamespace) rootNamespace = "" ' To make it pass compilation options' check End If End If ' Dev10 searches for the keyfile in the current directory and assembly output directory. ' We always look to base directory and then examine the search paths. If Not String.IsNullOrEmpty(baseDirectory) Then keyFileSearchPaths.Add(baseDirectory) End If If Not String.IsNullOrEmpty(outputDirectory) AndAlso baseDirectory <> outputDirectory Then keyFileSearchPaths.Add(outputDirectory) End If Dim parsedFeatures = ParseFeatures(features) Dim compilationName As String = Nothing GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, moduleAssemblyName, outputFileName, moduleName, compilationName) If Not IsScriptCommandLineParser AndAlso Not hasSourceFiles AndAlso Not managedResources.IsEmpty() AndAlso outputFileName = Nothing AndAlso Not flattenedArgs.IsEmpty() Then AddDiagnostic(diagnostics, ERRID.ERR_NoSourcesOut) End If flattenedArgs.Free() Dim parseOptions = New VisualBasicParseOptions( languageVersion:=languageVersion, documentationMode:=If(parseDocumentationComments, DocumentationMode.Diagnose, DocumentationMode.None), kind:=If(IsScriptCommandLineParser, SourceCodeKind.Script, SourceCodeKind.Regular), preprocessorSymbols:=AddPredefinedPreprocessorSymbols(outputKind, defines.AsImmutableOrEmpty()), features:=parsedFeatures) ' We want to report diagnostics with source suppression in the error log file. ' However, these diagnostics won't be reported on the command line. Dim reportSuppressedDiagnostics = errorLogOptions IsNot Nothing Dim options = New VisualBasicCompilationOptions( outputKind:=outputKind, moduleName:=moduleName, mainTypeName:=mainTypeName, scriptClassName:=WellKnownMemberNames.DefaultScriptClassName, globalImports:=globalImports, rootNamespace:=rootNamespace, optionStrict:=optionStrict, optionInfer:=optionInfer, optionExplicit:=optionExplicit, optionCompareText:=optionCompareText, embedVbCoreRuntime:=embedVbCoreRuntime, checkOverflow:=checkOverflow, concurrentBuild:=concurrentBuild, deterministic:=deterministic, cryptoKeyContainer:=keyContainerSetting, cryptoKeyFile:=keyFileSetting, delaySign:=delaySignSetting, publicSign:=publicSign, platform:=platform, generalDiagnosticOption:=generalDiagnosticOption, specificDiagnosticOptions:=specificDiagnosticOptions, optimizationLevel:=If(optimize, OptimizationLevel.Release, OptimizationLevel.Debug), parseOptions:=parseOptions, reportSuppressedDiagnostics:=reportSuppressedDiagnostics) Dim emitOptions = New EmitOptions( metadataOnly:=refOnly, includePrivateMembers:=Not refOnly AndAlso outputRefFileName Is Nothing, debugInformationFormat:=debugInformationFormat, pdbFilePath:=Nothing, ' to be determined later outputNameOverride:=Nothing, ' to be determined later fileAlignment:=fileAlignment, baseAddress:=baseAddress, highEntropyVirtualAddressSpace:=highEntropyVA, subsystemVersion:=ssVersion, runtimeMetadataVersion:=Nothing, instrumentationKinds:=instrumentationKinds.ToImmutableAndFree(), pdbChecksumAlgorithm:=HashAlgorithmName.SHA256) ' TODO: set from /checksumalgorithm (see https://github.com/dotnet/roslyn/issues/24735) ' add option incompatibility errors if any (parse options will be included in options.Errors) diagnostics.AddRange(options.Errors) If documentationPath Is GenerateFileNameForDocComment Then documentationPath = PathUtilities.CombineAbsoluteAndRelativePaths(outputDirectory, PathUtilities.RemoveExtension(outputFileName)) documentationPath = documentationPath + ".xml" End If ' Enable interactive mode if either `\i` option is passed in or no arguments are specified (`vbi`, `vbi script.vbx \i`). ' If the script is passed without the `\i` option simply execute the script (`vbi script.vbx`). interactiveMode = interactiveMode Or (IsScriptCommandLineParser AndAlso sourceFiles.Count = 0) pathMap = SortPathMap(pathMap) Return New VisualBasicCommandLineArguments With { .IsScriptRunner = IsScriptCommandLineParser, .InteractiveMode = interactiveMode, .BaseDirectory = baseDirectory, .Errors = diagnostics.AsImmutable(), .Utf8Output = utf8output, .CompilationName = compilationName, .OutputFileName = outputFileName, .OutputRefFilePath = outputRefFileName, .OutputDirectory = outputDirectory, .DocumentationPath = documentationPath, .ErrorLogOptions = errorLogOptions, .SourceFiles = sourceFiles.AsImmutable(), .PathMap = pathMap, .Encoding = codepage, .ChecksumAlgorithm = checksumAlgorithm, .MetadataReferences = metadataReferences.AsImmutable(), .AnalyzerReferences = analyzers.AsImmutable(), .AdditionalFiles = additionalFiles.AsImmutable(), .AnalyzerConfigPaths = analyzerConfigPaths.ToImmutableAndFree(), .ReferencePaths = searchPaths, .SourcePaths = sourcePaths.AsImmutable(), .KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), .Win32ResourceFile = win32ResourceFile, .Win32Icon = win32IconFile, .Win32Manifest = win32ManifestFile, .NoWin32Manifest = noWin32Manifest, .DisplayLogo = displayLogo, .DisplayHelp = displayHelp, .DisplayVersion = displayVersion, .DisplayLangVersions = displayLangVersions, .ManifestResources = managedResources.AsImmutable(), .CompilationOptions = options, .ParseOptions = parseOptions, .EmitOptions = emitOptions, .ScriptArguments = scriptArgs.AsImmutableOrEmpty(), .TouchedFilesPath = touchedFilesPath, .OutputLevel = outputLevel, .EmitPdb = emitPdb AndAlso Not refOnly, ' Silently ignore emitPdb when refOnly is set .SourceLink = sourceLink, .RuleSetPath = ruleSetPath, .DefaultCoreLibraryReference = defaultCoreLibraryReference, .PreferredUILang = preferredUILang, .ReportAnalyzer = reportAnalyzer, .SkipAnalyzers = skipAnalyzers, .EmbeddedFiles = embeddedFiles.AsImmutable() } End Function Private Function LoadCoreLibraryReference(sdkPaths As List(Of String), baseDirectory As String) As CommandLineReference? ' Load Core library in Dev11: ' Traditionally VB compiler has hard-coded the name of mscorlib.dll. In the Immersive profile the ' library is called System.Runtime.dll. Ideally we should get rid of the dependency on the name and ' identify the core library as the assembly that contains System.Object. At this point in the compiler, ' it is too early though as we haven't loaded any types or assemblies. Changing this now is a deep ' change. So the workaround here is to allow mscorlib or system.runtime and prefer system.runtime if present. ' There is an extra check to only pick an assembly with no other assembly refs. This is so that is an ' user drops a user-defined binary called System.runtime.dll into the fx directory we still want to pick ' mscorlib. Dim msCorLibPath As String = FindFileInSdkPath(sdkPaths, "mscorlib.dll", baseDirectory) Dim systemRuntimePath As String = FindFileInSdkPath(sdkPaths, "System.Runtime.dll", baseDirectory) If systemRuntimePath IsNot Nothing Then If msCorLibPath Is Nothing Then Return New CommandLineReference(systemRuntimePath, New MetadataReferenceProperties(MetadataImageKind.Assembly)) End If ' Load System.Runtime.dll and see if it has any references Try Using metadata = AssemblyMetadata.CreateFromFile(systemRuntimePath) ' Prefer 'System.Runtime.dll' if it does not have any references If metadata.GetModules()(0).Module.IsLinkedModule AndAlso metadata.GetAssembly().AssemblyReferences.Length = 0 Then Return New CommandLineReference(systemRuntimePath, New MetadataReferenceProperties(MetadataImageKind.Assembly)) End If End Using Catch ' If we caught anything, there is something wrong with System.Runtime.dll and we fall back to mscorlib.dll End Try ' Otherwise prefer 'mscorlib.dll' Return New CommandLineReference(msCorLibPath, New MetadataReferenceProperties(MetadataImageKind.Assembly)) End If If msCorLibPath IsNot Nothing Then ' We return a reference to 'mscorlib.dll' Return New CommandLineReference(msCorLibPath, New MetadataReferenceProperties(MetadataImageKind.Assembly)) End If Return Nothing End Function Private Shared Function FindFileInSdkPath(sdkPaths As List(Of String), fileName As String, baseDirectory As String) As String For Each path In sdkPaths Debug.Assert(path IsNot Nothing) Dim absolutePath = FileUtilities.ResolveRelativePath(path, baseDirectory) If absolutePath IsNot Nothing Then Dim filePath = PathUtilities.CombineAbsoluteAndRelativePaths(absolutePath, fileName) If File.Exists(filePath) Then Return filePath End If End If Next Return Nothing End Function Private Shared Function GetWin32Setting(arg As String, value As String, diagnostics As List(Of Diagnostic)) As String If value Is Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, arg, ":<file>") Else Dim noQuotes As String = RemoveQuotesAndSlashes(value) If String.IsNullOrWhiteSpace(noQuotes) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, arg, ":<file>") Else Return noQuotes End If End If Return Nothing End Function Private Shared Function BuildSearchPaths(baseDirectory As String, sdkPaths As List(Of String), responsePaths As List(Of String), libPaths As List(Of String)) As ImmutableArray(Of String) Dim builder = ArrayBuilder(Of String).GetInstance() ' Match how Dev11 builds the list of search paths ' see void GetSearchPath(CComBSTR& strSearchPath) ' current folder -- base directory is searched by default by the FileResolver ' SDK path is specified or current runtime directory AddNormalizedPaths(builder, sdkPaths, baseDirectory) ' Response file path, see the following comment from Dev11: ' // .NET FX 3.5 will have response file in the FX 3.5 directory but SdkPath will still be in 2.0 directory. ' // Therefore we need to make sure the response file directories are also on the search path ' // so response file authors can continue to use relative paths in the response files. builder.AddRange(responsePaths) ' libpath AddNormalizedPaths(builder, libPaths, baseDirectory) Return builder.ToImmutableAndFree() End Function Private Shared Sub AddNormalizedPaths(builder As ArrayBuilder(Of String), paths As List(Of String), baseDirectory As String) For Each path In paths Dim normalizedPath = FileUtilities.NormalizeRelativePath(path, basePath:=Nothing, baseDirectory:=baseDirectory) If normalizedPath Is Nothing Then ' just ignore invalid paths, native compiler doesn't report any errors Continue For End If builder.Add(normalizedPath) Next End Sub Private Shared Sub ValidateWin32Settings(noWin32Manifest As Boolean, win32ResSetting As String, win32IconSetting As String, win32ManifestSetting As String, outputKind As OutputKind, diagnostics As List(Of Diagnostic)) If noWin32Manifest AndAlso (win32ManifestSetting IsNot Nothing) Then AddDiagnostic(diagnostics, ERRID.ERR_ConflictingManifestSwitches) End If If win32ResSetting IsNot Nothing Then If win32IconSetting IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_IconFileAndWin32ResFile) End If If win32ManifestSetting IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_CantHaveWin32ResAndManifest) End If End If If win32ManifestSetting IsNot Nothing AndAlso outputKind.IsNetModule() Then AddDiagnostic(diagnostics, ERRID.WRN_IgnoreModuleManifest) End If End Sub Private Shared Function ParseTarget(optionName As String, value As String, diagnostics As IList(Of Diagnostic)) As OutputKind Select Case If(value, "").ToLowerInvariant() Case "exe" Return OutputKind.ConsoleApplication Case "winexe" Return OutputKind.WindowsApplication Case "library" Return OutputKind.DynamicallyLinkedLibrary Case "module" Return OutputKind.NetModule Case "appcontainerexe" Return OutputKind.WindowsRuntimeApplication Case "winmdobj" Return OutputKind.WindowsRuntimeMetadata Case "" AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, optionName, ":exe|winexe|library|module|appcontainerexe|winmdobj") Return OutputKind.ConsoleApplication Case Else AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, optionName, value) Return OutputKind.ConsoleApplication End Select End Function Friend Shared Function ParseAssemblyReferences(name As String, value As String, diagnostics As IList(Of Diagnostic), embedInteropTypes As Boolean) As IEnumerable(Of CommandLineReference) If String.IsNullOrEmpty(value) Then ' TODO: localize <file_list>? AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file_list>") Return SpecializedCollections.EmptyEnumerable(Of CommandLineReference)() End If Return ParseSeparatedPaths(value). Select(Function(path) New CommandLineReference(path, New MetadataReferenceProperties(MetadataImageKind.Assembly, embedInteropTypes:=embedInteropTypes))) End Function Private Shared Function ParseAnalyzers(name As String, value As String, diagnostics As IList(Of Diagnostic)) As IEnumerable(Of CommandLineAnalyzerReference) If String.IsNullOrEmpty(value) Then ' TODO: localize <file_list>? AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file_list>") Return SpecializedCollections.EmptyEnumerable(Of CommandLineAnalyzerReference)() End If Return ParseSeparatedPaths(value). Select(Function(path) Return New CommandLineAnalyzerReference(path) End Function) End Function ' See ParseCommandLine in vbc.cpp. Friend Overloads Shared Function ParseResourceDescription(name As String, resourceDescriptor As String, baseDirectory As String, diagnostics As IList(Of Diagnostic), embedded As Boolean) As ResourceDescription If String.IsNullOrEmpty(resourceDescriptor) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<resinfo>") Return Nothing End If ' NOTE: these are actually passed to out parameters of .ParseResourceDescription. Dim filePath As String = Nothing Dim fullPath As String = Nothing Dim fileName As String = Nothing Dim resourceName As String = Nothing Dim accessibility As String = Nothing ParseResourceDescription( resourceDescriptor.AsMemory(), baseDirectory, True, filePath, fullPath, fileName, resourceName, accessibility) If String.IsNullOrWhiteSpace(filePath) Then AddInvalidSwitchValueDiagnostic(diagnostics, name, filePath) Return Nothing End If If Not PathUtilities.IsValidFilePath(fullPath) Then AddDiagnostic(diagnostics, ERRID.FTL_InvalidInputFileName, filePath) Return Nothing End If Dim isPublic As Boolean If String.IsNullOrEmpty(accessibility) Then ' If no accessibility is given, we default to "public". ' NOTE: Dev10 treats empty the same as null (the difference being that empty indicates a comma after the resource name). ' NOTE: Dev10 distinguishes between empty and whitespace-only. isPublic = True ElseIf String.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase) Then isPublic = True ElseIf String.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase) Then isPublic = False Else AddInvalidSwitchValueDiagnostic(diagnostics, name, accessibility) Return Nothing End If Dim dataProvider As Func(Of Stream) = Function() ' Use FileShare.ReadWrite because the file could be opened by the current process. ' For example, it Is an XML doc file produced by the build. Return New FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) End Function Return New ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs:=False) End Function Private Shared Sub AddInvalidSwitchValueDiagnostic(diagnostics As IList(Of Diagnostic), ByVal name As String, ByVal nullStringText As String) If String.IsNullOrEmpty(name) Then ' NOTE: "(null)" to match Dev10. ' CONSIDER: should this be a resource string? name = "(null)" End If AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, name, nullStringText) End Sub Private Shared Sub ParseGlobalImports(value As String, globalImports As List(Of GlobalImport), errors As List(Of Diagnostic)) Dim importsArray = ParseSeparatedPaths(value) For Each importNamespace In importsArray Dim importDiagnostics As ImmutableArray(Of Diagnostic) = Nothing Dim import = GlobalImport.Parse(importNamespace, importDiagnostics) errors.AddRange(importDiagnostics) globalImports.Add(import) Next End Sub ''' <summary> ''' Converts a sequence of definitions provided by a caller (public API) into map ''' of definitions used internally. ''' </summary> ''' <exception cref="ArgumentException">Invalid value provided.</exception> Private Shared Function PublicSymbolsToInternalDefines(symbols As IEnumerable(Of KeyValuePair(Of String, Object)), diagnosticBuilder As ArrayBuilder(Of Diagnostic)) As ImmutableDictionary(Of String, InternalSyntax.CConst) Dim result = ImmutableDictionary.CreateBuilder(Of String, InternalSyntax.CConst)(CaseInsensitiveComparison.Comparer) If symbols IsNot Nothing Then For Each symbol In symbols Dim constant = InternalSyntax.CConst.TryCreate(symbol.Value) If constant Is Nothing Then diagnosticBuilder.Add(Diagnostic.Create(VisualBasic.MessageProvider.Instance, ERRID.ERR_InvalidPreprocessorConstantType, symbol.Key, symbol.Value.GetType())) End If result(symbol.Key) = constant Next End If Return result.ToImmutable() End Function ''' <summary> ''' Converts ImmutableDictionary of definitions used internally into IReadOnlyDictionary of definitions ''' returned to a caller (of public API) ''' </summary> Private Shared Function InternalDefinesToPublicSymbols(defines As ImmutableDictionary(Of String, InternalSyntax.CConst)) As IReadOnlyDictionary(Of String, Object) Dim result = ImmutableDictionary.CreateBuilder(Of String, Object)(CaseInsensitiveComparison.Comparer) For Each kvp In defines result(kvp.Key) = kvp.Value.ValueAsObject Next Return result.ToImmutable() End Function ''' <summary> ''' Parses Conditional Compilations Symbols. Given the string of conditional compilation symbols from the project system, parse them and merge them with an IReadOnlyDictionary ''' ready to be given to the compilation. ''' </summary> ''' <param name="symbolList"> ''' The conditional compilation string. This takes the form of a comma delimited list ''' of NAME=Value pairs, where Value may be a quoted string or integer. ''' </param> ''' <param name="diagnostics">A collection of reported diagnostics during parsing of symbolList, can be empty IEnumerable.</param> ''' <param name="symbols">A collection representing existing symbols. Symbols parsed from <paramref name="symbolList"/> will be merged with this dictionary. </param> ''' <exception cref="ArgumentException">Invalid value provided.</exception> Public Shared Function ParseConditionalCompilationSymbols( symbolList As String, <Out> ByRef diagnostics As IEnumerable(Of Diagnostic), Optional symbols As IEnumerable(Of KeyValuePair(Of String, Object)) = Nothing ) As IReadOnlyDictionary(Of String, Object) Dim diagnosticBuilder = ArrayBuilder(Of Diagnostic).GetInstance() Dim parsedTokensAsString As New StringBuilder Dim defines As ImmutableDictionary(Of String, InternalSyntax.CConst) = PublicSymbolsToInternalDefines(symbols, diagnosticBuilder) ' remove quotes around the whole /define argument (incl. nested) Dim unquotedString As String Do unquotedString = symbolList symbolList = symbolList.Unquote() Loop While Not String.Equals(symbolList, unquotedString, StringComparison.Ordinal) ' unescape quotes \" -> " symbolList = symbolList.Replace("\""", """") Dim trimmedSymbolList As String = symbolList.TrimEnd() If trimmedSymbolList.Length > 0 AndAlso IsConnectorPunctuation(trimmedSymbolList(trimmedSymbolList.Length - 1)) Then ' In case the symbol list ends with '_' we add ',' to the end of the list which in some ' cases will produce an error 30999 to match Dev11 behavior symbolList = symbolList + "," End If ' In order to determine our conditional compilation symbols, we must parse the string we get from the ' project system. We take a cue from the legacy language services and use the VB scanner, since this string ' apparently abides by the same tokenization rules Dim tokenList = SyntaxFactory.ParseTokens(symbolList) Using tokens = tokenList.GetEnumerator() If tokens.MoveNext() Then Do ' This is the beginning of declaration like 'A' or 'A=123' with optional extra ' separators (',' or ':') in the beginning, if this is NOT the first declaration, ' the tokens.Current should be either separator or EOF If tokens.Current.Position > 0 AndAlso Not IsSeparatorOrEndOfFile(tokens.Current) Then parsedTokensAsString.Append(" ^^ ^^ ") ' Complete parsedTokensAsString until the next comma or end of stream While Not IsSeparatorOrEndOfFile(tokens.Current) parsedTokensAsString.Append(tokens.Current.ToFullString()) tokens.MoveNext() End While diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedEOS), parsedTokensAsString.ToString), Location.None)) Exit Do End If Dim lastSeparatorToken As SyntaxToken = Nothing ' If we're on a comma, it means there was an empty item in the list (item1,,item2), ' so just eat it and move on... While tokens.Current.Kind = SyntaxKind.CommaToken OrElse tokens.Current.Kind = SyntaxKind.ColonToken If lastSeparatorToken.Kind = SyntaxKind.None Then ' accept multiple : or , lastSeparatorToken = tokens.Current ElseIf lastSeparatorToken.Kind <> tokens.Current.Kind Then ' but not mixing them, e.g. ::,,:: GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString, stopTokenKind:=lastSeparatorToken.Kind, includeCurrentToken:=True) diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedIdentifier), parsedTokensAsString.ToString), Location.None)) End If parsedTokensAsString.Append(tokens.Current.ToString) ' this can happen when the while loop above consumed all tokens for the diagnostic message If tokens.Current.Kind <> SyntaxKind.EndOfFileToken Then Dim moveNextResult = tokens.MoveNext Debug.Assert(moveNextResult) End If End While parsedTokensAsString.Clear() ' If we're at the end of the list, we're done If tokens.Current.Kind = SyntaxKind.EndOfFileToken Then Dim eof = tokens.Current If eof.FullWidth > 0 Then If Not eof.LeadingTrivia.All(Function(t) t.Kind = SyntaxKind.WhitespaceTrivia) Then ' This is an invalid line like "'Blah'" GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString, True) diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedIdentifier), parsedTokensAsString.ToString), Location.None)) End If End If Exit Do End If parsedTokensAsString.Append(tokens.Current.ToFullString()) If Not tokens.Current.Kind = SyntaxKind.IdentifierToken Then GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString) diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedIdentifier), parsedTokensAsString.ToString), Location.None)) Exit Do End If Dim symbolName = tokens.Current.ValueText ' there should at least be a end of file token Dim moveResult As Boolean = tokens.MoveNext Debug.Assert(moveResult) If tokens.Current.Kind = SyntaxKind.EqualsToken Then parsedTokensAsString.Append(tokens.Current.ToFullString()) ' there should at least be a end of file token moveResult = tokens.MoveNext Debug.Assert(moveResult) ' Parse expression starting with the offset Dim offset As Integer = tokens.Current.SpanStart Dim expression As ExpressionSyntax = ParseConditionalCompilationExpression(symbolList, offset) Dim parsedEnd As Integer = offset + expression.Span.End Dim atTheEndOrSeparator As Boolean = IsSeparatorOrEndOfFile(tokens.Current) ' Consume tokens that are supposed to belong to the expression; we loop ' until the token's end position is the end of the expression, but not consume ' the last token as it will be consumed in uppermost While While tokens.Current.Kind <> SyntaxKind.EndOfFileToken AndAlso tokens.Current.Span.End <= parsedEnd parsedTokensAsString.Append(tokens.Current.ToFullString()) moveResult = tokens.MoveNext Debug.Assert(moveResult) atTheEndOrSeparator = IsSeparatorOrEndOfFile(tokens.Current) End While If expression.ContainsDiagnostics Then ' Dev11 reports syntax errors in not consistent way, sometimes errors are not reported by ' command line utility at all; this implementation tries to repro Dev11 when possible parsedTokensAsString.Append(" ^^ ^^ ") ' Compete parsedTokensAsString until the next comma or end of stream While Not IsSeparatorOrEndOfFile(tokens.Current) parsedTokensAsString.Append(tokens.Current.ToFullString()) tokens.MoveNext() End While ' NOTE: Dev11 reports ERR_ExpectedExpression and ERR_BadCCExpression in different ' cases compared to what ParseConditionalCompilationExpression(...) generates, ' so we have to use different criteria here; if we don't want to match Dev11 ' errors we may simplify the code below Dim errorSkipped As Boolean = False For Each diag In expression.VbGreen.GetSyntaxErrors If diag.Code <> ERRID.ERR_ExpectedExpression AndAlso diag.Code <> ERRID.ERR_BadCCExpression Then diagnosticBuilder.Add(New DiagnosticWithInfo(ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, diag, parsedTokensAsString.ToString), Location.None)) Else errorSkipped = True End If Next If errorSkipped Then diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(If(atTheEndOrSeparator, ERRID.ERR_ExpectedExpression, ERRID.ERR_BadCCExpression)), parsedTokensAsString.ToString), Location.None)) End If Exit Do End If ' Expression parsed successfully --> evaluate it Dim value As InternalSyntax.CConst = InternalSyntax.ExpressionEvaluator.EvaluateExpression( DirectCast(expression.Green, InternalSyntax.ExpressionSyntax), defines) Dim err As ERRID = value.ErrorId If err <> 0 Then GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString) diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(err, value.ErrorArgs), parsedTokensAsString.ToString), Location.None)) Exit Do End If ' Expression evaluated successfully --> add to 'defines' defines = defines.SetItem(symbolName, value) ElseIf tokens.Current.Kind = SyntaxKind.CommaToken OrElse tokens.Current.Kind = SyntaxKind.ColonToken OrElse tokens.Current.Kind = SyntaxKind.EndOfFileToken Then ' We have no value being assigned, so we'll just assign it to true defines = defines.SetItem(symbolName, InternalSyntax.CConst.Create(True)) ElseIf tokens.Current.Kind = SyntaxKind.BadToken Then GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString) diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(ERRID.ERR_IllegalChar), parsedTokensAsString.ToString), Location.None)) Exit Do Else GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString) diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedEOS), parsedTokensAsString.ToString), Location.None)) Exit Do End If Loop End If End Using diagnostics = diagnosticBuilder.ToArrayAndFree() Return InternalDefinesToPublicSymbols(defines) End Function ''' <summary> ''' NOTE: implicit line continuation will not be handled here and an error will be generated, ''' but explicit one (like ".... _\r\n ....") should work fine ''' </summary> Private Shared Function ParseConditionalCompilationExpression(symbolList As String, offset As Integer) As ExpressionSyntax Using p = New InternalSyntax.Parser(SyntaxFactory.MakeSourceText(symbolList, offset), VisualBasicParseOptions.Default) p.GetNextToken() Return DirectCast(p.ParseConditionalCompilationExpression().CreateRed(Nothing, 0), ExpressionSyntax) End Using End Function Private Shared Iterator Function ParseInstrumentationKinds(value As String, diagnostics As IList(Of Diagnostic)) As IEnumerable(Of InstrumentationKind) Dim instrumentationKindStrs = value.Split({","c}, StringSplitOptions.RemoveEmptyEntries) For Each instrumentationKindStr In instrumentationKindStrs Select Case instrumentationKindStr.ToLower() Case "testcoverage" Yield InstrumentationKind.TestCoverage Case Else AddDiagnostic(diagnostics, ERRID.ERR_InvalidInstrumentationKind, instrumentationKindStr) End Select Next End Function Private Shared Function IsSeparatorOrEndOfFile(token As SyntaxToken) As Boolean Return token.Kind = SyntaxKind.EndOfFileToken OrElse token.Kind = SyntaxKind.ColonToken OrElse token.Kind = SyntaxKind.CommaToken End Function Private Shared Sub GetErrorStringForRemainderOfConditionalCompilation( tokens As IEnumerator(Of SyntaxToken), remainderErrorLine As StringBuilder, Optional includeCurrentToken As Boolean = False, Optional stopTokenKind As SyntaxKind = SyntaxKind.CommaToken ) If includeCurrentToken Then remainderErrorLine.Append(" ^^ ") If tokens.Current.Kind = SyntaxKind.ColonToken AndAlso tokens.Current.FullWidth = 0 Then remainderErrorLine.Append(SyntaxFacts.GetText(SyntaxKind.ColonToken)) Else remainderErrorLine.Append(tokens.Current.ToFullString()) End If remainderErrorLine.Append(" ^^ ") Else remainderErrorLine.Append(" ^^ ^^ ") End If While tokens.MoveNext AndAlso Not tokens.Current.Kind = stopTokenKind remainderErrorLine.Append(tokens.Current.ToFullString()) End While End Sub ''' <summary> ''' Parses the given platform option. Legal strings are "anycpu", "x64", "x86", "itanium", "anycpu32bitpreferred", "arm". ''' In case an invalid value was passed, anycpu is returned. ''' </summary> ''' <param name="value">The value for platform.</param> ''' <param name="errors">The error bag.</param> Private Shared Function ParsePlatform(name As String, value As String, errors As List(Of Diagnostic)) As Platform If value.IsEmpty Then AddDiagnostic(errors, ERRID.ERR_ArgumentRequired, name, ":<string>") Else Select Case value.ToLowerInvariant() Case "x86" Return Platform.X86 Case "x64" Return Platform.X64 Case "itanium" Return Platform.Itanium Case "anycpu" Return Platform.AnyCpu Case "anycpu32bitpreferred" Return Platform.AnyCpu32BitPreferred Case "arm" Return Platform.Arm Case "arm64" Return Platform.Arm64 Case Else AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, name, value) End Select End If Return Platform.AnyCpu End Function ''' <summary> ''' Parses the file alignment option. ''' In case an invalid value was passed, nothing is returned. ''' </summary> ''' <param name="name">The name of the option.</param> ''' <param name="value">The value for the option.</param> ''' <param name="errors">The error bag.</param><returns></returns> Private Shared Function ParseFileAlignment(name As String, value As String, errors As List(Of Diagnostic)) As Integer Dim alignment As UShort If String.IsNullOrEmpty(value) Then AddDiagnostic(errors, ERRID.ERR_ArgumentRequired, name, ":<number>") ElseIf Not TryParseUInt16(value, alignment) Then AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, name, value) ElseIf Not Microsoft.CodeAnalysis.CompilationOptions.IsValidFileAlignment(alignment) Then AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, name, value) Else Return alignment End If Return 0 End Function ''' <summary> ''' Parses the base address option. ''' In case an invalid value was passed, nothing is returned. ''' </summary> ''' <param name="name">The name of the option.</param> ''' <param name="value">The value for the option.</param> ''' <param name="errors">The error bag.</param><returns></returns> Private Shared Function ParseBaseAddress(name As String, value As String, errors As List(Of Diagnostic)) As ULong If String.IsNullOrEmpty(value) Then AddDiagnostic(errors, ERRID.ERR_ArgumentRequired, name, ":<number>") Else Dim baseAddress As ULong Dim parseValue As String = value If value.StartsWith("0x", StringComparison.OrdinalIgnoreCase) Then parseValue = value.Substring(2) ' UInt64.TryParse does not accept hex format strings End If ' always treat the base address string as being a hex number, regardless of the given format. ' This handling was hardcoded in the command line option parsing of Dev10 and Dev11. If Not ULong.TryParse(parseValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture, baseAddress) Then AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, name, value.ToString()) Else Return baseAddress End If End If Return 0 End Function ''' <summary> ''' Parses the warning option. ''' </summary> ''' <param name="value">The value for the option.</param> Private Shared Function ParseWarnings(value As String) As IEnumerable(Of String) Dim values = ParseSeparatedPaths(value) Dim results = New List(Of String)() For Each id In values Dim number As UShort If UShort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, number) AndAlso (VisualBasic.MessageProvider.Instance.GetSeverity(number) = DiagnosticSeverity.Warning) AndAlso (VisualBasic.MessageProvider.Instance.GetWarningLevel(number) = 1) Then ' The id refers to a compiler warning. ' Only accept real warnings from the compiler not including the command line warnings. ' Also only accept the numbers that are actually declared in the enum. results.Add(VisualBasic.MessageProvider.Instance.GetIdForErrorCode(CInt(number))) Else ' Previous versions of the compiler used to report warnings (BC2026, BC2014) ' whenever unrecognized warning codes were supplied in /nowarn or ' /warnaserror. We no longer generate a warning in such cases. ' Instead we assume that the unrecognized id refers to a custom diagnostic. results.Add(id) End If Next Return results End Function Private Shared Sub AddWarnings(d As IDictionary(Of String, ReportDiagnostic), kind As ReportDiagnostic, items As IEnumerable(Of String)) For Each id In items Dim existing As ReportDiagnostic If d.TryGetValue(id, existing) Then ' Rewrite the existing value with the latest one unless it is for /nowarn. If existing <> ReportDiagnostic.Suppress Then d(id) = kind End If Else d.Add(id, kind) End If Next End Sub Private Shared Sub UnimplementedSwitch(diagnostics As IList(Of Diagnostic), switchName As String) AddDiagnostic(diagnostics, ERRID.WRN_UnimplementedCommandLineSwitch, "/" + switchName) End Sub Friend Overrides Sub GenerateErrorForNoFilesFoundInRecurse(path As String, errors As IList(Of Diagnostic)) AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, "recurse", path) End Sub Private Shared Sub AddDiagnostic(diagnostics As IList(Of Diagnostic), errorCode As ERRID, ParamArray arguments As Object()) diagnostics.Add(Diagnostic.Create(VisualBasic.MessageProvider.Instance, CInt(errorCode), arguments)) End Sub ''' <summary> ''' In VB, if the output file name isn't specified explicitly, then it is derived from the name of the ''' first input file. ''' </summary> ''' <remarks> ''' http://msdn.microsoft.com/en-us/library/std9609e(v=vs.110) ''' Specify the full name and extension of the file to create. If you do not, the .exe file takes ''' its name from the source-code file containing the Sub Main procedure, and the .dll file takes ''' its name from the first source-code file. ''' ''' However, vbc.cpp has: ''' <![CDATA[ ''' // Calculate the output name and directory ''' dwCharCount = GetFullPathName(pszOut ? pszOut : g_strFirstFile, &wszFileName); ''' ]]> ''' </remarks> Private Sub GetCompilationAndModuleNames(diagnostics As List(Of Diagnostic), kind As OutputKind, sourceFiles As List(Of CommandLineSourceFile), moduleAssemblyName As String, ByRef outputFileName As String, ByRef moduleName As String, <Out> ByRef compilationName As String) Dim simpleName As String = Nothing If outputFileName Is Nothing Then Dim first = sourceFiles.FirstOrDefault() If first.Path IsNot Nothing Then simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(first.Path)) outputFileName = simpleName & kind.GetDefaultExtension() If simpleName.Length = 0 AndAlso Not kind.IsNetModule() Then AddDiagnostic(diagnostics, ERRID.FTL_InvalidInputFileName, outputFileName) simpleName = Nothing outputFileName = Nothing End If End If Else Dim ext As String = PathUtilities.GetExtension(outputFileName) If kind.IsNetModule() Then If ext.Length = 0 Then outputFileName = outputFileName & ".netmodule" End If Else If Not ext.Equals(".exe", StringComparison.OrdinalIgnoreCase) And Not ext.Equals(".dll", StringComparison.OrdinalIgnoreCase) And Not ext.Equals(".netmodule", StringComparison.OrdinalIgnoreCase) And Not ext.Equals(".winmdobj", StringComparison.OrdinalIgnoreCase) Then simpleName = outputFileName outputFileName = outputFileName & kind.GetDefaultExtension() End If If simpleName Is Nothing Then simpleName = PathUtilities.RemoveExtension(outputFileName) ' /out:".exe" ' Dev11 emits assembly with an empty name, we don't If simpleName.Length = 0 Then AddDiagnostic(diagnostics, ERRID.FTL_InvalidInputFileName, outputFileName) simpleName = Nothing outputFileName = Nothing End If End If End If End If If kind.IsNetModule() Then Debug.Assert(Not IsScriptCommandLineParser) compilationName = moduleAssemblyName Else If moduleAssemblyName IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_NeedModule) End If compilationName = simpleName End If If moduleName Is Nothing Then moduleName = outputFileName 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 System.Collections.Immutable Imports System.Globalization Imports System.IO Imports System.Runtime.InteropServices Imports System.Security.Cryptography Imports System.Text Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' The VisualBasicCommandLineParser class contains members used to perform various Visual Basic command line parsing operations. ''' </summary> Public Class VisualBasicCommandLineParser Inherits CommandLineParser ''' <summary> ''' Gets the current command line parser. ''' </summary> Public Shared ReadOnly Property [Default] As New VisualBasicCommandLineParser() ''' <summary> ''' Gets the current interactive command line parser. ''' </summary> Public Shared ReadOnly Property Script As New VisualBasicCommandLineParser(isScriptCommandLineParser:=True) ''' <summary> ''' Creates a new command line parser. ''' </summary> ''' <param name="isScriptCommandLineParser">An optional parameter indicating whether to create a interactive command line parser.</param> Friend Sub New(Optional isScriptCommandLineParser As Boolean = False) MyBase.New(VisualBasic.MessageProvider.Instance, isScriptCommandLineParser) End Sub Private Const s_win32Manifest As String = "win32manifest" Private Const s_win32Icon As String = "win32icon" Private Const s_win32Res As String = "win32resource" ''' <summary> ''' Gets the standard Visual Basic source file extension ''' </summary> ''' <returns>A string representing the standard Visual Basic source file extension.</returns> Protected Overrides ReadOnly Property RegularFileExtension As String Get Return ".vb" End Get End Property ''' <summary> ''' Gets the standard Visual Basic script file extension. ''' </summary> ''' <returns>A string representing the standard Visual Basic script file extension.</returns> Protected Overrides ReadOnly Property ScriptFileExtension As String Get Return ".vbx" End Get End Property Friend NotOverridable Overrides Function CommonParse(args As IEnumerable(Of String), baseDirectory As String, sdkDirectoryOpt As String, additionalReferenceDirectories As String) As CommandLineArguments Return Parse(args, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories) End Function ''' <summary> ''' Parses a command line. ''' </summary> ''' <param name="args">A collection of strings representing the command line arguments.</param> ''' <param name="baseDirectory">The base directory used for qualifying file locations.</param> ''' <param name="sdkDirectory">The directory to search for mscorlib, or Nothing if not available.</param> ''' <param name="additionalReferenceDirectories">A string representing additional reference paths.</param> ''' <returns>A CommandLineArguments object representing the parsed command line.</returns> Public Shadows Function Parse(args As IEnumerable(Of String), baseDirectory As String, sdkDirectory As String, Optional additionalReferenceDirectories As String = Nothing) As VisualBasicCommandLineArguments Debug.Assert(baseDirectory Is Nothing OrElse PathUtilities.IsAbsolute(baseDirectory)) Const GenerateFileNameForDocComment As String = "USE-OUTPUT-NAME" Dim diagnostics As List(Of Diagnostic) = New List(Of Diagnostic)() Dim flattenedArgs = ArrayBuilder(Of String).GetInstance() Dim scriptArgs As List(Of String) = If(IsScriptCommandLineParser, New List(Of String)(), Nothing) ' normalized paths to directories containing response files: Dim responsePaths As New List(Of String) FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory, responsePaths) Dim displayLogo As Boolean = True Dim displayHelp As Boolean = False Dim displayVersion As Boolean = False Dim displayLangVersions As Boolean = False Dim outputLevel As OutputLevel = OutputLevel.Normal Dim optimize As Boolean = False Dim checkOverflow As Boolean = True Dim concurrentBuild As Boolean = True Dim deterministic As Boolean = False Dim emitPdb As Boolean Dim debugInformationFormat As DebugInformationFormat = If(PathUtilities.IsUnixLikePlatform, DebugInformationFormat.PortablePdb, DebugInformationFormat.Pdb) Dim noStdLib As Boolean = False Dim utf8output As Boolean = False Dim outputFileName As String = Nothing Dim outputRefFileName As String = Nothing Dim refOnly As Boolean = False Dim outputDirectory As String = baseDirectory Dim documentationPath As String = Nothing Dim errorLogOptions As ErrorLogOptions = Nothing Dim parseDocumentationComments As Boolean = False ' Don't just null check documentationFileName because we want to do this even if the file name is invalid. Dim outputKind As OutputKind = OutputKind.ConsoleApplication Dim ssVersion As SubsystemVersion = SubsystemVersion.None Dim languageVersion As LanguageVersion = LanguageVersion.Default Dim mainTypeName As String = Nothing Dim win32ManifestFile As String = Nothing Dim win32ResourceFile As String = Nothing Dim win32IconFile As String = Nothing Dim noWin32Manifest As Boolean = False Dim managedResources = New List(Of ResourceDescription)() Dim sourceFiles = New List(Of CommandLineSourceFile)() Dim hasSourceFiles = False Dim additionalFiles = New List(Of CommandLineSourceFile)() Dim analyzerConfigPaths = ArrayBuilder(Of String).GetInstance() Dim embeddedFiles = New List(Of CommandLineSourceFile)() Dim embedAllSourceFiles = False Dim codepage As Encoding = Nothing Dim checksumAlgorithm = SourceHashAlgorithmUtils.DefaultContentHashAlgorithm Dim defines As IReadOnlyDictionary(Of String, Object) = Nothing Dim metadataReferences = New List(Of CommandLineReference)() Dim analyzers = New List(Of CommandLineAnalyzerReference)() Dim sdkPaths As New List(Of String)() Dim libPaths As New List(Of String)() Dim sourcePaths As New List(Of String)() Dim keyFileSearchPaths = New List(Of String)() Dim globalImports = New List(Of GlobalImport) Dim rootNamespace As String = "" Dim optionStrict As OptionStrict = OptionStrict.Off Dim optionInfer As Boolean = False ' MSDN says: ...The compiler default for this option is /optioninfer-. Dim optionExplicit As Boolean = True Dim optionCompareText As Boolean = False Dim embedVbCoreRuntime As Boolean = False Dim platform As Platform = Platform.AnyCpu Dim preferredUILang As CultureInfo = Nothing Dim fileAlignment As Integer = 0 Dim baseAddress As ULong = 0 Dim highEntropyVA As Boolean = False Dim vbRuntimePath As String = Nothing Dim includeVbRuntimeReference As Boolean = True Dim generalDiagnosticOption As ReportDiagnostic = ReportDiagnostic.Default Dim pathMap As ImmutableArray(Of KeyValuePair(Of String, String)) = ImmutableArray(Of KeyValuePair(Of String, String)).Empty ' Diagnostic ids specified via /nowarn /warnaserror must be processed in case-insensitive fashion. Dim specificDiagnosticOptionsFromRuleSet = New Dictionary(Of String, ReportDiagnostic)(CaseInsensitiveComparison.Comparer) Dim specificDiagnosticOptionsFromGeneralArguments = New Dictionary(Of String, ReportDiagnostic)(CaseInsensitiveComparison.Comparer) Dim specificDiagnosticOptionsFromSpecificArguments = New Dictionary(Of String, ReportDiagnostic)(CaseInsensitiveComparison.Comparer) Dim specificDiagnosticOptionsFromNoWarnArguments = New Dictionary(Of String, ReportDiagnostic)(CaseInsensitiveComparison.Comparer) Dim keyFileSetting As String = Nothing Dim keyContainerSetting As String = Nothing Dim delaySignSetting As Boolean? = Nothing Dim moduleAssemblyName As String = Nothing Dim moduleName As String = Nothing Dim touchedFilesPath As String = Nothing Dim features = New List(Of String)() Dim reportAnalyzer As Boolean = False Dim skipAnalyzers As Boolean = False Dim publicSign As Boolean = False Dim interactiveMode As Boolean = False Dim instrumentationKinds As ArrayBuilder(Of InstrumentationKind) = ArrayBuilder(Of InstrumentationKind).GetInstance() Dim sourceLink As String = Nothing Dim ruleSetPath As String = Nothing ' Process ruleset files first so that diagnostic severity settings specified on the command line via ' /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file. If Not IsScriptCommandLineParser Then For Each arg In flattenedArgs Dim name As String = Nothing Dim value As String = Nothing If TryParseOption(arg, name, value) AndAlso (name = "ruleset") Then Dim unquoted = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(unquoted) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file>") Continue For End If ruleSetPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory) generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(ruleSetPath, specificDiagnosticOptionsFromRuleSet, diagnostics) End If Next End If For Each arg In flattenedArgs Debug.Assert(Not arg.StartsWith("@", StringComparison.Ordinal)) Dim name As String = Nothing Dim value As String = Nothing If Not TryParseOption(arg, name, value) Then Dim builder = ArrayBuilder(Of String).GetInstance() ParseFileArgument(arg.AsMemory(), baseDirectory, builder, diagnostics) For Each path In builder sourceFiles.Add(ToCommandLineSourceFile(path)) Next builder.Free() hasSourceFiles = True Continue For End If Select Case name Case "?", "help" If value IsNot Nothing Then Exit Select End If displayHelp = True Continue For Case "version" If value IsNot Nothing Then Exit Select End If displayVersion = True Continue For Case "r", "reference" metadataReferences.AddRange(ParseAssemblyReferences(name, value, diagnostics, embedInteropTypes:=False)) Continue For Case "a", "analyzer" analyzers.AddRange(ParseAnalyzers(name, value, diagnostics)) Continue For Case "d", "define" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<symbol_list>") Continue For End If Dim conditionalCompilationDiagnostics As IEnumerable(Of Diagnostic) = Nothing defines = ParseConditionalCompilationSymbols(value, conditionalCompilationDiagnostics, defines) diagnostics.AddRange(conditionalCompilationDiagnostics) Continue For Case "imports", "import" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, If(name = "import", ":<str>", ":<import_list>")) Continue For End If ParseGlobalImports(value, globalImports, diagnostics) Continue For Case "optionstrict" value = RemoveQuotesAndSlashes(value) If value Is Nothing Then optionStrict = VisualBasic.OptionStrict.On ElseIf String.Equals(value, "custom", StringComparison.OrdinalIgnoreCase) Then optionStrict = VisualBasic.OptionStrict.Custom Else AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "optionstrict", ":custom") End If Continue For Case "optionstrict+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optionstrict") Continue For End If optionStrict = VisualBasic.OptionStrict.On Continue For Case "optionstrict-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optionstrict") Continue For End If optionStrict = VisualBasic.OptionStrict.Off Continue For Case "optioncompare" value = RemoveQuotesAndSlashes(value) If value Is Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "optioncompare", ":binary|text") ElseIf String.Equals(value, "text", StringComparison.OrdinalIgnoreCase) Then optionCompareText = True ElseIf String.Equals(value, "binary", StringComparison.OrdinalIgnoreCase) Then optionCompareText = False Else AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, "optioncompare", value) End If Continue For Case "optionexplicit", "optionexplicit+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optionexplicit") Continue For End If optionExplicit = True Continue For Case "optionexplicit-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optionexplicit") Continue For End If optionExplicit = False Continue For Case "optioninfer", "optioninfer+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optioninfer") Continue For End If optionInfer = True Continue For Case "optioninfer-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optioninfer") Continue For End If optionInfer = False Continue For Case "codepage" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "codepage", ":<number>") Continue For End If Dim encoding = TryParseEncodingName(value) If encoding Is Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_BadCodepage, value) Continue For End If codepage = encoding Continue For Case "checksumalgorithm" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "checksumalgorithm", ":<algorithm>") Continue For End If Dim newChecksumAlgorithm = TryParseHashAlgorithmName(value) If newChecksumAlgorithm = SourceHashAlgorithm.None Then AddDiagnostic(diagnostics, ERRID.ERR_BadChecksumAlgorithm, value) Continue For End If checksumAlgorithm = newChecksumAlgorithm Continue For Case "removeintchecks", "removeintchecks+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "removeintchecks") Continue For End If checkOverflow = False Continue For Case "removeintchecks-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "removeintchecks") Continue For End If checkOverflow = True Continue For Case "sqmsessionguid" ' The use of SQM is deprecated in the compiler but we still support the command line parsing for ' back compat reasons. value = RemoveQuotesAndSlashes(value) If String.IsNullOrWhiteSpace(value) = True Then AddDiagnostic(diagnostics, ERRID.ERR_MissingGuidForOption, value, name) Else Dim sqmsessionguid As Guid If Not Guid.TryParse(value, sqmsessionguid) Then AddDiagnostic(diagnostics, ERRID.ERR_InvalidFormatForGuidForOption, value, name) End If End If Continue For Case "preferreduilang" value = RemoveQuotesAndSlashes(value) If (String.IsNullOrEmpty(value)) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<string>") Continue For End If Try preferredUILang = New CultureInfo(value) If (preferredUILang.CultureTypes And CultureTypes.UserCustomCulture) <> 0 Then ' Do not use user custom cultures. preferredUILang = Nothing End If Catch ex As CultureNotFoundException End Try If preferredUILang Is Nothing Then AddDiagnostic(diagnostics, ERRID.WRN_BadUILang, value) End If Continue For Case "lib", "libpath", "libpaths" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<path_list>") Continue For End If libPaths.AddRange(ParseSeparatedPaths(value)) Continue For #If DEBUG Then Case "attachdebugger" Debugger.Launch() Continue For #End If End Select If IsScriptCommandLineParser Then Select Case name Case "-" If Console.IsInputRedirected Then sourceFiles.Add(New CommandLineSourceFile("-", isScript:=True, isInputRedirected:=True)) hasSourceFiles = True Else AddDiagnostic(diagnostics, ERRID.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected) End If Continue For Case "i", "i+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "i") End If interactiveMode = True Continue For Case "i-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "i") End If interactiveMode = False Continue For Case "loadpath", "loadpaths" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<path_list>") Continue For End If sourcePaths.AddRange(ParseSeparatedPaths(value)) Continue For End Select Else Select Case name Case "out" If String.IsNullOrWhiteSpace(value) Then ' When the value has " " (e.g., "/out: ") ' the Roslyn VB compiler reports "BC 2006 : option 'out' requires ':<file>', ' While the Dev11 VB compiler reports "BC2012 : can't open ' ' for writing, AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file>") Else ' Even when value is neither null or whitespace, the output file name still could be invalid. (e.g., "/out:sub\ ") ' While the Dev11 VB compiler reports "BC2012: can't open 'sub\ ' for writing, ' the Roslyn VB compiler reports "BC2032: File name 'sub\ ' is empty, contains invalid characters, ..." ' which is generated by the following ParseOutputFile. ParseOutputFile(value, diagnostics, baseDirectory, outputFileName, outputDirectory) End If Continue For Case "refout" Dim unquoted = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(unquoted) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file>") Else outputRefFileName = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory) End If Continue For Case "refonly", "refonly+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "refonly") End If refOnly = True Continue For Case "t", "target" value = RemoveQuotesAndSlashes(value) outputKind = ParseTarget(name, value, diagnostics) Continue For Case "moduleassemblyname" value = RemoveQuotesAndSlashes(value) Dim identity As AssemblyIdentity = Nothing ' Note that native compiler also extracts public key, but Roslyn doesn't use it. If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "moduleassemblyname", ":<string>") ElseIf Not AssemblyIdentity.TryParseDisplayName(value, identity) OrElse Not MetadataHelpers.IsValidAssemblyOrModuleName(identity.Name) Then AddDiagnostic(diagnostics, ERRID.ERR_InvalidAssemblyName, value, arg) Else moduleAssemblyName = identity.Name End If Continue For Case "rootnamespace" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "rootnamespace", ":<string>") Continue For End If rootNamespace = value Continue For Case "doc" value = RemoveQuotesAndSlashes(value) parseDocumentationComments = True If value Is Nothing Then ' Illegal in C#, but works in VB documentationPath = GenerateFileNameForDocComment Continue For End If Dim unquoted = RemoveQuotesAndSlashes(value) If unquoted.Length = 0 Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "doc", ":<file>") Else documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory, generateDiagnostic:=False) If String.IsNullOrWhiteSpace(documentationPath) Then AddDiagnostic(diagnostics, ERRID.WRN_XMLCannotWriteToXMLDocFile2, unquoted, New LocalizableErrorArgument(ERRID.IDS_TheSystemCannotFindThePathSpecified)) documentationPath = Nothing End If End If Continue For Case "doc+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "doc") End If ' Seems redundant with default values, but we need to clobber any preceding /doc switches documentationPath = GenerateFileNameForDocComment parseDocumentationComments = True Continue For Case "doc-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "doc") End If ' Seems redundant with default values, but we need to clobber any preceding /doc switches documentationPath = Nothing parseDocumentationComments = False Continue For Case "errorlog" Dim unquoted = RemoveQuotesAndSlashes(value) If (String.IsNullOrWhiteSpace(unquoted)) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "errorlog", ErrorLogOptionFormat) Else Dim diagnosticAlreadyReported As Boolean errorLogOptions = ParseErrorLogOptions(unquoted.AsMemory(), diagnostics, baseDirectory, diagnosticAlreadyReported) If errorLogOptions Is Nothing And Not diagnosticAlreadyReported Then AddDiagnostic(diagnostics, ERRID.ERR_BadSwitchValue, unquoted, "errorlog", ErrorLogOptionFormat) Continue For End If End If Continue For Case "netcf" ' Do nothing as we no longer have any use for implementing this switch and ' want to avoid failing with any warnings/errors Continue For Case "sdkpath" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "sdkpath", ":<path>") Continue For End If sdkPaths.Clear() sdkPaths.AddRange(ParseSeparatedPaths(value)) Continue For Case "nosdkpath" sdkDirectory = Nothing sdkPaths.Clear() Continue For Case "instrument" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "instrument", ":<string>") Continue For End If For Each instrumentationKind As InstrumentationKind In ParseInstrumentationKinds(value, diagnostics) If Not instrumentationKinds.Contains(instrumentationKind) Then instrumentationKinds.Add(instrumentationKind) End If Next Continue For Case "recurse" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "recurse", ":<wildcard>") Continue For End If Dim before As Integer = sourceFiles.Count sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics)) If sourceFiles.Count > before Then hasSourceFiles = True End If Continue For Case "addmodule" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "addmodule", ":<file_list>") Continue For End If ' NOTE(tomat): Dev10 reports "Command line error BC2017 : could not find library." ' Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. ' An error will be reported by the assembly manager anyways. metadataReferences.AddRange( ParseSeparatedPaths(value).Select( Function(path) New CommandLineReference(path, New MetadataReferenceProperties(MetadataImageKind.Module)))) Continue For Case "l", "link" metadataReferences.AddRange(ParseAssemblyReferences(name, value, diagnostics, embedInteropTypes:=True)) Continue For Case "win32resource" win32ResourceFile = GetWin32Setting(s_win32Res, RemoveQuotesAndSlashes(value), diagnostics) Continue For Case "win32icon" win32IconFile = GetWin32Setting(s_win32Icon, RemoveQuotesAndSlashes(value), diagnostics) Continue For Case "win32manifest" win32ManifestFile = GetWin32Setting(s_win32Manifest, RemoveQuotesAndSlashes(value), diagnostics) Continue For Case "nowin32manifest" If value IsNot Nothing Then Exit Select End If noWin32Manifest = True Continue For Case "res", "resource" Dim embeddedResource = ParseResourceDescription(name, value, baseDirectory, diagnostics, embedded:=True) If embeddedResource IsNot Nothing Then managedResources.Add(embeddedResource) End If Continue For Case "linkres", "linkresource" Dim linkedResource = ParseResourceDescription(name, value, baseDirectory, diagnostics, embedded:=False) If linkedResource IsNot Nothing Then managedResources.Add(linkedResource) End If Continue For Case "sourcelink" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "sourcelink", ":<file>") Else sourceLink = ParseGenericPathToFile(value, diagnostics, baseDirectory) End If Continue For Case "debug" ' parse only for backwards compat value = RemoveQuotesAndSlashes(value) If value IsNot Nothing Then Select Case value.ToLower() Case "full", "pdbonly" debugInformationFormat = If(PathUtilities.IsUnixLikePlatform, DebugInformationFormat.PortablePdb, DebugInformationFormat.Pdb) Case "portable" debugInformationFormat = DebugInformationFormat.PortablePdb Case "embedded" debugInformationFormat = DebugInformationFormat.Embedded Case Else AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, "debug", value) End Select End If emitPdb = True Continue For Case "debug+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "debug") End If emitPdb = True Continue For Case "debug-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "debug") End If emitPdb = False Continue For Case "optimize", "optimize+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optimize") Continue For End If optimize = True Continue For Case "optimize-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "optimize") Continue For End If optimize = False Continue For Case "parallel", "p" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name) Continue For End If concurrentBuild = True Continue For Case "deterministic", "deterministic+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name) Continue For End If deterministic = True Continue For Case "deterministic-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name) Continue For End If deterministic = False Continue For Case "parallel+", "p+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name.Substring(0, name.Length - 1)) Continue For End If concurrentBuild = True Continue For Case "parallel-", "p-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name.Substring(0, name.Length - 1)) Continue For End If concurrentBuild = False Continue For Case "warnaserror", "warnaserror+" If value Is Nothing Then generalDiagnosticOption = ReportDiagnostic.Error specificDiagnosticOptionsFromGeneralArguments.Clear() For Each pair In specificDiagnosticOptionsFromRuleSet If pair.Value = ReportDiagnostic.Warn Then specificDiagnosticOptionsFromGeneralArguments.Add(pair.Key, ReportDiagnostic.Error) End If Next Continue For End If AddWarnings(specificDiagnosticOptionsFromSpecificArguments, ReportDiagnostic.Error, ParseWarnings(value)) Continue For Case "warnaserror-" If value Is Nothing Then If generalDiagnosticOption <> ReportDiagnostic.Suppress Then generalDiagnosticOption = ReportDiagnostic.Default End If specificDiagnosticOptionsFromGeneralArguments.Clear() Continue For End If For Each id In ParseWarnings(value) Dim ruleSetValue As ReportDiagnostic If specificDiagnosticOptionsFromRuleSet.TryGetValue(id, ruleSetValue) Then specificDiagnosticOptionsFromSpecificArguments(id) = ruleSetValue Else specificDiagnosticOptionsFromSpecificArguments(id) = ReportDiagnostic.Default End If Next Continue For Case "nowarn" If value Is Nothing Then generalDiagnosticOption = ReportDiagnostic.Suppress specificDiagnosticOptionsFromGeneralArguments.Clear() For Each pair In specificDiagnosticOptionsFromRuleSet If pair.Value <> ReportDiagnostic.Error Then specificDiagnosticOptionsFromGeneralArguments.Add(pair.Key, ReportDiagnostic.Suppress) End If Next Continue For End If AddWarnings(specificDiagnosticOptionsFromNoWarnArguments, ReportDiagnostic.Suppress, ParseWarnings(value)) Continue For Case "langversion" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "langversion", ":<number>") ElseIf value = "?" Then displayLangVersions = True Else If Not TryParse(value, languageVersion) Then AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, "langversion", value) End If End If Continue For Case "delaysign", "delaysign+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "delaysign") Continue For End If delaySignSetting = True Continue For Case "delaysign-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "delaysign") Continue For End If delaySignSetting = False Continue For Case "publicsign", "publicsign+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "publicsign") Continue For End If publicSign = True Continue For Case "publicsign-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "publicsign") Continue For End If publicSign = False Continue For Case "keycontainer" ' NOTE: despite what MSDN says, Dev11 resets '/keyfile' in this case: ' ' MSDN: In case both /keyfile and /keycontainer are specified (either by command-line ' MSDN: option or by custom attribute) in the same compilation, the compiler first tries ' MSDN: the key container. If that succeeds, then the assembly is signed with the ' MSDN: information in the key container. If the compiler does not find the key container, ' MSDN: it tries the file specified with /keyfile. If this succeeds, the assembly is ' MSDN: signed with the information in the key file, and the key information is installed ' MSDN: in the key container (similar to sn -i) so that on the next compilation, ' MSDN: the key container will be valid. value = RemoveQuotesAndSlashes(value) keyFileSetting = Nothing If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "keycontainer", ":<string>") Else keyContainerSetting = value End If Continue For Case "keyfile" ' NOTE: despite what MSDN says, Dev11 resets '/keycontainer' in this case: ' ' MSDN: In case both /keyfile and /keycontainer are specified (either by command-line ' MSDN: option or by custom attribute) in the same compilation, the compiler first tries ' MSDN: the key container. If that succeeds, then the assembly is signed with the ' MSDN: information in the key container. If the compiler does not find the key container, ' MSDN: it tries the file specified with /keyfile. If this succeeds, the assembly is ' MSDN: signed with the information in the key file, and the key information is installed ' MSDN: in the key container (similar to sn -i) so that on the next compilation, ' MSDN: the key container will be valid. value = RemoveQuotesAndSlashes(value) keyContainerSetting = Nothing If String.IsNullOrWhiteSpace(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "keyfile", ":<file>") Else keyFileSetting = value End If Continue For Case "highentropyva", "highentropyva+" If value IsNot Nothing Then Exit Select End If highEntropyVA = True Continue For Case "highentropyva-" If value IsNot Nothing Then Exit Select End If highEntropyVA = False Continue For Case "nologo", "nologo+" If value IsNot Nothing Then Exit Select End If displayLogo = False Continue For Case "nologo-" If value IsNot Nothing Then Exit Select End If displayLogo = True Continue For Case "quiet+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "quiet") Continue For End If outputLevel = VisualBasic.OutputLevel.Quiet Continue For Case "quiet" If value IsNot Nothing Then Exit Select End If outputLevel = VisualBasic.OutputLevel.Quiet Continue For Case "verbose" If value IsNot Nothing Then Exit Select End If outputLevel = VisualBasic.OutputLevel.Verbose Continue For Case "verbose+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "verbose") Continue For End If outputLevel = VisualBasic.OutputLevel.Verbose Continue For Case "quiet-", "verbose-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, name.Substring(0, name.Length - 1)) Continue For End If outputLevel = VisualBasic.OutputLevel.Normal Continue For Case "utf8output", "utf8output+" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "utf8output") End If utf8output = True Continue For Case "utf8output-" If value IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_SwitchNeedsBool, "utf8output") End If utf8output = False Continue For Case "noconfig" ' It is already handled (see CommonCommandLineCompiler.cs). Continue For Case "bugreport" ' Do nothing as we no longer have any use for implementing this switch and ' want to avoid failing with any warnings/errors ' We do no further checking as to a value provided or not and ' ' this will cause no diagnostics for invalid values. Continue For Case "errorreport" ' Allows any value to be entered and will just silently do nothing ' previously we would validate value for prompt, send Or Queue ' This will cause no diagnostics for invalid values. Continue For Case "novbruntimeref" ' The switch is no longer supported and for backwards compat ignored. Continue For Case "m", "main" ' MSBuild can result in maintypename being passed in quoted when Cyrillic namespace was being used resulting ' in ERRID.ERR_StartupCodeNotFound1 diagnostic. The additional quotes cause problems and quotes are not a ' valid character in typename. value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<class>") Continue For End If mainTypeName = value Continue For Case "subsystemversion" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<version>") Continue For End If Dim version As SubsystemVersion = Nothing If SubsystemVersion.TryParse(value, version) Then ssVersion = version Else AddDiagnostic(diagnostics, ERRID.ERR_InvalidSubsystemVersion, value) End If Continue For Case "touchedfiles" Dim unquoted = RemoveQuotesAndSlashes(value) If (String.IsNullOrEmpty(unquoted)) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<touchedfiles>") Continue For Else touchedFilesPath = unquoted End If Continue For Case "fullpaths", "errorendlocation" UnimplementedSwitch(diagnostics, name) Continue For Case "pathmap" ' "/pathmap:K1=V1,K2=V2..." Dim unquoted = RemoveQuotesAndSlashes(value) If unquoted = Nothing Then Exit Select End If pathMap = pathMap.Concat(ParsePathMap(unquoted, diagnostics)) Continue For Case "reportanalyzer" reportAnalyzer = True Continue For Case "skipanalyzers", "skipanalyzers+" If value IsNot Nothing Then Exit Select End If skipAnalyzers = True Continue For Case "skipanalyzers-" If value IsNot Nothing Then Exit Select End If skipAnalyzers = False Continue For Case "nostdlib" If value IsNot Nothing Then Exit Select End If noStdLib = True Continue For Case "vbruntime" If value Is Nothing Then GoTo lVbRuntimePlus End If ' NOTE: that Dev11 does not report errors on empty or invalid file specified vbRuntimePath = RemoveQuotesAndSlashes(value) includeVbRuntimeReference = True embedVbCoreRuntime = False Continue For Case "vbruntime+" If value IsNot Nothing Then Exit Select End If lVbRuntimePlus: vbRuntimePath = Nothing includeVbRuntimeReference = True embedVbCoreRuntime = False Continue For Case "vbruntime-" If value IsNot Nothing Then Exit Select End If vbRuntimePath = Nothing includeVbRuntimeReference = False embedVbCoreRuntime = False Continue For Case "vbruntime*" If value IsNot Nothing Then Exit Select End If vbRuntimePath = Nothing includeVbRuntimeReference = False embedVbCoreRuntime = True Continue For Case "platform" value = RemoveQuotesAndSlashes(value) If value IsNot Nothing Then platform = ParsePlatform(name, value, diagnostics) Else AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, "platform", ":<string>") End If Continue For Case "filealign" fileAlignment = ParseFileAlignment(name, RemoveQuotesAndSlashes(value), diagnostics) Continue For Case "baseaddress" baseAddress = ParseBaseAddress(name, RemoveQuotesAndSlashes(value), diagnostics) Continue For Case "ruleset" ' The ruleset arg has already been processed in a separate pass above. Continue For Case "features" If value Is Nothing Then features.Clear() Else features.Add(RemoveQuotesAndSlashes(value)) End If Continue For Case "additionalfile" If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file_list>") Continue For End If For Each path In ParseSeparatedFileArgument(value, baseDirectory, diagnostics) additionalFiles.Add(ToCommandLineSourceFile(path)) Next Continue For Case "analyzerconfig" value = RemoveQuotesAndSlashes(value) If String.IsNullOrEmpty(value) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file_list>") Continue For End If analyzerConfigPaths.AddRange(ParseSeparatedFileArgument(value, baseDirectory, diagnostics)) Continue For Case "embed" If String.IsNullOrEmpty(value) Then embedAllSourceFiles = True Continue For End If For Each path In ParseSeparatedFileArgument(value, baseDirectory, diagnostics) embeddedFiles.Add(ToCommandLineSourceFile(path)) Next Continue For Case "-" If Console.IsInputRedirected Then sourceFiles.Add(New CommandLineSourceFile("-", isScript:=False, isInputRedirected:=True)) hasSourceFiles = True Else AddDiagnostic(diagnostics, ERRID.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected) End If Continue For End Select End If AddDiagnostic(diagnostics, ERRID.WRN_BadSwitch, arg) Next Dim specificDiagnosticOptions = New Dictionary(Of String, ReportDiagnostic)(specificDiagnosticOptionsFromRuleSet, CaseInsensitiveComparison.Comparer) For Each item In specificDiagnosticOptionsFromGeneralArguments specificDiagnosticOptions(item.Key) = item.Value Next For Each item In specificDiagnosticOptionsFromSpecificArguments specificDiagnosticOptions(item.Key) = item.Value Next For Each item In specificDiagnosticOptionsFromNoWarnArguments specificDiagnosticOptions(item.Key) = item.Value Next If refOnly AndAlso outputRefFileName IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_NoRefOutWhenRefOnly) End If If outputKind = OutputKind.NetModule AndAlso (refOnly OrElse outputRefFileName IsNot Nothing) Then AddDiagnostic(diagnostics, ERRID.ERR_NoNetModuleOutputWhenRefOutOrRefOnly) End If If Not IsScriptCommandLineParser AndAlso Not hasSourceFiles AndAlso managedResources.IsEmpty() Then ' VB displays help when there is nothing specified on the command line If flattenedArgs.Any Then AddDiagnostic(diagnostics, ERRID.ERR_NoSources) Else displayHelp = True End If End If ' Prepare SDK PATH If sdkDirectory IsNot Nothing AndAlso sdkPaths.Count = 0 Then sdkPaths.Add(sdkDirectory) End If ' Locate default 'mscorlib.dll' or 'System.Runtime.dll', if any. Dim defaultCoreLibraryReference As CommandLineReference? = LoadCoreLibraryReference(sdkPaths, baseDirectory) ' If /nostdlib is not specified, load System.dll ' Dev12 does it through combination of CompilerHost::InitStandardLibraryList and CompilerProject::AddStandardLibraries. If Not noStdLib Then Dim systemDllPath As String = FindFileInSdkPath(sdkPaths, "System.dll", baseDirectory) If systemDllPath Is Nothing Then AddDiagnostic(diagnostics, ERRID.WRN_CannotFindStandardLibrary1, "System.dll") Else metadataReferences.Add( New CommandLineReference(systemDllPath, New MetadataReferenceProperties(MetadataImageKind.Assembly))) End If ' Dev11 also adds System.Core.dll in VbHostedCompiler::CreateCompilerProject() End If ' Add reference to 'Microsoft.VisualBasic.dll' if needed If includeVbRuntimeReference Then If vbRuntimePath Is Nothing Then Dim msVbDllPath As String = FindFileInSdkPath(sdkPaths, "Microsoft.VisualBasic.dll", baseDirectory) If msVbDllPath Is Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_LibNotFound, "Microsoft.VisualBasic.dll") Else metadataReferences.Add( New CommandLineReference(msVbDllPath, New MetadataReferenceProperties(MetadataImageKind.Assembly))) End If Else metadataReferences.Add(New CommandLineReference(vbRuntimePath, New MetadataReferenceProperties(MetadataImageKind.Assembly))) End If End If ' add additional reference paths if specified If Not String.IsNullOrEmpty(additionalReferenceDirectories) Then libPaths.AddRange(ParseSeparatedPaths(additionalReferenceDirectories)) End If ' Build search path Dim searchPaths As ImmutableArray(Of String) = BuildSearchPaths(baseDirectory, sdkPaths, responsePaths, libPaths) ' Public sign doesn't use legacy search path settings If publicSign AndAlso Not String.IsNullOrEmpty(keyFileSetting) Then keyFileSetting = ParseGenericPathToFile(keyFileSetting, diagnostics, baseDirectory) End If ValidateWin32Settings(noWin32Manifest, win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics) If sourceLink IsNot Nothing And Not emitPdb Then AddDiagnostic(diagnostics, ERRID.ERR_SourceLinkRequiresPdb) End If If embedAllSourceFiles Then embeddedFiles.AddRange(sourceFiles) End If If embeddedFiles.Count > 0 And Not emitPdb Then AddDiagnostic(diagnostics, ERRID.ERR_CannotEmbedWithoutPdb) End If ' Validate root namespace if specified Debug.Assert(rootNamespace IsNot Nothing) ' NOTE: empty namespace is a valid option If Not String.Empty.Equals(rootNamespace) Then rootNamespace = rootNamespace.Unquote() If String.IsNullOrWhiteSpace(rootNamespace) OrElse Not OptionsValidator.IsValidNamespaceName(rootNamespace) Then AddDiagnostic(diagnostics, ERRID.ERR_BadNamespaceName1, rootNamespace) rootNamespace = "" ' To make it pass compilation options' check End If End If ' Dev10 searches for the keyfile in the current directory and assembly output directory. ' We always look to base directory and then examine the search paths. If Not String.IsNullOrEmpty(baseDirectory) Then keyFileSearchPaths.Add(baseDirectory) End If If Not String.IsNullOrEmpty(outputDirectory) AndAlso baseDirectory <> outputDirectory Then keyFileSearchPaths.Add(outputDirectory) End If Dim parsedFeatures = ParseFeatures(features) Dim compilationName As String = Nothing GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, moduleAssemblyName, outputFileName, moduleName, compilationName) If Not IsScriptCommandLineParser AndAlso Not hasSourceFiles AndAlso Not managedResources.IsEmpty() AndAlso outputFileName = Nothing AndAlso Not flattenedArgs.IsEmpty() Then AddDiagnostic(diagnostics, ERRID.ERR_NoSourcesOut) End If flattenedArgs.Free() Dim parseOptions = New VisualBasicParseOptions( languageVersion:=languageVersion, documentationMode:=If(parseDocumentationComments, DocumentationMode.Diagnose, DocumentationMode.None), kind:=If(IsScriptCommandLineParser, SourceCodeKind.Script, SourceCodeKind.Regular), preprocessorSymbols:=AddPredefinedPreprocessorSymbols(outputKind, defines.AsImmutableOrEmpty()), features:=parsedFeatures) ' We want to report diagnostics with source suppression in the error log file. ' However, these diagnostics won't be reported on the command line. Dim reportSuppressedDiagnostics = errorLogOptions IsNot Nothing Dim options = New VisualBasicCompilationOptions( outputKind:=outputKind, moduleName:=moduleName, mainTypeName:=mainTypeName, scriptClassName:=WellKnownMemberNames.DefaultScriptClassName, globalImports:=globalImports, rootNamespace:=rootNamespace, optionStrict:=optionStrict, optionInfer:=optionInfer, optionExplicit:=optionExplicit, optionCompareText:=optionCompareText, embedVbCoreRuntime:=embedVbCoreRuntime, checkOverflow:=checkOverflow, concurrentBuild:=concurrentBuild, deterministic:=deterministic, cryptoKeyContainer:=keyContainerSetting, cryptoKeyFile:=keyFileSetting, delaySign:=delaySignSetting, publicSign:=publicSign, platform:=platform, generalDiagnosticOption:=generalDiagnosticOption, specificDiagnosticOptions:=specificDiagnosticOptions, optimizationLevel:=If(optimize, OptimizationLevel.Release, OptimizationLevel.Debug), parseOptions:=parseOptions, reportSuppressedDiagnostics:=reportSuppressedDiagnostics) Dim emitOptions = New EmitOptions( metadataOnly:=refOnly, includePrivateMembers:=Not refOnly AndAlso outputRefFileName Is Nothing, debugInformationFormat:=debugInformationFormat, pdbFilePath:=Nothing, ' to be determined later outputNameOverride:=Nothing, ' to be determined later fileAlignment:=fileAlignment, baseAddress:=baseAddress, highEntropyVirtualAddressSpace:=highEntropyVA, subsystemVersion:=ssVersion, runtimeMetadataVersion:=Nothing, instrumentationKinds:=instrumentationKinds.ToImmutableAndFree(), pdbChecksumAlgorithm:=HashAlgorithmName.SHA256) ' TODO: set from /checksumalgorithm (see https://github.com/dotnet/roslyn/issues/24735) ' add option incompatibility errors if any (parse options will be included in options.Errors) diagnostics.AddRange(options.Errors) If documentationPath Is GenerateFileNameForDocComment Then documentationPath = PathUtilities.CombineAbsoluteAndRelativePaths(outputDirectory, PathUtilities.RemoveExtension(outputFileName)) documentationPath = documentationPath + ".xml" End If ' Enable interactive mode if either `\i` option is passed in or no arguments are specified (`vbi`, `vbi script.vbx \i`). ' If the script is passed without the `\i` option simply execute the script (`vbi script.vbx`). interactiveMode = interactiveMode Or (IsScriptCommandLineParser AndAlso sourceFiles.Count = 0) pathMap = SortPathMap(pathMap) Return New VisualBasicCommandLineArguments With { .IsScriptRunner = IsScriptCommandLineParser, .InteractiveMode = interactiveMode, .BaseDirectory = baseDirectory, .Errors = diagnostics.AsImmutable(), .Utf8Output = utf8output, .CompilationName = compilationName, .OutputFileName = outputFileName, .OutputRefFilePath = outputRefFileName, .OutputDirectory = outputDirectory, .DocumentationPath = documentationPath, .ErrorLogOptions = errorLogOptions, .SourceFiles = sourceFiles.AsImmutable(), .PathMap = pathMap, .Encoding = codepage, .ChecksumAlgorithm = checksumAlgorithm, .MetadataReferences = metadataReferences.AsImmutable(), .AnalyzerReferences = analyzers.AsImmutable(), .AdditionalFiles = additionalFiles.AsImmutable(), .AnalyzerConfigPaths = analyzerConfigPaths.ToImmutableAndFree(), .ReferencePaths = searchPaths, .SourcePaths = sourcePaths.AsImmutable(), .KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), .Win32ResourceFile = win32ResourceFile, .Win32Icon = win32IconFile, .Win32Manifest = win32ManifestFile, .NoWin32Manifest = noWin32Manifest, .DisplayLogo = displayLogo, .DisplayHelp = displayHelp, .DisplayVersion = displayVersion, .DisplayLangVersions = displayLangVersions, .ManifestResources = managedResources.AsImmutable(), .CompilationOptions = options, .ParseOptions = parseOptions, .EmitOptions = emitOptions, .ScriptArguments = scriptArgs.AsImmutableOrEmpty(), .TouchedFilesPath = touchedFilesPath, .OutputLevel = outputLevel, .EmitPdb = emitPdb AndAlso Not refOnly, ' Silently ignore emitPdb when refOnly is set .SourceLink = sourceLink, .RuleSetPath = ruleSetPath, .DefaultCoreLibraryReference = defaultCoreLibraryReference, .PreferredUILang = preferredUILang, .ReportAnalyzer = reportAnalyzer, .SkipAnalyzers = skipAnalyzers, .EmbeddedFiles = embeddedFiles.AsImmutable() } End Function Private Function LoadCoreLibraryReference(sdkPaths As List(Of String), baseDirectory As String) As CommandLineReference? ' Load Core library in Dev11: ' Traditionally VB compiler has hard-coded the name of mscorlib.dll. In the Immersive profile the ' library is called System.Runtime.dll. Ideally we should get rid of the dependency on the name and ' identify the core library as the assembly that contains System.Object. At this point in the compiler, ' it is too early though as we haven't loaded any types or assemblies. Changing this now is a deep ' change. So the workaround here is to allow mscorlib or system.runtime and prefer system.runtime if present. ' There is an extra check to only pick an assembly with no other assembly refs. This is so that is an ' user drops a user-defined binary called System.runtime.dll into the fx directory we still want to pick ' mscorlib. Dim msCorLibPath As String = FindFileInSdkPath(sdkPaths, "mscorlib.dll", baseDirectory) Dim systemRuntimePath As String = FindFileInSdkPath(sdkPaths, "System.Runtime.dll", baseDirectory) If systemRuntimePath IsNot Nothing Then If msCorLibPath Is Nothing Then Return New CommandLineReference(systemRuntimePath, New MetadataReferenceProperties(MetadataImageKind.Assembly)) End If ' Load System.Runtime.dll and see if it has any references Try Using metadata = AssemblyMetadata.CreateFromFile(systemRuntimePath) ' Prefer 'System.Runtime.dll' if it does not have any references If metadata.GetModules()(0).Module.IsLinkedModule AndAlso metadata.GetAssembly().AssemblyReferences.Length = 0 Then Return New CommandLineReference(systemRuntimePath, New MetadataReferenceProperties(MetadataImageKind.Assembly)) End If End Using Catch ' If we caught anything, there is something wrong with System.Runtime.dll and we fall back to mscorlib.dll End Try ' Otherwise prefer 'mscorlib.dll' Return New CommandLineReference(msCorLibPath, New MetadataReferenceProperties(MetadataImageKind.Assembly)) End If If msCorLibPath IsNot Nothing Then ' We return a reference to 'mscorlib.dll' Return New CommandLineReference(msCorLibPath, New MetadataReferenceProperties(MetadataImageKind.Assembly)) End If Return Nothing End Function Private Shared Function FindFileInSdkPath(sdkPaths As List(Of String), fileName As String, baseDirectory As String) As String For Each path In sdkPaths Debug.Assert(path IsNot Nothing) Dim absolutePath = FileUtilities.ResolveRelativePath(path, baseDirectory) If absolutePath IsNot Nothing Then Dim filePath = PathUtilities.CombineAbsoluteAndRelativePaths(absolutePath, fileName) If File.Exists(filePath) Then Return filePath End If End If Next Return Nothing End Function Private Shared Function GetWin32Setting(arg As String, value As String, diagnostics As List(Of Diagnostic)) As String If value Is Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, arg, ":<file>") Else Dim noQuotes As String = RemoveQuotesAndSlashes(value) If String.IsNullOrWhiteSpace(noQuotes) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, arg, ":<file>") Else Return noQuotes End If End If Return Nothing End Function Private Shared Function BuildSearchPaths(baseDirectory As String, sdkPaths As List(Of String), responsePaths As List(Of String), libPaths As List(Of String)) As ImmutableArray(Of String) Dim builder = ArrayBuilder(Of String).GetInstance() ' Match how Dev11 builds the list of search paths ' see void GetSearchPath(CComBSTR& strSearchPath) ' current folder -- base directory is searched by default by the FileResolver ' SDK path is specified or current runtime directory AddNormalizedPaths(builder, sdkPaths, baseDirectory) ' Response file path, see the following comment from Dev11: ' // .NET FX 3.5 will have response file in the FX 3.5 directory but SdkPath will still be in 2.0 directory. ' // Therefore we need to make sure the response file directories are also on the search path ' // so response file authors can continue to use relative paths in the response files. builder.AddRange(responsePaths) ' libpath AddNormalizedPaths(builder, libPaths, baseDirectory) Return builder.ToImmutableAndFree() End Function Private Shared Sub AddNormalizedPaths(builder As ArrayBuilder(Of String), paths As List(Of String), baseDirectory As String) For Each path In paths Dim normalizedPath = FileUtilities.NormalizeRelativePath(path, basePath:=Nothing, baseDirectory:=baseDirectory) If normalizedPath Is Nothing Then ' just ignore invalid paths, native compiler doesn't report any errors Continue For End If builder.Add(normalizedPath) Next End Sub Private Shared Sub ValidateWin32Settings(noWin32Manifest As Boolean, win32ResSetting As String, win32IconSetting As String, win32ManifestSetting As String, outputKind As OutputKind, diagnostics As List(Of Diagnostic)) If noWin32Manifest AndAlso (win32ManifestSetting IsNot Nothing) Then AddDiagnostic(diagnostics, ERRID.ERR_ConflictingManifestSwitches) End If If win32ResSetting IsNot Nothing Then If win32IconSetting IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_IconFileAndWin32ResFile) End If If win32ManifestSetting IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_CantHaveWin32ResAndManifest) End If End If If win32ManifestSetting IsNot Nothing AndAlso outputKind.IsNetModule() Then AddDiagnostic(diagnostics, ERRID.WRN_IgnoreModuleManifest) End If End Sub Private Shared Function ParseTarget(optionName As String, value As String, diagnostics As IList(Of Diagnostic)) As OutputKind Select Case If(value, "").ToLowerInvariant() Case "exe" Return OutputKind.ConsoleApplication Case "winexe" Return OutputKind.WindowsApplication Case "library" Return OutputKind.DynamicallyLinkedLibrary Case "module" Return OutputKind.NetModule Case "appcontainerexe" Return OutputKind.WindowsRuntimeApplication Case "winmdobj" Return OutputKind.WindowsRuntimeMetadata Case "" AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, optionName, ":exe|winexe|library|module|appcontainerexe|winmdobj") Return OutputKind.ConsoleApplication Case Else AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, optionName, value) Return OutputKind.ConsoleApplication End Select End Function Friend Shared Function ParseAssemblyReferences(name As String, value As String, diagnostics As IList(Of Diagnostic), embedInteropTypes As Boolean) As IEnumerable(Of CommandLineReference) If String.IsNullOrEmpty(value) Then ' TODO: localize <file_list>? AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file_list>") Return SpecializedCollections.EmptyEnumerable(Of CommandLineReference)() End If Return ParseSeparatedPaths(value). Select(Function(path) New CommandLineReference(path, New MetadataReferenceProperties(MetadataImageKind.Assembly, embedInteropTypes:=embedInteropTypes))) End Function Private Shared Function ParseAnalyzers(name As String, value As String, diagnostics As IList(Of Diagnostic)) As IEnumerable(Of CommandLineAnalyzerReference) If String.IsNullOrEmpty(value) Then ' TODO: localize <file_list>? AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<file_list>") Return SpecializedCollections.EmptyEnumerable(Of CommandLineAnalyzerReference)() End If Return ParseSeparatedPaths(value). Select(Function(path) Return New CommandLineAnalyzerReference(path) End Function) End Function ' See ParseCommandLine in vbc.cpp. Friend Overloads Shared Function ParseResourceDescription(name As String, resourceDescriptor As String, baseDirectory As String, diagnostics As IList(Of Diagnostic), embedded As Boolean) As ResourceDescription If String.IsNullOrEmpty(resourceDescriptor) Then AddDiagnostic(diagnostics, ERRID.ERR_ArgumentRequired, name, ":<resinfo>") Return Nothing End If ' NOTE: these are actually passed to out parameters of .ParseResourceDescription. Dim filePath As String = Nothing Dim fullPath As String = Nothing Dim fileName As String = Nothing Dim resourceName As String = Nothing Dim accessibility As String = Nothing ParseResourceDescription( resourceDescriptor.AsMemory(), baseDirectory, True, filePath, fullPath, fileName, resourceName, accessibility) If String.IsNullOrWhiteSpace(filePath) Then AddInvalidSwitchValueDiagnostic(diagnostics, name, filePath) Return Nothing End If If Not PathUtilities.IsValidFilePath(fullPath) Then AddDiagnostic(diagnostics, ERRID.FTL_InvalidInputFileName, filePath) Return Nothing End If Dim isPublic As Boolean If String.IsNullOrEmpty(accessibility) Then ' If no accessibility is given, we default to "public". ' NOTE: Dev10 treats empty the same as null (the difference being that empty indicates a comma after the resource name). ' NOTE: Dev10 distinguishes between empty and whitespace-only. isPublic = True ElseIf String.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase) Then isPublic = True ElseIf String.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase) Then isPublic = False Else AddInvalidSwitchValueDiagnostic(diagnostics, name, accessibility) Return Nothing End If Dim dataProvider As Func(Of Stream) = Function() ' Use FileShare.ReadWrite because the file could be opened by the current process. ' For example, it Is an XML doc file produced by the build. Return New FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) End Function Return New ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs:=False) End Function Private Shared Sub AddInvalidSwitchValueDiagnostic(diagnostics As IList(Of Diagnostic), ByVal name As String, ByVal nullStringText As String) If String.IsNullOrEmpty(name) Then ' NOTE: "(null)" to match Dev10. ' CONSIDER: should this be a resource string? name = "(null)" End If AddDiagnostic(diagnostics, ERRID.ERR_InvalidSwitchValue, name, nullStringText) End Sub Private Shared Sub ParseGlobalImports(value As String, globalImports As List(Of GlobalImport), errors As List(Of Diagnostic)) Dim importsArray = ParseSeparatedPaths(value) For Each importNamespace In importsArray Dim importDiagnostics As ImmutableArray(Of Diagnostic) = Nothing Dim import = GlobalImport.Parse(importNamespace, importDiagnostics) errors.AddRange(importDiagnostics) globalImports.Add(import) Next End Sub ''' <summary> ''' Converts a sequence of definitions provided by a caller (public API) into map ''' of definitions used internally. ''' </summary> ''' <exception cref="ArgumentException">Invalid value provided.</exception> Private Shared Function PublicSymbolsToInternalDefines(symbols As IEnumerable(Of KeyValuePair(Of String, Object)), diagnosticBuilder As ArrayBuilder(Of Diagnostic)) As ImmutableDictionary(Of String, InternalSyntax.CConst) Dim result = ImmutableDictionary.CreateBuilder(Of String, InternalSyntax.CConst)(CaseInsensitiveComparison.Comparer) If symbols IsNot Nothing Then For Each symbol In symbols Dim constant = InternalSyntax.CConst.TryCreate(symbol.Value) If constant Is Nothing Then diagnosticBuilder.Add(Diagnostic.Create(VisualBasic.MessageProvider.Instance, ERRID.ERR_InvalidPreprocessorConstantType, symbol.Key, symbol.Value.GetType())) End If result(symbol.Key) = constant Next End If Return result.ToImmutable() End Function ''' <summary> ''' Converts ImmutableDictionary of definitions used internally into IReadOnlyDictionary of definitions ''' returned to a caller (of public API) ''' </summary> Private Shared Function InternalDefinesToPublicSymbols(defines As ImmutableDictionary(Of String, InternalSyntax.CConst)) As IReadOnlyDictionary(Of String, Object) Dim result = ImmutableDictionary.CreateBuilder(Of String, Object)(CaseInsensitiveComparison.Comparer) For Each kvp In defines result(kvp.Key) = kvp.Value.ValueAsObject Next Return result.ToImmutable() End Function ''' <summary> ''' Parses Conditional Compilations Symbols. Given the string of conditional compilation symbols from the project system, parse them and merge them with an IReadOnlyDictionary ''' ready to be given to the compilation. ''' </summary> ''' <param name="symbolList"> ''' The conditional compilation string. This takes the form of a comma delimited list ''' of NAME=Value pairs, where Value may be a quoted string or integer. ''' </param> ''' <param name="diagnostics">A collection of reported diagnostics during parsing of symbolList, can be empty IEnumerable.</param> ''' <param name="symbols">A collection representing existing symbols. Symbols parsed from <paramref name="symbolList"/> will be merged with this dictionary. </param> ''' <exception cref="ArgumentException">Invalid value provided.</exception> Public Shared Function ParseConditionalCompilationSymbols( symbolList As String, <Out> ByRef diagnostics As IEnumerable(Of Diagnostic), Optional symbols As IEnumerable(Of KeyValuePair(Of String, Object)) = Nothing ) As IReadOnlyDictionary(Of String, Object) Dim diagnosticBuilder = ArrayBuilder(Of Diagnostic).GetInstance() Dim parsedTokensAsString As New StringBuilder Dim defines As ImmutableDictionary(Of String, InternalSyntax.CConst) = PublicSymbolsToInternalDefines(symbols, diagnosticBuilder) ' remove quotes around the whole /define argument (incl. nested) Dim unquotedString As String Do unquotedString = symbolList symbolList = symbolList.Unquote() Loop While Not String.Equals(symbolList, unquotedString, StringComparison.Ordinal) ' unescape quotes \" -> " symbolList = symbolList.Replace("\""", """") Dim trimmedSymbolList As String = symbolList.TrimEnd() If trimmedSymbolList.Length > 0 AndAlso IsConnectorPunctuation(trimmedSymbolList(trimmedSymbolList.Length - 1)) Then ' In case the symbol list ends with '_' we add ',' to the end of the list which in some ' cases will produce an error 30999 to match Dev11 behavior symbolList = symbolList + "," End If ' In order to determine our conditional compilation symbols, we must parse the string we get from the ' project system. We take a cue from the legacy language services and use the VB scanner, since this string ' apparently abides by the same tokenization rules Dim tokenList = SyntaxFactory.ParseTokens(symbolList) Using tokens = tokenList.GetEnumerator() If tokens.MoveNext() Then Do ' This is the beginning of declaration like 'A' or 'A=123' with optional extra ' separators (',' or ':') in the beginning, if this is NOT the first declaration, ' the tokens.Current should be either separator or EOF If tokens.Current.Position > 0 AndAlso Not IsSeparatorOrEndOfFile(tokens.Current) Then parsedTokensAsString.Append(" ^^ ^^ ") ' Complete parsedTokensAsString until the next comma or end of stream While Not IsSeparatorOrEndOfFile(tokens.Current) parsedTokensAsString.Append(tokens.Current.ToFullString()) tokens.MoveNext() End While diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedEOS), parsedTokensAsString.ToString), Location.None)) Exit Do End If Dim lastSeparatorToken As SyntaxToken = Nothing ' If we're on a comma, it means there was an empty item in the list (item1,,item2), ' so just eat it and move on... While tokens.Current.Kind = SyntaxKind.CommaToken OrElse tokens.Current.Kind = SyntaxKind.ColonToken If lastSeparatorToken.Kind = SyntaxKind.None Then ' accept multiple : or , lastSeparatorToken = tokens.Current ElseIf lastSeparatorToken.Kind <> tokens.Current.Kind Then ' but not mixing them, e.g. ::,,:: GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString, stopTokenKind:=lastSeparatorToken.Kind, includeCurrentToken:=True) diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedIdentifier), parsedTokensAsString.ToString), Location.None)) End If parsedTokensAsString.Append(tokens.Current.ToString) ' this can happen when the while loop above consumed all tokens for the diagnostic message If tokens.Current.Kind <> SyntaxKind.EndOfFileToken Then Dim moveNextResult = tokens.MoveNext Debug.Assert(moveNextResult) End If End While parsedTokensAsString.Clear() ' If we're at the end of the list, we're done If tokens.Current.Kind = SyntaxKind.EndOfFileToken Then Dim eof = tokens.Current If eof.FullWidth > 0 Then If Not eof.LeadingTrivia.All(Function(t) t.Kind = SyntaxKind.WhitespaceTrivia) Then ' This is an invalid line like "'Blah'" GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString, True) diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedIdentifier), parsedTokensAsString.ToString), Location.None)) End If End If Exit Do End If parsedTokensAsString.Append(tokens.Current.ToFullString()) If Not tokens.Current.Kind = SyntaxKind.IdentifierToken Then GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString) diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedIdentifier), parsedTokensAsString.ToString), Location.None)) Exit Do End If Dim symbolName = tokens.Current.ValueText ' there should at least be a end of file token Dim moveResult As Boolean = tokens.MoveNext Debug.Assert(moveResult) If tokens.Current.Kind = SyntaxKind.EqualsToken Then parsedTokensAsString.Append(tokens.Current.ToFullString()) ' there should at least be a end of file token moveResult = tokens.MoveNext Debug.Assert(moveResult) ' Parse expression starting with the offset Dim offset As Integer = tokens.Current.SpanStart Dim expression As ExpressionSyntax = ParseConditionalCompilationExpression(symbolList, offset) Dim parsedEnd As Integer = offset + expression.Span.End Dim atTheEndOrSeparator As Boolean = IsSeparatorOrEndOfFile(tokens.Current) ' Consume tokens that are supposed to belong to the expression; we loop ' until the token's end position is the end of the expression, but not consume ' the last token as it will be consumed in uppermost While While tokens.Current.Kind <> SyntaxKind.EndOfFileToken AndAlso tokens.Current.Span.End <= parsedEnd parsedTokensAsString.Append(tokens.Current.ToFullString()) moveResult = tokens.MoveNext Debug.Assert(moveResult) atTheEndOrSeparator = IsSeparatorOrEndOfFile(tokens.Current) End While If expression.ContainsDiagnostics Then ' Dev11 reports syntax errors in not consistent way, sometimes errors are not reported by ' command line utility at all; this implementation tries to repro Dev11 when possible parsedTokensAsString.Append(" ^^ ^^ ") ' Compete parsedTokensAsString until the next comma or end of stream While Not IsSeparatorOrEndOfFile(tokens.Current) parsedTokensAsString.Append(tokens.Current.ToFullString()) tokens.MoveNext() End While ' NOTE: Dev11 reports ERR_ExpectedExpression and ERR_BadCCExpression in different ' cases compared to what ParseConditionalCompilationExpression(...) generates, ' so we have to use different criteria here; if we don't want to match Dev11 ' errors we may simplify the code below Dim errorSkipped As Boolean = False For Each diag In expression.VbGreen.GetSyntaxErrors If diag.Code <> ERRID.ERR_ExpectedExpression AndAlso diag.Code <> ERRID.ERR_BadCCExpression Then diagnosticBuilder.Add(New DiagnosticWithInfo(ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, diag, parsedTokensAsString.ToString), Location.None)) Else errorSkipped = True End If Next If errorSkipped Then diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(If(atTheEndOrSeparator, ERRID.ERR_ExpectedExpression, ERRID.ERR_BadCCExpression)), parsedTokensAsString.ToString), Location.None)) End If Exit Do End If ' Expression parsed successfully --> evaluate it Dim value As InternalSyntax.CConst = InternalSyntax.ExpressionEvaluator.EvaluateExpression( DirectCast(expression.Green, InternalSyntax.ExpressionSyntax), defines) Dim err As ERRID = value.ErrorId If err <> 0 Then GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString) diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(err, value.ErrorArgs), parsedTokensAsString.ToString), Location.None)) Exit Do End If ' Expression evaluated successfully --> add to 'defines' defines = defines.SetItem(symbolName, value) ElseIf tokens.Current.Kind = SyntaxKind.CommaToken OrElse tokens.Current.Kind = SyntaxKind.ColonToken OrElse tokens.Current.Kind = SyntaxKind.EndOfFileToken Then ' We have no value being assigned, so we'll just assign it to true defines = defines.SetItem(symbolName, InternalSyntax.CConst.Create(True)) ElseIf tokens.Current.Kind = SyntaxKind.BadToken Then GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString) diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(ERRID.ERR_IllegalChar), parsedTokensAsString.ToString), Location.None)) Exit Do Else GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString) diagnosticBuilder.Add( New DiagnosticWithInfo( ErrorFactory.ErrorInfo(ERRID.ERR_ConditionalCompilationConstantNotValid, ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedEOS), parsedTokensAsString.ToString), Location.None)) Exit Do End If Loop End If End Using diagnostics = diagnosticBuilder.ToArrayAndFree() Return InternalDefinesToPublicSymbols(defines) End Function ''' <summary> ''' NOTE: implicit line continuation will not be handled here and an error will be generated, ''' but explicit one (like ".... _\r\n ....") should work fine ''' </summary> Private Shared Function ParseConditionalCompilationExpression(symbolList As String, offset As Integer) As ExpressionSyntax Using p = New InternalSyntax.Parser(SyntaxFactory.MakeSourceText(symbolList, offset), VisualBasicParseOptions.Default) p.GetNextToken() Return DirectCast(p.ParseConditionalCompilationExpression().CreateRed(Nothing, 0), ExpressionSyntax) End Using End Function Private Shared Iterator Function ParseInstrumentationKinds(value As String, diagnostics As IList(Of Diagnostic)) As IEnumerable(Of InstrumentationKind) Dim instrumentationKindStrs = value.Split({","c}, StringSplitOptions.RemoveEmptyEntries) For Each instrumentationKindStr In instrumentationKindStrs Select Case instrumentationKindStr.ToLower() Case "testcoverage" Yield InstrumentationKind.TestCoverage Case Else AddDiagnostic(diagnostics, ERRID.ERR_InvalidInstrumentationKind, instrumentationKindStr) End Select Next End Function Private Shared Function IsSeparatorOrEndOfFile(token As SyntaxToken) As Boolean Return token.Kind = SyntaxKind.EndOfFileToken OrElse token.Kind = SyntaxKind.ColonToken OrElse token.Kind = SyntaxKind.CommaToken End Function Private Shared Sub GetErrorStringForRemainderOfConditionalCompilation( tokens As IEnumerator(Of SyntaxToken), remainderErrorLine As StringBuilder, Optional includeCurrentToken As Boolean = False, Optional stopTokenKind As SyntaxKind = SyntaxKind.CommaToken ) If includeCurrentToken Then remainderErrorLine.Append(" ^^ ") If tokens.Current.Kind = SyntaxKind.ColonToken AndAlso tokens.Current.FullWidth = 0 Then remainderErrorLine.Append(SyntaxFacts.GetText(SyntaxKind.ColonToken)) Else remainderErrorLine.Append(tokens.Current.ToFullString()) End If remainderErrorLine.Append(" ^^ ") Else remainderErrorLine.Append(" ^^ ^^ ") End If While tokens.MoveNext AndAlso Not tokens.Current.Kind = stopTokenKind remainderErrorLine.Append(tokens.Current.ToFullString()) End While End Sub ''' <summary> ''' Parses the given platform option. Legal strings are "anycpu", "x64", "x86", "itanium", "anycpu32bitpreferred", "arm". ''' In case an invalid value was passed, anycpu is returned. ''' </summary> ''' <param name="value">The value for platform.</param> ''' <param name="errors">The error bag.</param> Private Shared Function ParsePlatform(name As String, value As String, errors As List(Of Diagnostic)) As Platform If value.IsEmpty Then AddDiagnostic(errors, ERRID.ERR_ArgumentRequired, name, ":<string>") Else Select Case value.ToLowerInvariant() Case "x86" Return Platform.X86 Case "x64" Return Platform.X64 Case "itanium" Return Platform.Itanium Case "anycpu" Return Platform.AnyCpu Case "anycpu32bitpreferred" Return Platform.AnyCpu32BitPreferred Case "arm" Return Platform.Arm Case "arm64" Return Platform.Arm64 Case Else AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, name, value) End Select End If Return Platform.AnyCpu End Function ''' <summary> ''' Parses the file alignment option. ''' In case an invalid value was passed, nothing is returned. ''' </summary> ''' <param name="name">The name of the option.</param> ''' <param name="value">The value for the option.</param> ''' <param name="errors">The error bag.</param><returns></returns> Private Shared Function ParseFileAlignment(name As String, value As String, errors As List(Of Diagnostic)) As Integer Dim alignment As UShort If String.IsNullOrEmpty(value) Then AddDiagnostic(errors, ERRID.ERR_ArgumentRequired, name, ":<number>") ElseIf Not TryParseUInt16(value, alignment) Then AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, name, value) ElseIf Not Microsoft.CodeAnalysis.CompilationOptions.IsValidFileAlignment(alignment) Then AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, name, value) Else Return alignment End If Return 0 End Function ''' <summary> ''' Parses the base address option. ''' In case an invalid value was passed, nothing is returned. ''' </summary> ''' <param name="name">The name of the option.</param> ''' <param name="value">The value for the option.</param> ''' <param name="errors">The error bag.</param><returns></returns> Private Shared Function ParseBaseAddress(name As String, value As String, errors As List(Of Diagnostic)) As ULong If String.IsNullOrEmpty(value) Then AddDiagnostic(errors, ERRID.ERR_ArgumentRequired, name, ":<number>") Else Dim baseAddress As ULong Dim parseValue As String = value If value.StartsWith("0x", StringComparison.OrdinalIgnoreCase) Then parseValue = value.Substring(2) ' UInt64.TryParse does not accept hex format strings End If ' always treat the base address string as being a hex number, regardless of the given format. ' This handling was hardcoded in the command line option parsing of Dev10 and Dev11. If Not ULong.TryParse(parseValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture, baseAddress) Then AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, name, value.ToString()) Else Return baseAddress End If End If Return 0 End Function ''' <summary> ''' Parses the warning option. ''' </summary> ''' <param name="value">The value for the option.</param> Private Shared Function ParseWarnings(value As String) As IEnumerable(Of String) Dim values = ParseSeparatedPaths(value) Dim results = New List(Of String)() For Each id In values Dim number As UShort If UShort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, number) AndAlso (VisualBasic.MessageProvider.Instance.GetSeverity(number) = DiagnosticSeverity.Warning) AndAlso (VisualBasic.MessageProvider.Instance.GetWarningLevel(number) = 1) Then ' The id refers to a compiler warning. ' Only accept real warnings from the compiler not including the command line warnings. ' Also only accept the numbers that are actually declared in the enum. results.Add(VisualBasic.MessageProvider.Instance.GetIdForErrorCode(CInt(number))) Else ' Previous versions of the compiler used to report warnings (BC2026, BC2014) ' whenever unrecognized warning codes were supplied in /nowarn or ' /warnaserror. We no longer generate a warning in such cases. ' Instead we assume that the unrecognized id refers to a custom diagnostic. results.Add(id) End If Next Return results End Function Private Shared Sub AddWarnings(d As IDictionary(Of String, ReportDiagnostic), kind As ReportDiagnostic, items As IEnumerable(Of String)) For Each id In items Dim existing As ReportDiagnostic If d.TryGetValue(id, existing) Then ' Rewrite the existing value with the latest one unless it is for /nowarn. If existing <> ReportDiagnostic.Suppress Then d(id) = kind End If Else d.Add(id, kind) End If Next End Sub Private Shared Sub UnimplementedSwitch(diagnostics As IList(Of Diagnostic), switchName As String) AddDiagnostic(diagnostics, ERRID.WRN_UnimplementedCommandLineSwitch, "/" + switchName) End Sub Friend Overrides Sub GenerateErrorForNoFilesFoundInRecurse(path As String, errors As IList(Of Diagnostic)) AddDiagnostic(errors, ERRID.ERR_InvalidSwitchValue, "recurse", path) End Sub Private Shared Sub AddDiagnostic(diagnostics As IList(Of Diagnostic), errorCode As ERRID, ParamArray arguments As Object()) diagnostics.Add(Diagnostic.Create(VisualBasic.MessageProvider.Instance, CInt(errorCode), arguments)) End Sub ''' <summary> ''' In VB, if the output file name isn't specified explicitly, then it is derived from the name of the ''' first input file. ''' </summary> ''' <remarks> ''' http://msdn.microsoft.com/en-us/library/std9609e(v=vs.110) ''' Specify the full name and extension of the file to create. If you do not, the .exe file takes ''' its name from the source-code file containing the Sub Main procedure, and the .dll file takes ''' its name from the first source-code file. ''' ''' However, vbc.cpp has: ''' <![CDATA[ ''' // Calculate the output name and directory ''' dwCharCount = GetFullPathName(pszOut ? pszOut : g_strFirstFile, &wszFileName); ''' ]]> ''' </remarks> Private Sub GetCompilationAndModuleNames(diagnostics As List(Of Diagnostic), kind As OutputKind, sourceFiles As List(Of CommandLineSourceFile), moduleAssemblyName As String, ByRef outputFileName As String, ByRef moduleName As String, <Out> ByRef compilationName As String) Dim simpleName As String = Nothing If outputFileName Is Nothing Then Dim first = sourceFiles.FirstOrDefault() If first.Path IsNot Nothing Then simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(first.Path)) outputFileName = simpleName & kind.GetDefaultExtension() If simpleName.Length = 0 AndAlso Not kind.IsNetModule() Then AddDiagnostic(diagnostics, ERRID.FTL_InvalidInputFileName, outputFileName) simpleName = Nothing outputFileName = Nothing End If End If Else Dim ext As String = PathUtilities.GetExtension(outputFileName) If kind.IsNetModule() Then If ext.Length = 0 Then outputFileName = outputFileName & ".netmodule" End If Else If Not ext.Equals(".exe", StringComparison.OrdinalIgnoreCase) And Not ext.Equals(".dll", StringComparison.OrdinalIgnoreCase) And Not ext.Equals(".netmodule", StringComparison.OrdinalIgnoreCase) And Not ext.Equals(".winmdobj", StringComparison.OrdinalIgnoreCase) Then simpleName = outputFileName outputFileName = outputFileName & kind.GetDefaultExtension() End If If simpleName Is Nothing Then simpleName = PathUtilities.RemoveExtension(outputFileName) ' /out:".exe" ' Dev11 emits assembly with an empty name, we don't If simpleName.Length = 0 Then AddDiagnostic(diagnostics, ERRID.FTL_InvalidInputFileName, outputFileName) simpleName = Nothing outputFileName = Nothing End If End If End If End If If kind.IsNetModule() Then Debug.Assert(Not IsScriptCommandLineParser) compilationName = moduleAssemblyName Else If moduleAssemblyName IsNot Nothing Then AddDiagnostic(diagnostics, ERRID.ERR_NeedModule) End If compilationName = simpleName End If If moduleName Is Nothing Then moduleName = outputFileName End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Tools/BuildBoss/StructuredLoggerCheckerUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using Microsoft.Build.Logging.StructuredLogger; namespace BuildBoss { /// <summary> /// This type invokes the analyzer here: /// /// https://github.com/KirillOsenkov/MSBuildStructuredLog/blob/master/src/StructuredLogger/Analyzers/DoubleWritesAnalyzer.cs /// /// </summary> internal sealed class StructuredLoggerCheckerUtil : ICheckerUtil { private readonly string _logFilePath; internal StructuredLoggerCheckerUtil(string logFilePath) { _logFilePath = logFilePath; } public bool Check(TextWriter textWriter) { try { var build = Serialization.Read(_logFilePath); var doubleWrites = DoubleWritesAnalyzer.GetDoubleWrites(build).ToArray(); if (doubleWrites.Any()) { foreach (var doubleWrite in doubleWrites) { textWriter.WriteLine($"Multiple writes to {doubleWrite.Key}"); foreach (var source in doubleWrite.Value) { textWriter.WriteLine($"\t{source}"); } textWriter.WriteLine(); } return false; } return true; } catch (Exception ex) { textWriter.WriteLine($"Error processing binary log file: {ex.Message}"); 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; using System.IO; using System.Linq; using Microsoft.Build.Logging.StructuredLogger; namespace BuildBoss { /// <summary> /// This type invokes the analyzer here: /// /// https://github.com/KirillOsenkov/MSBuildStructuredLog/blob/master/src/StructuredLogger/Analyzers/DoubleWritesAnalyzer.cs /// /// </summary> internal sealed class StructuredLoggerCheckerUtil : ICheckerUtil { private readonly string _logFilePath; internal StructuredLoggerCheckerUtil(string logFilePath) { _logFilePath = logFilePath; } public bool Check(TextWriter textWriter) { try { var build = Serialization.Read(_logFilePath); var doubleWrites = DoubleWritesAnalyzer.GetDoubleWrites(build).ToArray(); if (doubleWrites.Any()) { foreach (var doubleWrite in doubleWrites) { textWriter.WriteLine($"Multiple writes to {doubleWrite.Key}"); foreach (var source in doubleWrite.Value) { textWriter.WriteLine($"\t{source}"); } textWriter.WriteLine(); } return false; } return true; } catch (Exception ex) { textWriter.WriteLine($"Error processing binary log file: {ex.Message}"); return false; } } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/CSharp/Portable/ConvertBetweenRegularAndVerbatimString/ConvertBetweenRegularAndVerbatimInterpolatedStringCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.ConvertBetweenRegularAndVerbatimString { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimInterpolatedString), Shared] [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.ConvertToInterpolatedString)] internal class ConvertBetweenRegularAndVerbatimInterpolatedStringCodeRefactoringProvider : AbstractConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider<InterpolatedStringExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ConvertBetweenRegularAndVerbatimInterpolatedStringCodeRefactoringProvider() { } protected override bool IsInterpolation { get; } = true; protected override bool IsAppropriateLiteralKind(InterpolatedStringExpressionSyntax literalExpression) => true; protected override void AddSubStringTokens(InterpolatedStringExpressionSyntax literalExpression, ArrayBuilder<SyntaxToken> subStringTokens) { foreach (var content in literalExpression.Contents) { if (content is InterpolatedStringTextSyntax textSyntax) subStringTokens.Add(textSyntax.TextToken); } } protected override bool IsVerbatim(InterpolatedStringExpressionSyntax literalExpression) => literalExpression.StringStartToken.Kind() == SyntaxKind.InterpolatedVerbatimStringStartToken; private static InterpolatedStringExpressionSyntax Convert( IVirtualCharService charService, StringBuilder sb, InterpolatedStringExpressionSyntax stringExpression, SyntaxKind newStartKind, Action<IVirtualCharService, StringBuilder, SyntaxToken> addStringText) { using var _ = ArrayBuilder<InterpolatedStringContentSyntax>.GetInstance(out var newContents); foreach (var content in stringExpression.Contents) { if (content is InterpolatedStringTextSyntax textSyntax) { // Ensure our temp builder is in a empty starting state. sb.Clear(); addStringText(charService, sb, textSyntax.TextToken); newContents.Add(textSyntax.WithTextToken(CreateTextToken(textSyntax.TextToken, sb))); } else { // not text (i.e. it's an interpolation). just add as is. newContents.Add(content); } } var startToken = stringExpression.StringStartToken; var newStartToken = SyntaxFactory.Token( leading: startToken.LeadingTrivia, kind: newStartKind, trailing: startToken.TrailingTrivia); return stringExpression.Update( newStartToken, SyntaxFactory.List(newContents), stringExpression.StringEndToken); } private static SyntaxToken CreateTextToken(SyntaxToken textToken, StringBuilder sb) => SyntaxFactory.Token( leading: textToken.LeadingTrivia, SyntaxKind.InterpolatedStringTextToken, sb.ToString(), valueText: "", trailing: textToken.TrailingTrivia); protected override InterpolatedStringExpressionSyntax CreateVerbatimStringExpression(IVirtualCharService charService, StringBuilder sb, InterpolatedStringExpressionSyntax stringExpression) => Convert(charService, sb, stringExpression, SyntaxKind.InterpolatedVerbatimStringStartToken, AddVerbatimStringText); protected override InterpolatedStringExpressionSyntax CreateRegularStringExpression(IVirtualCharService charService, StringBuilder sb, InterpolatedStringExpressionSyntax stringExpression) => Convert(charService, sb, stringExpression, SyntaxKind.InterpolatedStringStartToken, AddRegularStringText); } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.ConvertBetweenRegularAndVerbatimString { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimInterpolatedString), Shared] [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.ConvertToInterpolatedString)] internal class ConvertBetweenRegularAndVerbatimInterpolatedStringCodeRefactoringProvider : AbstractConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider<InterpolatedStringExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ConvertBetweenRegularAndVerbatimInterpolatedStringCodeRefactoringProvider() { } protected override bool IsInterpolation { get; } = true; protected override bool IsAppropriateLiteralKind(InterpolatedStringExpressionSyntax literalExpression) => true; protected override void AddSubStringTokens(InterpolatedStringExpressionSyntax literalExpression, ArrayBuilder<SyntaxToken> subStringTokens) { foreach (var content in literalExpression.Contents) { if (content is InterpolatedStringTextSyntax textSyntax) subStringTokens.Add(textSyntax.TextToken); } } protected override bool IsVerbatim(InterpolatedStringExpressionSyntax literalExpression) => literalExpression.StringStartToken.Kind() == SyntaxKind.InterpolatedVerbatimStringStartToken; private static InterpolatedStringExpressionSyntax Convert( IVirtualCharService charService, StringBuilder sb, InterpolatedStringExpressionSyntax stringExpression, SyntaxKind newStartKind, Action<IVirtualCharService, StringBuilder, SyntaxToken> addStringText) { using var _ = ArrayBuilder<InterpolatedStringContentSyntax>.GetInstance(out var newContents); foreach (var content in stringExpression.Contents) { if (content is InterpolatedStringTextSyntax textSyntax) { // Ensure our temp builder is in a empty starting state. sb.Clear(); addStringText(charService, sb, textSyntax.TextToken); newContents.Add(textSyntax.WithTextToken(CreateTextToken(textSyntax.TextToken, sb))); } else { // not text (i.e. it's an interpolation). just add as is. newContents.Add(content); } } var startToken = stringExpression.StringStartToken; var newStartToken = SyntaxFactory.Token( leading: startToken.LeadingTrivia, kind: newStartKind, trailing: startToken.TrailingTrivia); return stringExpression.Update( newStartToken, SyntaxFactory.List(newContents), stringExpression.StringEndToken); } private static SyntaxToken CreateTextToken(SyntaxToken textToken, StringBuilder sb) => SyntaxFactory.Token( leading: textToken.LeadingTrivia, SyntaxKind.InterpolatedStringTextToken, sb.ToString(), valueText: "", trailing: textToken.TrailingTrivia); protected override InterpolatedStringExpressionSyntax CreateVerbatimStringExpression(IVirtualCharService charService, StringBuilder sb, InterpolatedStringExpressionSyntax stringExpression) => Convert(charService, sb, stringExpression, SyntaxKind.InterpolatedVerbatimStringStartToken, AddVerbatimStringText); protected override InterpolatedStringExpressionSyntax CreateRegularStringExpression(IVirtualCharService charService, StringBuilder sb, InterpolatedStringExpressionSyntax stringExpression) => Convert(charService, sb, stringExpression, SyntaxKind.InterpolatedStringStartToken, AddRegularStringText); } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/EditorFeatures/VisualBasicTest/Structure/CompilationUnitStructureTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class CompilationUnitStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of CompilationUnitSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New CompilationUnitStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestImports() As Task Const code = " {|span:$$Imports System Imports System.Linq|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "Imports ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestImportsAliases() As Task Const code = " {|span:$$Imports System Imports linq = System.Linq|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "Imports ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestComments() As Task Const code = " {|span1:$$'Top 'Of 'File|} Class C End Class {|span2:'Bottom 'Of 'File|} " Await VerifyBlockSpansAsync(code, Region("span1", "' Top ...", autoCollapse:=True), Region("span2", "' Bottom ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestImportsAndComments() As Task Const code = " {|span1:$$'Top 'Of 'File|} {|span2:Imports System Imports System.Linq|} {|span3:'Bottom 'Of 'File|} " Await VerifyBlockSpansAsync(code, Region("span1", "' Top ...", autoCollapse:=True), Region("span2", "Imports ...", autoCollapse:=True), Region("span3", "' Bottom ...", autoCollapse:=True)) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class CompilationUnitStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of CompilationUnitSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New CompilationUnitStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestImports() As Task Const code = " {|span:$$Imports System Imports System.Linq|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "Imports ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestImportsAliases() As Task Const code = " {|span:$$Imports System Imports linq = System.Linq|} Class C1 End Class " Await VerifyBlockSpansAsync(code, Region("span", "Imports ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestComments() As Task Const code = " {|span1:$$'Top 'Of 'File|} Class C End Class {|span2:'Bottom 'Of 'File|} " Await VerifyBlockSpansAsync(code, Region("span1", "' Top ...", autoCollapse:=True), Region("span2", "' Bottom ...", autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestImportsAndComments() As Task Const code = " {|span1:$$'Top 'Of 'File|} {|span2:Imports System Imports System.Linq|} {|span3:'Bottom 'Of 'File|} " Await VerifyBlockSpansAsync(code, Region("span1", "' Top ...", autoCollapse:=True), Region("span2", "Imports ...", autoCollapse:=True), Region("span3", "' Bottom ...", autoCollapse:=True)) End Function End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/Test/Resources/Core/DiagnosticTests/ErrTestMod02.cs
// Licensed to the .NET Foundation under one or more 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 NS { namespace Util { public class A { } } }
// Licensed to the .NET Foundation under one or more 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 NS { namespace Util { public class A { } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/VisualBasic/Test/Syntax/Syntax/ManualTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class GeneratedTests <Fact> Public Sub TestUpdateWithNull() ' create type parameter with constraint clause Dim tp = SyntaxFactory.TypeParameter(Nothing, SyntaxFactory.Identifier("T"), SyntaxFactory.TypeParameterSingleConstraintClause(SyntaxFactory.TypeConstraint(SyntaxFactory.IdentifierName("IGoo")))) ' attempt to make variant w/o constraint clause (do not access property first) Dim tp2 = tp.WithTypeParameterConstraintClause(Nothing) ' correctly creates variant w/o constraint clause Assert.Null(tp2.TypeParameterConstraintClause) End Sub <Fact, WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestConstructClassBlock() Dim c = SyntaxFactory.ClassBlock(SyntaxFactory.ClassStatement("C").AddTypeParameterListParameters(SyntaxFactory.TypeParameter("T"))) _ .AddImplements(SyntaxFactory.ImplementsStatement(SyntaxFactory.ParseTypeName("X"), SyntaxFactory.ParseTypeName("Y"))) Dim expectedText As String = _ "Class C(Of T)" + vbCrLf + _ " Implements X, Y" + vbCrLf + _ vbCrLf + _ "End Class" Dim actualText = c.NormalizeWhitespace().ToFullString() Assert.Equal(expectedText, actualText) End Sub <Fact()> Public Sub TestCastExpression() Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.CTypeExpression(SyntaxFactory.Token(SyntaxKind.CTypeKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), GenerateRedCharacterLiteralExpression(), SyntaxFactory.Token(SyntaxKind.CommaToken), GenerateRedArrayType(), SyntaxFactory.Token(SyntaxKind.CloseParenToken)) Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing") End Sub <Fact()> Public Sub TestOnErrorGoToStatement() Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.OnErrorGoToStatement(SyntaxKind.OnErrorGoToLabelStatement, SyntaxFactory.Token(SyntaxKind.OnKeyword), SyntaxFactory.Token(SyntaxKind.ErrorKeyword), SyntaxFactory.Token(SyntaxKind.GoToKeyword), Nothing, SyntaxFactory.IdentifierLabel(GenerateRedIdentifierToken())) Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing") End Sub <Fact()> Public Sub TestMissingToken() For k = CInt(SyntaxKind.AddHandlerKeyword) To CInt(SyntaxKind.AggregateKeyword) - 1 If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind)) Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind)) Next k For k = CInt(SyntaxKind.CommaToken) To CInt(SyntaxKind.AtToken) - 1 If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind)) Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind)) Next k End Sub ''' Bug 7983 <Fact()> Public Sub TestParsedSyntaxTreeToString() Dim input = " Module m1" + vbCrLf + _ "Sub Main(args As String())" + vbCrLf + _ "Sub1 ( Function(p As Integer )" + vbCrLf + _ "Sub2( )" + vbCrLf + _ "End FUNCTION)" + vbCrLf + _ "End Sub" + vbCrLf + _ "End Module " Dim node = VisualBasicSyntaxTree.ParseText(input) Assert.Equal(input, node.ToString()) End Sub ''' Bug 10283 <Fact()> Public Sub Bug_10283() Dim input = "Dim goo()" Dim node = VisualBasicSyntaxTree.ParseText(input) Dim arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0) Assert.Equal(1, arrayRankSpecifier.Rank) Assert.Equal(0, arrayRankSpecifier.CommaTokens.Count) input = "Dim goo(,,,)" node = VisualBasicSyntaxTree.ParseText(input) arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0) Assert.Equal(4, arrayRankSpecifier.Rank) Assert.Equal(3, arrayRankSpecifier.CommaTokens.Count) End Sub <WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")> <Fact()> Public Sub SyntaxDotParseCompilationUnitContainingOnlyWhitespace() Dim node = SyntaxFactory.ParseCompilationUnit(" ") Assert.True(node.HasLeadingTrivia) Assert.Equal(1, node.GetLeadingTrivia().Count) Assert.Equal(1, node.DescendantTrivia().Count()) Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()) End Sub <WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")> <Fact()> Public Sub SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace() Dim node = VisualBasicSyntaxTree.ParseText(" ").GetRoot() Assert.True(node.HasLeadingTrivia) Assert.Equal(1, node.GetLeadingTrivia().Count) Assert.Equal(1, node.DescendantTrivia().Count()) Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()) End Sub <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact()> Public Sub SyntaxTreeIsHidden_Bug13776() Dim source = <![CDATA[ Module Program Sub Main() If a Then a() Else If b Then #End ExternalSource b() #ExternalSource Else c() End If End Sub End Module ]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(source) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(0)) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.Length - 2)) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("a()", StringComparison.Ordinal))) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("b()", StringComparison.Ordinal))) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("c()", StringComparison.Ordinal))) End Sub <WorkItem(546586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546586")> <Fact()> Public Sub KindsWithSameNameAsTypeShouldNotDropKindWhenUpdating_Bug16244() Dim assignmentStatement = GeneratedTests.GenerateRedAddAssignmentStatement() Dim newAssignmentStatement = assignmentStatement.Update(assignmentStatement.Kind, GeneratedTests.GenerateRedAddExpression(), SyntaxFactory.Token(SyntaxKind.PlusEqualsToken), GeneratedTests.GenerateRedAddExpression()) Assert.Equal(assignmentStatement.Kind, newAssignmentStatement.Kind) End Sub <Fact> Public Sub TestSeparatedListFactory_DefaultSeparators() Dim null1 = SyntaxFactory.SeparatedList(CType(Nothing, ParameterSyntax())) Assert.Equal(0, null1.Count) Assert.Equal(0, null1.SeparatorCount) Assert.Equal("", null1.ToString()) Dim null2 = SyntaxFactory.SeparatedList(CType(Nothing, IEnumerable(Of ModifiedIdentifierSyntax))) Assert.Equal(0, null2.Count) Assert.Equal(0, null2.SeparatorCount) Assert.Equal("", null2.ToString()) Dim empty1 = SyntaxFactory.SeparatedList(New TypeArgumentListSyntax() {}) Assert.Equal(0, empty1.Count) Assert.Equal(0, empty1.SeparatorCount) Assert.Equal("", empty1.ToString()) Dim empty2 = SyntaxFactory.SeparatedList(Enumerable.Empty(Of TypeParameterSyntax)()) Assert.Equal(0, empty2.Count) Assert.Equal(0, empty2.SeparatorCount) Assert.Equal("", empty2.ToString()) Dim singleton1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a")}) Assert.Equal(1, singleton1.Count) Assert.Equal(0, singleton1.SeparatorCount) Assert.Equal("a", singleton1.ToString()) Dim singleton2 = SyntaxFactory.SeparatedList(CType({SyntaxFactory.IdentifierName("x")}, IEnumerable(Of ExpressionSyntax))) Assert.Equal(1, singleton2.Count) Assert.Equal(0, singleton2.SeparatorCount) Assert.Equal("x", singleton2.ToString()) Dim list1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a"), SyntaxFactory.IdentifierName("b"), SyntaxFactory.IdentifierName("c")}) Assert.Equal(3, list1.Count) Assert.Equal(2, list1.SeparatorCount) Assert.Equal("a,b,c", list1.ToString()) Dim builder = New List(Of ArgumentSyntax)() builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("x"))) builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("y"))) builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("z"))) Dim list2 = SyntaxFactory.SeparatedList(builder) Assert.Equal(3, list2.Count) Assert.Equal(2, list2.SeparatorCount) Assert.Equal("x,y,z", list2.ToString()) End Sub <Fact(), WorkItem(701158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/701158")> Public Sub FindTokenOnStartOfContinuedLine() Dim code = <code> Namespace a &lt;TestClass&gt; _ Public Class UnitTest1 End Class End Namespace </code>.Value Dim text = SourceText.From(code) Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim token = tree.GetRoot().FindToken(text.Lines.Item(3).Start) Assert.Equal(">", token.ToString()) End Sub <Fact, WorkItem(7182, "https://github.com/dotnet/roslyn/issues/7182")> Public Sub WhenTextContainsTrailingTrivia_SyntaxNode_ContainsSkippedText_ReturnsTrue() Dim parsedTypeName = SyntaxFactory.ParseTypeName("System.Collections.Generic.List(Of Integer), mscorlib") Assert.True(parsedTypeName.ContainsSkippedText) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class GeneratedTests <Fact> Public Sub TestUpdateWithNull() ' create type parameter with constraint clause Dim tp = SyntaxFactory.TypeParameter(Nothing, SyntaxFactory.Identifier("T"), SyntaxFactory.TypeParameterSingleConstraintClause(SyntaxFactory.TypeConstraint(SyntaxFactory.IdentifierName("IGoo")))) ' attempt to make variant w/o constraint clause (do not access property first) Dim tp2 = tp.WithTypeParameterConstraintClause(Nothing) ' correctly creates variant w/o constraint clause Assert.Null(tp2.TypeParameterConstraintClause) End Sub <Fact, WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestConstructClassBlock() Dim c = SyntaxFactory.ClassBlock(SyntaxFactory.ClassStatement("C").AddTypeParameterListParameters(SyntaxFactory.TypeParameter("T"))) _ .AddImplements(SyntaxFactory.ImplementsStatement(SyntaxFactory.ParseTypeName("X"), SyntaxFactory.ParseTypeName("Y"))) Dim expectedText As String = _ "Class C(Of T)" + vbCrLf + _ " Implements X, Y" + vbCrLf + _ vbCrLf + _ "End Class" Dim actualText = c.NormalizeWhitespace().ToFullString() Assert.Equal(expectedText, actualText) End Sub <Fact()> Public Sub TestCastExpression() Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.CTypeExpression(SyntaxFactory.Token(SyntaxKind.CTypeKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), GenerateRedCharacterLiteralExpression(), SyntaxFactory.Token(SyntaxKind.CommaToken), GenerateRedArrayType(), SyntaxFactory.Token(SyntaxKind.CloseParenToken)) Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing") End Sub <Fact()> Public Sub TestOnErrorGoToStatement() Dim objUnderTest As VisualBasicSyntaxNode = SyntaxFactory.OnErrorGoToStatement(SyntaxKind.OnErrorGoToLabelStatement, SyntaxFactory.Token(SyntaxKind.OnKeyword), SyntaxFactory.Token(SyntaxKind.ErrorKeyword), SyntaxFactory.Token(SyntaxKind.GoToKeyword), Nothing, SyntaxFactory.IdentifierLabel(GenerateRedIdentifierToken())) Assert.True(Not objUnderTest Is Nothing, "obj can't be Nothing") End Sub <Fact()> Public Sub TestMissingToken() For k = CInt(SyntaxKind.AddHandlerKeyword) To CInt(SyntaxKind.AggregateKeyword) - 1 If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind)) Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind)) Next k For k = CInt(SyntaxKind.CommaToken) To CInt(SyntaxKind.AtToken) - 1 If CType(k, SyntaxKind).ToString() = k.ToString Then Continue For ' Skip any "holes" in the SyntaxKind enum Dim objUnderTest As SyntaxToken = SyntaxFactory.MissingToken(CType(k, SyntaxKind)) Assert.Equal(objUnderTest.Kind, CType(k, SyntaxKind)) Next k End Sub ''' Bug 7983 <Fact()> Public Sub TestParsedSyntaxTreeToString() Dim input = " Module m1" + vbCrLf + _ "Sub Main(args As String())" + vbCrLf + _ "Sub1 ( Function(p As Integer )" + vbCrLf + _ "Sub2( )" + vbCrLf + _ "End FUNCTION)" + vbCrLf + _ "End Sub" + vbCrLf + _ "End Module " Dim node = VisualBasicSyntaxTree.ParseText(input) Assert.Equal(input, node.ToString()) End Sub ''' Bug 10283 <Fact()> Public Sub Bug_10283() Dim input = "Dim goo()" Dim node = VisualBasicSyntaxTree.ParseText(input) Dim arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0) Assert.Equal(1, arrayRankSpecifier.Rank) Assert.Equal(0, arrayRankSpecifier.CommaTokens.Count) input = "Dim goo(,,,)" node = VisualBasicSyntaxTree.ParseText(input) arrayRankSpecifier = DirectCast(node.GetCompilationUnitRoot().Members(0), FieldDeclarationSyntax).Declarators(0).Names(0).ArrayRankSpecifiers(0) Assert.Equal(4, arrayRankSpecifier.Rank) Assert.Equal(3, arrayRankSpecifier.CommaTokens.Count) End Sub <WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")> <Fact()> Public Sub SyntaxDotParseCompilationUnitContainingOnlyWhitespace() Dim node = SyntaxFactory.ParseCompilationUnit(" ") Assert.True(node.HasLeadingTrivia) Assert.Equal(1, node.GetLeadingTrivia().Count) Assert.Equal(1, node.DescendantTrivia().Count()) Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()) End Sub <WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")> <Fact()> Public Sub SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace() Dim node = VisualBasicSyntaxTree.ParseText(" ").GetRoot() Assert.True(node.HasLeadingTrivia) Assert.Equal(1, node.GetLeadingTrivia().Count) Assert.Equal(1, node.DescendantTrivia().Count()) Assert.Equal(" ", node.GetLeadingTrivia().First().ToString()) End Sub <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact()> Public Sub SyntaxTreeIsHidden_Bug13776() Dim source = <![CDATA[ Module Program Sub Main() If a Then a() Else If b Then #End ExternalSource b() #ExternalSource Else c() End If End Sub End Module ]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(source) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(0)) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.Length - 2)) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("a()", StringComparison.Ordinal))) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("b()", StringComparison.Ordinal))) Assert.Equal(LineVisibility.Visible, tree.GetLineVisibility(source.IndexOf("c()", StringComparison.Ordinal))) End Sub <WorkItem(546586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546586")> <Fact()> Public Sub KindsWithSameNameAsTypeShouldNotDropKindWhenUpdating_Bug16244() Dim assignmentStatement = GeneratedTests.GenerateRedAddAssignmentStatement() Dim newAssignmentStatement = assignmentStatement.Update(assignmentStatement.Kind, GeneratedTests.GenerateRedAddExpression(), SyntaxFactory.Token(SyntaxKind.PlusEqualsToken), GeneratedTests.GenerateRedAddExpression()) Assert.Equal(assignmentStatement.Kind, newAssignmentStatement.Kind) End Sub <Fact> Public Sub TestSeparatedListFactory_DefaultSeparators() Dim null1 = SyntaxFactory.SeparatedList(CType(Nothing, ParameterSyntax())) Assert.Equal(0, null1.Count) Assert.Equal(0, null1.SeparatorCount) Assert.Equal("", null1.ToString()) Dim null2 = SyntaxFactory.SeparatedList(CType(Nothing, IEnumerable(Of ModifiedIdentifierSyntax))) Assert.Equal(0, null2.Count) Assert.Equal(0, null2.SeparatorCount) Assert.Equal("", null2.ToString()) Dim empty1 = SyntaxFactory.SeparatedList(New TypeArgumentListSyntax() {}) Assert.Equal(0, empty1.Count) Assert.Equal(0, empty1.SeparatorCount) Assert.Equal("", empty1.ToString()) Dim empty2 = SyntaxFactory.SeparatedList(Enumerable.Empty(Of TypeParameterSyntax)()) Assert.Equal(0, empty2.Count) Assert.Equal(0, empty2.SeparatorCount) Assert.Equal("", empty2.ToString()) Dim singleton1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a")}) Assert.Equal(1, singleton1.Count) Assert.Equal(0, singleton1.SeparatorCount) Assert.Equal("a", singleton1.ToString()) Dim singleton2 = SyntaxFactory.SeparatedList(CType({SyntaxFactory.IdentifierName("x")}, IEnumerable(Of ExpressionSyntax))) Assert.Equal(1, singleton2.Count) Assert.Equal(0, singleton2.SeparatorCount) Assert.Equal("x", singleton2.ToString()) Dim list1 = SyntaxFactory.SeparatedList({SyntaxFactory.IdentifierName("a"), SyntaxFactory.IdentifierName("b"), SyntaxFactory.IdentifierName("c")}) Assert.Equal(3, list1.Count) Assert.Equal(2, list1.SeparatorCount) Assert.Equal("a,b,c", list1.ToString()) Dim builder = New List(Of ArgumentSyntax)() builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("x"))) builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("y"))) builder.Add(SyntaxFactory.SimpleArgument(SyntaxFactory.IdentifierName("z"))) Dim list2 = SyntaxFactory.SeparatedList(builder) Assert.Equal(3, list2.Count) Assert.Equal(2, list2.SeparatorCount) Assert.Equal("x,y,z", list2.ToString()) End Sub <Fact(), WorkItem(701158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/701158")> Public Sub FindTokenOnStartOfContinuedLine() Dim code = <code> Namespace a &lt;TestClass&gt; _ Public Class UnitTest1 End Class End Namespace </code>.Value Dim text = SourceText.From(code) Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim token = tree.GetRoot().FindToken(text.Lines.Item(3).Start) Assert.Equal(">", token.ToString()) End Sub <Fact, WorkItem(7182, "https://github.com/dotnet/roslyn/issues/7182")> Public Sub WhenTextContainsTrailingTrivia_SyntaxNode_ContainsSkippedText_ReturnsTrue() Dim parsedTypeName = SyntaxFactory.ParseTypeName("System.Collections.Generic.List(Of Integer), mscorlib") Assert.True(parsedTypeName.ContainsSkippedText) End Sub End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Workspaces/Core/Portable/Differencing/LongestCommonImmutableArraySubsequence.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Differencing { /// <summary> /// Calculates Longest Common Subsequence for immutable arrays. /// </summary> internal abstract class LongestCommonImmutableArraySubsequence<TElement> : LongestCommonSubsequence<ImmutableArray<TElement>> { protected abstract bool Equals(TElement oldElement, TElement newElement); protected sealed override bool ItemsEqual(ImmutableArray<TElement> oldSequence, int oldIndex, ImmutableArray<TElement> newSequence, int newIndex) => Equals(oldSequence[oldIndex], newSequence[newIndex]); public IEnumerable<SequenceEdit> GetEdits(ImmutableArray<TElement> oldSequence, ImmutableArray<TElement> newSequence) => GetEdits(oldSequence, oldSequence.Length, newSequence, newSequence.Length); public double ComputeDistance(ImmutableArray<TElement> oldSequence, ImmutableArray<TElement> newSequence) => ComputeDistance(oldSequence, oldSequence.Length, newSequence, newSequence.Length); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Differencing { /// <summary> /// Calculates Longest Common Subsequence for immutable arrays. /// </summary> internal abstract class LongestCommonImmutableArraySubsequence<TElement> : LongestCommonSubsequence<ImmutableArray<TElement>> { protected abstract bool Equals(TElement oldElement, TElement newElement); protected sealed override bool ItemsEqual(ImmutableArray<TElement> oldSequence, int oldIndex, ImmutableArray<TElement> newSequence, int newIndex) => Equals(oldSequence[oldIndex], newSequence[newIndex]); public IEnumerable<SequenceEdit> GetEdits(ImmutableArray<TElement> oldSequence, ImmutableArray<TElement> newSequence) => GetEdits(oldSequence, oldSequence.Length, newSequence, newSequence.Length); public double ComputeDistance(ImmutableArray<TElement> oldSequence, ImmutableArray<TElement> newSequence) => ComputeDistance(oldSequence, oldSequence.Length, newSequence, newSequence.Length); } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForMethodsAnalyzerTests.cs
// Licensed to the .NET Foundation under one or more 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { using VerifyCS = CSharpCodeFixVerifier< UseExpressionBodyDiagnosticAnalyzer, UseExpressionBodyCodeFixProvider>; public class UseExpressionBodyForMethodsAnalyzerTests { private static async Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, ExpressionBodyPreference.WhenPossible } } }.RunAsync(); } private static async Task TestWithUseBlockBody(string code, string fixedCode, ReferenceAssemblies? referenceAssemblies = null) { await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, ExpressionBodyPreference.Never } }, ReferenceAssemblies = referenceAssemblies ?? ReferenceAssemblies.Default, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public void TestOptionSerialization1() { // Verify that bool-options can migrate to ExpressionBodyPreference-options. var option = new CodeStyleOption2<bool>(false, NotificationOption2.Silent); var serialized = option.ToXElement(); var deserialized = CodeStyleOption2<ExpressionBodyPreference>.FromXElement(serialized); Assert.Equal(ExpressionBodyPreference.Never, deserialized.Value); option = new CodeStyleOption2<bool>(true, NotificationOption2.Silent); serialized = option.ToXElement(); deserialized = CodeStyleOption2<ExpressionBodyPreference>.FromXElement(serialized); Assert.Equal(ExpressionBodyPreference.WhenPossible, deserialized.Value); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public void TestOptionSerialization2() { // Verify that ExpressionBodyPreference-options can migrate to bool-options. var option = new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.Silent); var serialized = option.ToXElement(); var deserialized = CodeStyleOption2<bool>.FromXElement(serialized); Assert.False(deserialized.Value); option = new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent); serialized = option.ToXElement(); deserialized = CodeStyleOption2<bool>.FromXElement(serialized); Assert.True(deserialized.Value); // This new values can't actually translate back to a bool. So we'll just get the default // value for this option. option = new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.Silent); serialized = option.ToXElement(); deserialized = CodeStyleOption2<bool>.FromXElement(serialized); Assert.Equal(default, deserialized.Value); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public void TestOptionEditorConfig1() { var option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("true", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.WhenPossible, option.Value); Assert.Equal(NotificationOption2.Silent, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("false", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.Never, option.Value); Assert.Equal(NotificationOption2.Silent, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("when_on_single_line", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.WhenOnSingleLine, option.Value); Assert.Equal(NotificationOption2.Silent, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("true:blah", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.Never, option.Value); Assert.Equal(NotificationOption2.Silent, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("when_blah:error", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.Never, option.Value); Assert.Equal(NotificationOption2.Silent, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("false:error", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.Never, option.Value); Assert.Equal(NotificationOption2.Error, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("true:warning", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.WhenPossible, option.Value); Assert.Equal(NotificationOption2.Warning, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("when_on_single_line:suggestion", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.WhenOnSingleLine, option.Value); Assert.Equal(NotificationOption2.Suggestion, option.Notification); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { var code = @" class C { void Bar() => Bar(); {|IDE0022:void Goo() { Bar(); }|} }"; var fixedCode = @" class C { void Bar() => Bar(); void Goo() => Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody2() { var code = @" class C { int Bar() => 0; {|IDE0022:int Goo() { return Bar(); }|} }"; var fixedCode = @" class C { int Bar() => 0; int Goo() => Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { var code = @" using System; class C { {|IDE0022:int Goo() { throw new NotImplementedException(); }|} }"; var fixedCode = @" using System; class C { int Goo() => throw new NotImplementedException(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { var code = @" using System; class C { {|IDE0022:int Goo() { throw new NotImplementedException(); // comment }|} }"; var fixedCode = @" using System; class C { int Goo() => throw new NotImplementedException(); // comment }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { var code = @" class C { void Bar() { } {|IDE0022:void Goo() => Bar();|} }"; var fixedCode = @" class C { void Bar() { } void Goo() { Bar(); } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody2() { var code = @" class C { int Bar() { return 0; } {|IDE0022:int Goo() => Bar();|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo() { return Bar(); } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { var code = @" using System; class C { {|IDE0022:int Goo() => throw new NotImplementedException();|} }"; var fixedCode = @" using System; class C { int Goo() { throw new NotImplementedException(); } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { var code = @" using System; class C { {|IDE0022:int Goo() => throw new NotImplementedException();|} // comment }"; var fixedCode = @" using System; class C { int Goo() { throw new NotImplementedException(); // comment } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestComments1() { var code = @" class C { void Bar() => Bar(); {|IDE0022:void Goo() { // Comment Bar(); }|} }"; var fixedCode = @" class C { void Bar() => Bar(); void Goo() => // Comment Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestComments2() { var code = @" class C { int Bar() => 0; {|IDE0022:int Goo() { // Comment return Bar(); }|} }"; var fixedCode = @" class C { int Bar() => 0; int Goo() => // Comment Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestComments3() { var code = @" using System; class C { Exception Bar() => new Exception(); {|IDE0022:void Goo() { // Comment throw Bar(); }|} }"; var fixedCode = @" using System; class C { Exception Bar() => new Exception(); void Goo() => // Comment throw Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestComments4() { var code = @" class C { void Bar() => Bar(); {|IDE0022:void Goo() { Bar(); // Comment }|} }"; var fixedCode = @" class C { void Bar() => Bar(); void Goo() => Bar(); // Comment }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestComments5() { var code = @" class C { int Bar() => 0; {|IDE0022:int Goo() { return Bar(); // Comment }|} }"; var fixedCode = @" class C { int Bar() => 0; int Goo() => Bar(); // Comment }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestComments6() { var code = @" using System; class C { Exception Bar() => new Exception(); {|IDE0022:void Goo() { throw Bar(); // Comment }|} }"; var fixedCode = @" using System; class C { Exception Bar() => new Exception(); void Goo() => throw Bar(); // Comment }"; await TestWithUseExpressionBody(code, fixedCode); } [WorkItem(17120, "https://github.com/dotnet/roslyn/issues/17120")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestDirectives1() { var code = @" #define DEBUG using System; class Program { {|IDE0022:void Method() { #if DEBUG Console.WriteLine(); #endif }|} }"; var fixedCode = @" #define DEBUG using System; class Program { void Method() => #if DEBUG Console.WriteLine(); #endif }"; await TestWithUseExpressionBody(code, fixedCode); } [WorkItem(17120, "https://github.com/dotnet/roslyn/issues/17120")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestDirectives2() { var code = @" #define DEBUG using System; class Program { {|IDE0022:void Method() { #if DEBUG Console.WriteLine(0); #else Console.WriteLine(1); #endif }|} }"; var fixedCode = @" #define DEBUG using System; class Program { void Method() => #if DEBUG Console.WriteLine(0); #else Console.WriteLine(1); #endif }"; await TestWithUseExpressionBody(code, fixedCode); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp6() { var code = @" using System; class C { {|IDE0022:void M() {|CS8026:=> {|CS8026:throw new NotImplementedException()|}|};|} }"; var fixedCode = @" using System; class C { void M() { throw new NotImplementedException(); } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp5); } [WorkItem(20352, "https://github.com/dotnet/roslyn/issues/20352")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestDoNotOfferToConvertToBlockIfExpressionBodyPreferredIfCSharp6() { var code = @" using System; class C { int M() => 0; }"; await TestWithUseExpressionBody(code, code, LanguageVersion.CSharp6); } [WorkItem(20352, "https://github.com/dotnet/roslyn/issues/20352")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToExpressionIfCSharp6() { var code = @" using System; class C { {|IDE0022:int M() { return 0; }|} }"; var fixedCode = @" using System; class C { int M() => 0; }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } [WorkItem(20352, "https://github.com/dotnet/roslyn/issues/20352")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestDoNotOfferToConvertToExpressionInCSharp6IfThrowExpression() { var code = @" using System; class C { // throw expressions not supported in C# 6. void M() { throw new Exception(); } }"; await TestWithUseExpressionBody(code, code, LanguageVersion.CSharp6); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp6_FixAll() { var code = @" using System; class C { {|IDE0022:void M() => {|CS8059:throw new NotImplementedException()|};|} {|IDE0022:void M(int i) => {|CS8059:throw new NotImplementedException()|};|} int M(bool b) => 0; }"; var fixedCode = @" using System; class C { void M() { throw new NotImplementedException(); } void M(int i) { throw new NotImplementedException(); } int M(bool b) => 0; }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } [WorkItem(25202, "https://github.com/dotnet/roslyn/issues/25202")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyAsync1() { var code = @" using System.Threading.Tasks; class C { {|IDE0022:async Task Goo() => await Bar();|} Task Bar() { return Task.CompletedTask; } }"; var fixedCode = @" using System.Threading.Tasks; class C { async Task Goo() { await Bar(); } Task Bar() { return Task.CompletedTask; } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(25202, "https://github.com/dotnet/roslyn/issues/25202")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyAsync2() { var code = @" using System.Threading.Tasks; class C { {|IDE0022:async void Goo() => await Bar();|} Task Bar() { return Task.CompletedTask; } }"; var fixedCode = @" using System.Threading.Tasks; class C { async void Goo() { await Bar(); } Task Bar() { return Task.CompletedTask; } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(25202, "https://github.com/dotnet/roslyn/issues/25202")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyAsync3() { var code = @" using System.Threading.Tasks; class C { {|IDE0022:async void Goo() => await Bar();|} Task Bar() { return Task.CompletedTask; } }"; var fixedCode = @" using System.Threading.Tasks; class C { async void Goo() { await Bar(); } Task Bar() { return Task.CompletedTask; } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(25202, "https://github.com/dotnet/roslyn/issues/25202")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyAsync4() { var code = @" using System.Threading.Tasks; class C { {|IDE0022:async ValueTask Goo() => await Bar();|} Task Bar() { return Task.CompletedTask; } }"; var fixedCode = @" using System.Threading.Tasks; class C { async ValueTask Goo() { await Bar(); } Task Bar() { return Task.CompletedTask; } }"; await TestWithUseBlockBody(code, fixedCode, ReferenceAssemblies.NetStandard.NetStandard21); } [WorkItem(25202, "https://github.com/dotnet/roslyn/issues/25202")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyAsync5() { var code = @" using System.Threading.Tasks; class C { {|IDE0022:async Task<int> Goo() => await Bar();|} Task<int> Bar() { return Task.FromResult(0); } }"; var fixedCode = @" using System.Threading.Tasks; class C { async Task<int> Goo() { return await Bar(); } Task<int> Bar() { return Task.FromResult(0); } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(25202, "https://github.com/dotnet/roslyn/issues/25202")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyAsync6() { var code = @" using System.Threading.Tasks; class C { {|IDE0022:Task Goo() => Bar();|} Task Bar() { return Task.CompletedTask; } }"; var fixedCode = @" using System.Threading.Tasks; class C { Task Goo() { return Bar(); } Task Bar() { return Task.CompletedTask; } }"; await TestWithUseBlockBody(code, fixedCode); } } }
// Licensed to the .NET Foundation under one or more 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { using VerifyCS = CSharpCodeFixVerifier< UseExpressionBodyDiagnosticAnalyzer, UseExpressionBodyCodeFixProvider>; public class UseExpressionBodyForMethodsAnalyzerTests { private static async Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, ExpressionBodyPreference.WhenPossible } } }.RunAsync(); } private static async Task TestWithUseBlockBody(string code, string fixedCode, ReferenceAssemblies? referenceAssemblies = null) { await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, ExpressionBodyPreference.Never } }, ReferenceAssemblies = referenceAssemblies ?? ReferenceAssemblies.Default, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public void TestOptionSerialization1() { // Verify that bool-options can migrate to ExpressionBodyPreference-options. var option = new CodeStyleOption2<bool>(false, NotificationOption2.Silent); var serialized = option.ToXElement(); var deserialized = CodeStyleOption2<ExpressionBodyPreference>.FromXElement(serialized); Assert.Equal(ExpressionBodyPreference.Never, deserialized.Value); option = new CodeStyleOption2<bool>(true, NotificationOption2.Silent); serialized = option.ToXElement(); deserialized = CodeStyleOption2<ExpressionBodyPreference>.FromXElement(serialized); Assert.Equal(ExpressionBodyPreference.WhenPossible, deserialized.Value); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public void TestOptionSerialization2() { // Verify that ExpressionBodyPreference-options can migrate to bool-options. var option = new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.Silent); var serialized = option.ToXElement(); var deserialized = CodeStyleOption2<bool>.FromXElement(serialized); Assert.False(deserialized.Value); option = new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent); serialized = option.ToXElement(); deserialized = CodeStyleOption2<bool>.FromXElement(serialized); Assert.True(deserialized.Value); // This new values can't actually translate back to a bool. So we'll just get the default // value for this option. option = new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.Silent); serialized = option.ToXElement(); deserialized = CodeStyleOption2<bool>.FromXElement(serialized); Assert.Equal(default, deserialized.Value); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public void TestOptionEditorConfig1() { var option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("true", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.WhenPossible, option.Value); Assert.Equal(NotificationOption2.Silent, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("false", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.Never, option.Value); Assert.Equal(NotificationOption2.Silent, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("when_on_single_line", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.WhenOnSingleLine, option.Value); Assert.Equal(NotificationOption2.Silent, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("true:blah", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.Never, option.Value); Assert.Equal(NotificationOption2.Silent, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("when_blah:error", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.Never, option.Value); Assert.Equal(NotificationOption2.Silent, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("false:error", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.Never, option.Value); Assert.Equal(NotificationOption2.Error, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("true:warning", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.WhenPossible, option.Value); Assert.Equal(NotificationOption2.Warning, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("when_on_single_line:suggestion", CSharpCodeStyleOptions.NeverWithSilentEnforcement); Assert.Equal(ExpressionBodyPreference.WhenOnSingleLine, option.Value); Assert.Equal(NotificationOption2.Suggestion, option.Notification); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { var code = @" class C { void Bar() => Bar(); {|IDE0022:void Goo() { Bar(); }|} }"; var fixedCode = @" class C { void Bar() => Bar(); void Goo() => Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody2() { var code = @" class C { int Bar() => 0; {|IDE0022:int Goo() { return Bar(); }|} }"; var fixedCode = @" class C { int Bar() => 0; int Goo() => Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { var code = @" using System; class C { {|IDE0022:int Goo() { throw new NotImplementedException(); }|} }"; var fixedCode = @" using System; class C { int Goo() => throw new NotImplementedException(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { var code = @" using System; class C { {|IDE0022:int Goo() { throw new NotImplementedException(); // comment }|} }"; var fixedCode = @" using System; class C { int Goo() => throw new NotImplementedException(); // comment }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { var code = @" class C { void Bar() { } {|IDE0022:void Goo() => Bar();|} }"; var fixedCode = @" class C { void Bar() { } void Goo() { Bar(); } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody2() { var code = @" class C { int Bar() { return 0; } {|IDE0022:int Goo() => Bar();|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo() { return Bar(); } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { var code = @" using System; class C { {|IDE0022:int Goo() => throw new NotImplementedException();|} }"; var fixedCode = @" using System; class C { int Goo() { throw new NotImplementedException(); } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { var code = @" using System; class C { {|IDE0022:int Goo() => throw new NotImplementedException();|} // comment }"; var fixedCode = @" using System; class C { int Goo() { throw new NotImplementedException(); // comment } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestComments1() { var code = @" class C { void Bar() => Bar(); {|IDE0022:void Goo() { // Comment Bar(); }|} }"; var fixedCode = @" class C { void Bar() => Bar(); void Goo() => // Comment Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestComments2() { var code = @" class C { int Bar() => 0; {|IDE0022:int Goo() { // Comment return Bar(); }|} }"; var fixedCode = @" class C { int Bar() => 0; int Goo() => // Comment Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestComments3() { var code = @" using System; class C { Exception Bar() => new Exception(); {|IDE0022:void Goo() { // Comment throw Bar(); }|} }"; var fixedCode = @" using System; class C { Exception Bar() => new Exception(); void Goo() => // Comment throw Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestComments4() { var code = @" class C { void Bar() => Bar(); {|IDE0022:void Goo() { Bar(); // Comment }|} }"; var fixedCode = @" class C { void Bar() => Bar(); void Goo() => Bar(); // Comment }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestComments5() { var code = @" class C { int Bar() => 0; {|IDE0022:int Goo() { return Bar(); // Comment }|} }"; var fixedCode = @" class C { int Bar() => 0; int Goo() => Bar(); // Comment }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestComments6() { var code = @" using System; class C { Exception Bar() => new Exception(); {|IDE0022:void Goo() { throw Bar(); // Comment }|} }"; var fixedCode = @" using System; class C { Exception Bar() => new Exception(); void Goo() => throw Bar(); // Comment }"; await TestWithUseExpressionBody(code, fixedCode); } [WorkItem(17120, "https://github.com/dotnet/roslyn/issues/17120")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestDirectives1() { var code = @" #define DEBUG using System; class Program { {|IDE0022:void Method() { #if DEBUG Console.WriteLine(); #endif }|} }"; var fixedCode = @" #define DEBUG using System; class Program { void Method() => #if DEBUG Console.WriteLine(); #endif }"; await TestWithUseExpressionBody(code, fixedCode); } [WorkItem(17120, "https://github.com/dotnet/roslyn/issues/17120")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestDirectives2() { var code = @" #define DEBUG using System; class Program { {|IDE0022:void Method() { #if DEBUG Console.WriteLine(0); #else Console.WriteLine(1); #endif }|} }"; var fixedCode = @" #define DEBUG using System; class Program { void Method() => #if DEBUG Console.WriteLine(0); #else Console.WriteLine(1); #endif }"; await TestWithUseExpressionBody(code, fixedCode); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp6() { var code = @" using System; class C { {|IDE0022:void M() {|CS8026:=> {|CS8026:throw new NotImplementedException()|}|};|} }"; var fixedCode = @" using System; class C { void M() { throw new NotImplementedException(); } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp5); } [WorkItem(20352, "https://github.com/dotnet/roslyn/issues/20352")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestDoNotOfferToConvertToBlockIfExpressionBodyPreferredIfCSharp6() { var code = @" using System; class C { int M() => 0; }"; await TestWithUseExpressionBody(code, code, LanguageVersion.CSharp6); } [WorkItem(20352, "https://github.com/dotnet/roslyn/issues/20352")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToExpressionIfCSharp6() { var code = @" using System; class C { {|IDE0022:int M() { return 0; }|} }"; var fixedCode = @" using System; class C { int M() => 0; }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } [WorkItem(20352, "https://github.com/dotnet/roslyn/issues/20352")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestDoNotOfferToConvertToExpressionInCSharp6IfThrowExpression() { var code = @" using System; class C { // throw expressions not supported in C# 6. void M() { throw new Exception(); } }"; await TestWithUseExpressionBody(code, code, LanguageVersion.CSharp6); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp6_FixAll() { var code = @" using System; class C { {|IDE0022:void M() => {|CS8059:throw new NotImplementedException()|};|} {|IDE0022:void M(int i) => {|CS8059:throw new NotImplementedException()|};|} int M(bool b) => 0; }"; var fixedCode = @" using System; class C { void M() { throw new NotImplementedException(); } void M(int i) { throw new NotImplementedException(); } int M(bool b) => 0; }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } [WorkItem(25202, "https://github.com/dotnet/roslyn/issues/25202")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyAsync1() { var code = @" using System.Threading.Tasks; class C { {|IDE0022:async Task Goo() => await Bar();|} Task Bar() { return Task.CompletedTask; } }"; var fixedCode = @" using System.Threading.Tasks; class C { async Task Goo() { await Bar(); } Task Bar() { return Task.CompletedTask; } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(25202, "https://github.com/dotnet/roslyn/issues/25202")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyAsync2() { var code = @" using System.Threading.Tasks; class C { {|IDE0022:async void Goo() => await Bar();|} Task Bar() { return Task.CompletedTask; } }"; var fixedCode = @" using System.Threading.Tasks; class C { async void Goo() { await Bar(); } Task Bar() { return Task.CompletedTask; } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(25202, "https://github.com/dotnet/roslyn/issues/25202")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyAsync3() { var code = @" using System.Threading.Tasks; class C { {|IDE0022:async void Goo() => await Bar();|} Task Bar() { return Task.CompletedTask; } }"; var fixedCode = @" using System.Threading.Tasks; class C { async void Goo() { await Bar(); } Task Bar() { return Task.CompletedTask; } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(25202, "https://github.com/dotnet/roslyn/issues/25202")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyAsync4() { var code = @" using System.Threading.Tasks; class C { {|IDE0022:async ValueTask Goo() => await Bar();|} Task Bar() { return Task.CompletedTask; } }"; var fixedCode = @" using System.Threading.Tasks; class C { async ValueTask Goo() { await Bar(); } Task Bar() { return Task.CompletedTask; } }"; await TestWithUseBlockBody(code, fixedCode, ReferenceAssemblies.NetStandard.NetStandard21); } [WorkItem(25202, "https://github.com/dotnet/roslyn/issues/25202")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyAsync5() { var code = @" using System.Threading.Tasks; class C { {|IDE0022:async Task<int> Goo() => await Bar();|} Task<int> Bar() { return Task.FromResult(0); } }"; var fixedCode = @" using System.Threading.Tasks; class C { async Task<int> Goo() { return await Bar(); } Task<int> Bar() { return Task.FromResult(0); } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(25202, "https://github.com/dotnet/roslyn/issues/25202")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyAsync6() { var code = @" using System.Threading.Tasks; class C { {|IDE0022:Task Goo() => Bar();|} Task Bar() { return Task.CompletedTask; } }"; var fixedCode = @" using System.Threading.Tasks; class C { Task Goo() { return Bar(); } Task Bar() { return Task.CompletedTask; } }"; await TestWithUseBlockBody(code, fixedCode); } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/Core/Portable/CodeRefactorings/PredefinedCodeRefactoringProviderNames.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeRefactorings { internal static class PredefinedCodeRefactoringProviderNames { public const string AddAwait = "Add Await Code Action Provider"; public const string AddConstructorParametersFromMembers = "Add Parameters From Members Code Action Provider"; public const string AddFileBanner = "Add Banner To File Code Action Provider"; public const string AddMissingImports = "Add Missing Imports On Paste Code Action Provider"; public const string ChangeSignature = "Change Signature Code Action Provider"; public const string ConvertAnonymousTypeToClass = "Convert Anonymous Type to Class Code Action Provider"; public const string ConvertDirectCastToTryCast = "Convert Direct Cast to Try Cast"; public const string ConvertNamespace = "Convert Namespace"; public const string ConvertTryCastToDirectCast = "Convert Try Cast to Direct Cast"; public const string ConvertToInterpolatedString = "Convert To Interpolated String Code Action Provider"; public const string ConvertTupleToStruct = "Convert Tuple to Struct Code Action Provider"; public const string EncapsulateField = "Encapsulate Field"; public const string ExtractClass = "Extract Class Code Action Provider"; public const string ExtractInterface = "Extract Interface Code Action Provider"; public const string ExtractMethod = "Extract Method Code Action Provider"; public const string GenerateConstructorFromMembers = "Generate Constructor From Members Code Action Provider"; public const string GenerateDefaultConstructors = "Generate Default Constructors Code Action Provider"; public const string GenerateEqualsAndGetHashCodeFromMembers = "Generate Equals and GetHashCode Code Action Provider"; public const string GenerateOverrides = "Generate Overrides Code Action Provider"; public const string InlineTemporary = "Inline Temporary Code Action Provider"; public const string IntroduceUsingStatement = "Introduce Using Statement Code Action Provider"; public const string IntroduceVariable = "Introduce Variable Code Action Provider"; public const string InvertConditional = "Invert Conditional Code Action Provider"; public const string InvertIf = "Invert If Code Action Provider"; public const string InvertLogical = "Invert Logical Code Action Provider"; public const string MergeConsecutiveIfStatements = "Merge Consecutive If Statements Code Action Provider"; public const string MergeNestedIfStatements = "Merge Nested If Statements Code Action Provider"; public const string MoveDeclarationNearReference = "Move Declaration Near Reference Code Action Provider"; public const string MoveToNamespace = "Move To Namespace Code Action Provider"; public const string MoveTypeToFile = "Move Type To File Code Action Provider"; public const string PullMemberUp = "Pull Member Up Code Action Provider"; public const string InlineMethod = "Inline Method Code Action Provider"; public const string ReplaceDocCommentTextWithTag = "Replace Documentation Comment Text With Tag Code Action Provider"; public const string SplitIntoConsecutiveIfStatements = "Split Into Consecutive If Statements Code Action Provider"; public const string SplitIntoNestedIfStatements = "Split Into Nested If Statements Code Action Provider"; public const string SyncNamespace = "Sync Namespace and Folder Name Code Action Provider"; public const string UseExplicitType = "Use Explicit Type Code Action Provider"; public const string UseExpressionBody = "Use Expression Body Code Action Provider"; public const string UseImplicitType = "Use Implicit Type Code Action Provider"; public const string Wrapping = "Wrapping Code Action Provider"; public const string MakeLocalFunctionStatic = nameof(MakeLocalFunctionStatic); public const string GenerateComparisonOperators = nameof(GenerateComparisonOperators); public const string ReplacePropertyWithMethods = nameof(ReplacePropertyWithMethods); public const string ReplaceMethodWithProperty = nameof(ReplaceMethodWithProperty); public const string AddDebuggerDisplay = nameof(AddDebuggerDisplay); public const string ConvertAutoPropertyToFullProperty = nameof(ConvertAutoPropertyToFullProperty); public const string ReverseForStatement = nameof(ReverseForStatement); public const string ConvertLocalFunctionToMethod = nameof(ConvertLocalFunctionToMethod); public const string ConvertForEachToFor = nameof(ConvertForEachToFor); public const string ConvertLinqQueryToForEach = nameof(ConvertLinqQueryToForEach); public const string ConvertForEachToLinqQuery = nameof(ConvertForEachToLinqQuery); public const string ConvertNumericLiteral = nameof(ConvertNumericLiteral); public const string IntroduceLocalForExpression = nameof(IntroduceLocalForExpression); public const string IntroduceParameter = nameof(IntroduceParameter); public const string AddParameterCheck = nameof(AddParameterCheck); public const string InitializeMemberFromParameter = nameof(InitializeMemberFromParameter); public const string NameTupleElement = nameof(NameTupleElement); public const string UseNamedArguments = nameof(UseNamedArguments); public const string ConvertForToForEach = nameof(ConvertForToForEach); public const string ConvertIfToSwitch = nameof(ConvertIfToSwitch); public const string ConvertBetweenRegularAndVerbatimString = nameof(ConvertBetweenRegularAndVerbatimString); public const string ConvertBetweenRegularAndVerbatimInterpolatedString = nameof(ConvertBetweenRegularAndVerbatimInterpolatedString); public const string RenameTracking = nameof(RenameTracking); public const string UseExpressionBodyForLambda = nameof(UseExpressionBodyForLambda); public const string ImplementInterfaceExplicitly = nameof(ImplementInterfaceExplicitly); public const string ImplementInterfaceImplicitly = nameof(ImplementInterfaceImplicitly); public const string ConvertPlaceholderToInterpolatedString = nameof(ConvertPlaceholderToInterpolatedString); public const string ConvertConcatenationToInterpolatedString = nameof(ConvertConcatenationToInterpolatedString); public const string InvertMultiLineIf = nameof(InvertMultiLineIf); public const string UseRecursivePatterns = nameof(UseRecursivePatterns); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeRefactorings { internal static class PredefinedCodeRefactoringProviderNames { public const string AddAwait = "Add Await Code Action Provider"; public const string AddConstructorParametersFromMembers = "Add Parameters From Members Code Action Provider"; public const string AddFileBanner = "Add Banner To File Code Action Provider"; public const string AddMissingImports = "Add Missing Imports On Paste Code Action Provider"; public const string ChangeSignature = "Change Signature Code Action Provider"; public const string ConvertAnonymousTypeToClass = "Convert Anonymous Type to Class Code Action Provider"; public const string ConvertDirectCastToTryCast = "Convert Direct Cast to Try Cast"; public const string ConvertNamespace = "Convert Namespace"; public const string ConvertTryCastToDirectCast = "Convert Try Cast to Direct Cast"; public const string ConvertToInterpolatedString = "Convert To Interpolated String Code Action Provider"; public const string ConvertTupleToStruct = "Convert Tuple to Struct Code Action Provider"; public const string EncapsulateField = "Encapsulate Field"; public const string ExtractClass = "Extract Class Code Action Provider"; public const string ExtractInterface = "Extract Interface Code Action Provider"; public const string ExtractMethod = "Extract Method Code Action Provider"; public const string GenerateConstructorFromMembers = "Generate Constructor From Members Code Action Provider"; public const string GenerateDefaultConstructors = "Generate Default Constructors Code Action Provider"; public const string GenerateEqualsAndGetHashCodeFromMembers = "Generate Equals and GetHashCode Code Action Provider"; public const string GenerateOverrides = "Generate Overrides Code Action Provider"; public const string InlineTemporary = "Inline Temporary Code Action Provider"; public const string IntroduceUsingStatement = "Introduce Using Statement Code Action Provider"; public const string IntroduceVariable = "Introduce Variable Code Action Provider"; public const string InvertConditional = "Invert Conditional Code Action Provider"; public const string InvertIf = "Invert If Code Action Provider"; public const string InvertLogical = "Invert Logical Code Action Provider"; public const string MergeConsecutiveIfStatements = "Merge Consecutive If Statements Code Action Provider"; public const string MergeNestedIfStatements = "Merge Nested If Statements Code Action Provider"; public const string MoveDeclarationNearReference = "Move Declaration Near Reference Code Action Provider"; public const string MoveToNamespace = "Move To Namespace Code Action Provider"; public const string MoveTypeToFile = "Move Type To File Code Action Provider"; public const string PullMemberUp = "Pull Member Up Code Action Provider"; public const string InlineMethod = "Inline Method Code Action Provider"; public const string ReplaceDocCommentTextWithTag = "Replace Documentation Comment Text With Tag Code Action Provider"; public const string SplitIntoConsecutiveIfStatements = "Split Into Consecutive If Statements Code Action Provider"; public const string SplitIntoNestedIfStatements = "Split Into Nested If Statements Code Action Provider"; public const string SyncNamespace = "Sync Namespace and Folder Name Code Action Provider"; public const string UseExplicitType = "Use Explicit Type Code Action Provider"; public const string UseExpressionBody = "Use Expression Body Code Action Provider"; public const string UseImplicitType = "Use Implicit Type Code Action Provider"; public const string Wrapping = "Wrapping Code Action Provider"; public const string MakeLocalFunctionStatic = nameof(MakeLocalFunctionStatic); public const string GenerateComparisonOperators = nameof(GenerateComparisonOperators); public const string ReplacePropertyWithMethods = nameof(ReplacePropertyWithMethods); public const string ReplaceMethodWithProperty = nameof(ReplaceMethodWithProperty); public const string AddDebuggerDisplay = nameof(AddDebuggerDisplay); public const string ConvertAutoPropertyToFullProperty = nameof(ConvertAutoPropertyToFullProperty); public const string ReverseForStatement = nameof(ReverseForStatement); public const string ConvertLocalFunctionToMethod = nameof(ConvertLocalFunctionToMethod); public const string ConvertForEachToFor = nameof(ConvertForEachToFor); public const string ConvertLinqQueryToForEach = nameof(ConvertLinqQueryToForEach); public const string ConvertForEachToLinqQuery = nameof(ConvertForEachToLinqQuery); public const string ConvertNumericLiteral = nameof(ConvertNumericLiteral); public const string IntroduceLocalForExpression = nameof(IntroduceLocalForExpression); public const string IntroduceParameter = nameof(IntroduceParameter); public const string AddParameterCheck = nameof(AddParameterCheck); public const string InitializeMemberFromParameter = nameof(InitializeMemberFromParameter); public const string NameTupleElement = nameof(NameTupleElement); public const string UseNamedArguments = nameof(UseNamedArguments); public const string ConvertForToForEach = nameof(ConvertForToForEach); public const string ConvertIfToSwitch = nameof(ConvertIfToSwitch); public const string ConvertBetweenRegularAndVerbatimString = nameof(ConvertBetweenRegularAndVerbatimString); public const string ConvertBetweenRegularAndVerbatimInterpolatedString = nameof(ConvertBetweenRegularAndVerbatimInterpolatedString); public const string RenameTracking = nameof(RenameTracking); public const string UseExpressionBodyForLambda = nameof(UseExpressionBodyForLambda); public const string ImplementInterfaceExplicitly = nameof(ImplementInterfaceExplicitly); public const string ImplementInterfaceImplicitly = nameof(ImplementInterfaceImplicitly); public const string ConvertPlaceholderToInterpolatedString = nameof(ConvertPlaceholderToInterpolatedString); public const string ConvertConcatenationToInterpolatedString = nameof(ConvertConcatenationToInterpolatedString); public const string InvertMultiLineIf = nameof(InvertMultiLineIf); public const string UseRecursivePatterns = nameof(UseRecursivePatterns); } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/EditorFeatures/Test2/Diagnostics/ImplementInterface/ImplementInterfaceCrossLanguageTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.ImplementInterface Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.ImplementInterface Public Class ImplementInterfaceCrossLanguageTests Inherits AbstractCrossLanguageUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, language As String) As (DiagnosticAnalyzer, CodeFixProvider) If language = LanguageNames.CSharp Then Throw New NotSupportedException("Please add C# Implement interface tests to CSharpEditorTestTests.csproj. These tests require DiagnosticAnalyzer based test base and are NYI for AbstractCrossLanguageUserDiagnosticTest test base.") Else Return (Nothing, New VisualBasicImplementInterfaceCodeFixProvider()) End If End Function <WorkItem(545692, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545692")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_EnumsWithConflictingNames1() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> public enum E { _ = 1 } public interface I { void Goo(E x = E._); } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$I End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements I Public Sub Goo(Optional x As E = 1) Implements I.Goo Throw New NotImplementedException() End Sub End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function <WorkItem(545743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545743")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_EnumsWithConflictingNames2() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> public enum E { x, X, } public interface I { void Goo(E x = E.X); } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$I End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements I Public Sub Goo(Optional x As E = 1) Implements I.Goo Throw New NotImplementedException() End Sub End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function <WorkItem(545788, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545788"), WorkItem(715013, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715013")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_EnumsWithConflictingNames3() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> using System; [Flags] public enum E { A = 1, a = 2, B = 4, } public interface I { void Goo(E x = E.A | E.a | E.B); } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$I End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements I Public Sub Goo(Optional x As E = CType(1, E) Or CType(2, E) Or E.B) Implements I.Goo Throw New NotImplementedException() End Sub End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function <WorkItem(545699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545699")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_OptionalWithNoDefaultValue() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> using System.Runtime.InteropServices; public interface I { void Goo([Optional] int x); } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$I End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements I Public Sub Goo(Optional x As Integer = Nothing) Implements I.Goo Throw New NotImplementedException() End Sub End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function <WorkItem(545820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545820")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_IndexerWithNoRequiredParameters() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> public interface I { int this[params int[] y] { get; } } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$I End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements I Public ReadOnly Property Item(ParamArray y() As Integer) As Integer Implements I.Item Get Throw New NotImplementedException() End Get End Property End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function <WorkItem(545868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545868")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_ConflictingParameterNames1() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> public interface IA { void Goo(int a, int A); } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$IA End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements IA Public Sub Goo(a1 As Integer, a2 As Integer) Implements IA.Goo Throw New NotImplementedException() End Sub End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function <WorkItem(545868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545868")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_ConflictingParameterNames2() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> public interface IA { int this[int a, int A] { get; } } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$IA End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements IA Default Public ReadOnly Property Item(a1 As Integer, a2 As Integer) As Integer Implements IA.Item Get Throw New NotImplementedException() End Get End Property End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.ImplementInterface Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.ImplementInterface Public Class ImplementInterfaceCrossLanguageTests Inherits AbstractCrossLanguageUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, language As String) As (DiagnosticAnalyzer, CodeFixProvider) If language = LanguageNames.CSharp Then Throw New NotSupportedException("Please add C# Implement interface tests to CSharpEditorTestTests.csproj. These tests require DiagnosticAnalyzer based test base and are NYI for AbstractCrossLanguageUserDiagnosticTest test base.") Else Return (Nothing, New VisualBasicImplementInterfaceCodeFixProvider()) End If End Function <WorkItem(545692, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545692")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_EnumsWithConflictingNames1() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> public enum E { _ = 1 } public interface I { void Goo(E x = E._); } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$I End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements I Public Sub Goo(Optional x As E = 1) Implements I.Goo Throw New NotImplementedException() End Sub End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function <WorkItem(545743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545743")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_EnumsWithConflictingNames2() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> public enum E { x, X, } public interface I { void Goo(E x = E.X); } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$I End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements I Public Sub Goo(Optional x As E = 1) Implements I.Goo Throw New NotImplementedException() End Sub End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function <WorkItem(545788, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545788"), WorkItem(715013, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715013")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_EnumsWithConflictingNames3() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> using System; [Flags] public enum E { A = 1, a = 2, B = 4, } public interface I { void Goo(E x = E.A | E.a | E.B); } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$I End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements I Public Sub Goo(Optional x As E = CType(1, E) Or CType(2, E) Or E.B) Implements I.Goo Throw New NotImplementedException() End Sub End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function <WorkItem(545699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545699")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_OptionalWithNoDefaultValue() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> using System.Runtime.InteropServices; public interface I { void Goo([Optional] int x); } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$I End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements I Public Sub Goo(Optional x As Integer = Nothing) Implements I.Goo Throw New NotImplementedException() End Sub End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function <WorkItem(545820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545820")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_IndexerWithNoRequiredParameters() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> public interface I { int this[params int[] y] { get; } } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$I End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements I Public ReadOnly Property Item(ParamArray y() As Integer) As Integer Implements I.Item Get Throw New NotImplementedException() End Get End Property End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function <WorkItem(545868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545868")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_ConflictingParameterNames1() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> public interface IA { void Goo(int a, int A); } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$IA End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements IA Public Sub Goo(a1 As Integer, a2 As Integer) Implements IA.Goo Throw New NotImplementedException() End Sub End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function <WorkItem(545868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545868")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)> Public Async Function Test_ConflictingParameterNames2() As Task Dim input = <Workspace> <Project Language='C#' AssemblyName='CSharpAssembly1' CommonReferences='true'> <Document FilePath='Test1.cs'> public interface IA { int this[int a, int A] { get; } } </Document> </Project> <Project Language='Visual Basic' AssemblyName='VBAssembly1' CommonReferences='true'> <ProjectReference>CSharpAssembly1</ProjectReference> <Document> Class C Implements $$IA End Class </Document> </Project> </Workspace> Dim expected = <text> Class C Implements IA Default Public ReadOnly Property Item(a1 As Integer, a2 As Integer) As Integer Implements IA.Item Get Throw New NotImplementedException() End Get End Property End Class </text>.Value.Trim() Await TestAsync(input, expected) End Function End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/VisualBasic/Portable/Symbols/EmbeddedSymbols/VbMyTemplateText.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Option Strict On Option Explicit On Option Compare Binary #If TARGET = "module" AndAlso _MYTYPE = "" Then #Const _MYTYPE="Empty" #End If #If _MYTYPE = "WindowsForms" Then #Const _MYFORMS = True #Const _MYWEBSERVICES = True #Const _MYUSERTYPE = "Windows" #Const _MYCOMPUTERTYPE = "Windows" #Const _MYAPPLICATIONTYPE = "WindowsForms" #ElseIf _MYTYPE = "WindowsFormsWithCustomSubMain" Then #Const _MYFORMS = True #Const _MYWEBSERVICES = True #Const _MYUSERTYPE = "Windows" #Const _MYCOMPUTERTYPE = "Windows" #Const _MYAPPLICATIONTYPE = "Console" #ElseIf _MYTYPE = "Windows" OrElse _MYTYPE = "" Then #Const _MYWEBSERVICES = True #Const _MYUSERTYPE = "Windows" #Const _MYCOMPUTERTYPE = "Windows" #Const _MYAPPLICATIONTYPE = "Windows" #ElseIf _MYTYPE = "Console" Then #Const _MYWEBSERVICES = True #Const _MYUSERTYPE = "Windows" #Const _MYCOMPUTERTYPE = "Windows" #Const _MYAPPLICATIONTYPE = "Console" #ElseIf _MYTYPE = "Web" Then #Const _MYFORMS = False #Const _MYWEBSERVICES = False #Const _MYUSERTYPE = "Web" #Const _MYCOMPUTERTYPE = "Web" #ElseIf _MYTYPE = "WebControl" Then #Const _MYFORMS = False #Const _MYWEBSERVICES = True #Const _MYUSERTYPE = "Web" #Const _MYCOMPUTERTYPE = "Web" #ElseIf _MYTYPE = "Custom" Then #ElseIf _MYTYPE <> "Empty" Then #Const _MYTYPE = "Empty" #End If #If _MYTYPE <> "Empty" Then Namespace My #If _MYAPPLICATIONTYPE = "WindowsForms" OrElse _MYAPPLICATIONTYPE = "Windows" OrElse _MYAPPLICATIONTYPE = "Console" Then <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("MyTemplate", "11.0.0.0")> _ <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> Partial Friend Class MyApplication #If _MYAPPLICATIONTYPE = "WindowsForms" Then Inherits Global.Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase #If TARGET = "winexe" Then <Global.System.STAThread(), Global.System.Diagnostics.DebuggerHidden(), Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Shared Sub Main(ByVal Args As String()) Try Global.System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(MyApplication.UseCompatibleTextRendering()) Finally End Try My.Application.Run(Args) End Sub #End If #ElseIf _MYAPPLICATIONTYPE = "Windows" Then Inherits Global.Microsoft.VisualBasic.ApplicationServices.ApplicationBase #ElseIf _MYAPPLICATIONTYPE = "Console" Then Inherits Global.Microsoft.VisualBasic.ApplicationServices.ConsoleApplicationBase #End If '_MYAPPLICATIONTYPE = "WindowsForms" End Class #End If '#If _MYAPPLICATIONTYPE = "WindowsForms" Or _MYAPPLICATIONTYPE = "Windows" or _MYAPPLICATIONTYPE = "Console" #If _MYCOMPUTERTYPE <> "" Then <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("MyTemplate", "11.0.0.0")> _ <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> Partial Friend Class MyComputer #If _MYCOMPUTERTYPE = "Windows" Then Inherits Global.Microsoft.VisualBasic.Devices.Computer #ElseIf _MYCOMPUTERTYPE = "Web" Then Inherits Global.Microsoft.VisualBasic.Devices.ServerComputer #End If <Global.System.Diagnostics.DebuggerHidden()> _ <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ Public Sub New() MyBase.New() End Sub End Class #End If <Global.Microsoft.VisualBasic.HideModuleName()> _ <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("MyTemplate", "11.0.0.0")> _ Friend Module MyProject #If _MYCOMPUTERTYPE <> "" Then <Global.System.ComponentModel.Design.HelpKeyword("My.Computer")> _ Friend ReadOnly Property Computer() As MyComputer <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_ComputerObjectProvider.GetInstance() End Get End Property Private ReadOnly m_ComputerObjectProvider As New ThreadSafeObjectProvider(Of MyComputer) #End If #If _MYAPPLICATIONTYPE = "Windows" Or _MYAPPLICATIONTYPE = "WindowsForms" Or _MYAPPLICATIONTYPE = "Console" Then <Global.System.ComponentModel.Design.HelpKeyword("My.Application")> _ Friend ReadOnly Property Application() As MyApplication <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_AppObjectProvider.GetInstance() End Get End Property Private ReadOnly m_AppObjectProvider As New ThreadSafeObjectProvider(Of MyApplication) #End If #If _MYUSERTYPE = "Windows" Then <Global.System.ComponentModel.Design.HelpKeyword("My.User")> _ Friend ReadOnly Property User() As Global.Microsoft.VisualBasic.ApplicationServices.User <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_UserObjectProvider.GetInstance() End Get End Property Private ReadOnly m_UserObjectProvider As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.ApplicationServices.User) #ElseIf _MYUSERTYPE = "Web" Then <Global.System.ComponentModel.Design.HelpKeyword("My.User")> _ Friend ReadOnly Property User() As Global.Microsoft.VisualBasic.ApplicationServices.WebUser <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_UserObjectProvider.GetInstance() End Get End Property Private ReadOnly m_UserObjectProvider As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.ApplicationServices.WebUser) #End If #If _MYFORMS = True Then #Const STARTUP_MY_FORM_FACTORY = "My.MyProject.Forms" <Global.System.ComponentModel.Design.HelpKeyword("My.Forms")> _ Friend ReadOnly Property Forms() As MyForms <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_MyFormsObjectProvider.GetInstance() End Get End Property <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ <Global.Microsoft.VisualBasic.MyGroupCollection("System.Windows.Forms.Form", "Create__Instance__", "Dispose__Instance__", "My.MyProject.Forms")> _ Friend NotInheritable Class MyForms <Global.System.Diagnostics.DebuggerHidden()> _ Private Shared Function Create__Instance__(Of T As {New, Global.System.Windows.Forms.Form})(ByVal Instance As T) As T If Instance Is Nothing OrElse Instance.IsDisposed Then If m_FormBeingCreated IsNot Nothing Then If m_FormBeingCreated.ContainsKey(GetType(T)) = True Then Throw New Global.System.InvalidOperationException(Global.Microsoft.VisualBasic.CompilerServices.Utils.GetResourceString("WinForms_RecursiveFormCreate")) End If Else m_FormBeingCreated = New Global.System.Collections.Hashtable() End If m_FormBeingCreated.Add(GetType(T), Nothing) Try Return New T() Catch ex As Global.System.Reflection.TargetInvocationException When ex.InnerException IsNot Nothing Dim BetterMessage As String = Global.Microsoft.VisualBasic.CompilerServices.Utils.GetResourceString("WinForms_SeeInnerException", ex.InnerException.Message) Throw New Global.System.InvalidOperationException(BetterMessage, ex.InnerException) Finally m_FormBeingCreated.Remove(GetType(T)) End Try Else Return Instance End If End Function <Global.System.Diagnostics.DebuggerHidden()> _ Private Sub Dispose__Instance__(Of T As Global.System.Windows.Forms.Form)(ByRef instance As T) instance.Dispose() instance = Nothing End Sub <Global.System.Diagnostics.DebuggerHidden()> _ <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ Public Sub New() MyBase.New() End Sub <Global.System.ThreadStatic()> Private Shared m_FormBeingCreated As Global.System.Collections.Hashtable <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Public Overrides Function Equals(ByVal o As Object) As Boolean Return MyBase.Equals(o) End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Public Overrides Function GetHashCode() As Integer Return MyBase.GetHashCode End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> _ Friend Overloads Function [GetType]() As Global.System.Type Return GetType(MyForms) End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Public Overrides Function ToString() As String Return MyBase.ToString End Function End Class Private m_MyFormsObjectProvider As New ThreadSafeObjectProvider(Of MyForms) #End If #If _MYWEBSERVICES = True Then <Global.System.ComponentModel.Design.HelpKeyword("My.WebServices")> _ Friend ReadOnly Property WebServices() As MyWebServices <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_MyWebServicesObjectProvider.GetInstance() End Get End Property <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ <Global.Microsoft.VisualBasic.MyGroupCollection("System.Web.Services.Protocols.SoapHttpClientProtocol", "Create__Instance__", "Dispose__Instance__", "")> _ Friend NotInheritable Class MyWebServices <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never), Global.System.Diagnostics.DebuggerHidden()> _ Public Overrides Function Equals(ByVal o As Object) As Boolean Return MyBase.Equals(o) End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never), Global.System.Diagnostics.DebuggerHidden()> _ Public Overrides Function GetHashCode() As Integer Return MyBase.GetHashCode End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never), Global.System.Diagnostics.DebuggerHidden()> _ Friend Overloads Function [GetType]() As Global.System.Type Return GetType(MyWebServices) End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never), Global.System.Diagnostics.DebuggerHidden()> _ Public Overrides Function ToString() As String Return MyBase.ToString End Function <Global.System.Diagnostics.DebuggerHidden()> _ Private Shared Function Create__Instance__(Of T As {New})(ByVal instance As T) As T If instance Is Nothing Then Return New T() Else Return instance End If End Function <Global.System.Diagnostics.DebuggerHidden()> _ Private Sub Dispose__Instance__(Of T)(ByRef instance As T) instance = Nothing End Sub <Global.System.Diagnostics.DebuggerHidden()> _ <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ Public Sub New() MyBase.New() End Sub End Class Private ReadOnly m_MyWebServicesObjectProvider As New ThreadSafeObjectProvider(Of MyWebServices) #End If #If _MYTYPE = "Web" Then <Global.System.ComponentModel.Design.HelpKeyword("My.Request")> _ Friend ReadOnly Property Request() As Global.System.Web.HttpRequest <Global.System.Diagnostics.DebuggerHidden()> _ Get Dim CurrentContext As Global.System.Web.HttpContext = Global.System.Web.HttpContext.Current If CurrentContext IsNot Nothing Then Return CurrentContext.Request End If Return Nothing End Get End Property <Global.System.ComponentModel.Design.HelpKeyword("My.Response")> _ Friend ReadOnly Property Response() As Global.System.Web.HttpResponse <Global.System.Diagnostics.DebuggerHidden()> _ Get Dim CurrentContext As Global.System.Web.HttpContext = Global.System.Web.HttpContext.Current If CurrentContext IsNot Nothing Then Return CurrentContext.Response End If Return Nothing End Get End Property <Global.System.ComponentModel.Design.HelpKeyword("My.Application.Log")> _ Friend ReadOnly Property Log() As Global.Microsoft.VisualBasic.Logging.AspLog <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_LogObjectProvider.GetInstance() End Get End Property Private ReadOnly m_LogObjectProvider As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.Logging.AspLog) #End If '_MYTYPE="Web" <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ <Global.System.Runtime.InteropServices.ComVisible(False)> _ Friend NotInheritable Class ThreadSafeObjectProvider(Of T As New) Friend ReadOnly Property GetInstance() As T #If TARGET = "library" Then <Global.System.Diagnostics.DebuggerHidden()> _ Get Dim Value As T = m_Context.Value If Value Is Nothing Then Value = New T m_Context.Value() = Value End If Return Value End Get #Else <Global.System.Diagnostics.DebuggerHidden()> _ Get If m_ThreadStaticValue Is Nothing Then m_ThreadStaticValue = New T Return m_ThreadStaticValue End Get #End If End Property <Global.System.Diagnostics.DebuggerHidden()> _ <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ Public Sub New() MyBase.New() End Sub #If TARGET = "library" Then Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T) #Else <Global.System.Runtime.CompilerServices.CompilerGenerated(), Global.System.ThreadStatic()> Private Shared m_ThreadStaticValue As T #End If End Class End Module End Namespace #End If
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Option Strict On Option Explicit On Option Compare Binary #If TARGET = "module" AndAlso _MYTYPE = "" Then #Const _MYTYPE="Empty" #End If #If _MYTYPE = "WindowsForms" Then #Const _MYFORMS = True #Const _MYWEBSERVICES = True #Const _MYUSERTYPE = "Windows" #Const _MYCOMPUTERTYPE = "Windows" #Const _MYAPPLICATIONTYPE = "WindowsForms" #ElseIf _MYTYPE = "WindowsFormsWithCustomSubMain" Then #Const _MYFORMS = True #Const _MYWEBSERVICES = True #Const _MYUSERTYPE = "Windows" #Const _MYCOMPUTERTYPE = "Windows" #Const _MYAPPLICATIONTYPE = "Console" #ElseIf _MYTYPE = "Windows" OrElse _MYTYPE = "" Then #Const _MYWEBSERVICES = True #Const _MYUSERTYPE = "Windows" #Const _MYCOMPUTERTYPE = "Windows" #Const _MYAPPLICATIONTYPE = "Windows" #ElseIf _MYTYPE = "Console" Then #Const _MYWEBSERVICES = True #Const _MYUSERTYPE = "Windows" #Const _MYCOMPUTERTYPE = "Windows" #Const _MYAPPLICATIONTYPE = "Console" #ElseIf _MYTYPE = "Web" Then #Const _MYFORMS = False #Const _MYWEBSERVICES = False #Const _MYUSERTYPE = "Web" #Const _MYCOMPUTERTYPE = "Web" #ElseIf _MYTYPE = "WebControl" Then #Const _MYFORMS = False #Const _MYWEBSERVICES = True #Const _MYUSERTYPE = "Web" #Const _MYCOMPUTERTYPE = "Web" #ElseIf _MYTYPE = "Custom" Then #ElseIf _MYTYPE <> "Empty" Then #Const _MYTYPE = "Empty" #End If #If _MYTYPE <> "Empty" Then Namespace My #If _MYAPPLICATIONTYPE = "WindowsForms" OrElse _MYAPPLICATIONTYPE = "Windows" OrElse _MYAPPLICATIONTYPE = "Console" Then <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("MyTemplate", "11.0.0.0")> _ <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> Partial Friend Class MyApplication #If _MYAPPLICATIONTYPE = "WindowsForms" Then Inherits Global.Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase #If TARGET = "winexe" Then <Global.System.STAThread(), Global.System.Diagnostics.DebuggerHidden(), Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Shared Sub Main(ByVal Args As String()) Try Global.System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(MyApplication.UseCompatibleTextRendering()) Finally End Try My.Application.Run(Args) End Sub #End If #ElseIf _MYAPPLICATIONTYPE = "Windows" Then Inherits Global.Microsoft.VisualBasic.ApplicationServices.ApplicationBase #ElseIf _MYAPPLICATIONTYPE = "Console" Then Inherits Global.Microsoft.VisualBasic.ApplicationServices.ConsoleApplicationBase #End If '_MYAPPLICATIONTYPE = "WindowsForms" End Class #End If '#If _MYAPPLICATIONTYPE = "WindowsForms" Or _MYAPPLICATIONTYPE = "Windows" or _MYAPPLICATIONTYPE = "Console" #If _MYCOMPUTERTYPE <> "" Then <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("MyTemplate", "11.0.0.0")> _ <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> Partial Friend Class MyComputer #If _MYCOMPUTERTYPE = "Windows" Then Inherits Global.Microsoft.VisualBasic.Devices.Computer #ElseIf _MYCOMPUTERTYPE = "Web" Then Inherits Global.Microsoft.VisualBasic.Devices.ServerComputer #End If <Global.System.Diagnostics.DebuggerHidden()> _ <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ Public Sub New() MyBase.New() End Sub End Class #End If <Global.Microsoft.VisualBasic.HideModuleName()> _ <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("MyTemplate", "11.0.0.0")> _ Friend Module MyProject #If _MYCOMPUTERTYPE <> "" Then <Global.System.ComponentModel.Design.HelpKeyword("My.Computer")> _ Friend ReadOnly Property Computer() As MyComputer <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_ComputerObjectProvider.GetInstance() End Get End Property Private ReadOnly m_ComputerObjectProvider As New ThreadSafeObjectProvider(Of MyComputer) #End If #If _MYAPPLICATIONTYPE = "Windows" Or _MYAPPLICATIONTYPE = "WindowsForms" Or _MYAPPLICATIONTYPE = "Console" Then <Global.System.ComponentModel.Design.HelpKeyword("My.Application")> _ Friend ReadOnly Property Application() As MyApplication <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_AppObjectProvider.GetInstance() End Get End Property Private ReadOnly m_AppObjectProvider As New ThreadSafeObjectProvider(Of MyApplication) #End If #If _MYUSERTYPE = "Windows" Then <Global.System.ComponentModel.Design.HelpKeyword("My.User")> _ Friend ReadOnly Property User() As Global.Microsoft.VisualBasic.ApplicationServices.User <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_UserObjectProvider.GetInstance() End Get End Property Private ReadOnly m_UserObjectProvider As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.ApplicationServices.User) #ElseIf _MYUSERTYPE = "Web" Then <Global.System.ComponentModel.Design.HelpKeyword("My.User")> _ Friend ReadOnly Property User() As Global.Microsoft.VisualBasic.ApplicationServices.WebUser <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_UserObjectProvider.GetInstance() End Get End Property Private ReadOnly m_UserObjectProvider As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.ApplicationServices.WebUser) #End If #If _MYFORMS = True Then #Const STARTUP_MY_FORM_FACTORY = "My.MyProject.Forms" <Global.System.ComponentModel.Design.HelpKeyword("My.Forms")> _ Friend ReadOnly Property Forms() As MyForms <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_MyFormsObjectProvider.GetInstance() End Get End Property <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ <Global.Microsoft.VisualBasic.MyGroupCollection("System.Windows.Forms.Form", "Create__Instance__", "Dispose__Instance__", "My.MyProject.Forms")> _ Friend NotInheritable Class MyForms <Global.System.Diagnostics.DebuggerHidden()> _ Private Shared Function Create__Instance__(Of T As {New, Global.System.Windows.Forms.Form})(ByVal Instance As T) As T If Instance Is Nothing OrElse Instance.IsDisposed Then If m_FormBeingCreated IsNot Nothing Then If m_FormBeingCreated.ContainsKey(GetType(T)) = True Then Throw New Global.System.InvalidOperationException(Global.Microsoft.VisualBasic.CompilerServices.Utils.GetResourceString("WinForms_RecursiveFormCreate")) End If Else m_FormBeingCreated = New Global.System.Collections.Hashtable() End If m_FormBeingCreated.Add(GetType(T), Nothing) Try Return New T() Catch ex As Global.System.Reflection.TargetInvocationException When ex.InnerException IsNot Nothing Dim BetterMessage As String = Global.Microsoft.VisualBasic.CompilerServices.Utils.GetResourceString("WinForms_SeeInnerException", ex.InnerException.Message) Throw New Global.System.InvalidOperationException(BetterMessage, ex.InnerException) Finally m_FormBeingCreated.Remove(GetType(T)) End Try Else Return Instance End If End Function <Global.System.Diagnostics.DebuggerHidden()> _ Private Sub Dispose__Instance__(Of T As Global.System.Windows.Forms.Form)(ByRef instance As T) instance.Dispose() instance = Nothing End Sub <Global.System.Diagnostics.DebuggerHidden()> _ <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ Public Sub New() MyBase.New() End Sub <Global.System.ThreadStatic()> Private Shared m_FormBeingCreated As Global.System.Collections.Hashtable <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Public Overrides Function Equals(ByVal o As Object) As Boolean Return MyBase.Equals(o) End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Public Overrides Function GetHashCode() As Integer Return MyBase.GetHashCode End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> _ Friend Overloads Function [GetType]() As Global.System.Type Return GetType(MyForms) End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)> Public Overrides Function ToString() As String Return MyBase.ToString End Function End Class Private m_MyFormsObjectProvider As New ThreadSafeObjectProvider(Of MyForms) #End If #If _MYWEBSERVICES = True Then <Global.System.ComponentModel.Design.HelpKeyword("My.WebServices")> _ Friend ReadOnly Property WebServices() As MyWebServices <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_MyWebServicesObjectProvider.GetInstance() End Get End Property <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ <Global.Microsoft.VisualBasic.MyGroupCollection("System.Web.Services.Protocols.SoapHttpClientProtocol", "Create__Instance__", "Dispose__Instance__", "")> _ Friend NotInheritable Class MyWebServices <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never), Global.System.Diagnostics.DebuggerHidden()> _ Public Overrides Function Equals(ByVal o As Object) As Boolean Return MyBase.Equals(o) End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never), Global.System.Diagnostics.DebuggerHidden()> _ Public Overrides Function GetHashCode() As Integer Return MyBase.GetHashCode End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never), Global.System.Diagnostics.DebuggerHidden()> _ Friend Overloads Function [GetType]() As Global.System.Type Return GetType(MyWebServices) End Function <Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never), Global.System.Diagnostics.DebuggerHidden()> _ Public Overrides Function ToString() As String Return MyBase.ToString End Function <Global.System.Diagnostics.DebuggerHidden()> _ Private Shared Function Create__Instance__(Of T As {New})(ByVal instance As T) As T If instance Is Nothing Then Return New T() Else Return instance End If End Function <Global.System.Diagnostics.DebuggerHidden()> _ Private Sub Dispose__Instance__(Of T)(ByRef instance As T) instance = Nothing End Sub <Global.System.Diagnostics.DebuggerHidden()> _ <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ Public Sub New() MyBase.New() End Sub End Class Private ReadOnly m_MyWebServicesObjectProvider As New ThreadSafeObjectProvider(Of MyWebServices) #End If #If _MYTYPE = "Web" Then <Global.System.ComponentModel.Design.HelpKeyword("My.Request")> _ Friend ReadOnly Property Request() As Global.System.Web.HttpRequest <Global.System.Diagnostics.DebuggerHidden()> _ Get Dim CurrentContext As Global.System.Web.HttpContext = Global.System.Web.HttpContext.Current If CurrentContext IsNot Nothing Then Return CurrentContext.Request End If Return Nothing End Get End Property <Global.System.ComponentModel.Design.HelpKeyword("My.Response")> _ Friend ReadOnly Property Response() As Global.System.Web.HttpResponse <Global.System.Diagnostics.DebuggerHidden()> _ Get Dim CurrentContext As Global.System.Web.HttpContext = Global.System.Web.HttpContext.Current If CurrentContext IsNot Nothing Then Return CurrentContext.Response End If Return Nothing End Get End Property <Global.System.ComponentModel.Design.HelpKeyword("My.Application.Log")> _ Friend ReadOnly Property Log() As Global.Microsoft.VisualBasic.Logging.AspLog <Global.System.Diagnostics.DebuggerHidden()> _ Get Return m_LogObjectProvider.GetInstance() End Get End Property Private ReadOnly m_LogObjectProvider As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.Logging.AspLog) #End If '_MYTYPE="Web" <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ <Global.System.Runtime.InteropServices.ComVisible(False)> _ Friend NotInheritable Class ThreadSafeObjectProvider(Of T As New) Friend ReadOnly Property GetInstance() As T #If TARGET = "library" Then <Global.System.Diagnostics.DebuggerHidden()> _ Get Dim Value As T = m_Context.Value If Value Is Nothing Then Value = New T m_Context.Value() = Value End If Return Value End Get #Else <Global.System.Diagnostics.DebuggerHidden()> _ Get If m_ThreadStaticValue Is Nothing Then m_ThreadStaticValue = New T Return m_ThreadStaticValue End Get #End If End Property <Global.System.Diagnostics.DebuggerHidden()> _ <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Never)> _ Public Sub New() MyBase.New() End Sub #If TARGET = "library" Then Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T) #Else <Global.System.Runtime.CompilerServices.CompilerGenerated(), Global.System.ThreadStatic()> Private Shared m_ThreadStaticValue As T #End If End Class End Module End Namespace #End If
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/IDkmClrFullNameProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System.Collections.ObjectModel; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; namespace Microsoft.VisualStudio.Debugger.ComponentInterfaces { public interface IDkmClrFullNameProvider { string GetClrTypeName( DkmInspectionContext inspectionContext, DkmClrType clrType, DkmClrCustomTypeInfo customTypeInfo); string GetClrArrayIndexExpression( DkmInspectionContext inspectionContext, string[] indices); string GetClrCastExpression( DkmInspectionContext inspectionContext, string argument, DkmClrType clrType, DkmClrCustomTypeInfo customTypeInfo, DkmClrCastExpressionOptions castExpressionOptions); string GetClrObjectCreationExpression( DkmInspectionContext inspectionContext, DkmClrType clrType, DkmClrCustomTypeInfo customTypeInfo, string[] arguments); string GetClrValidIdentifier( DkmInspectionContext inspectionContext, string identifier); string GetClrMemberName( DkmInspectionContext inspectionContext, string parentFullName, DkmClrType clrType, DkmClrCustomTypeInfo customTypeInfo, string memberName, bool requiresExplicitCast, bool isStatic); bool ClrExpressionMayRequireParentheses( DkmInspectionContext inspectionContext, string expression); string GetClrExpressionAndFormatSpecifiers( DkmInspectionContext inspectionContext, string expression, out ReadOnlyCollection<string> formatSpecifiers); string GetClrExpressionForNull(DkmInspectionContext inspectionContext); string GetClrExpressionForThis(DkmInspectionContext inspectionContext); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System.Collections.ObjectModel; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; namespace Microsoft.VisualStudio.Debugger.ComponentInterfaces { public interface IDkmClrFullNameProvider { string GetClrTypeName( DkmInspectionContext inspectionContext, DkmClrType clrType, DkmClrCustomTypeInfo customTypeInfo); string GetClrArrayIndexExpression( DkmInspectionContext inspectionContext, string[] indices); string GetClrCastExpression( DkmInspectionContext inspectionContext, string argument, DkmClrType clrType, DkmClrCustomTypeInfo customTypeInfo, DkmClrCastExpressionOptions castExpressionOptions); string GetClrObjectCreationExpression( DkmInspectionContext inspectionContext, DkmClrType clrType, DkmClrCustomTypeInfo customTypeInfo, string[] arguments); string GetClrValidIdentifier( DkmInspectionContext inspectionContext, string identifier); string GetClrMemberName( DkmInspectionContext inspectionContext, string parentFullName, DkmClrType clrType, DkmClrCustomTypeInfo customTypeInfo, string memberName, bool requiresExplicitCast, bool isStatic); bool ClrExpressionMayRequireParentheses( DkmInspectionContext inspectionContext, string expression); string GetClrExpressionAndFormatSpecifiers( DkmInspectionContext inspectionContext, string expression, out ReadOnlyCollection<string> formatSpecifiers); string GetClrExpressionForNull(DkmInspectionContext inspectionContext); string GetClrExpressionForThis(DkmInspectionContext inspectionContext); } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/EditorFeatures/CSharpTest2/Recommendations/DelegateKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class DelegateKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); await VerifyAbsenceAsync( @"using Goo = d$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); await VerifyAbsenceAsync( @"global using Goo = d$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingAliasTypeParameter() { await VerifyKeywordAsync( @"using Goo = T<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGlobalUsingAliasTypeParameter() { await VerifyKeywordAsync( @"global using Goo = T<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"static $$"); await VerifyKeywordAsync(SourceCodeKind.Script, @"static $$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(SourceCodeKind.Regular, AddInsideMethod(@$"{keyword} $$")); await VerifyKeywordAsync(SourceCodeKind.Script, AddInsideMethod(@$"{keyword} $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"static public $$"); await VerifyKeywordAsync(SourceCodeKind.Script, @"static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegate() => await VerifyKeywordAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateAsArgument() { await VerifyKeywordAsync(AddInsideMethod( @"Assert.Throws<InvalidOperationException>($$")); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInConstMemberInitializer1() { await VerifyAbsenceAsync( @"class E { const int a = $$ }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumMemberInitializer1() { await VerifyAbsenceAsync( @"enum E { a = $$ }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInConstLocalInitializer1() { await VerifyAbsenceAsync( @"class E { void Goo() { const int a = $$ } }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMemberInitializer1() { await VerifyKeywordAsync( @"class E { int a = $$ }"); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(607197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607197")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsyncInMethodBody() { await VerifyKeywordAsync(@" using System; class C { void M() { Action a = async $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsyncInMemberDeclaration() { await VerifyKeywordAsync(@" using System; class C { async $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeList() { await VerifyKeywordAsync(@" using System; class C { delegate*<$$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class DelegateKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); await VerifyAbsenceAsync( @"using Goo = d$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); await VerifyAbsenceAsync( @"global using Goo = d$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingAliasTypeParameter() { await VerifyKeywordAsync( @"using Goo = T<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGlobalUsingAliasTypeParameter() { await VerifyKeywordAsync( @"global using Goo = T<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"static $$"); await VerifyKeywordAsync(SourceCodeKind.Script, @"static $$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(SourceCodeKind.Regular, AddInsideMethod(@$"{keyword} $$")); await VerifyKeywordAsync(SourceCodeKind.Script, AddInsideMethod(@$"{keyword} $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"static public $$"); await VerifyKeywordAsync(SourceCodeKind.Script, @"static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegate() => await VerifyKeywordAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateAsArgument() { await VerifyKeywordAsync(AddInsideMethod( @"Assert.Throws<InvalidOperationException>($$")); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInConstMemberInitializer1() { await VerifyAbsenceAsync( @"class E { const int a = $$ }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumMemberInitializer1() { await VerifyAbsenceAsync( @"enum E { a = $$ }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInConstLocalInitializer1() { await VerifyAbsenceAsync( @"class E { void Goo() { const int a = $$ } }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMemberInitializer1() { await VerifyKeywordAsync( @"class E { int a = $$ }"); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(607197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607197")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsyncInMethodBody() { await VerifyKeywordAsync(@" using System; class C { void M() { Action a = async $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsyncInMemberDeclaration() { await VerifyKeywordAsync(@" using System; class C { async $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeList() { await VerifyKeywordAsync(@" using System; class C { delegate*<$$"); } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Analyzers/VisualBasic/Tests/NewLines/MultipleBlankLines/MultipleBlankLinesTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeStyle Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.VisualBasic.NewLines.MultipleBlankLines.VisualBasicMultipleBlankLinesDiagnosticAnalyzer, Microsoft.CodeAnalysis.NewLines.MultipleBlankLines.MultipleBlankLinesCodeFixProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.NewLines.MultipleBlankLines Public Class MultipleBlankLinesTests Private Shared Async Function TestWithOptionOn(testCode As String, fixedCode As String) As Task Dim test = New VerifyVB.Test() With { .TestCode = testCode, .FixedCode = fixedCode } test.Options.Add(CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSilentEnforcement) Await test.RunAsync() End Function <Fact> Public Async Function TestOneBlankLineAtTopOfFile() As Task Dim code = " ' comment" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineAtTopOfFile() As Task Dim code = "[||] ' comment" Dim fixedCode = " ' comment" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestTwoBlankLineAtTopOfFile_NotWithOptionOff() As Task Dim code = " ' comment" Await New VerifyVB.Test() With { .TestCode = code, .FixedCode = code }.RunAsync() End Function <Fact> Public Async Function TestThreeBlankLineAtTopOfFile() As Task Dim code = "[||] ' comment" Dim fixedCode = " ' comment" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineAtTopOfFile() As Task Dim code = "[||] ' comment" Dim fixedCode = " ' comment" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestOneBlankLineAtTopOfEmptyFile() As Task Dim code = " " Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLinesAtTopOfEmptyFile() As Task Dim code = "[||] " Dim fixedCode = " " Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLinesAtTopOfEmptyFile() As Task Dim code = "[||] " Dim fixedCode = " " Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLinesAtTopOfEmptyFile() As Task Dim code = "[||] " Dim fixedCode = " " Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestNoBlankLineAtEndOfFile_1() As Task Dim code = "Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestNoBlankLineAtEndOfFile_2() As Task Dim code = "Class C End Class " Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestOneBlankLineAtEndOfFile() As Task Dim code = "Class C End Class " Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineAtEndOfFile() As Task Dim code = "Class C End Class [||] " Dim fixedCode = "Class C End Class " Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLineAtEndOfFile() As Task Dim code = "Class C End Class [||] " Dim fixedCode = "Class C End Class " Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineAtEndOfFile() As Task Dim code = "Class C End Class [||] " Dim fixedCode = "Class C End Class " Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestNoBlankLineBetweenTokens() As Task Dim code = "Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestOneBlankLineBetweenTokens() As Task Dim code = "Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineBetweenTokens() As Task Dim code = "Class C [||] End Class" Dim fixedCode = "Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLineBetweenTokens() As Task Dim code = "Class C [||] End Class" Dim fixedCode = "Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineBetweenTokens() As Task Dim code = "Class C [||] End Class" Dim fixedCode = "Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestNoBlankLineAfterComment() As Task Dim code = "Class C ' comment End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestOneBlankLineAfterComment() As Task Dim code = "Class C ' comment End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineAfterComment() As Task Dim code = "Class C ' comment [||] End Class" Dim fixedCode = "Class C ' comment End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLineAfterComment() As Task Dim code = "Class C ' comment [||] End Class" Dim fixedCode = "Class C ' comment End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineAfterComment() As Task Dim code = "Class C ' comment [||] End Class" Dim fixedCode = "Class C ' comment End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestNoBlankLineAfterDirective() As Task Dim code = "Class C #Const X = 0 End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestOneBlankLineAfterDirective() As Task Dim code = "Class C #Const X = 0 End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineAfterDirective() As Task Dim code = "Class C #Const X = 0 [||] End Class" Dim fixedCode = "Class C #Const X = 0 End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLineAfterDirective() As Task Dim code = "Class C #Const X = 0 [||] End Class" Dim fixedCode = "Class C #Const X = 0 End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineAfterDirective() As Task Dim code = "Class C #Const X = 0 [||] End Class" Dim fixedCode = "Class C #Const X = 0 End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestNoBlankLineAfterDocComment() As Task Dim code = " ''' <summary/> Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestOneBlankLineAfterDocComment() As Task Dim code = " ''' <summary/> Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineAfterDocComment() As Task Dim code = " ''' <summary/> [||] Class C End Class" Dim fixedCode = " ''' <summary/> Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLineAfterDocComment() As Task Dim code = " ''' <summary/> [||] Class C End Class" Dim fixedCode = " ''' <summary/> Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineAfterDocComment() As Task Dim code = " ''' <summary/> [||] Class C End Class" Dim fixedCode = " ''' <summary/> Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestNoBlankLineAllConstructs() As Task Dim code = "''' <summary/> ' #Const X = 0 Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestOneBlankLineAllConstructs() As Task Dim code = " ''' <summary/> ' #Const X = 0 Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineAllConstructs() As Task Dim code = "[||] ''' <summary/> ' #Const X = 0 Class C End Class" Dim fixedCode = " ''' <summary/> ' #Const X = 0 Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLineAllConstructs() As Task Dim code = "[||] ''' <summary/> ' #Const X = 0 Class C End Class" Dim fixedCode = " ''' <summary/> ' #Const X = 0 Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineAllConstructs() As Task Dim code = "[||] ''' <summary/> ' #Const X = 0 Class C End Class" Dim fixedCode = " ''' <summary/> ' #Const X = 0 Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeStyle Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.VisualBasic.NewLines.MultipleBlankLines.VisualBasicMultipleBlankLinesDiagnosticAnalyzer, Microsoft.CodeAnalysis.NewLines.MultipleBlankLines.MultipleBlankLinesCodeFixProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.NewLines.MultipleBlankLines Public Class MultipleBlankLinesTests Private Shared Async Function TestWithOptionOn(testCode As String, fixedCode As String) As Task Dim test = New VerifyVB.Test() With { .TestCode = testCode, .FixedCode = fixedCode } test.Options.Add(CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSilentEnforcement) Await test.RunAsync() End Function <Fact> Public Async Function TestOneBlankLineAtTopOfFile() As Task Dim code = " ' comment" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineAtTopOfFile() As Task Dim code = "[||] ' comment" Dim fixedCode = " ' comment" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestTwoBlankLineAtTopOfFile_NotWithOptionOff() As Task Dim code = " ' comment" Await New VerifyVB.Test() With { .TestCode = code, .FixedCode = code }.RunAsync() End Function <Fact> Public Async Function TestThreeBlankLineAtTopOfFile() As Task Dim code = "[||] ' comment" Dim fixedCode = " ' comment" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineAtTopOfFile() As Task Dim code = "[||] ' comment" Dim fixedCode = " ' comment" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestOneBlankLineAtTopOfEmptyFile() As Task Dim code = " " Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLinesAtTopOfEmptyFile() As Task Dim code = "[||] " Dim fixedCode = " " Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLinesAtTopOfEmptyFile() As Task Dim code = "[||] " Dim fixedCode = " " Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLinesAtTopOfEmptyFile() As Task Dim code = "[||] " Dim fixedCode = " " Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestNoBlankLineAtEndOfFile_1() As Task Dim code = "Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestNoBlankLineAtEndOfFile_2() As Task Dim code = "Class C End Class " Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestOneBlankLineAtEndOfFile() As Task Dim code = "Class C End Class " Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineAtEndOfFile() As Task Dim code = "Class C End Class [||] " Dim fixedCode = "Class C End Class " Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLineAtEndOfFile() As Task Dim code = "Class C End Class [||] " Dim fixedCode = "Class C End Class " Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineAtEndOfFile() As Task Dim code = "Class C End Class [||] " Dim fixedCode = "Class C End Class " Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestNoBlankLineBetweenTokens() As Task Dim code = "Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestOneBlankLineBetweenTokens() As Task Dim code = "Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineBetweenTokens() As Task Dim code = "Class C [||] End Class" Dim fixedCode = "Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLineBetweenTokens() As Task Dim code = "Class C [||] End Class" Dim fixedCode = "Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineBetweenTokens() As Task Dim code = "Class C [||] End Class" Dim fixedCode = "Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestNoBlankLineAfterComment() As Task Dim code = "Class C ' comment End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestOneBlankLineAfterComment() As Task Dim code = "Class C ' comment End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineAfterComment() As Task Dim code = "Class C ' comment [||] End Class" Dim fixedCode = "Class C ' comment End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLineAfterComment() As Task Dim code = "Class C ' comment [||] End Class" Dim fixedCode = "Class C ' comment End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineAfterComment() As Task Dim code = "Class C ' comment [||] End Class" Dim fixedCode = "Class C ' comment End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestNoBlankLineAfterDirective() As Task Dim code = "Class C #Const X = 0 End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestOneBlankLineAfterDirective() As Task Dim code = "Class C #Const X = 0 End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineAfterDirective() As Task Dim code = "Class C #Const X = 0 [||] End Class" Dim fixedCode = "Class C #Const X = 0 End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLineAfterDirective() As Task Dim code = "Class C #Const X = 0 [||] End Class" Dim fixedCode = "Class C #Const X = 0 End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineAfterDirective() As Task Dim code = "Class C #Const X = 0 [||] End Class" Dim fixedCode = "Class C #Const X = 0 End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestNoBlankLineAfterDocComment() As Task Dim code = " ''' <summary/> Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestOneBlankLineAfterDocComment() As Task Dim code = " ''' <summary/> Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineAfterDocComment() As Task Dim code = " ''' <summary/> [||] Class C End Class" Dim fixedCode = " ''' <summary/> Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLineAfterDocComment() As Task Dim code = " ''' <summary/> [||] Class C End Class" Dim fixedCode = " ''' <summary/> Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineAfterDocComment() As Task Dim code = " ''' <summary/> [||] Class C End Class" Dim fixedCode = " ''' <summary/> Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestNoBlankLineAllConstructs() As Task Dim code = "''' <summary/> ' #Const X = 0 Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestOneBlankLineAllConstructs() As Task Dim code = " ''' <summary/> ' #Const X = 0 Class C End Class" Await TestWithOptionOn(code, code) End Function <Fact> Public Async Function TestTwoBlankLineAllConstructs() As Task Dim code = "[||] ''' <summary/> ' #Const X = 0 Class C End Class" Dim fixedCode = " ''' <summary/> ' #Const X = 0 Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestThreeBlankLineAllConstructs() As Task Dim code = "[||] ''' <summary/> ' #Const X = 0 Class C End Class" Dim fixedCode = " ''' <summary/> ' #Const X = 0 Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function <Fact> Public Async Function TestFourBlankLineAllConstructs() As Task Dim code = "[||] ''' <summary/> ' #Const X = 0 Class C End Class" Dim fixedCode = " ''' <summary/> ' #Const X = 0 Class C End Class" Await TestWithOptionOn(code, fixedCode) End Function End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/VisualStudio/CSharp/Impl/ObjectBrowser/CSharpLibraryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.Library; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ObjectBrowser { [ExportLanguageService(typeof(ILibraryService), LanguageNames.CSharp), Shared] internal class CSharpLibraryService : AbstractLibraryService { private static readonly SymbolDisplayFormat s_typeDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); private static readonly SymbolDisplayFormat s_memberDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpLibraryService() : base(Guids.CSharpLibraryId, __SymbolToolLanguage.SymbolToolLanguage_CSharp, s_typeDisplayFormat, s_memberDisplayFormat) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.Library; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ObjectBrowser { [ExportLanguageService(typeof(ILibraryService), LanguageNames.CSharp), Shared] internal class CSharpLibraryService : AbstractLibraryService { private static readonly SymbolDisplayFormat s_typeDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); private static readonly SymbolDisplayFormat s_memberDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpLibraryService() : base(Guids.CSharpLibraryId, __SymbolToolLanguage.SymbolToolLanguage_CSharp, s_typeDisplayFormat, s_memberDisplayFormat) { } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/Core/Portable/AddFileBanner/AbstractAddFileBannerCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddFileBanner { internal abstract class AbstractAddFileBannerCodeRefactoringProvider : CodeRefactoringProvider { protected abstract bool IsCommentStartCharacter(char ch); protected abstract SyntaxTrivia CreateTrivia(SyntaxTrivia trivia, string text); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; if (!span.IsEmpty) { return; } var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (document.Project.AnalyzerOptions.TryGetEditorConfigOption<string>(CodeStyleOptions2.FileHeaderTemplate, tree, out var fileHeaderTemplate) && !string.IsNullOrEmpty(fileHeaderTemplate)) { // If we have a defined file header template, allow the analyzer and code fix to handle it return; } var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var position = span.Start; var firstToken = root.GetFirstToken(); if (!firstToken.FullSpan.IntersectsWith(position)) { return; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var banner = syntaxFacts.GetFileBanner(root); if (banner.Length > 0) { // Already has a banner. return; } // Process the other documents in this document's project. Look at the // ones that we can get a root from (without having to parse). Then // look at the ones we'd need to parse. var siblingDocumentsAndRoots = document.Project.Documents .Where(d => d != document) .Select(d => { d.TryGetSyntaxRoot(out var siblingRoot); return (document: d, root: siblingRoot); }) .OrderBy((t1, t2) => (t1.root != null) == (t2.root != null) ? 0 : t1.root != null ? -1 : 1); foreach (var (siblingDocument, siblingRoot) in siblingDocumentsAndRoots) { cancellationToken.ThrowIfCancellationRequested(); var siblingBanner = await TryGetBannerAsync(siblingDocument, siblingRoot, cancellationToken).ConfigureAwait(false); if (siblingBanner.Length > 0 && !siblingDocument.IsGeneratedCode(cancellationToken)) { context.RegisterRefactoring( new MyCodeAction(_ => AddBannerAsync(document, root, siblingDocument, siblingBanner)), new Text.TextSpan(position, length: 0)); return; } } } private Task<Document> AddBannerAsync( Document document, SyntaxNode root, Document siblingDocument, ImmutableArray<SyntaxTrivia> banner) { banner = UpdateEmbeddedFileNames(siblingDocument, document, banner); var newRoot = root.WithPrependedLeadingTrivia(new SyntaxTriviaList(banner)); return Task.FromResult(document.WithSyntaxRoot(newRoot)); } /// <summary> /// Looks at <paramref name="banner"/> to see if it contains the name of <paramref name="sourceDocument"/> /// in it. If so, those names will be replaced with <paramref name="destinationDocument"/>'s name. /// </summary> private ImmutableArray<SyntaxTrivia> UpdateEmbeddedFileNames( Document sourceDocument, Document destinationDocument, ImmutableArray<SyntaxTrivia> banner) { var sourceName = IOUtilities.PerformIO(() => Path.GetFileName(sourceDocument.FilePath)); var destinationName = IOUtilities.PerformIO(() => Path.GetFileName(destinationDocument.FilePath)); if (string.IsNullOrEmpty(sourceName) || string.IsNullOrEmpty(destinationName)) { return banner; } using var _ = ArrayBuilder<SyntaxTrivia>.GetInstance(out var result); foreach (var trivia in banner) { var updated = CreateTrivia(trivia, trivia.ToFullString().Replace(sourceName, destinationName)); result.Add(updated); } return result.ToImmutable(); } private async Task<ImmutableArray<SyntaxTrivia>> TryGetBannerAsync( Document document, SyntaxNode root, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // If we have a tree already for this document, then just check to see // if it has a banner. if (root != null) { return syntaxFacts.GetFileBanner(root); } // Didn't have a tree. Don't want to parse the file if we can avoid it. var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (text.Length == 0 || !IsCommentStartCharacter(text[0])) { // Didn't start with a comment character, don't bother looking at // this file. return ImmutableArray<SyntaxTrivia>.Empty; } var token = syntaxFacts.ParseToken(text.ToString()); return syntaxFacts.GetFileBanner(token); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CodeFixesResources.Add_file_header, createChangedDocument, nameof(CodeFixesResources.Add_file_header)) { } } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddFileBanner { internal abstract class AbstractAddFileBannerCodeRefactoringProvider : CodeRefactoringProvider { protected abstract bool IsCommentStartCharacter(char ch); protected abstract SyntaxTrivia CreateTrivia(SyntaxTrivia trivia, string text); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; if (!span.IsEmpty) { return; } var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (document.Project.AnalyzerOptions.TryGetEditorConfigOption<string>(CodeStyleOptions2.FileHeaderTemplate, tree, out var fileHeaderTemplate) && !string.IsNullOrEmpty(fileHeaderTemplate)) { // If we have a defined file header template, allow the analyzer and code fix to handle it return; } var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var position = span.Start; var firstToken = root.GetFirstToken(); if (!firstToken.FullSpan.IntersectsWith(position)) { return; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var banner = syntaxFacts.GetFileBanner(root); if (banner.Length > 0) { // Already has a banner. return; } // Process the other documents in this document's project. Look at the // ones that we can get a root from (without having to parse). Then // look at the ones we'd need to parse. var siblingDocumentsAndRoots = document.Project.Documents .Where(d => d != document) .Select(d => { d.TryGetSyntaxRoot(out var siblingRoot); return (document: d, root: siblingRoot); }) .OrderBy((t1, t2) => (t1.root != null) == (t2.root != null) ? 0 : t1.root != null ? -1 : 1); foreach (var (siblingDocument, siblingRoot) in siblingDocumentsAndRoots) { cancellationToken.ThrowIfCancellationRequested(); var siblingBanner = await TryGetBannerAsync(siblingDocument, siblingRoot, cancellationToken).ConfigureAwait(false); if (siblingBanner.Length > 0 && !siblingDocument.IsGeneratedCode(cancellationToken)) { context.RegisterRefactoring( new MyCodeAction(_ => AddBannerAsync(document, root, siblingDocument, siblingBanner)), new Text.TextSpan(position, length: 0)); return; } } } private Task<Document> AddBannerAsync( Document document, SyntaxNode root, Document siblingDocument, ImmutableArray<SyntaxTrivia> banner) { banner = UpdateEmbeddedFileNames(siblingDocument, document, banner); var newRoot = root.WithPrependedLeadingTrivia(new SyntaxTriviaList(banner)); return Task.FromResult(document.WithSyntaxRoot(newRoot)); } /// <summary> /// Looks at <paramref name="banner"/> to see if it contains the name of <paramref name="sourceDocument"/> /// in it. If so, those names will be replaced with <paramref name="destinationDocument"/>'s name. /// </summary> private ImmutableArray<SyntaxTrivia> UpdateEmbeddedFileNames( Document sourceDocument, Document destinationDocument, ImmutableArray<SyntaxTrivia> banner) { var sourceName = IOUtilities.PerformIO(() => Path.GetFileName(sourceDocument.FilePath)); var destinationName = IOUtilities.PerformIO(() => Path.GetFileName(destinationDocument.FilePath)); if (string.IsNullOrEmpty(sourceName) || string.IsNullOrEmpty(destinationName)) { return banner; } using var _ = ArrayBuilder<SyntaxTrivia>.GetInstance(out var result); foreach (var trivia in banner) { var updated = CreateTrivia(trivia, trivia.ToFullString().Replace(sourceName, destinationName)); result.Add(updated); } return result.ToImmutable(); } private async Task<ImmutableArray<SyntaxTrivia>> TryGetBannerAsync( Document document, SyntaxNode root, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // If we have a tree already for this document, then just check to see // if it has a banner. if (root != null) { return syntaxFacts.GetFileBanner(root); } // Didn't have a tree. Don't want to parse the file if we can avoid it. var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (text.Length == 0 || !IsCommentStartCharacter(text[0])) { // Didn't start with a comment character, don't bother looking at // this file. return ImmutableArray<SyntaxTrivia>.Empty; } var token = syntaxFacts.ParseToken(text.ToString()); return syntaxFacts.GetFileBanner(token); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CodeFixesResources.Add_file_header, createChangedDocument, nameof(CodeFixesResources.Add_file_header)) { } } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/VisualBasic/Portable/Syntax/InternalSyntax/SyntaxFactory.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.Generic Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend Class SyntaxFactory Friend Shared ReadOnly CarriageReturnLineFeed As SyntaxTrivia = EndOfLine(vbCrLf) Friend Shared ReadOnly LineFeed As SyntaxTrivia = EndOfLine(vbLf) Friend Shared ReadOnly CarriageReturn As SyntaxTrivia = EndOfLine(vbCr) Friend Shared ReadOnly Space As SyntaxTrivia = Whitespace(" ") Friend Shared ReadOnly Tab As SyntaxTrivia = Whitespace(vbTab) Friend Shared ReadOnly ElasticCarriageReturnLineFeed As SyntaxTrivia = EndOfLine(vbCrLf, elastic:=True) Friend Shared ReadOnly ElasticLineFeed As SyntaxTrivia = EndOfLine(vbLf, elastic:=True) Friend Shared ReadOnly ElasticCarriageReturn As SyntaxTrivia = EndOfLine(vbCr, elastic:=True) Friend Shared ReadOnly ElasticSpace As SyntaxTrivia = Whitespace(" ", elastic:=True) Friend Shared ReadOnly ElasticTab As SyntaxTrivia = Whitespace(vbTab, elastic:=True) Friend Shared ReadOnly ElasticZeroSpace As SyntaxTrivia = Whitespace(String.Empty, elastic:=True) Friend Shared Function EndOfLine(text As String, Optional elastic As Boolean = False) As SyntaxTrivia Dim trivia As SyntaxTrivia = Nothing ' use predefined trivia Select Case text Case vbCr trivia = If(elastic, SyntaxFactory.ElasticCarriageReturn, SyntaxFactory.CarriageReturn) Case vbLf trivia = If(elastic, SyntaxFactory.ElasticLineFeed, SyntaxFactory.LineFeed) Case vbCrLf trivia = If(elastic, SyntaxFactory.ElasticCarriageReturnLineFeed, SyntaxFactory.CarriageReturnLineFeed) End Select ' note: predefined trivia might not yet be defined during initialization If trivia IsNot Nothing Then Return trivia End If trivia = SyntaxTrivia(SyntaxKind.EndOfLineTrivia, text) If Not elastic Then Return trivia End If Return trivia.WithAnnotations(SyntaxAnnotation.ElasticAnnotation) End Function Friend Shared Function Whitespace(text As String, Optional elastic As Boolean = False) As SyntaxTrivia Dim trivia = SyntaxTrivia(SyntaxKind.WhitespaceTrivia, text) If Not elastic Then Return trivia End If Return trivia.WithAnnotations(SyntaxAnnotation.ElasticAnnotation) End Function Friend Shared Function Token(leading As GreenNode, kind As SyntaxKind, trailing As GreenNode, Optional text As String = Nothing) As SyntaxToken Return SyntaxToken.Create(kind, leading, trailing, If(text Is Nothing, SyntaxFacts.GetText(kind), text)) End Function Friend Shared Function GetWellKnownTrivia() As IEnumerable(Of SyntaxTrivia) Return New SyntaxTrivia() { CarriageReturn, CarriageReturnLineFeed, LineFeed, Space, Tab, ElasticCarriageReturn, ElasticLineFeed, ElasticCarriageReturnLineFeed, ElasticSpace, ElasticTab, ElasticZeroSpace, Whitespace(" "), Whitespace(" "), Whitespace(" ") } 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.Generic Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend Class SyntaxFactory Friend Shared ReadOnly CarriageReturnLineFeed As SyntaxTrivia = EndOfLine(vbCrLf) Friend Shared ReadOnly LineFeed As SyntaxTrivia = EndOfLine(vbLf) Friend Shared ReadOnly CarriageReturn As SyntaxTrivia = EndOfLine(vbCr) Friend Shared ReadOnly Space As SyntaxTrivia = Whitespace(" ") Friend Shared ReadOnly Tab As SyntaxTrivia = Whitespace(vbTab) Friend Shared ReadOnly ElasticCarriageReturnLineFeed As SyntaxTrivia = EndOfLine(vbCrLf, elastic:=True) Friend Shared ReadOnly ElasticLineFeed As SyntaxTrivia = EndOfLine(vbLf, elastic:=True) Friend Shared ReadOnly ElasticCarriageReturn As SyntaxTrivia = EndOfLine(vbCr, elastic:=True) Friend Shared ReadOnly ElasticSpace As SyntaxTrivia = Whitespace(" ", elastic:=True) Friend Shared ReadOnly ElasticTab As SyntaxTrivia = Whitespace(vbTab, elastic:=True) Friend Shared ReadOnly ElasticZeroSpace As SyntaxTrivia = Whitespace(String.Empty, elastic:=True) Friend Shared Function EndOfLine(text As String, Optional elastic As Boolean = False) As SyntaxTrivia Dim trivia As SyntaxTrivia = Nothing ' use predefined trivia Select Case text Case vbCr trivia = If(elastic, SyntaxFactory.ElasticCarriageReturn, SyntaxFactory.CarriageReturn) Case vbLf trivia = If(elastic, SyntaxFactory.ElasticLineFeed, SyntaxFactory.LineFeed) Case vbCrLf trivia = If(elastic, SyntaxFactory.ElasticCarriageReturnLineFeed, SyntaxFactory.CarriageReturnLineFeed) End Select ' note: predefined trivia might not yet be defined during initialization If trivia IsNot Nothing Then Return trivia End If trivia = SyntaxTrivia(SyntaxKind.EndOfLineTrivia, text) If Not elastic Then Return trivia End If Return trivia.WithAnnotations(SyntaxAnnotation.ElasticAnnotation) End Function Friend Shared Function Whitespace(text As String, Optional elastic As Boolean = False) As SyntaxTrivia Dim trivia = SyntaxTrivia(SyntaxKind.WhitespaceTrivia, text) If Not elastic Then Return trivia End If Return trivia.WithAnnotations(SyntaxAnnotation.ElasticAnnotation) End Function Friend Shared Function Token(leading As GreenNode, kind As SyntaxKind, trailing As GreenNode, Optional text As String = Nothing) As SyntaxToken Return SyntaxToken.Create(kind, leading, trailing, If(text Is Nothing, SyntaxFacts.GetText(kind), text)) End Function Friend Shared Function GetWellKnownTrivia() As IEnumerable(Of SyntaxTrivia) Return New SyntaxTrivia() { CarriageReturn, CarriageReturnLineFeed, LineFeed, Space, Tab, ElasticCarriageReturn, ElasticLineFeed, ElasticCarriageReturnLineFeed, ElasticSpace, ElasticTab, ElasticZeroSpace, Whitespace(" "), Whitespace(" "), Whitespace(" ") } End Function End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/VisualBasic/Portable/IntroduceVariable/VisualBasicIntroduceVariableService_IntroduceLocal.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.IntroduceVariable Partial Friend Class VisualBasicIntroduceVariableService Protected Overrides Async Function IntroduceLocalAsync( document As SemanticDocument, expression As ExpressionSyntax, allOccurrences As Boolean, isConstant As Boolean, cancellationToken As CancellationToken) As Task(Of Document) Dim container = GetContainerToGenerateInfo(document, expression, cancellationToken) Dim newLocalNameToken = GenerateUniqueLocalName( document, expression, isConstant, container, cancellationToken) Dim newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken) Dim modifier = If(isConstant, SyntaxFactory.Token(SyntaxKind.ConstKeyword), SyntaxFactory.Token(SyntaxKind.DimKeyword)) Dim type = GetTypeSymbol(document, expression, cancellationToken) Dim asClause = If(type.ContainsAnonymousType(), Nothing, SyntaxFactory.SimpleAsClause(type.GenerateTypeSyntax())) Dim declarationStatement = SyntaxFactory.LocalDeclarationStatement( modifiers:=SyntaxFactory.TokenList(modifier), declarators:=SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( SyntaxFactory.SingletonSeparatedList(SyntaxFactory.ModifiedIdentifier(newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()))), asClause, SyntaxFactory.EqualsValue(value:=expression.WithoutTrailingTrivia().WithoutLeadingTrivia())))) If Not declarationStatement.GetTrailingTrivia().Any(SyntaxKind.EndOfLineTrivia) Then declarationStatement = declarationStatement.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed) End If If TypeOf container Is SingleLineLambdaExpressionSyntax Then Return IntroduceLocalDeclarationIntoLambda( document, DirectCast(container, SingleLineLambdaExpressionSyntax), expression, newLocalName, declarationStatement, allOccurrences, cancellationToken) Else Return Await IntroduceLocalDeclarationIntoBlockAsync( document, container, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken).ConfigureAwait(False) End If End Function Private Shared Function GetContainerToGenerateInfo( document As SemanticDocument, expression As ExpressionSyntax, cancellationToken As CancellationToken) As SyntaxNode Dim anonymousMethodParameters = GetAnonymousMethodParameters(document, expression, cancellationToken) Dim lambdas = anonymousMethodParameters.SelectMany(Function(p) p.ContainingSymbol.DeclaringSyntaxReferences). Select(Function(r) r.GetSyntax()). OfType(Of SingleLineLambdaExpressionSyntax). Where(Function(lambda) lambda.Kind = SyntaxKind.SingleLineFunctionLambdaExpression). ToSet() Dim parentLambda = GetParentLambda(expression, lambdas) If parentLambda IsNot Nothing Then Return parentLambda End If Return expression.GetContainingExecutableBlocks().LastOrDefault() End Function Private Function IntroduceLocalDeclarationIntoLambda( document As SemanticDocument, oldLambda As SingleLineLambdaExpressionSyntax, expression As ExpressionSyntax, newLocalName As IdentifierNameSyntax, declarationStatement As StatementSyntax, allOccurrences As Boolean, cancellationToken As CancellationToken) As Document Dim oldBody = DirectCast(oldLambda.Body, ExpressionSyntax) Dim rewrittenBody = Rewrite( document, expression, newLocalName, document, oldBody, allOccurrences, cancellationToken) Dim statements = {declarationStatement, SyntaxFactory.ReturnStatement(rewrittenBody)} Dim newLambda As ExpressionSyntax = SyntaxFactory.MultiLineFunctionLambdaExpression( oldLambda.SubOrFunctionHeader, SyntaxFactory.List(statements), SyntaxFactory.EndFunctionStatement()).WithAdditionalAnnotations(Formatter.Annotation) Dim newRoot = document.Root.ReplaceNode(oldLambda, newLambda) Return document.Document.WithSyntaxRoot(newRoot) End Function Private Shared Function GetParentLambda(expression As ExpressionSyntax, lambdas As ISet(Of SingleLineLambdaExpressionSyntax)) As SingleLineLambdaExpressionSyntax Dim current = expression While current IsNot Nothing Dim parent = TryCast(current.Parent, SingleLineLambdaExpressionSyntax) If parent IsNot Nothing Then If lambdas.Contains(parent) Then Return parent End If End If current = TryCast(current.Parent, ExpressionSyntax) End While Return Nothing End Function Private Async Function IntroduceLocalDeclarationIntoBlockAsync( document As SemanticDocument, container As SyntaxNode, expression As ExpressionSyntax, newLocalName As NameSyntax, declarationStatement As LocalDeclarationStatementSyntax, allOccurrences As Boolean, cancellationToken As CancellationToken) As Task(Of Document) Dim localAnnotation = New SyntaxAnnotation() declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation, localAnnotation) Dim oldOutermostBlock = container If oldOutermostBlock.IsSingleLineExecutableBlock() Then oldOutermostBlock = oldOutermostBlock.Parent End If Dim matches = FindMatches(document, expression, document, oldOutermostBlock, allOccurrences, cancellationToken) Dim complexified = Await ComplexifyParentingStatementsAsync(document, matches, cancellationToken).ConfigureAwait(False) document = complexified.newSemanticDocument matches = complexified.newMatches ' Our original expression should have been one of the matches, which were tracked as part ' of complexification, so we can retrieve the latest version of the expression here. expression = document.Root.GetCurrentNodes(expression).First() Dim innermostStatements = New HashSet(Of StatementSyntax)(matches.Select(Function(expr) expr.GetAncestorOrThis(Of StatementSyntax)())) If innermostStatements.Count = 1 Then Return IntroduceLocalForSingleOccurrenceIntoBlock( document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken) End If Dim oldInnerMostCommonBlock = matches.FindInnermostCommonExecutableBlock() Dim allAffectedStatements = New HashSet(Of StatementSyntax)(matches.SelectMany(Function(expr) expr.GetAncestorsOrThis(Of StatementSyntax)())) Dim firstStatementAffectedInBlock = oldInnerMostCommonBlock.GetExecutableBlockStatements().First(AddressOf allAffectedStatements.Contains) Dim firstStatementAffectedIndex = oldInnerMostCommonBlock.GetExecutableBlockStatements().IndexOf(firstStatementAffectedInBlock) Dim newInnerMostBlock = Rewrite(document, expression, newLocalName, document, oldInnerMostCommonBlock, allOccurrences, cancellationToken) Dim statements = newInnerMostBlock.GetExecutableBlockStatements().Insert(firstStatementAffectedIndex, declarationStatement) Dim finalInnerMostBlock = oldInnerMostCommonBlock.ReplaceStatements(statements, Formatter.Annotation) Dim newRoot = document.Root.ReplaceNode(oldInnerMostCommonBlock, finalInnerMostBlock) Return document.Document.WithSyntaxRoot(newRoot) End Function Private Function IntroduceLocalForSingleOccurrenceIntoBlock( semanticDocument As SemanticDocument, expression As ExpressionSyntax, localName As NameSyntax, localDeclaration As LocalDeclarationStatementSyntax, allOccurrences As Boolean, cancellationToken As CancellationToken) As Document Dim oldStatement = expression.GetAncestorsOrThis(Of StatementSyntax)().Where( Function(s) s.Parent.IsExecutableBlock() AndAlso s.Parent.GetExecutableBlockStatements().Contains(s)).First() Dim newStatement = Rewrite(semanticDocument, expression, localName, semanticDocument, oldStatement, allOccurrences, cancellationToken) localDeclaration = localDeclaration.WithLeadingTrivia(newStatement.GetLeadingTrivia()) newStatement = newStatement.WithLeadingTrivia(newStatement.GetLeadingTrivia().Where(Function(trivia) trivia.IsKind(SyntaxKind.WhitespaceTrivia))) Dim oldBlock = oldStatement.Parent If oldBlock.IsSingleLineExecutableBlock() Then Dim tree = semanticDocument.SyntaxTree Dim statements = SyntaxFactory.List({localDeclaration, newStatement}) Dim newRoot = tree.ConvertSingleLineToMultiLineExecutableBlock(oldBlock, statements, Formatter.Annotation) Return semanticDocument.Document.WithSyntaxRoot(newRoot) Else Dim statementIndex = oldBlock.GetExecutableBlockStatements().IndexOf(oldStatement) Dim newStatements = oldBlock.GetExecutableBlockStatements().Replace(oldStatement, newStatement).Insert(statementIndex, localDeclaration) Dim newBlock = oldBlock.ReplaceStatements(newStatements) Dim oldRoot = semanticDocument.Root Dim newRoot = oldRoot.ReplaceNode(oldBlock, newBlock) Return semanticDocument.Document.WithSyntaxRoot(newRoot) End If End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.IntroduceVariable Partial Friend Class VisualBasicIntroduceVariableService Protected Overrides Async Function IntroduceLocalAsync( document As SemanticDocument, expression As ExpressionSyntax, allOccurrences As Boolean, isConstant As Boolean, cancellationToken As CancellationToken) As Task(Of Document) Dim container = GetContainerToGenerateInfo(document, expression, cancellationToken) Dim newLocalNameToken = GenerateUniqueLocalName( document, expression, isConstant, container, cancellationToken) Dim newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken) Dim modifier = If(isConstant, SyntaxFactory.Token(SyntaxKind.ConstKeyword), SyntaxFactory.Token(SyntaxKind.DimKeyword)) Dim type = GetTypeSymbol(document, expression, cancellationToken) Dim asClause = If(type.ContainsAnonymousType(), Nothing, SyntaxFactory.SimpleAsClause(type.GenerateTypeSyntax())) Dim declarationStatement = SyntaxFactory.LocalDeclarationStatement( modifiers:=SyntaxFactory.TokenList(modifier), declarators:=SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( SyntaxFactory.SingletonSeparatedList(SyntaxFactory.ModifiedIdentifier(newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()))), asClause, SyntaxFactory.EqualsValue(value:=expression.WithoutTrailingTrivia().WithoutLeadingTrivia())))) If Not declarationStatement.GetTrailingTrivia().Any(SyntaxKind.EndOfLineTrivia) Then declarationStatement = declarationStatement.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed) End If If TypeOf container Is SingleLineLambdaExpressionSyntax Then Return IntroduceLocalDeclarationIntoLambda( document, DirectCast(container, SingleLineLambdaExpressionSyntax), expression, newLocalName, declarationStatement, allOccurrences, cancellationToken) Else Return Await IntroduceLocalDeclarationIntoBlockAsync( document, container, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken).ConfigureAwait(False) End If End Function Private Shared Function GetContainerToGenerateInfo( document As SemanticDocument, expression As ExpressionSyntax, cancellationToken As CancellationToken) As SyntaxNode Dim anonymousMethodParameters = GetAnonymousMethodParameters(document, expression, cancellationToken) Dim lambdas = anonymousMethodParameters.SelectMany(Function(p) p.ContainingSymbol.DeclaringSyntaxReferences). Select(Function(r) r.GetSyntax()). OfType(Of SingleLineLambdaExpressionSyntax). Where(Function(lambda) lambda.Kind = SyntaxKind.SingleLineFunctionLambdaExpression). ToSet() Dim parentLambda = GetParentLambda(expression, lambdas) If parentLambda IsNot Nothing Then Return parentLambda End If Return expression.GetContainingExecutableBlocks().LastOrDefault() End Function Private Function IntroduceLocalDeclarationIntoLambda( document As SemanticDocument, oldLambda As SingleLineLambdaExpressionSyntax, expression As ExpressionSyntax, newLocalName As IdentifierNameSyntax, declarationStatement As StatementSyntax, allOccurrences As Boolean, cancellationToken As CancellationToken) As Document Dim oldBody = DirectCast(oldLambda.Body, ExpressionSyntax) Dim rewrittenBody = Rewrite( document, expression, newLocalName, document, oldBody, allOccurrences, cancellationToken) Dim statements = {declarationStatement, SyntaxFactory.ReturnStatement(rewrittenBody)} Dim newLambda As ExpressionSyntax = SyntaxFactory.MultiLineFunctionLambdaExpression( oldLambda.SubOrFunctionHeader, SyntaxFactory.List(statements), SyntaxFactory.EndFunctionStatement()).WithAdditionalAnnotations(Formatter.Annotation) Dim newRoot = document.Root.ReplaceNode(oldLambda, newLambda) Return document.Document.WithSyntaxRoot(newRoot) End Function Private Shared Function GetParentLambda(expression As ExpressionSyntax, lambdas As ISet(Of SingleLineLambdaExpressionSyntax)) As SingleLineLambdaExpressionSyntax Dim current = expression While current IsNot Nothing Dim parent = TryCast(current.Parent, SingleLineLambdaExpressionSyntax) If parent IsNot Nothing Then If lambdas.Contains(parent) Then Return parent End If End If current = TryCast(current.Parent, ExpressionSyntax) End While Return Nothing End Function Private Async Function IntroduceLocalDeclarationIntoBlockAsync( document As SemanticDocument, container As SyntaxNode, expression As ExpressionSyntax, newLocalName As NameSyntax, declarationStatement As LocalDeclarationStatementSyntax, allOccurrences As Boolean, cancellationToken As CancellationToken) As Task(Of Document) Dim localAnnotation = New SyntaxAnnotation() declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation, localAnnotation) Dim oldOutermostBlock = container If oldOutermostBlock.IsSingleLineExecutableBlock() Then oldOutermostBlock = oldOutermostBlock.Parent End If Dim matches = FindMatches(document, expression, document, oldOutermostBlock, allOccurrences, cancellationToken) Dim complexified = Await ComplexifyParentingStatementsAsync(document, matches, cancellationToken).ConfigureAwait(False) document = complexified.newSemanticDocument matches = complexified.newMatches ' Our original expression should have been one of the matches, which were tracked as part ' of complexification, so we can retrieve the latest version of the expression here. expression = document.Root.GetCurrentNodes(expression).First() Dim innermostStatements = New HashSet(Of StatementSyntax)(matches.Select(Function(expr) expr.GetAncestorOrThis(Of StatementSyntax)())) If innermostStatements.Count = 1 Then Return IntroduceLocalForSingleOccurrenceIntoBlock( document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken) End If Dim oldInnerMostCommonBlock = matches.FindInnermostCommonExecutableBlock() Dim allAffectedStatements = New HashSet(Of StatementSyntax)(matches.SelectMany(Function(expr) expr.GetAncestorsOrThis(Of StatementSyntax)())) Dim firstStatementAffectedInBlock = oldInnerMostCommonBlock.GetExecutableBlockStatements().First(AddressOf allAffectedStatements.Contains) Dim firstStatementAffectedIndex = oldInnerMostCommonBlock.GetExecutableBlockStatements().IndexOf(firstStatementAffectedInBlock) Dim newInnerMostBlock = Rewrite(document, expression, newLocalName, document, oldInnerMostCommonBlock, allOccurrences, cancellationToken) Dim statements = newInnerMostBlock.GetExecutableBlockStatements().Insert(firstStatementAffectedIndex, declarationStatement) Dim finalInnerMostBlock = oldInnerMostCommonBlock.ReplaceStatements(statements, Formatter.Annotation) Dim newRoot = document.Root.ReplaceNode(oldInnerMostCommonBlock, finalInnerMostBlock) Return document.Document.WithSyntaxRoot(newRoot) End Function Private Function IntroduceLocalForSingleOccurrenceIntoBlock( semanticDocument As SemanticDocument, expression As ExpressionSyntax, localName As NameSyntax, localDeclaration As LocalDeclarationStatementSyntax, allOccurrences As Boolean, cancellationToken As CancellationToken) As Document Dim oldStatement = expression.GetAncestorsOrThis(Of StatementSyntax)().Where( Function(s) s.Parent.IsExecutableBlock() AndAlso s.Parent.GetExecutableBlockStatements().Contains(s)).First() Dim newStatement = Rewrite(semanticDocument, expression, localName, semanticDocument, oldStatement, allOccurrences, cancellationToken) localDeclaration = localDeclaration.WithLeadingTrivia(newStatement.GetLeadingTrivia()) newStatement = newStatement.WithLeadingTrivia(newStatement.GetLeadingTrivia().Where(Function(trivia) trivia.IsKind(SyntaxKind.WhitespaceTrivia))) Dim oldBlock = oldStatement.Parent If oldBlock.IsSingleLineExecutableBlock() Then Dim tree = semanticDocument.SyntaxTree Dim statements = SyntaxFactory.List({localDeclaration, newStatement}) Dim newRoot = tree.ConvertSingleLineToMultiLineExecutableBlock(oldBlock, statements, Formatter.Annotation) Return semanticDocument.Document.WithSyntaxRoot(newRoot) Else Dim statementIndex = oldBlock.GetExecutableBlockStatements().IndexOf(oldStatement) Dim newStatements = oldBlock.GetExecutableBlockStatements().Replace(oldStatement, newStatement).Insert(statementIndex, localDeclaration) Dim newBlock = oldBlock.ReplaceStatements(newStatements) Dim oldRoot = semanticDocument.Root Dim newRoot = oldRoot.ReplaceNode(oldBlock, newBlock) Return semanticDocument.Document.WithSyntaxRoot(newRoot) End If End Function End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/Core/Portable/Shared/Extensions/SyntaxTokenListExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.PooledObjects; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SyntaxTokenListExtensions { /// <summary> /// Gets the concatenated value text for the token list. /// </summary> /// <returns>The concatenated value text, or an empty string if there are no tokens in the list.</returns> internal static string GetValueText(this SyntaxTokenList tokens) { switch (tokens.Count) { case 0: return string.Empty; case 1: return tokens[0].ValueText; default: var pooledBuilder = PooledStringBuilder.GetInstance(); foreach (var token in tokens) { pooledBuilder.Builder.Append(token.ValueText); } return pooledBuilder.ToStringAndFree(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.PooledObjects; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SyntaxTokenListExtensions { /// <summary> /// Gets the concatenated value text for the token list. /// </summary> /// <returns>The concatenated value text, or an empty string if there are no tokens in the list.</returns> internal static string GetValueText(this SyntaxTokenList tokens) { switch (tokens.Count) { case 0: return string.Empty; case 1: return tokens[0].ValueText; default: var pooledBuilder = PooledStringBuilder.GetInstance(); foreach (var token in tokens) { pooledBuilder.Builder.Append(token.ValueText); } return pooledBuilder.ToStringAndFree(); } } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/Core/Portable/Emit/EditAndContinue/SymbolMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal abstract class SymbolMatcher { public abstract Cci.ITypeReference? MapReference(Cci.ITypeReference reference); public abstract Cci.IDefinition? MapDefinition(Cci.IDefinition definition); public abstract Cci.INamespace? MapNamespace(Cci.INamespace @namespace); public ISymbolInternal? MapDefinitionOrNamespace(ISymbolInternal symbol) { var adapter = symbol.GetCciAdapter(); return (adapter is Cci.IDefinition definition) ? MapDefinition(definition)?.GetInternalSymbol() : MapNamespace((Cci.INamespace)adapter)?.GetInternalSymbol(); } public EmitBaseline MapBaselineToCompilation( EmitBaseline baseline, Compilation targetCompilation, CommonPEModuleBuilder targetModuleBuilder, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> mappedSynthesizedMembers) { // Map all definitions to this compilation. var typesAdded = MapDefinitions(baseline.TypesAdded); var eventsAdded = MapDefinitions(baseline.EventsAdded); var fieldsAdded = MapDefinitions(baseline.FieldsAdded); var methodsAdded = MapDefinitions(baseline.MethodsAdded); var propertiesAdded = MapDefinitions(baseline.PropertiesAdded); var generationOrdinals = MapDefinitions(baseline.GenerationOrdinals); return baseline.With( targetCompilation, targetModuleBuilder, baseline.Ordinal, baseline.EncId, generationOrdinals, typesAdded, eventsAdded, fieldsAdded, methodsAdded, firstParamRowMap: baseline.FirstParamRowMap, propertiesAdded, eventMapAdded: baseline.EventMapAdded, propertyMapAdded: baseline.PropertyMapAdded, methodImplsAdded: baseline.MethodImplsAdded, customAttributesAdded: baseline.CustomAttributesAdded, tableEntriesAdded: baseline.TableEntriesAdded, blobStreamLengthAdded: baseline.BlobStreamLengthAdded, stringStreamLengthAdded: baseline.StringStreamLengthAdded, userStringStreamLengthAdded: baseline.UserStringStreamLengthAdded, guidStreamLengthAdded: baseline.GuidStreamLengthAdded, anonymousTypeMap: MapAnonymousTypes(baseline.AnonymousTypeMap), synthesizedMembers: mappedSynthesizedMembers, addedOrChangedMethods: MapAddedOrChangedMethods(baseline.AddedOrChangedMethods), debugInformationProvider: baseline.DebugInformationProvider, localSignatureProvider: baseline.LocalSignatureProvider); } private IReadOnlyDictionary<K, V> MapDefinitions<K, V>(IReadOnlyDictionary<K, V> items) where K : class, Cci.IDefinition { var result = new Dictionary<K, V>(Cci.SymbolEquivalentEqualityComparer.Instance); foreach (var pair in items) { var key = (K?)MapDefinition(pair.Key); // Result may be null if the definition was deleted, or if the definition // was synthesized (e.g.: an iterator type) and the method that generated // the synthesized definition was unchanged and not recompiled. if (key != null) { result.Add(key, pair.Value); } } return result; } private IReadOnlyDictionary<int, AddedOrChangedMethodInfo> MapAddedOrChangedMethods(IReadOnlyDictionary<int, AddedOrChangedMethodInfo> addedOrChangedMethods) { var result = new Dictionary<int, AddedOrChangedMethodInfo>(); foreach (var pair in addedOrChangedMethods) { result.Add(pair.Key, pair.Value.MapTypes(this)); } return result; } private IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> MapAnonymousTypes(IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap) { var result = new Dictionary<AnonymousTypeKey, AnonymousTypeValue>(); foreach (var pair in anonymousTypeMap) { var key = pair.Key; var value = pair.Value; var type = (Cci.ITypeDefinition?)MapDefinition(value.Type); RoslynDebug.Assert(type != null); result.Add(key, new AnonymousTypeValue(value.Name, value.UniqueIndex, type)); } return result; } /// <summary> /// Merges synthesized members generated during lowering of the current compilation with aggregate synthesized members /// from all previous source generations (gen >= 1). /// </summary> /// <remarks> /// Suppose {S -> {A, B, D}, T -> {E, F}} are all synthesized members in previous generations, /// and {S' -> {A', B', C}, U -> {G, H}} members are generated in the current compilation. /// /// Where X matches X' via this matcher, i.e. X' is from the new compilation and /// represents the same metadata entity as X in the previous compilation. /// /// Then the resulting collection shall have the following entries: /// {S' -> {A', B', C, D}, U -> {G, H}, T -> {E, F}} /// </remarks> internal ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> MapSynthesizedMembers( ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> previousMembers, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> newMembers) { // Note: we can't just return previous members if there are no new members, since we still need to map the symbols to the new compilation. if (previousMembers.Count == 0) { return newMembers; } var synthesizedMembersBuilder = ImmutableDictionary.CreateBuilder<ISymbolInternal, ImmutableArray<ISymbolInternal>>(); synthesizedMembersBuilder.AddRange(newMembers); foreach (var pair in previousMembers) { var previousContainer = pair.Key; var members = pair.Value; var mappedContainer = MapDefinitionOrNamespace(previousContainer); if (mappedContainer == null) { // No update to any member of the container type. synthesizedMembersBuilder.Add(previousContainer, members); continue; } if (!newMembers.TryGetValue(mappedContainer, out var newSynthesizedMembers)) { // The container has been updated but the update didn't produce any synthesized members. synthesizedMembersBuilder.Add(mappedContainer, members); continue; } // The container has been updated and synthesized members produced. // They might be new or replacing existing ones. Merge existing with new. var memberBuilder = ArrayBuilder<ISymbolInternal>.GetInstance(); memberBuilder.AddRange(newSynthesizedMembers); foreach (var member in members) { var mappedMember = MapDefinitionOrNamespace(member); if (mappedMember != null) { // If the matcher found a member in the current compilation corresponding to previous memberDef, // then the member has to be synthesized and produced as a result of a method update // and thus already contained in newSynthesizedMembers. Debug.Assert(newSynthesizedMembers.Contains(mappedMember)); } else { memberBuilder.Add(member); } } synthesizedMembersBuilder[mappedContainer] = memberBuilder.ToImmutableAndFree(); } return synthesizedMembersBuilder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal abstract class SymbolMatcher { public abstract Cci.ITypeReference? MapReference(Cci.ITypeReference reference); public abstract Cci.IDefinition? MapDefinition(Cci.IDefinition definition); public abstract Cci.INamespace? MapNamespace(Cci.INamespace @namespace); public ISymbolInternal? MapDefinitionOrNamespace(ISymbolInternal symbol) { var adapter = symbol.GetCciAdapter(); return (adapter is Cci.IDefinition definition) ? MapDefinition(definition)?.GetInternalSymbol() : MapNamespace((Cci.INamespace)adapter)?.GetInternalSymbol(); } public EmitBaseline MapBaselineToCompilation( EmitBaseline baseline, Compilation targetCompilation, CommonPEModuleBuilder targetModuleBuilder, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> mappedSynthesizedMembers) { // Map all definitions to this compilation. var typesAdded = MapDefinitions(baseline.TypesAdded); var eventsAdded = MapDefinitions(baseline.EventsAdded); var fieldsAdded = MapDefinitions(baseline.FieldsAdded); var methodsAdded = MapDefinitions(baseline.MethodsAdded); var propertiesAdded = MapDefinitions(baseline.PropertiesAdded); var generationOrdinals = MapDefinitions(baseline.GenerationOrdinals); return baseline.With( targetCompilation, targetModuleBuilder, baseline.Ordinal, baseline.EncId, generationOrdinals, typesAdded, eventsAdded, fieldsAdded, methodsAdded, firstParamRowMap: baseline.FirstParamRowMap, propertiesAdded, eventMapAdded: baseline.EventMapAdded, propertyMapAdded: baseline.PropertyMapAdded, methodImplsAdded: baseline.MethodImplsAdded, customAttributesAdded: baseline.CustomAttributesAdded, tableEntriesAdded: baseline.TableEntriesAdded, blobStreamLengthAdded: baseline.BlobStreamLengthAdded, stringStreamLengthAdded: baseline.StringStreamLengthAdded, userStringStreamLengthAdded: baseline.UserStringStreamLengthAdded, guidStreamLengthAdded: baseline.GuidStreamLengthAdded, anonymousTypeMap: MapAnonymousTypes(baseline.AnonymousTypeMap), synthesizedMembers: mappedSynthesizedMembers, addedOrChangedMethods: MapAddedOrChangedMethods(baseline.AddedOrChangedMethods), debugInformationProvider: baseline.DebugInformationProvider, localSignatureProvider: baseline.LocalSignatureProvider); } private IReadOnlyDictionary<K, V> MapDefinitions<K, V>(IReadOnlyDictionary<K, V> items) where K : class, Cci.IDefinition { var result = new Dictionary<K, V>(Cci.SymbolEquivalentEqualityComparer.Instance); foreach (var pair in items) { var key = (K?)MapDefinition(pair.Key); // Result may be null if the definition was deleted, or if the definition // was synthesized (e.g.: an iterator type) and the method that generated // the synthesized definition was unchanged and not recompiled. if (key != null) { result.Add(key, pair.Value); } } return result; } private IReadOnlyDictionary<int, AddedOrChangedMethodInfo> MapAddedOrChangedMethods(IReadOnlyDictionary<int, AddedOrChangedMethodInfo> addedOrChangedMethods) { var result = new Dictionary<int, AddedOrChangedMethodInfo>(); foreach (var pair in addedOrChangedMethods) { result.Add(pair.Key, pair.Value.MapTypes(this)); } return result; } private IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> MapAnonymousTypes(IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap) { var result = new Dictionary<AnonymousTypeKey, AnonymousTypeValue>(); foreach (var pair in anonymousTypeMap) { var key = pair.Key; var value = pair.Value; var type = (Cci.ITypeDefinition?)MapDefinition(value.Type); RoslynDebug.Assert(type != null); result.Add(key, new AnonymousTypeValue(value.Name, value.UniqueIndex, type)); } return result; } /// <summary> /// Merges synthesized members generated during lowering of the current compilation with aggregate synthesized members /// from all previous source generations (gen >= 1). /// </summary> /// <remarks> /// Suppose {S -> {A, B, D}, T -> {E, F}} are all synthesized members in previous generations, /// and {S' -> {A', B', C}, U -> {G, H}} members are generated in the current compilation. /// /// Where X matches X' via this matcher, i.e. X' is from the new compilation and /// represents the same metadata entity as X in the previous compilation. /// /// Then the resulting collection shall have the following entries: /// {S' -> {A', B', C, D}, U -> {G, H}, T -> {E, F}} /// </remarks> internal ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> MapSynthesizedMembers( ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> previousMembers, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> newMembers) { // Note: we can't just return previous members if there are no new members, since we still need to map the symbols to the new compilation. if (previousMembers.Count == 0) { return newMembers; } var synthesizedMembersBuilder = ImmutableDictionary.CreateBuilder<ISymbolInternal, ImmutableArray<ISymbolInternal>>(); synthesizedMembersBuilder.AddRange(newMembers); foreach (var pair in previousMembers) { var previousContainer = pair.Key; var members = pair.Value; var mappedContainer = MapDefinitionOrNamespace(previousContainer); if (mappedContainer == null) { // No update to any member of the container type. synthesizedMembersBuilder.Add(previousContainer, members); continue; } if (!newMembers.TryGetValue(mappedContainer, out var newSynthesizedMembers)) { // The container has been updated but the update didn't produce any synthesized members. synthesizedMembersBuilder.Add(mappedContainer, members); continue; } // The container has been updated and synthesized members produced. // They might be new or replacing existing ones. Merge existing with new. var memberBuilder = ArrayBuilder<ISymbolInternal>.GetInstance(); memberBuilder.AddRange(newSynthesizedMembers); foreach (var member in members) { var mappedMember = MapDefinitionOrNamespace(member); if (mappedMember != null) { // If the matcher found a member in the current compilation corresponding to previous memberDef, // then the member has to be synthesized and produced as a result of a method update // and thus already contained in newSynthesizedMembers. Debug.Assert(newSynthesizedMembers.Contains(mappedMember)); } else { memberBuilder.Add(member); } } synthesizedMembersBuilder[mappedContainer] = memberBuilder.ToImmutableAndFree(); } return synthesizedMembersBuilder.ToImmutable(); } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/VisualBasic/Portable/BoundTree/Statement.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundNode Implements IBoundNodeWithIOperationChildren Public ReadOnly Property IBoundNodeWithIOperationChildren_Children As ImmutableArray(Of BoundNode) Implements IBoundNodeWithIOperationChildren.Children Get Return Me.Children End Get End Property ''' <summary> ''' Override this property to return the child nodes if the IOperation API corresponding to this bound node is not yet designed or implemented. ''' </summary> ''' <remarks> ''' Note that any of the child bound nodes may be null. ''' </remarks> Protected Overridable ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return ImmutableArray(Of BoundNode).Empty End Get End Property End Class Partial Friend Class BoundCaseBlock Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return ImmutableArray.Create(Of BoundNode)(Me.CaseStatement, Me.Body) End Get End Property End Class Partial Friend Class BoundCaseStatement Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return StaticCast(Of BoundNode).From(Me.CaseClauses).Add(Me.ConditionOpt) End Get End Property End Class Partial Friend Class BoundBadStatement Implements IBoundInvalidNode Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return Me.ChildBoundNodes End Get End Property Private ReadOnly Property IBoundInvalidNode_InvalidNodeChildren As ImmutableArray(Of BoundNode) Implements IBoundInvalidNode.InvalidNodeChildren Get Return ChildBoundNodes End Get End Property End Class Partial Friend Class BoundEraseStatement Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return StaticCast(Of BoundNode).From(Me.Clauses) End Get End Property End Class Partial Friend Class BoundRaiseEventStatement Implements IBoundInvalidNode Private ReadOnly Property IBoundInvalidNode_InvalidNodeChildren As ImmutableArray(Of BoundNode) Implements IBoundInvalidNode.InvalidNodeChildren Get Return ImmutableArray.Create(Of BoundNode)(Me.EventInvocation) End Get End Property End Class Partial Friend Class BoundResumeStatement Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return ImmutableArray.Create(Of BoundNode)(Me.LabelExpressionOpt) End Get End Property End Class Partial Friend Class BoundOnErrorStatement Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return ImmutableArray.Create(Of BoundNode)(Me.LabelExpressionOpt) End Get End Property End Class Partial Friend Class BoundUnstructuredExceptionHandlingStatement Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return ImmutableArray.Create(Of BoundNode)(Me.Body) End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundNode Implements IBoundNodeWithIOperationChildren Public ReadOnly Property IBoundNodeWithIOperationChildren_Children As ImmutableArray(Of BoundNode) Implements IBoundNodeWithIOperationChildren.Children Get Return Me.Children End Get End Property ''' <summary> ''' Override this property to return the child nodes if the IOperation API corresponding to this bound node is not yet designed or implemented. ''' </summary> ''' <remarks> ''' Note that any of the child bound nodes may be null. ''' </remarks> Protected Overridable ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return ImmutableArray(Of BoundNode).Empty End Get End Property End Class Partial Friend Class BoundCaseBlock Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return ImmutableArray.Create(Of BoundNode)(Me.CaseStatement, Me.Body) End Get End Property End Class Partial Friend Class BoundCaseStatement Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return StaticCast(Of BoundNode).From(Me.CaseClauses).Add(Me.ConditionOpt) End Get End Property End Class Partial Friend Class BoundBadStatement Implements IBoundInvalidNode Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return Me.ChildBoundNodes End Get End Property Private ReadOnly Property IBoundInvalidNode_InvalidNodeChildren As ImmutableArray(Of BoundNode) Implements IBoundInvalidNode.InvalidNodeChildren Get Return ChildBoundNodes End Get End Property End Class Partial Friend Class BoundEraseStatement Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return StaticCast(Of BoundNode).From(Me.Clauses) End Get End Property End Class Partial Friend Class BoundRaiseEventStatement Implements IBoundInvalidNode Private ReadOnly Property IBoundInvalidNode_InvalidNodeChildren As ImmutableArray(Of BoundNode) Implements IBoundInvalidNode.InvalidNodeChildren Get Return ImmutableArray.Create(Of BoundNode)(Me.EventInvocation) End Get End Property End Class Partial Friend Class BoundResumeStatement Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return ImmutableArray.Create(Of BoundNode)(Me.LabelExpressionOpt) End Get End Property End Class Partial Friend Class BoundOnErrorStatement Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return ImmutableArray.Create(Of BoundNode)(Me.LabelExpressionOpt) End Get End Property End Class Partial Friend Class BoundUnstructuredExceptionHandlingStatement Protected Overrides ReadOnly Property Children As ImmutableArray(Of BoundNode) Get Return ImmutableArray.Create(Of BoundNode)(Me.Body) End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/VisualStudio/Core/Def/Implementation/Venus/ContainedLanguageCodeSupport.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { internal static class ContainedLanguageCodeSupport { public static bool IsValidId(Document document, string identifier) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); return syntaxFacts.IsValidIdentifier(identifier); } public static bool TryGetBaseClassName(Document document, string className, CancellationToken cancellationToken, out string baseClassName) { baseClassName = null; var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); if (type == null || type.BaseType == null) { return false; } baseClassName = type.BaseType.ToDisplayString(); return true; } public static string CreateUniqueEventName( Document document, string className, string objectName, string nameOfEvent, CancellationToken cancellationToken) { var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); var name = objectName + "_" + nameOfEvent; var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var tree = document.GetSyntaxTreeSynchronously(cancellationToken); var typeNode = type.DeclaringSyntaxReferences.Where(r => r.SyntaxTree == tree).Select(r => r.GetSyntax(cancellationToken)).First(); var codeModel = document.GetRequiredLanguageService<ICodeModelNavigationPointService>(); var options = document.GetOptionsAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var point = codeModel.GetStartPoint(typeNode, options, EnvDTE.vsCMPart.vsCMPartBody); var reservedNames = semanticModel.LookupSymbols(point.Value.Position, type).Select(m => m.Name); return NameGenerator.EnsureUniqueness(name, reservedNames, document.GetLanguageService<ISyntaxFactsService>().IsCaseSensitive); } /// <summary> /// Determine what methods of <paramref name=" className"/> could possibly be used as event /// handlers. /// </summary> /// <param name="document">The document containing <paramref name="className"/>.</param> /// <param name="className">The name of the type whose methods should be considered.</param> /// <param name="objectTypeName">The fully qualified name of the type containing a member /// that is an event. (E.g. "System.Web.Forms.Button")</param> /// <param name="nameOfEvent">The name of the member in <paramref name="objectTypeName"/> /// that is the event (E.g. "Clicked")</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The display name of the method, and a unique to for the method.</returns> public static IEnumerable<Tuple<string, string>> GetCompatibleEventHandlers( Document document, string className, string objectTypeName, string nameOfEvent, CancellationToken cancellationToken) { var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var type = compilation.GetTypeByMetadataName(className); if (type == null) { throw new InvalidOperationException(); } var eventMember = GetEventSymbol(document, objectTypeName, nameOfEvent, type, cancellationToken); if (eventMember == null) { throw new InvalidOperationException(); } var eventType = ((IEventSymbol)eventMember).Type; if (eventType.Kind != SymbolKind.NamedType) { throw new InvalidOperationException(ServicesVSResources.Event_type_is_invalid); } var methods = type.GetMembers().OfType<IMethodSymbol>().Where(m => m.CompatibleSignatureToDelegate((INamedTypeSymbol)eventType)); return methods.Select(m => Tuple.Create(m.Name, ConstructMemberId(m))); } public static string GetEventHandlerMemberId(Document document, string className, string objectTypeName, string nameOfEvent, string eventHandlerName, CancellationToken cancellationToken) { var nameAndId = GetCompatibleEventHandlers(document, className, objectTypeName, nameOfEvent, cancellationToken).SingleOrDefault(pair => pair.Item1 == eventHandlerName); return nameAndId == null ? null : nameAndId.Item2; } /// <summary> /// Ensure that an event handler exists for a given event. /// </summary> /// <param name="thisDocument">The document corresponding to this operation.</param> /// <param name="targetDocument">The document to generate the event handler in if it doesn't /// exist.</param> /// <param name="className">The name of the type to generate the event handler in.</param> /// <param name="objectName">The name of the event member (if <paramref /// name="useHandlesClause"/> is true)</param> /// <param name="objectTypeName">The name of the type containing the event.</param> /// <param name="nameOfEvent">The name of the event member in <paramref /// name="objectTypeName"/></param> /// <param name="eventHandlerName">The name of the method to be hooked up to the /// event.</param> /// <param name="itemidInsertionPoint">The VS itemid of the file to generate the event /// handler in.</param> /// <param name="useHandlesClause">If true, a vb "Handles" clause will be generated for the /// handler.</param> /// <param name="additionalFormattingRule">An additional formatting rule that can be used to /// format the newly inserted method</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Either the unique id of the method if it already exists, or the unique id of /// the to be generated method, the text of the to be generated method, and the position in /// <paramref name="itemidInsertionPoint"/> where the text should be inserted.</returns> #pragma warning disable IDE0060 // Remove unused parameter - API used by partner (Venus), avoid build break. public static Tuple<string, string, VsTextSpan> EnsureEventHandler( Document thisDocument, Document targetDocument, string className, string objectName, string objectTypeName, string nameOfEvent, string eventHandlerName, uint itemidInsertionPoint, bool useHandlesClause, AbstractFormattingRule additionalFormattingRule, CancellationToken cancellationToken) #pragma warning restore IDE0060 // Remove unused parameter { var thisCompilation = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var type = thisCompilation.GetTypeByMetadataName(className); var existingEventHandlers = GetCompatibleEventHandlers(targetDocument, className, objectTypeName, nameOfEvent, cancellationToken); var existingHandler = existingEventHandlers.SingleOrDefault(e => e.Item1 == eventHandlerName); if (existingHandler != null) { return Tuple.Create(existingHandler.Item2, (string)null, default(VsTextSpan)); } // Okay, it doesn't exist yet. Let's create it. var codeGenerationService = targetDocument.GetLanguageService<ICodeGenerationService>(); var syntaxFactory = targetDocument.GetLanguageService<SyntaxGenerator>(); var eventMember = GetEventSymbol(thisDocument, objectTypeName, nameOfEvent, type, cancellationToken); if (eventMember == null) { throw new InvalidOperationException(); } var eventType = ((IEventSymbol)eventMember).Type; if (eventType.Kind != SymbolKind.NamedType || ((INamedTypeSymbol)eventType).DelegateInvokeMethod == null) { throw new InvalidOperationException(ServicesVSResources.Event_type_is_invalid); } var handlesExpressions = useHandlesClause ? ImmutableArray.Create(syntaxFactory.MemberAccessExpression( objectName != null ? syntaxFactory.IdentifierName(objectName) : syntaxFactory.ThisExpression(), syntaxFactory.IdentifierName(nameOfEvent))) : default; var invokeMethod = ((INamedTypeSymbol)eventType).DelegateInvokeMethod; var newMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.Protected, modifiers: new DeclarationModifiers(), returnType: targetDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetSpecialType(SpecialType.System_Void), refKind: RefKind.None, explicitInterfaceImplementations: default, name: eventHandlerName, typeParameters: default, parameters: invokeMethod.Parameters, statements: default, handlesExpressions: handlesExpressions); var annotation = new SyntaxAnnotation(); newMethod = annotation.AddAnnotationToSymbol(newMethod); var codeModel = targetDocument.Project.LanguageServices.GetRequiredService<ICodeModelNavigationPointService>(); var syntaxFacts = targetDocument.Project.LanguageServices.GetRequiredService<ISyntaxFactsService>(); var targetSyntaxTree = targetDocument.GetSyntaxTreeSynchronously(cancellationToken); var position = type.Locations.First(loc => loc.SourceTree == targetSyntaxTree).SourceSpan.Start; var destinationType = syntaxFacts.GetContainingTypeDeclaration(targetSyntaxTree.GetRoot(cancellationToken), position); var options = targetDocument.GetOptionsAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var insertionPoint = codeModel.GetEndPoint(destinationType, options, EnvDTE.vsCMPart.vsCMPartBody); if (insertionPoint == null) { throw new InvalidOperationException(ServicesVSResources.Can_t_find_where_to_insert_member); } var newType = codeGenerationService.AddMethod(destinationType, newMethod, new CodeGenerationOptions(autoInsertionLocation: false), cancellationToken); var newRoot = targetSyntaxTree.GetRoot(cancellationToken).ReplaceNode(destinationType, newType); newRoot = Simplifier.ReduceAsync( targetDocument.WithSyntaxRoot(newRoot), Simplifier.Annotation, null, cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetSyntaxRootSynchronously(cancellationToken); var formattingRules = additionalFormattingRule.Concat(Formatter.GetDefaultFormattingRules(targetDocument)); newRoot = Formatter.Format( newRoot, Formatter.Annotation, targetDocument.Project.Solution.Workspace, targetDocument.GetOptionsAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken), formattingRules, cancellationToken); var newMember = newRoot.GetAnnotatedNodesAndTokens(annotation).Single(); var newMemberText = newMember.ToFullString(); // In VB, the final newline is likely a statement terminator in the parent - just add // one on so that things don't get messed. if (!newMemberText.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { newMemberText += Environment.NewLine; } return Tuple.Create(ConstructMemberId(newMethod), newMemberText, insertionPoint.Value.ToVsTextSpan()); } public static bool TryGetMemberNavigationPoint( Document thisDocument, string className, string uniqueMemberID, out VsTextSpan textSpan, out Document targetDocument, CancellationToken cancellationToken) { targetDocument = null; textSpan = default; var type = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); var member = LookupMemberId(type, uniqueMemberID); if (member == null) { return false; } var codeModel = thisDocument.Project.LanguageServices.GetService<ICodeModelNavigationPointService>(); var memberNode = member.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).FirstOrDefault(); if (memberNode != null) { var memberNodeDocument = thisDocument.Project.Solution.GetDocument(memberNode.SyntaxTree); var options = memberNodeDocument.GetOptionsAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var navigationPoint = codeModel.GetStartPoint(memberNode, options, EnvDTE.vsCMPart.vsCMPartNavigate); if (navigationPoint != null) { targetDocument = memberNodeDocument; textSpan = navigationPoint.Value.ToVsTextSpan(); return true; } } return false; } /// <summary> /// Get the display names and unique ids of all the members of the given type in <paramref /// name="className"/>. /// </summary> public static IEnumerable<Tuple<string, string>> GetMembers( Document document, string className, CODEMEMBERTYPE codeMemberType, CancellationToken cancellationToken) { var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var allMembers = codeMemberType == CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS ? semanticModel.LookupSymbols(position: type.Locations[0].SourceSpan.Start, container: type, name: null) : type.GetMembers(); var members = allMembers.Where(m => IncludeMember(m, codeMemberType, compilation)); return members.Select(m => Tuple.Create(m.Name, ConstructMemberId(m))); } /// <summary> /// Try to do a symbolic rename the specified symbol. /// </summary> /// <returns>False ONLY if it can't resolve the name. Other errors result in the normal /// exception being propagated.</returns> public static bool TryRenameElement( Document document, ContainedLanguageRenameType clrt, string oldFullyQualifiedName, string newFullyQualifiedName, IEnumerable<IRefactorNotifyService> refactorNotifyServices, CancellationToken cancellationToken) { var symbol = FindSymbol(document, clrt, oldFullyQualifiedName, cancellationToken); if (symbol == null) { return false; } if (CodeAnalysis.Workspace.TryGetWorkspace(document.GetTextSynchronously(cancellationToken).Container, out var workspace)) { var newName = newFullyQualifiedName.Substring(newFullyQualifiedName.LastIndexOf('.') + 1); var optionSet = document.Project.Solution.Workspace.Options; var newSolution = Renamer.RenameSymbolAsync(document.Project.Solution, symbol, newName, optionSet, cancellationToken).WaitAndGetResult_Venus(cancellationToken); var changedDocuments = newSolution.GetChangedDocuments(document.Project.Solution); var undoTitle = string.Format(EditorFeaturesResources.Rename_0_to_1, symbol.Name, newName); using (var workspaceUndoTransaction = workspace.OpenGlobalUndoTransaction(undoTitle)) { // Notify third parties about the coming rename operation on the workspace, and let // any exceptions propagate through refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); if (!workspace.TryApplyChanges(newSolution)) { Exceptions.ThrowEFail(); } // Notify third parties about the completed rename operation on the workspace, and // let any exceptions propagate through refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); workspaceUndoTransaction.Commit(); } RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments); return true; } else { return false; } } private static bool IncludeMember(ISymbol member, CODEMEMBERTYPE memberType, Compilation compilation) { if (!member.CanBeReferencedByName) { return false; } switch (memberType) { case CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS: // NOTE: the Dev10 C# codebase just returned if (member.Kind != SymbolKind.Method) { return false; } var method = (IMethodSymbol)member; if (!method.ReturnsVoid) { return false; } if (method.Parameters.Length != 2) { return false; } if (!method.Parameters[0].Type.Equals(compilation.ObjectType)) { return false; } if (!method.Parameters[1].Type.InheritsFromOrEquals(compilation.EventArgsType())) { return false; } return true; case CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS: return member.Kind == SymbolKind.Event; case CODEMEMBERTYPE.CODEMEMBERTYPE_USER_FUNCTIONS: return member.Kind == SymbolKind.Method; default: throw new ArgumentException("InvalidValue", nameof(memberType)); } } private static ISymbol FindSymbol( Document document, ContainedLanguageRenameType renameType, string fullyQualifiedName, CancellationToken cancellationToken) { switch (renameType) { case ContainedLanguageRenameType.CLRT_CLASS: return document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(fullyQualifiedName); case ContainedLanguageRenameType.CLRT_CLASSMEMBER: var lastDot = fullyQualifiedName.LastIndexOf('.'); var typeName = fullyQualifiedName.Substring(0, lastDot); var memberName = fullyQualifiedName.Substring(lastDot + 1, fullyQualifiedName.Length - lastDot - 1); var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(typeName); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var membersOfName = type.GetMembers(memberName); return membersOfName.SingleOrDefault(); case ContainedLanguageRenameType.CLRT_NAMESPACE: var ns = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GlobalNamespace; var parts = fullyQualifiedName.Split('.'); for (var i = 0; i < parts.Length && ns != null; i++) { ns = ns.GetNamespaceMembers().SingleOrDefault(n => n.Name == parts[i]); } return ns; case ContainedLanguageRenameType.CLRT_OTHER: throw new NotSupportedException(ServicesVSResources.Can_t_rename_other_elements); default: throw new InvalidOperationException(ServicesVSResources.Unknown_rename_type); } } internal static string ConstructMemberId(ISymbol member) { if (member.Kind == SymbolKind.Method) { return string.Format("{0}({1})", member.Name, string.Join(",", ((IMethodSymbol)member).Parameters.Select(p => p.Type.ToDisplayString()))); } else if (member.Kind == SymbolKind.Event) { return member.Name + "(EVENT)"; } else { throw new NotSupportedException(ServicesVSResources.IDs_are_not_supported_for_this_symbol_type); } } internal static ISymbol LookupMemberId(INamedTypeSymbol type, string uniqueMemberID) { var memberName = uniqueMemberID.Substring(0, uniqueMemberID.IndexOf('(')); var members = type.GetMembers(memberName).Where(m => m.Kind == SymbolKind.Method); foreach (var m in members) { if (ConstructMemberId(m) == uniqueMemberID) { return m; } } return null; } private static ISymbol GetEventSymbol( Document document, string objectTypeName, string nameOfEvent, INamedTypeSymbol type, CancellationToken cancellationToken) { var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var objectType = compilation.GetTypeByMetadataName(objectTypeName); if (objectType == null) { throw new InvalidOperationException(); } var containingTree = document.GetSyntaxTreeSynchronously(cancellationToken); var typeLocation = type.Locations.FirstOrDefault(d => d.SourceTree == containingTree); if (typeLocation == null) { throw new InvalidOperationException(); } return semanticModel.LookupSymbols(typeLocation.SourceSpan.Start, objectType, nameOfEvent).SingleOrDefault(m => m.Kind == SymbolKind.Event); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { internal static class ContainedLanguageCodeSupport { public static bool IsValidId(Document document, string identifier) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); return syntaxFacts.IsValidIdentifier(identifier); } public static bool TryGetBaseClassName(Document document, string className, CancellationToken cancellationToken, out string baseClassName) { baseClassName = null; var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); if (type == null || type.BaseType == null) { return false; } baseClassName = type.BaseType.ToDisplayString(); return true; } public static string CreateUniqueEventName( Document document, string className, string objectName, string nameOfEvent, CancellationToken cancellationToken) { var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); var name = objectName + "_" + nameOfEvent; var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var tree = document.GetSyntaxTreeSynchronously(cancellationToken); var typeNode = type.DeclaringSyntaxReferences.Where(r => r.SyntaxTree == tree).Select(r => r.GetSyntax(cancellationToken)).First(); var codeModel = document.GetRequiredLanguageService<ICodeModelNavigationPointService>(); var options = document.GetOptionsAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var point = codeModel.GetStartPoint(typeNode, options, EnvDTE.vsCMPart.vsCMPartBody); var reservedNames = semanticModel.LookupSymbols(point.Value.Position, type).Select(m => m.Name); return NameGenerator.EnsureUniqueness(name, reservedNames, document.GetLanguageService<ISyntaxFactsService>().IsCaseSensitive); } /// <summary> /// Determine what methods of <paramref name=" className"/> could possibly be used as event /// handlers. /// </summary> /// <param name="document">The document containing <paramref name="className"/>.</param> /// <param name="className">The name of the type whose methods should be considered.</param> /// <param name="objectTypeName">The fully qualified name of the type containing a member /// that is an event. (E.g. "System.Web.Forms.Button")</param> /// <param name="nameOfEvent">The name of the member in <paramref name="objectTypeName"/> /// that is the event (E.g. "Clicked")</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The display name of the method, and a unique to for the method.</returns> public static IEnumerable<Tuple<string, string>> GetCompatibleEventHandlers( Document document, string className, string objectTypeName, string nameOfEvent, CancellationToken cancellationToken) { var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var type = compilation.GetTypeByMetadataName(className); if (type == null) { throw new InvalidOperationException(); } var eventMember = GetEventSymbol(document, objectTypeName, nameOfEvent, type, cancellationToken); if (eventMember == null) { throw new InvalidOperationException(); } var eventType = ((IEventSymbol)eventMember).Type; if (eventType.Kind != SymbolKind.NamedType) { throw new InvalidOperationException(ServicesVSResources.Event_type_is_invalid); } var methods = type.GetMembers().OfType<IMethodSymbol>().Where(m => m.CompatibleSignatureToDelegate((INamedTypeSymbol)eventType)); return methods.Select(m => Tuple.Create(m.Name, ConstructMemberId(m))); } public static string GetEventHandlerMemberId(Document document, string className, string objectTypeName, string nameOfEvent, string eventHandlerName, CancellationToken cancellationToken) { var nameAndId = GetCompatibleEventHandlers(document, className, objectTypeName, nameOfEvent, cancellationToken).SingleOrDefault(pair => pair.Item1 == eventHandlerName); return nameAndId == null ? null : nameAndId.Item2; } /// <summary> /// Ensure that an event handler exists for a given event. /// </summary> /// <param name="thisDocument">The document corresponding to this operation.</param> /// <param name="targetDocument">The document to generate the event handler in if it doesn't /// exist.</param> /// <param name="className">The name of the type to generate the event handler in.</param> /// <param name="objectName">The name of the event member (if <paramref /// name="useHandlesClause"/> is true)</param> /// <param name="objectTypeName">The name of the type containing the event.</param> /// <param name="nameOfEvent">The name of the event member in <paramref /// name="objectTypeName"/></param> /// <param name="eventHandlerName">The name of the method to be hooked up to the /// event.</param> /// <param name="itemidInsertionPoint">The VS itemid of the file to generate the event /// handler in.</param> /// <param name="useHandlesClause">If true, a vb "Handles" clause will be generated for the /// handler.</param> /// <param name="additionalFormattingRule">An additional formatting rule that can be used to /// format the newly inserted method</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Either the unique id of the method if it already exists, or the unique id of /// the to be generated method, the text of the to be generated method, and the position in /// <paramref name="itemidInsertionPoint"/> where the text should be inserted.</returns> #pragma warning disable IDE0060 // Remove unused parameter - API used by partner (Venus), avoid build break. public static Tuple<string, string, VsTextSpan> EnsureEventHandler( Document thisDocument, Document targetDocument, string className, string objectName, string objectTypeName, string nameOfEvent, string eventHandlerName, uint itemidInsertionPoint, bool useHandlesClause, AbstractFormattingRule additionalFormattingRule, CancellationToken cancellationToken) #pragma warning restore IDE0060 // Remove unused parameter { var thisCompilation = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var type = thisCompilation.GetTypeByMetadataName(className); var existingEventHandlers = GetCompatibleEventHandlers(targetDocument, className, objectTypeName, nameOfEvent, cancellationToken); var existingHandler = existingEventHandlers.SingleOrDefault(e => e.Item1 == eventHandlerName); if (existingHandler != null) { return Tuple.Create(existingHandler.Item2, (string)null, default(VsTextSpan)); } // Okay, it doesn't exist yet. Let's create it. var codeGenerationService = targetDocument.GetLanguageService<ICodeGenerationService>(); var syntaxFactory = targetDocument.GetLanguageService<SyntaxGenerator>(); var eventMember = GetEventSymbol(thisDocument, objectTypeName, nameOfEvent, type, cancellationToken); if (eventMember == null) { throw new InvalidOperationException(); } var eventType = ((IEventSymbol)eventMember).Type; if (eventType.Kind != SymbolKind.NamedType || ((INamedTypeSymbol)eventType).DelegateInvokeMethod == null) { throw new InvalidOperationException(ServicesVSResources.Event_type_is_invalid); } var handlesExpressions = useHandlesClause ? ImmutableArray.Create(syntaxFactory.MemberAccessExpression( objectName != null ? syntaxFactory.IdentifierName(objectName) : syntaxFactory.ThisExpression(), syntaxFactory.IdentifierName(nameOfEvent))) : default; var invokeMethod = ((INamedTypeSymbol)eventType).DelegateInvokeMethod; var newMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.Protected, modifiers: new DeclarationModifiers(), returnType: targetDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetSpecialType(SpecialType.System_Void), refKind: RefKind.None, explicitInterfaceImplementations: default, name: eventHandlerName, typeParameters: default, parameters: invokeMethod.Parameters, statements: default, handlesExpressions: handlesExpressions); var annotation = new SyntaxAnnotation(); newMethod = annotation.AddAnnotationToSymbol(newMethod); var codeModel = targetDocument.Project.LanguageServices.GetRequiredService<ICodeModelNavigationPointService>(); var syntaxFacts = targetDocument.Project.LanguageServices.GetRequiredService<ISyntaxFactsService>(); var targetSyntaxTree = targetDocument.GetSyntaxTreeSynchronously(cancellationToken); var position = type.Locations.First(loc => loc.SourceTree == targetSyntaxTree).SourceSpan.Start; var destinationType = syntaxFacts.GetContainingTypeDeclaration(targetSyntaxTree.GetRoot(cancellationToken), position); var options = targetDocument.GetOptionsAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var insertionPoint = codeModel.GetEndPoint(destinationType, options, EnvDTE.vsCMPart.vsCMPartBody); if (insertionPoint == null) { throw new InvalidOperationException(ServicesVSResources.Can_t_find_where_to_insert_member); } var newType = codeGenerationService.AddMethod(destinationType, newMethod, new CodeGenerationOptions(autoInsertionLocation: false), cancellationToken); var newRoot = targetSyntaxTree.GetRoot(cancellationToken).ReplaceNode(destinationType, newType); newRoot = Simplifier.ReduceAsync( targetDocument.WithSyntaxRoot(newRoot), Simplifier.Annotation, null, cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetSyntaxRootSynchronously(cancellationToken); var formattingRules = additionalFormattingRule.Concat(Formatter.GetDefaultFormattingRules(targetDocument)); newRoot = Formatter.Format( newRoot, Formatter.Annotation, targetDocument.Project.Solution.Workspace, targetDocument.GetOptionsAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken), formattingRules, cancellationToken); var newMember = newRoot.GetAnnotatedNodesAndTokens(annotation).Single(); var newMemberText = newMember.ToFullString(); // In VB, the final newline is likely a statement terminator in the parent - just add // one on so that things don't get messed. if (!newMemberText.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { newMemberText += Environment.NewLine; } return Tuple.Create(ConstructMemberId(newMethod), newMemberText, insertionPoint.Value.ToVsTextSpan()); } public static bool TryGetMemberNavigationPoint( Document thisDocument, string className, string uniqueMemberID, out VsTextSpan textSpan, out Document targetDocument, CancellationToken cancellationToken) { targetDocument = null; textSpan = default; var type = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); var member = LookupMemberId(type, uniqueMemberID); if (member == null) { return false; } var codeModel = thisDocument.Project.LanguageServices.GetService<ICodeModelNavigationPointService>(); var memberNode = member.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).FirstOrDefault(); if (memberNode != null) { var memberNodeDocument = thisDocument.Project.Solution.GetDocument(memberNode.SyntaxTree); var options = memberNodeDocument.GetOptionsAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var navigationPoint = codeModel.GetStartPoint(memberNode, options, EnvDTE.vsCMPart.vsCMPartNavigate); if (navigationPoint != null) { targetDocument = memberNodeDocument; textSpan = navigationPoint.Value.ToVsTextSpan(); return true; } } return false; } /// <summary> /// Get the display names and unique ids of all the members of the given type in <paramref /// name="className"/>. /// </summary> public static IEnumerable<Tuple<string, string>> GetMembers( Document document, string className, CODEMEMBERTYPE codeMemberType, CancellationToken cancellationToken) { var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var allMembers = codeMemberType == CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS ? semanticModel.LookupSymbols(position: type.Locations[0].SourceSpan.Start, container: type, name: null) : type.GetMembers(); var members = allMembers.Where(m => IncludeMember(m, codeMemberType, compilation)); return members.Select(m => Tuple.Create(m.Name, ConstructMemberId(m))); } /// <summary> /// Try to do a symbolic rename the specified symbol. /// </summary> /// <returns>False ONLY if it can't resolve the name. Other errors result in the normal /// exception being propagated.</returns> public static bool TryRenameElement( Document document, ContainedLanguageRenameType clrt, string oldFullyQualifiedName, string newFullyQualifiedName, IEnumerable<IRefactorNotifyService> refactorNotifyServices, CancellationToken cancellationToken) { var symbol = FindSymbol(document, clrt, oldFullyQualifiedName, cancellationToken); if (symbol == null) { return false; } if (CodeAnalysis.Workspace.TryGetWorkspace(document.GetTextSynchronously(cancellationToken).Container, out var workspace)) { var newName = newFullyQualifiedName.Substring(newFullyQualifiedName.LastIndexOf('.') + 1); var optionSet = document.Project.Solution.Workspace.Options; var newSolution = Renamer.RenameSymbolAsync(document.Project.Solution, symbol, newName, optionSet, cancellationToken).WaitAndGetResult_Venus(cancellationToken); var changedDocuments = newSolution.GetChangedDocuments(document.Project.Solution); var undoTitle = string.Format(EditorFeaturesResources.Rename_0_to_1, symbol.Name, newName); using (var workspaceUndoTransaction = workspace.OpenGlobalUndoTransaction(undoTitle)) { // Notify third parties about the coming rename operation on the workspace, and let // any exceptions propagate through refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); if (!workspace.TryApplyChanges(newSolution)) { Exceptions.ThrowEFail(); } // Notify third parties about the completed rename operation on the workspace, and // let any exceptions propagate through refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); workspaceUndoTransaction.Commit(); } RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments); return true; } else { return false; } } private static bool IncludeMember(ISymbol member, CODEMEMBERTYPE memberType, Compilation compilation) { if (!member.CanBeReferencedByName) { return false; } switch (memberType) { case CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS: // NOTE: the Dev10 C# codebase just returned if (member.Kind != SymbolKind.Method) { return false; } var method = (IMethodSymbol)member; if (!method.ReturnsVoid) { return false; } if (method.Parameters.Length != 2) { return false; } if (!method.Parameters[0].Type.Equals(compilation.ObjectType)) { return false; } if (!method.Parameters[1].Type.InheritsFromOrEquals(compilation.EventArgsType())) { return false; } return true; case CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS: return member.Kind == SymbolKind.Event; case CODEMEMBERTYPE.CODEMEMBERTYPE_USER_FUNCTIONS: return member.Kind == SymbolKind.Method; default: throw new ArgumentException("InvalidValue", nameof(memberType)); } } private static ISymbol FindSymbol( Document document, ContainedLanguageRenameType renameType, string fullyQualifiedName, CancellationToken cancellationToken) { switch (renameType) { case ContainedLanguageRenameType.CLRT_CLASS: return document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(fullyQualifiedName); case ContainedLanguageRenameType.CLRT_CLASSMEMBER: var lastDot = fullyQualifiedName.LastIndexOf('.'); var typeName = fullyQualifiedName.Substring(0, lastDot); var memberName = fullyQualifiedName.Substring(lastDot + 1, fullyQualifiedName.Length - lastDot - 1); var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(typeName); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var membersOfName = type.GetMembers(memberName); return membersOfName.SingleOrDefault(); case ContainedLanguageRenameType.CLRT_NAMESPACE: var ns = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GlobalNamespace; var parts = fullyQualifiedName.Split('.'); for (var i = 0; i < parts.Length && ns != null; i++) { ns = ns.GetNamespaceMembers().SingleOrDefault(n => n.Name == parts[i]); } return ns; case ContainedLanguageRenameType.CLRT_OTHER: throw new NotSupportedException(ServicesVSResources.Can_t_rename_other_elements); default: throw new InvalidOperationException(ServicesVSResources.Unknown_rename_type); } } internal static string ConstructMemberId(ISymbol member) { if (member.Kind == SymbolKind.Method) { return string.Format("{0}({1})", member.Name, string.Join(",", ((IMethodSymbol)member).Parameters.Select(p => p.Type.ToDisplayString()))); } else if (member.Kind == SymbolKind.Event) { return member.Name + "(EVENT)"; } else { throw new NotSupportedException(ServicesVSResources.IDs_are_not_supported_for_this_symbol_type); } } internal static ISymbol LookupMemberId(INamedTypeSymbol type, string uniqueMemberID) { var memberName = uniqueMemberID.Substring(0, uniqueMemberID.IndexOf('(')); var members = type.GetMembers(memberName).Where(m => m.Kind == SymbolKind.Method); foreach (var m in members) { if (ConstructMemberId(m) == uniqueMemberID) { return m; } } return null; } private static ISymbol GetEventSymbol( Document document, string objectTypeName, string nameOfEvent, INamedTypeSymbol type, CancellationToken cancellationToken) { var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var objectType = compilation.GetTypeByMetadataName(objectTypeName); if (objectType == null) { throw new InvalidOperationException(); } var containingTree = document.GetSyntaxTreeSynchronously(cancellationToken); var typeLocation = type.Locations.FirstOrDefault(d => d.SourceTree == containingTree); if (typeLocation == null) { throw new InvalidOperationException(); } return semanticModel.LookupSymbols(typeLocation.SourceSpan.Start, objectType, nameOfEvent).SingleOrDefault(m => m.Kind == SymbolKind.Event); } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/CompilerUtilities/ImmutableHashMapExtensions.cs
// Licensed to the .NET Foundation under one or more 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 Roslyn.Collections.Immutable; namespace Roslyn.Utilities { internal static class ImmutableHashMapExtensions { /// <summary> /// Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist. /// </summary> /// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam> /// <typeparam name="TArg">The type of argument supplied to the value factory.</typeparam> /// <param name="location">The variable or field to atomically update if the specified <paramref name="key" /> is not in the dictionary.</param> /// <param name="key">The key for the value to retrieve or add.</param> /// <param name="valueProvider">The function to execute to obtain the value to insert into the dictionary if the key is not found. Returns null if the value can't be obtained.</param> /// <param name="factoryArgument">The argument to pass to the value factory.</param> /// <returns>The value obtained from the dictionary or <paramref name="valueProvider" /> if it was not present.</returns> public static TValue? GetOrAdd<TKey, TValue, TArg>(ref ImmutableHashMap<TKey, TValue> location, TKey key, Func<TKey, TArg, TValue?> valueProvider, TArg factoryArgument) where TKey : notnull where TValue : class { Contract.ThrowIfNull(valueProvider); var map = Volatile.Read(ref location); Contract.ThrowIfNull(map); if (map.TryGetValue(key, out var existingValue)) { return existingValue; } var newValue = valueProvider(key, factoryArgument); if (newValue is null) { return null; } do { var augmentedMap = map.Add(key, newValue); var replacedMap = Interlocked.CompareExchange(ref location, augmentedMap, map); if (replacedMap == map) { return newValue; } map = replacedMap; } while (!map.TryGetValue(key, out existingValue)); return existingValue; } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Collections.Immutable; namespace Roslyn.Utilities { internal static class ImmutableHashMapExtensions { /// <summary> /// Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist. /// </summary> /// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam> /// <typeparam name="TArg">The type of argument supplied to the value factory.</typeparam> /// <param name="location">The variable or field to atomically update if the specified <paramref name="key" /> is not in the dictionary.</param> /// <param name="key">The key for the value to retrieve or add.</param> /// <param name="valueProvider">The function to execute to obtain the value to insert into the dictionary if the key is not found. Returns null if the value can't be obtained.</param> /// <param name="factoryArgument">The argument to pass to the value factory.</param> /// <returns>The value obtained from the dictionary or <paramref name="valueProvider" /> if it was not present.</returns> public static TValue? GetOrAdd<TKey, TValue, TArg>(ref ImmutableHashMap<TKey, TValue> location, TKey key, Func<TKey, TArg, TValue?> valueProvider, TArg factoryArgument) where TKey : notnull where TValue : class { Contract.ThrowIfNull(valueProvider); var map = Volatile.Read(ref location); Contract.ThrowIfNull(map); if (map.TryGetValue(key, out var existingValue)) { return existingValue; } var newValue = valueProvider(key, factoryArgument); if (newValue is null) { return null; } do { var augmentedMap = map.Add(key, newValue); var replacedMap = Interlocked.CompareExchange(ref location, augmentedMap, map); if (replacedMap == map) { return newValue; } map = replacedMap; } while (!map.TryGetValue(key, out existingValue)); return existingValue; } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Workspaces/Core/Portable/Diagnostics/DiagnosticDataLocation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { [DataContract] internal sealed class DiagnosticDataLocation { [DataMember(Order = 0)] public readonly DocumentId? DocumentId; // text can be either given or calculated from original line/column [DataMember(Order = 1)] public readonly TextSpan? SourceSpan; [DataMember(Order = 2)] public readonly string? OriginalFilePath; [DataMember(Order = 3)] public readonly int OriginalStartLine; [DataMember(Order = 4)] public readonly int OriginalStartColumn; [DataMember(Order = 5)] public readonly int OriginalEndLine; [DataMember(Order = 6)] public readonly int OriginalEndColumn; /// <summary> /// Null if path is not mapped and <see cref="OriginalFilePath"/> contains the actual path. /// Note that the value might be a relative path. In that case <see cref="OriginalFilePath"/> should be used /// as a base path for path resolution. /// </summary> [DataMember(Order = 7)] public readonly string? MappedFilePath; [DataMember(Order = 8)] public readonly int MappedStartLine; [DataMember(Order = 9)] public readonly int MappedStartColumn; [DataMember(Order = 10)] public readonly int MappedEndLine; [DataMember(Order = 11)] public readonly int MappedEndColumn; public DiagnosticDataLocation( DocumentId? documentId = null, TextSpan? sourceSpan = null, string? originalFilePath = null, int originalStartLine = 0, int originalStartColumn = 0, int originalEndLine = 0, int originalEndColumn = 0, string? mappedFilePath = null, int mappedStartLine = 0, int mappedStartColumn = 0, int mappedEndLine = 0, int mappedEndColumn = 0) { // If the original source location path is not available then mapped must be as well. Contract.ThrowIfFalse(originalFilePath != null || mappedFilePath == null); DocumentId = documentId; SourceSpan = sourceSpan; MappedFilePath = mappedFilePath; MappedStartLine = mappedStartLine; MappedStartColumn = mappedStartColumn; MappedEndLine = mappedEndLine; MappedEndColumn = mappedEndColumn; OriginalFilePath = originalFilePath; OriginalStartLine = originalStartLine; OriginalStartColumn = originalStartColumn; OriginalEndLine = originalEndLine; OriginalEndColumn = originalEndColumn; } public bool IsMapped => MappedFilePath != null; internal DiagnosticDataLocation WithCalculatedSpan(TextSpan newSourceSpan) { Contract.ThrowIfTrue(SourceSpan.HasValue); return new DiagnosticDataLocation(DocumentId, newSourceSpan, OriginalFilePath, OriginalStartLine, OriginalStartColumn, OriginalEndLine, OriginalEndColumn, MappedFilePath, MappedStartLine, MappedStartColumn, MappedEndLine, MappedEndColumn); } internal FileLinePositionSpan GetFileLinePositionSpan() { var filePath = GetFilePath(); if (filePath == null) { return default; } return IsMapped ? new(filePath, new(MappedStartLine, MappedStartColumn), new(MappedEndLine, MappedEndColumn)) : new(filePath, new(OriginalStartLine, OriginalStartColumn), new(OriginalEndLine, OriginalEndColumn)); } internal string? GetFilePath() => GetFilePath(OriginalFilePath, MappedFilePath); internal static string? GetFilePath(string? original, string? mapped) { if (RoslynString.IsNullOrEmpty(mapped)) { return original; } var combined = PathUtilities.CombinePaths(PathUtilities.GetDirectoryName(original), mapped); try { return Path.GetFullPath(combined); } catch { return combined; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { [DataContract] internal sealed class DiagnosticDataLocation { [DataMember(Order = 0)] public readonly DocumentId? DocumentId; // text can be either given or calculated from original line/column [DataMember(Order = 1)] public readonly TextSpan? SourceSpan; [DataMember(Order = 2)] public readonly string? OriginalFilePath; [DataMember(Order = 3)] public readonly int OriginalStartLine; [DataMember(Order = 4)] public readonly int OriginalStartColumn; [DataMember(Order = 5)] public readonly int OriginalEndLine; [DataMember(Order = 6)] public readonly int OriginalEndColumn; /// <summary> /// Null if path is not mapped and <see cref="OriginalFilePath"/> contains the actual path. /// Note that the value might be a relative path. In that case <see cref="OriginalFilePath"/> should be used /// as a base path for path resolution. /// </summary> [DataMember(Order = 7)] public readonly string? MappedFilePath; [DataMember(Order = 8)] public readonly int MappedStartLine; [DataMember(Order = 9)] public readonly int MappedStartColumn; [DataMember(Order = 10)] public readonly int MappedEndLine; [DataMember(Order = 11)] public readonly int MappedEndColumn; public DiagnosticDataLocation( DocumentId? documentId = null, TextSpan? sourceSpan = null, string? originalFilePath = null, int originalStartLine = 0, int originalStartColumn = 0, int originalEndLine = 0, int originalEndColumn = 0, string? mappedFilePath = null, int mappedStartLine = 0, int mappedStartColumn = 0, int mappedEndLine = 0, int mappedEndColumn = 0) { // If the original source location path is not available then mapped must be as well. Contract.ThrowIfFalse(originalFilePath != null || mappedFilePath == null); DocumentId = documentId; SourceSpan = sourceSpan; MappedFilePath = mappedFilePath; MappedStartLine = mappedStartLine; MappedStartColumn = mappedStartColumn; MappedEndLine = mappedEndLine; MappedEndColumn = mappedEndColumn; OriginalFilePath = originalFilePath; OriginalStartLine = originalStartLine; OriginalStartColumn = originalStartColumn; OriginalEndLine = originalEndLine; OriginalEndColumn = originalEndColumn; } public bool IsMapped => MappedFilePath != null; internal DiagnosticDataLocation WithCalculatedSpan(TextSpan newSourceSpan) { Contract.ThrowIfTrue(SourceSpan.HasValue); return new DiagnosticDataLocation(DocumentId, newSourceSpan, OriginalFilePath, OriginalStartLine, OriginalStartColumn, OriginalEndLine, OriginalEndColumn, MappedFilePath, MappedStartLine, MappedStartColumn, MappedEndLine, MappedEndColumn); } internal FileLinePositionSpan GetFileLinePositionSpan() { var filePath = GetFilePath(); if (filePath == null) { return default; } return IsMapped ? new(filePath, new(MappedStartLine, MappedStartColumn), new(MappedEndLine, MappedEndColumn)) : new(filePath, new(OriginalStartLine, OriginalStartColumn), new(OriginalEndLine, OriginalEndColumn)); } internal string? GetFilePath() => GetFilePath(OriginalFilePath, MappedFilePath); internal static string? GetFilePath(string? original, string? mapped) { if (RoslynString.IsNullOrEmpty(mapped)) { return original; } var combined = PathUtilities.CombinePaths(PathUtilities.GetDirectoryName(original), mapped); try { return Path.GetFullPath(combined); } catch { return combined; } } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceEventSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Class SourceEventSymbol Inherits EventSymbol Implements IAttributeTargetSymbol Private ReadOnly _containingType As SourceMemberContainerTypeSymbol Private ReadOnly _name As String Private ReadOnly _syntaxRef As SyntaxReference Private ReadOnly _location As Location Private ReadOnly _memberFlags As SourceMemberFlags Private ReadOnly _addMethod As MethodSymbol Private ReadOnly _removeMethod As MethodSymbol Private ReadOnly _raiseMethod As MethodSymbol Private ReadOnly _backingField As FieldSymbol ' Misc flags defining the state of this symbol (StateFlags) Private _lazyState As Integer <Flags> Private Enum StateFlags As Integer IsTypeInferred = &H1 ' Bit value valid once m_lazyType is assigned. IsDelegateFromImplements = &H2 ' Bit value valid once m_lazyType is assigned. ReportedExplicitImplementationDiagnostics = &H4 SymbolDeclaredEvent = &H8 ' Bit value for generating SymbolDeclaredEvent End Enum Private _lazyType As TypeSymbol Private _lazyImplementedEvents As ImmutableArray(Of EventSymbol) Private _lazyDelegateParameters As ImmutableArray(Of ParameterSymbol) Private _lazyDocComment As String Private _lazyExpandedDocComment As String ' Attributes on event. Set once after construction. IsNull means not set. Private _lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) ''' <summary> ''' Indicates whether event created a new delegate type. ''' In such case the Type must be added to the members of the containing type ''' </summary> Friend ReadOnly Property IsTypeInferred As Boolean Get Dim unused = Type ' Ensure lazy state is computed. Return (_lazyState And StateFlags.IsTypeInferred) <> 0 End Get End Property Friend Sub New(containingType As SourceMemberContainerTypeSymbol, binder As Binder, syntax As EventStatementSyntax, blockSyntaxOpt As EventBlockSyntax, diagnostics As DiagnosticBag) Debug.Assert(containingType IsNot Nothing) Debug.Assert(syntax IsNot Nothing) _containingType = containingType ' Decode the flags. ' This will validate modifiers against container (i.e. Protected is invalid in a structure...) Dim modifiers = DecodeModifiers(syntax.Modifiers, containingType, binder, diagnostics) _memberFlags = modifiers.AllFlags Dim identifier = syntax.Identifier _name = identifier.ValueText ' Events cannot have type characters If identifier.GetTypeCharacter() <> TypeCharacter.None Then Binder.ReportDiagnostic(diagnostics, identifier, ERRID.ERR_TypecharNotallowed) End If Dim location = identifier.GetLocation() _location = location _syntaxRef = binder.GetSyntaxReference(syntax) binder = New LocationSpecificBinder(BindingLocation.EventSignature, Me, binder) If blockSyntaxOpt IsNot Nothing Then For Each accessorSyntax In blockSyntaxOpt.Accessors Dim accessor As CustomEventAccessorSymbol = BindEventAccessor(accessorSyntax, binder) Select Case (accessor.MethodKind) Case MethodKind.EventAdd If _addMethod Is Nothing Then _addMethod = accessor Else diagnostics.Add(ERRID.ERR_DuplicateAddHandlerDef, accessor.Locations(0)) End If Case MethodKind.EventRemove If _removeMethod Is Nothing Then _removeMethod = accessor Else diagnostics.Add(ERRID.ERR_DuplicateRemoveHandlerDef, accessor.Locations(0)) End If Case MethodKind.EventRaise If _raiseMethod Is Nothing Then _raiseMethod = accessor Else diagnostics.Add(ERRID.ERR_DuplicateRaiseEventDef, accessor.Locations(0)) End If Case Else Throw ExceptionUtilities.UnexpectedValue(accessor.MethodKind) End Select Next If _addMethod Is Nothing Then diagnostics.Add(ERRID.ERR_MissingAddHandlerDef1, location, Me) End If If _removeMethod Is Nothing Then diagnostics.Add(ERRID.ERR_MissingRemoveHandlerDef1, location, Me) End If If _raiseMethod Is Nothing Then diagnostics.Add(ERRID.ERR_MissingRaiseEventDef1, location, Me) End If Else ' Synthesize accessors _addMethod = New SynthesizedAddAccessorSymbol(containingType, Me) _removeMethod = New SynthesizedRemoveAccessorSymbol(containingType, Me) ' if this is a concrete class, add a backing field too If Not containingType.IsInterfaceType Then _backingField = New SynthesizedEventBackingFieldSymbol(Me, Me.Name & StringConstants.EventVariableSuffix, Me.IsShared) End If End If End Sub Private Function ComputeType(diagnostics As BindingDiagnosticBag, <Out()> ByRef isTypeInferred As Boolean, <Out()> ByRef isDelegateFromImplements As Boolean) As TypeSymbol Dim binder = CreateBinderForTypeDeclaration() Dim syntax = DirectCast(_syntaxRef.GetSyntax(), EventStatementSyntax) isTypeInferred = False isDelegateFromImplements = False Dim type As TypeSymbol ' TODO: why AsClause is not a SimpleAsClause in events? There can't be "As New" ' WinRT events require either an as-clause or an implements-clause. Dim requiresDelegateType As Boolean = syntax.ImplementsClause Is Nothing AndAlso Me.IsWindowsRuntimeEvent ' if there is an As clause we use its type as event's type If syntax.AsClause IsNot Nothing Then type = binder.DecodeIdentifierType(syntax.Identifier, syntax.AsClause, Nothing, diagnostics) If Not syntax.AsClause.AsKeyword.IsMissing Then If Not type.IsDelegateType Then Binder.ReportDiagnostic(diagnostics, syntax.AsClause.Type, ERRID.ERR_EventTypeNotDelegate) Else Dim invoke = DirectCast(type, NamedTypeSymbol).DelegateInvokeMethod If invoke Is Nothing Then Binder.ReportDiagnostic(diagnostics, syntax.AsClause.Type, ERRID.ERR_UnsupportedType1, type.Name) Else If Not invoke.IsSub Then Binder.ReportDiagnostic(diagnostics, syntax.AsClause.Type, ERRID.ERR_EventDelegatesCantBeFunctions) End If End If End If ElseIf requiresDelegateType Then ' This will always be a cascading diagnostic but, arguably, it does provide additional context ' and dev11 reports it. Binder.ReportDiagnostic(diagnostics, syntax.Identifier, ERRID.ERR_WinRTEventWithoutDelegate) End If Else If requiresDelegateType Then Binder.ReportDiagnostic(diagnostics, syntax.Identifier, ERRID.ERR_WinRTEventWithoutDelegate) End If Dim implementedEvents = ExplicitInterfaceImplementations ' when we have a match with interface event we should take the type from ' the implemented event. If Not implementedEvents.IsEmpty Then ' use the type of the first implemented event Dim implementedEventType = implementedEvents(0).Type ' all other implemented events must be of the same type as the first For i As Integer = 1 To implementedEvents.Length - 1 Dim implemented = implementedEvents(i) If Not implemented.Type.IsSameType(implementedEventType, TypeCompareKind.IgnoreTupleNames) Then Dim errLocation = GetImplementingLocation(implemented) Binder.ReportDiagnostic(diagnostics, errLocation, ERRID.ERR_MultipleEventImplMismatch3, Me, implemented, implemented.ContainingType) End If Next type = implementedEventType isDelegateFromImplements = True Else ' get event's type from the containing type Dim types = _containingType.GetTypeMembers(Me.Name & StringConstants.EventDelegateSuffix) Debug.Assert(Not types.IsDefault) type = Nothing For Each candidate In types If candidate.AssociatedSymbol Is Me Then type = candidate Exit For End If Next If type Is Nothing Then ' if we still do not know the type, get a temporary one (it is not a member of the containing class) type = New SynthesizedEventDelegateSymbol(Me._syntaxRef, _containingType) End If isTypeInferred = True End If End If If Not type.IsErrorType() Then AccessCheck.VerifyAccessExposureForMemberType(Me, syntax.Identifier, type, diagnostics, isDelegateFromImplements) End If Return type End Function Private Function ComputeImplementedEvents(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of EventSymbol) Dim syntax = DirectCast(_syntaxRef.GetSyntax(), EventStatementSyntax) Dim implementsClause = syntax.ImplementsClause If implementsClause IsNot Nothing Then Dim binder = CreateBinderForTypeDeclaration() If _containingType.IsInterfaceType Then Dim implementsKeyword = implementsClause.ImplementsKeyword ' // Interface events can't claim to implement anything Binder.ReportDiagnostic(diagnostics, implementsKeyword, ERRID.ERR_InterfaceEventCantUse1, implementsKeyword.ValueText) ElseIf IsShared AndAlso Not _containingType.IsModuleType Then ' // Implementing with shared events is illegal. Binder.ReportDiagnostic(diagnostics, syntax.Modifiers.First(SyntaxKind.SharedKeyword), ERRID.ERR_SharedOnProcThatImpl) Else ' if event is inferred, only signature needs to match ' otherwise event types must match exactly Return ProcessImplementsClause(Of EventSymbol)(implementsClause, Me, _containingType, binder, diagnostics) End If End If Return ImmutableArray(Of EventSymbol).Empty End Function ''' <summary> ''' Unless the type is inferred, check that all ''' implemented events have the same type. ''' </summary> Private Sub CheckExplicitImplementationTypes() If (_lazyState And (StateFlags.IsTypeInferred Or StateFlags.IsDelegateFromImplements Or StateFlags.ReportedExplicitImplementationDiagnostics)) <> 0 Then Return End If Dim diagnostics As BindingDiagnosticBag = Nothing Dim type = Me.Type For Each implemented In ExplicitInterfaceImplementations If Not implemented.Type.IsSameType(type, TypeCompareKind.IgnoreTupleNames) Then If diagnostics Is Nothing Then diagnostics = BindingDiagnosticBag.GetInstance() End If Dim errLocation = GetImplementingLocation(implemented) diagnostics.Add(ERRID.ERR_EventImplMismatch5, errLocation, {Me, implemented, implemented.ContainingType, type, implemented.Type}) End If Next If diagnostics IsNot Nothing Then ContainingSourceModule.AtomicSetFlagAndStoreDiagnostics(_lazyState, StateFlags.ReportedExplicitImplementationDiagnostics, 0, diagnostics) diagnostics.Free() End If End Sub Friend Overrides ReadOnly Property DelegateParameters As ImmutableArray(Of ParameterSymbol) Get If _lazyDelegateParameters.IsDefault Then Dim syntax = DirectCast(_syntaxRef.GetSyntax(), EventStatementSyntax) If syntax.AsClause IsNot Nothing Then ' We can access use the base implementation which relies ' on the Type property since the type in "Event E As D" is explicit. _lazyDelegateParameters = MyBase.DelegateParameters Else ' Avoid using the base implementation since that relies ' on Type which is inferred, potentially from interface ' implementations which relies on DelegateParameters. Dim binder = CreateBinderForTypeDeclaration() Dim diagnostics = BindingDiagnosticBag.GetInstance() ContainingSourceModule.AtomicStoreArrayAndDiagnostics( _lazyDelegateParameters, binder.DecodeParameterListOfDelegateDeclaration(Me, syntax.ParameterList, diagnostics), diagnostics) diagnostics.Free() End If End If Return _lazyDelegateParameters End Get End Property Private Function BindEventAccessor(blockSyntax As AccessorBlockSyntax, binder As Binder) As CustomEventAccessorSymbol Dim syntax = blockSyntax.BlockStatement Debug.Assert(syntax.Modifiers.IsEmpty, "event accessors cannot have modifiers") ' Include modifiers from the containing event. Dim flags = Me._memberFlags If Me.IsImplementing Then flags = flags Or SourceMemberFlags.Overrides Or SourceMemberFlags.NotOverridable End If ' All event accessors are subs. Select Case blockSyntax.Kind Case SyntaxKind.AddHandlerAccessorBlock flags = flags Or SourceMemberFlags.MethodKindEventAdd Or SourceMemberFlags.MethodIsSub Case SyntaxKind.RemoveHandlerAccessorBlock flags = flags Or SourceMemberFlags.MethodKindEventRemove Or SourceMemberFlags.MethodIsSub Case SyntaxKind.RaiseEventAccessorBlock flags = flags Or SourceMemberFlags.MethodKindEventRaise Or SourceMemberFlags.MethodIsSub Case Else Throw ExceptionUtilities.UnexpectedValue(blockSyntax.Kind) End Select Dim location = syntax.GetLocation() ' Event symbols aren't affected if the output kind is winmd, mark false Dim method As New CustomEventAccessorSymbol( Me._containingType, Me, binder.GetAccessorName(Me.Name, flags.ToMethodKind(), isWinMd:=False), flags, binder.GetSyntaxReference(syntax), location) ' TODO: Handle custom modifiers, including modifiers. Return method End Function Private Function IsImplementing() As Boolean Return Not ExplicitInterfaceImplementations.IsEmpty End Function ''' <summary> ''' Helper method for accessors to get the overridden accessor methods. Should only be called by the ''' accessor method symbols. ''' </summary> Friend Function GetAccessorImplementations(kind As MethodKind) As ImmutableArray(Of MethodSymbol) Dim implementedEvents = ExplicitInterfaceImplementations Debug.Assert(Not implementedEvents.IsDefault) If implementedEvents.IsEmpty Then Return ImmutableArray(Of MethodSymbol).Empty Else Dim builder As ArrayBuilder(Of MethodSymbol) = ArrayBuilder(Of MethodSymbol).GetInstance() For Each implementedEvent In implementedEvents Dim accessor As MethodSymbol Select Case kind Case MethodKind.EventAdd accessor = implementedEvent.AddMethod Case MethodKind.EventRemove accessor = implementedEvent.RemoveMethod Case MethodKind.EventRaise accessor = implementedEvent.RaiseMethod Case Else Throw ExceptionUtilities.UnexpectedValue(kind) End Select If accessor IsNot Nothing Then builder.Add(accessor) End If Next Return builder.ToImmutableAndFree() End If End Function Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return _containingType End Get End Property Public ReadOnly Property ContainingSourceModule As SourceModuleSymbol Get Return _containingType.ContainingSourceModule End Get End Property Friend Overrides Function GetLexicalSortKey() As LexicalSortKey ' WARNING: this should not allocate memory! Return New LexicalSortKey(_location, Me.DeclaringCompilation) End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(_location) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(_syntaxRef) End Get End Property Friend NotOverridable Overrides Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean Dim eventBlock = Me._syntaxRef.GetSyntax(cancellationToken).Parent Return IsDefinedInSourceTree(eventBlock, tree, definedWithinSpan, cancellationToken) End Function Public Overrides ReadOnly Property Type As TypeSymbol Get If _lazyType Is Nothing Then Dim diagnostics = BindingDiagnosticBag.GetInstance() Dim isTypeInferred = False Dim isDelegateFromImplements = False Dim eventType = ComputeType(diagnostics, isTypeInferred, isDelegateFromImplements) Dim newState = If(isTypeInferred, StateFlags.IsTypeInferred, 0) Or If(isDelegateFromImplements, StateFlags.IsDelegateFromImplements, 0) ThreadSafeFlagOperations.Set(_lazyState, newState) ContainingSourceModule.AtomicStoreReferenceAndDiagnostics(_lazyType, eventType, diagnostics) diagnostics.Free() End If Return _lazyType End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property AddMethod As MethodSymbol Get Return _addMethod End Get End Property Public Overrides ReadOnly Property RemoveMethod As MethodSymbol Get Return _removeMethod End Get End Property Public Overrides ReadOnly Property RaiseMethod As MethodSymbol Get Return _raiseMethod End Get End Property Friend Overrides ReadOnly Property AssociatedField As FieldSymbol Get Return _backingField End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of EventSymbol) Get If _lazyImplementedEvents.IsDefault Then Dim diagnostics = BindingDiagnosticBag.GetInstance() ContainingSourceModule.AtomicStoreArrayAndDiagnostics(_lazyImplementedEvents, ComputeImplementedEvents(diagnostics), diagnostics) diagnostics.Free() End If Return _lazyImplementedEvents End Get End Property Friend ReadOnly Property SyntaxReference As SyntaxReference Get Return Me._syntaxRef End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return (_memberFlags And SourceMemberFlags.Shared) <> 0 End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get ' event can be MustOverride if it is defined in an interface Return (_memberFlags And SourceMemberFlags.MustOverride) <> 0 End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Debug.Assert((_memberFlags And SourceMemberFlags.Overridable) = 0) Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Debug.Assert((_memberFlags And SourceMemberFlags.Overrides) = 0) Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Debug.Assert((_memberFlags And SourceMemberFlags.NotOverridable) = 0) Return False End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return CType((_memberFlags And SourceMemberFlags.AccessibilityMask), Accessibility) End Get End Property Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean Get Return (_memberFlags And SourceMemberFlags.Shadows) <> 0 End Get End Property Friend ReadOnly Property AttributeDeclarationSyntaxList As SyntaxList(Of AttributeListSyntax) Get Return DirectCast(_syntaxRef.GetSyntax, EventStatementSyntax).AttributeLists End Get End Property Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation Get Return AttributeLocation.Event End Get End Property Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get ' If there are no attributes then this symbol is not Obsolete. If (Not Me._containingType.AnyMemberHasAttributes) Then Return Nothing End If Dim lazyCustomAttributesBag = Me._lazyCustomAttributesBag If (lazyCustomAttributesBag IsNot Nothing AndAlso lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) Then Dim data = DirectCast(_lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData, CommonEventEarlyWellKnownAttributeData) Return If(data IsNot Nothing, data.ObsoleteAttributeData, Nothing) End If Return ObsoleteAttributeData.Uninitialized End Get End Property ''' <summary> ''' Gets the attributes applied on this symbol. ''' Returns an empty array if there are no attributes. ''' </summary> ''' <remarks> ''' NOTE: This method should always be kept as a NotOverridable method. ''' If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method. ''' </remarks> Public NotOverridable Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetAttributesBag().Attributes End Function Private Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If _lazyCustomAttributesBag Is Nothing OrElse Not _lazyCustomAttributesBag.IsSealed Then LoadAndValidateAttributes(OneOrMany.Create(Me.AttributeDeclarationSyntaxList), _lazyCustomAttributesBag) End If Return _lazyCustomAttributesBag End Function Friend Function GetDecodedWellKnownAttributeData() As EventWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, EventWellKnownAttributeData) End Function Friend Overrides Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Debug.Assert(arguments.AttributeType IsNot Nothing) Debug.Assert(Not arguments.AttributeType.IsErrorType()) Dim boundAttribute As VisualBasicAttributeData = Nothing Dim obsoleteData As ObsoleteAttributeData = Nothing If EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(arguments, boundAttribute, obsoleteData) Then If obsoleteData IsNot Nothing Then arguments.GetOrCreateData(Of CommonEventEarlyWellKnownAttributeData)().ObsoleteAttributeData = obsoleteData End If Return boundAttribute End If Return MyBase.EarlyDecodeWellKnownAttribute(arguments) End Function Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Dim attrData = arguments.Attribute If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location) End If If attrData.IsTargetAttribute(Me, AttributeDescription.NonSerializedAttribute) Then ' Although NonSerialized attribute is only applicable on fields we relax that restriction and allow application on events as well ' to allow making the backing field non-serializable. If Me.ContainingType.IsSerializable Then arguments.GetOrCreateData(Of EventWellKnownAttributeData).HasNonSerializedAttribute = True Else DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_InvalidNonSerializedUsage, arguments.AttributeSyntaxOpt.GetLocation()) End If ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SpecialNameAttribute) Then arguments.GetOrCreateData(Of EventWellKnownAttributeData).HasSpecialNameAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ExcludeFromCodeCoverageAttribute) Then arguments.GetOrCreateData(Of EventWellKnownAttributeData).HasExcludeFromCodeCoverageAttribute = True End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Friend NotOverridable Overrides ReadOnly Property IsDirectlyExcludedFromCodeCoverage As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasExcludeFromCodeCoverageAttribute End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasSpecialNameAttribute End Get End Property Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String If expandIncludes Then Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyExpandedDocComment, cancellationToken) Else Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyDocComment, cancellationToken) End If End Function Friend Shared Function DecodeModifiers(modifiers As SyntaxTokenList, container As SourceMemberContainerTypeSymbol, binder As Binder, diagBag As DiagnosticBag) As MemberModifiers ' Decode the flags. Dim eventModifiers = binder.DecodeModifiers(modifiers, SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Or SourceMemberFlags.Shared, ERRID.ERR_BadEventFlags1, Accessibility.Public, diagBag) eventModifiers = binder.ValidateEventModifiers(modifiers, eventModifiers, container, diagBag) Return eventModifiers End Function ' Get the location of the implements name for an explicit implemented event, for later error reporting. Friend Function GetImplementingLocation(implementedEvent As EventSymbol) As Location Dim eventSyntax = DirectCast(_syntaxRef.GetSyntax(), EventStatementSyntax) Dim syntaxTree = _syntaxRef.SyntaxTree If eventSyntax.ImplementsClause IsNot Nothing Then Dim binder = CreateBinderForTypeDeclaration() Dim implementingSyntax = FindImplementingSyntax(Of EventSymbol)(eventSyntax.ImplementsClause, Me, implementedEvent, _containingType, binder) Return implementingSyntax.GetLocation() End If Return If(Locations.FirstOrDefault(), NoLocation.Singleton) End Function Private Function CreateBinderForTypeDeclaration() As Binder Dim binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, _syntaxRef.SyntaxTree, _containingType) Return New LocationSpecificBinder(BindingLocation.EventSignature, Me, binder) End Function Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) MyBase.GenerateDeclarationErrors(cancellationToken) Dim unusedType = Me.Type Dim unusedImplementations = Me.ExplicitInterfaceImplementations Me.CheckExplicitImplementationTypes() If DeclaringCompilation.EventQueue IsNot Nothing Then Me.ContainingSourceModule.AtomicSetFlagAndRaiseSymbolDeclaredEvent(_lazyState, StateFlags.SymbolDeclaredEvent, 0, Me) End If End Sub Public Overrides ReadOnly Property IsWindowsRuntimeEvent As Boolean Get ' The first implemented event wins - if the others disagree, we'll produce diagnostics. ' If no interface events are implemented, then the result is based on the output kind of the compilation. Dim implementedEvents As ImmutableArray(Of EventSymbol) = ExplicitInterfaceImplementations Return If(implementedEvents.Any, implementedEvents(0).IsWindowsRuntimeEvent, Me.IsCompilationOutputWinMdObj()) End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) If Me.Type.ContainsTupleNames() Then AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(Type)) 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 System.Collections.Immutable Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Class SourceEventSymbol Inherits EventSymbol Implements IAttributeTargetSymbol Private ReadOnly _containingType As SourceMemberContainerTypeSymbol Private ReadOnly _name As String Private ReadOnly _syntaxRef As SyntaxReference Private ReadOnly _location As Location Private ReadOnly _memberFlags As SourceMemberFlags Private ReadOnly _addMethod As MethodSymbol Private ReadOnly _removeMethod As MethodSymbol Private ReadOnly _raiseMethod As MethodSymbol Private ReadOnly _backingField As FieldSymbol ' Misc flags defining the state of this symbol (StateFlags) Private _lazyState As Integer <Flags> Private Enum StateFlags As Integer IsTypeInferred = &H1 ' Bit value valid once m_lazyType is assigned. IsDelegateFromImplements = &H2 ' Bit value valid once m_lazyType is assigned. ReportedExplicitImplementationDiagnostics = &H4 SymbolDeclaredEvent = &H8 ' Bit value for generating SymbolDeclaredEvent End Enum Private _lazyType As TypeSymbol Private _lazyImplementedEvents As ImmutableArray(Of EventSymbol) Private _lazyDelegateParameters As ImmutableArray(Of ParameterSymbol) Private _lazyDocComment As String Private _lazyExpandedDocComment As String ' Attributes on event. Set once after construction. IsNull means not set. Private _lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) ''' <summary> ''' Indicates whether event created a new delegate type. ''' In such case the Type must be added to the members of the containing type ''' </summary> Friend ReadOnly Property IsTypeInferred As Boolean Get Dim unused = Type ' Ensure lazy state is computed. Return (_lazyState And StateFlags.IsTypeInferred) <> 0 End Get End Property Friend Sub New(containingType As SourceMemberContainerTypeSymbol, binder As Binder, syntax As EventStatementSyntax, blockSyntaxOpt As EventBlockSyntax, diagnostics As DiagnosticBag) Debug.Assert(containingType IsNot Nothing) Debug.Assert(syntax IsNot Nothing) _containingType = containingType ' Decode the flags. ' This will validate modifiers against container (i.e. Protected is invalid in a structure...) Dim modifiers = DecodeModifiers(syntax.Modifiers, containingType, binder, diagnostics) _memberFlags = modifiers.AllFlags Dim identifier = syntax.Identifier _name = identifier.ValueText ' Events cannot have type characters If identifier.GetTypeCharacter() <> TypeCharacter.None Then Binder.ReportDiagnostic(diagnostics, identifier, ERRID.ERR_TypecharNotallowed) End If Dim location = identifier.GetLocation() _location = location _syntaxRef = binder.GetSyntaxReference(syntax) binder = New LocationSpecificBinder(BindingLocation.EventSignature, Me, binder) If blockSyntaxOpt IsNot Nothing Then For Each accessorSyntax In blockSyntaxOpt.Accessors Dim accessor As CustomEventAccessorSymbol = BindEventAccessor(accessorSyntax, binder) Select Case (accessor.MethodKind) Case MethodKind.EventAdd If _addMethod Is Nothing Then _addMethod = accessor Else diagnostics.Add(ERRID.ERR_DuplicateAddHandlerDef, accessor.Locations(0)) End If Case MethodKind.EventRemove If _removeMethod Is Nothing Then _removeMethod = accessor Else diagnostics.Add(ERRID.ERR_DuplicateRemoveHandlerDef, accessor.Locations(0)) End If Case MethodKind.EventRaise If _raiseMethod Is Nothing Then _raiseMethod = accessor Else diagnostics.Add(ERRID.ERR_DuplicateRaiseEventDef, accessor.Locations(0)) End If Case Else Throw ExceptionUtilities.UnexpectedValue(accessor.MethodKind) End Select Next If _addMethod Is Nothing Then diagnostics.Add(ERRID.ERR_MissingAddHandlerDef1, location, Me) End If If _removeMethod Is Nothing Then diagnostics.Add(ERRID.ERR_MissingRemoveHandlerDef1, location, Me) End If If _raiseMethod Is Nothing Then diagnostics.Add(ERRID.ERR_MissingRaiseEventDef1, location, Me) End If Else ' Synthesize accessors _addMethod = New SynthesizedAddAccessorSymbol(containingType, Me) _removeMethod = New SynthesizedRemoveAccessorSymbol(containingType, Me) ' if this is a concrete class, add a backing field too If Not containingType.IsInterfaceType Then _backingField = New SynthesizedEventBackingFieldSymbol(Me, Me.Name & StringConstants.EventVariableSuffix, Me.IsShared) End If End If End Sub Private Function ComputeType(diagnostics As BindingDiagnosticBag, <Out()> ByRef isTypeInferred As Boolean, <Out()> ByRef isDelegateFromImplements As Boolean) As TypeSymbol Dim binder = CreateBinderForTypeDeclaration() Dim syntax = DirectCast(_syntaxRef.GetSyntax(), EventStatementSyntax) isTypeInferred = False isDelegateFromImplements = False Dim type As TypeSymbol ' TODO: why AsClause is not a SimpleAsClause in events? There can't be "As New" ' WinRT events require either an as-clause or an implements-clause. Dim requiresDelegateType As Boolean = syntax.ImplementsClause Is Nothing AndAlso Me.IsWindowsRuntimeEvent ' if there is an As clause we use its type as event's type If syntax.AsClause IsNot Nothing Then type = binder.DecodeIdentifierType(syntax.Identifier, syntax.AsClause, Nothing, diagnostics) If Not syntax.AsClause.AsKeyword.IsMissing Then If Not type.IsDelegateType Then Binder.ReportDiagnostic(diagnostics, syntax.AsClause.Type, ERRID.ERR_EventTypeNotDelegate) Else Dim invoke = DirectCast(type, NamedTypeSymbol).DelegateInvokeMethod If invoke Is Nothing Then Binder.ReportDiagnostic(diagnostics, syntax.AsClause.Type, ERRID.ERR_UnsupportedType1, type.Name) Else If Not invoke.IsSub Then Binder.ReportDiagnostic(diagnostics, syntax.AsClause.Type, ERRID.ERR_EventDelegatesCantBeFunctions) End If End If End If ElseIf requiresDelegateType Then ' This will always be a cascading diagnostic but, arguably, it does provide additional context ' and dev11 reports it. Binder.ReportDiagnostic(diagnostics, syntax.Identifier, ERRID.ERR_WinRTEventWithoutDelegate) End If Else If requiresDelegateType Then Binder.ReportDiagnostic(diagnostics, syntax.Identifier, ERRID.ERR_WinRTEventWithoutDelegate) End If Dim implementedEvents = ExplicitInterfaceImplementations ' when we have a match with interface event we should take the type from ' the implemented event. If Not implementedEvents.IsEmpty Then ' use the type of the first implemented event Dim implementedEventType = implementedEvents(0).Type ' all other implemented events must be of the same type as the first For i As Integer = 1 To implementedEvents.Length - 1 Dim implemented = implementedEvents(i) If Not implemented.Type.IsSameType(implementedEventType, TypeCompareKind.IgnoreTupleNames) Then Dim errLocation = GetImplementingLocation(implemented) Binder.ReportDiagnostic(diagnostics, errLocation, ERRID.ERR_MultipleEventImplMismatch3, Me, implemented, implemented.ContainingType) End If Next type = implementedEventType isDelegateFromImplements = True Else ' get event's type from the containing type Dim types = _containingType.GetTypeMembers(Me.Name & StringConstants.EventDelegateSuffix) Debug.Assert(Not types.IsDefault) type = Nothing For Each candidate In types If candidate.AssociatedSymbol Is Me Then type = candidate Exit For End If Next If type Is Nothing Then ' if we still do not know the type, get a temporary one (it is not a member of the containing class) type = New SynthesizedEventDelegateSymbol(Me._syntaxRef, _containingType) End If isTypeInferred = True End If End If If Not type.IsErrorType() Then AccessCheck.VerifyAccessExposureForMemberType(Me, syntax.Identifier, type, diagnostics, isDelegateFromImplements) End If Return type End Function Private Function ComputeImplementedEvents(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of EventSymbol) Dim syntax = DirectCast(_syntaxRef.GetSyntax(), EventStatementSyntax) Dim implementsClause = syntax.ImplementsClause If implementsClause IsNot Nothing Then Dim binder = CreateBinderForTypeDeclaration() If _containingType.IsInterfaceType Then Dim implementsKeyword = implementsClause.ImplementsKeyword ' // Interface events can't claim to implement anything Binder.ReportDiagnostic(diagnostics, implementsKeyword, ERRID.ERR_InterfaceEventCantUse1, implementsKeyword.ValueText) ElseIf IsShared AndAlso Not _containingType.IsModuleType Then ' // Implementing with shared events is illegal. Binder.ReportDiagnostic(diagnostics, syntax.Modifiers.First(SyntaxKind.SharedKeyword), ERRID.ERR_SharedOnProcThatImpl) Else ' if event is inferred, only signature needs to match ' otherwise event types must match exactly Return ProcessImplementsClause(Of EventSymbol)(implementsClause, Me, _containingType, binder, diagnostics) End If End If Return ImmutableArray(Of EventSymbol).Empty End Function ''' <summary> ''' Unless the type is inferred, check that all ''' implemented events have the same type. ''' </summary> Private Sub CheckExplicitImplementationTypes() If (_lazyState And (StateFlags.IsTypeInferred Or StateFlags.IsDelegateFromImplements Or StateFlags.ReportedExplicitImplementationDiagnostics)) <> 0 Then Return End If Dim diagnostics As BindingDiagnosticBag = Nothing Dim type = Me.Type For Each implemented In ExplicitInterfaceImplementations If Not implemented.Type.IsSameType(type, TypeCompareKind.IgnoreTupleNames) Then If diagnostics Is Nothing Then diagnostics = BindingDiagnosticBag.GetInstance() End If Dim errLocation = GetImplementingLocation(implemented) diagnostics.Add(ERRID.ERR_EventImplMismatch5, errLocation, {Me, implemented, implemented.ContainingType, type, implemented.Type}) End If Next If diagnostics IsNot Nothing Then ContainingSourceModule.AtomicSetFlagAndStoreDiagnostics(_lazyState, StateFlags.ReportedExplicitImplementationDiagnostics, 0, diagnostics) diagnostics.Free() End If End Sub Friend Overrides ReadOnly Property DelegateParameters As ImmutableArray(Of ParameterSymbol) Get If _lazyDelegateParameters.IsDefault Then Dim syntax = DirectCast(_syntaxRef.GetSyntax(), EventStatementSyntax) If syntax.AsClause IsNot Nothing Then ' We can access use the base implementation which relies ' on the Type property since the type in "Event E As D" is explicit. _lazyDelegateParameters = MyBase.DelegateParameters Else ' Avoid using the base implementation since that relies ' on Type which is inferred, potentially from interface ' implementations which relies on DelegateParameters. Dim binder = CreateBinderForTypeDeclaration() Dim diagnostics = BindingDiagnosticBag.GetInstance() ContainingSourceModule.AtomicStoreArrayAndDiagnostics( _lazyDelegateParameters, binder.DecodeParameterListOfDelegateDeclaration(Me, syntax.ParameterList, diagnostics), diagnostics) diagnostics.Free() End If End If Return _lazyDelegateParameters End Get End Property Private Function BindEventAccessor(blockSyntax As AccessorBlockSyntax, binder As Binder) As CustomEventAccessorSymbol Dim syntax = blockSyntax.BlockStatement Debug.Assert(syntax.Modifiers.IsEmpty, "event accessors cannot have modifiers") ' Include modifiers from the containing event. Dim flags = Me._memberFlags If Me.IsImplementing Then flags = flags Or SourceMemberFlags.Overrides Or SourceMemberFlags.NotOverridable End If ' All event accessors are subs. Select Case blockSyntax.Kind Case SyntaxKind.AddHandlerAccessorBlock flags = flags Or SourceMemberFlags.MethodKindEventAdd Or SourceMemberFlags.MethodIsSub Case SyntaxKind.RemoveHandlerAccessorBlock flags = flags Or SourceMemberFlags.MethodKindEventRemove Or SourceMemberFlags.MethodIsSub Case SyntaxKind.RaiseEventAccessorBlock flags = flags Or SourceMemberFlags.MethodKindEventRaise Or SourceMemberFlags.MethodIsSub Case Else Throw ExceptionUtilities.UnexpectedValue(blockSyntax.Kind) End Select Dim location = syntax.GetLocation() ' Event symbols aren't affected if the output kind is winmd, mark false Dim method As New CustomEventAccessorSymbol( Me._containingType, Me, binder.GetAccessorName(Me.Name, flags.ToMethodKind(), isWinMd:=False), flags, binder.GetSyntaxReference(syntax), location) ' TODO: Handle custom modifiers, including modifiers. Return method End Function Private Function IsImplementing() As Boolean Return Not ExplicitInterfaceImplementations.IsEmpty End Function ''' <summary> ''' Helper method for accessors to get the overridden accessor methods. Should only be called by the ''' accessor method symbols. ''' </summary> Friend Function GetAccessorImplementations(kind As MethodKind) As ImmutableArray(Of MethodSymbol) Dim implementedEvents = ExplicitInterfaceImplementations Debug.Assert(Not implementedEvents.IsDefault) If implementedEvents.IsEmpty Then Return ImmutableArray(Of MethodSymbol).Empty Else Dim builder As ArrayBuilder(Of MethodSymbol) = ArrayBuilder(Of MethodSymbol).GetInstance() For Each implementedEvent In implementedEvents Dim accessor As MethodSymbol Select Case kind Case MethodKind.EventAdd accessor = implementedEvent.AddMethod Case MethodKind.EventRemove accessor = implementedEvent.RemoveMethod Case MethodKind.EventRaise accessor = implementedEvent.RaiseMethod Case Else Throw ExceptionUtilities.UnexpectedValue(kind) End Select If accessor IsNot Nothing Then builder.Add(accessor) End If Next Return builder.ToImmutableAndFree() End If End Function Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return _containingType End Get End Property Public ReadOnly Property ContainingSourceModule As SourceModuleSymbol Get Return _containingType.ContainingSourceModule End Get End Property Friend Overrides Function GetLexicalSortKey() As LexicalSortKey ' WARNING: this should not allocate memory! Return New LexicalSortKey(_location, Me.DeclaringCompilation) End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(_location) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(_syntaxRef) End Get End Property Friend NotOverridable Overrides Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean Dim eventBlock = Me._syntaxRef.GetSyntax(cancellationToken).Parent Return IsDefinedInSourceTree(eventBlock, tree, definedWithinSpan, cancellationToken) End Function Public Overrides ReadOnly Property Type As TypeSymbol Get If _lazyType Is Nothing Then Dim diagnostics = BindingDiagnosticBag.GetInstance() Dim isTypeInferred = False Dim isDelegateFromImplements = False Dim eventType = ComputeType(diagnostics, isTypeInferred, isDelegateFromImplements) Dim newState = If(isTypeInferred, StateFlags.IsTypeInferred, 0) Or If(isDelegateFromImplements, StateFlags.IsDelegateFromImplements, 0) ThreadSafeFlagOperations.Set(_lazyState, newState) ContainingSourceModule.AtomicStoreReferenceAndDiagnostics(_lazyType, eventType, diagnostics) diagnostics.Free() End If Return _lazyType End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property AddMethod As MethodSymbol Get Return _addMethod End Get End Property Public Overrides ReadOnly Property RemoveMethod As MethodSymbol Get Return _removeMethod End Get End Property Public Overrides ReadOnly Property RaiseMethod As MethodSymbol Get Return _raiseMethod End Get End Property Friend Overrides ReadOnly Property AssociatedField As FieldSymbol Get Return _backingField End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of EventSymbol) Get If _lazyImplementedEvents.IsDefault Then Dim diagnostics = BindingDiagnosticBag.GetInstance() ContainingSourceModule.AtomicStoreArrayAndDiagnostics(_lazyImplementedEvents, ComputeImplementedEvents(diagnostics), diagnostics) diagnostics.Free() End If Return _lazyImplementedEvents End Get End Property Friend ReadOnly Property SyntaxReference As SyntaxReference Get Return Me._syntaxRef End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return (_memberFlags And SourceMemberFlags.Shared) <> 0 End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get ' event can be MustOverride if it is defined in an interface Return (_memberFlags And SourceMemberFlags.MustOverride) <> 0 End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Debug.Assert((_memberFlags And SourceMemberFlags.Overridable) = 0) Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Debug.Assert((_memberFlags And SourceMemberFlags.Overrides) = 0) Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Debug.Assert((_memberFlags And SourceMemberFlags.NotOverridable) = 0) Return False End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return CType((_memberFlags And SourceMemberFlags.AccessibilityMask), Accessibility) End Get End Property Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean Get Return (_memberFlags And SourceMemberFlags.Shadows) <> 0 End Get End Property Friend ReadOnly Property AttributeDeclarationSyntaxList As SyntaxList(Of AttributeListSyntax) Get Return DirectCast(_syntaxRef.GetSyntax, EventStatementSyntax).AttributeLists End Get End Property Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation Get Return AttributeLocation.Event End Get End Property Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get ' If there are no attributes then this symbol is not Obsolete. If (Not Me._containingType.AnyMemberHasAttributes) Then Return Nothing End If Dim lazyCustomAttributesBag = Me._lazyCustomAttributesBag If (lazyCustomAttributesBag IsNot Nothing AndAlso lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) Then Dim data = DirectCast(_lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData, CommonEventEarlyWellKnownAttributeData) Return If(data IsNot Nothing, data.ObsoleteAttributeData, Nothing) End If Return ObsoleteAttributeData.Uninitialized End Get End Property ''' <summary> ''' Gets the attributes applied on this symbol. ''' Returns an empty array if there are no attributes. ''' </summary> ''' <remarks> ''' NOTE: This method should always be kept as a NotOverridable method. ''' If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method. ''' </remarks> Public NotOverridable Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetAttributesBag().Attributes End Function Private Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If _lazyCustomAttributesBag Is Nothing OrElse Not _lazyCustomAttributesBag.IsSealed Then LoadAndValidateAttributes(OneOrMany.Create(Me.AttributeDeclarationSyntaxList), _lazyCustomAttributesBag) End If Return _lazyCustomAttributesBag End Function Friend Function GetDecodedWellKnownAttributeData() As EventWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, EventWellKnownAttributeData) End Function Friend Overrides Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Debug.Assert(arguments.AttributeType IsNot Nothing) Debug.Assert(Not arguments.AttributeType.IsErrorType()) Dim boundAttribute As VisualBasicAttributeData = Nothing Dim obsoleteData As ObsoleteAttributeData = Nothing If EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(arguments, boundAttribute, obsoleteData) Then If obsoleteData IsNot Nothing Then arguments.GetOrCreateData(Of CommonEventEarlyWellKnownAttributeData)().ObsoleteAttributeData = obsoleteData End If Return boundAttribute End If Return MyBase.EarlyDecodeWellKnownAttribute(arguments) End Function Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Dim attrData = arguments.Attribute If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location) End If If attrData.IsTargetAttribute(Me, AttributeDescription.NonSerializedAttribute) Then ' Although NonSerialized attribute is only applicable on fields we relax that restriction and allow application on events as well ' to allow making the backing field non-serializable. If Me.ContainingType.IsSerializable Then arguments.GetOrCreateData(Of EventWellKnownAttributeData).HasNonSerializedAttribute = True Else DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_InvalidNonSerializedUsage, arguments.AttributeSyntaxOpt.GetLocation()) End If ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SpecialNameAttribute) Then arguments.GetOrCreateData(Of EventWellKnownAttributeData).HasSpecialNameAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ExcludeFromCodeCoverageAttribute) Then arguments.GetOrCreateData(Of EventWellKnownAttributeData).HasExcludeFromCodeCoverageAttribute = True End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Friend NotOverridable Overrides ReadOnly Property IsDirectlyExcludedFromCodeCoverage As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasExcludeFromCodeCoverageAttribute End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasSpecialNameAttribute End Get End Property Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String If expandIncludes Then Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyExpandedDocComment, cancellationToken) Else Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyDocComment, cancellationToken) End If End Function Friend Shared Function DecodeModifiers(modifiers As SyntaxTokenList, container As SourceMemberContainerTypeSymbol, binder As Binder, diagBag As DiagnosticBag) As MemberModifiers ' Decode the flags. Dim eventModifiers = binder.DecodeModifiers(modifiers, SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Or SourceMemberFlags.Shared, ERRID.ERR_BadEventFlags1, Accessibility.Public, diagBag) eventModifiers = binder.ValidateEventModifiers(modifiers, eventModifiers, container, diagBag) Return eventModifiers End Function ' Get the location of the implements name for an explicit implemented event, for later error reporting. Friend Function GetImplementingLocation(implementedEvent As EventSymbol) As Location Dim eventSyntax = DirectCast(_syntaxRef.GetSyntax(), EventStatementSyntax) Dim syntaxTree = _syntaxRef.SyntaxTree If eventSyntax.ImplementsClause IsNot Nothing Then Dim binder = CreateBinderForTypeDeclaration() Dim implementingSyntax = FindImplementingSyntax(Of EventSymbol)(eventSyntax.ImplementsClause, Me, implementedEvent, _containingType, binder) Return implementingSyntax.GetLocation() End If Return If(Locations.FirstOrDefault(), NoLocation.Singleton) End Function Private Function CreateBinderForTypeDeclaration() As Binder Dim binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, _syntaxRef.SyntaxTree, _containingType) Return New LocationSpecificBinder(BindingLocation.EventSignature, Me, binder) End Function Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) MyBase.GenerateDeclarationErrors(cancellationToken) Dim unusedType = Me.Type Dim unusedImplementations = Me.ExplicitInterfaceImplementations Me.CheckExplicitImplementationTypes() If DeclaringCompilation.EventQueue IsNot Nothing Then Me.ContainingSourceModule.AtomicSetFlagAndRaiseSymbolDeclaredEvent(_lazyState, StateFlags.SymbolDeclaredEvent, 0, Me) End If End Sub Public Overrides ReadOnly Property IsWindowsRuntimeEvent As Boolean Get ' The first implemented event wins - if the others disagree, we'll produce diagnostics. ' If no interface events are implemented, then the result is based on the output kind of the compilation. Dim implementedEvents As ImmutableArray(Of EventSymbol) = ExplicitInterfaceImplementations Return If(implementedEvents.Any, implementedEvents(0).IsWindowsRuntimeEvent, Me.IsCompilationOutputWinMdObj()) End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) If Me.Type.ContainsTupleNames() Then AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(Type)) End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/EditorFeatures/Core/Shared/Extensions/SnapshotSpanExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class SnapshotSpanExtensions { public static ITrackingSpan CreateTrackingSpan(this SnapshotSpan snapshotSpan, SpanTrackingMode trackingMode) => snapshotSpan.Snapshot.CreateTrackingSpan(snapshotSpan.Span, trackingMode); public static void GetLinesAndCharacters( this SnapshotSpan snapshotSpan, out int startLineNumber, out int startCharacterIndex, out int endLineNumber, out int endCharacterIndex) { snapshotSpan.Snapshot.GetLineAndCharacter(snapshotSpan.Span.Start, out startLineNumber, out startCharacterIndex); snapshotSpan.Snapshot.GetLineAndCharacter(snapshotSpan.Span.End, out endLineNumber, out endCharacterIndex); } public static LinePositionSpan ToLinePositionSpan(this SnapshotSpan snapshotSpan) { snapshotSpan.GetLinesAndCharacters(out var startLine, out var startChar, out var endLine, out var endChar); return new LinePositionSpan(new LinePosition(startLine, startChar), new LinePosition(endLine, endChar)); } public static bool IntersectsWith(this SnapshotSpan snapshotSpan, TextSpan textSpan) => snapshotSpan.IntersectsWith(textSpan.ToSpan()); public static bool IntersectsWith(this SnapshotSpan snapshotSpan, int position) => snapshotSpan.Span.IntersectsWith(position); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class SnapshotSpanExtensions { public static ITrackingSpan CreateTrackingSpan(this SnapshotSpan snapshotSpan, SpanTrackingMode trackingMode) => snapshotSpan.Snapshot.CreateTrackingSpan(snapshotSpan.Span, trackingMode); public static void GetLinesAndCharacters( this SnapshotSpan snapshotSpan, out int startLineNumber, out int startCharacterIndex, out int endLineNumber, out int endCharacterIndex) { snapshotSpan.Snapshot.GetLineAndCharacter(snapshotSpan.Span.Start, out startLineNumber, out startCharacterIndex); snapshotSpan.Snapshot.GetLineAndCharacter(snapshotSpan.Span.End, out endLineNumber, out endCharacterIndex); } public static LinePositionSpan ToLinePositionSpan(this SnapshotSpan snapshotSpan) { snapshotSpan.GetLinesAndCharacters(out var startLine, out var startChar, out var endLine, out var endChar); return new LinePositionSpan(new LinePosition(startLine, startChar), new LinePosition(endLine, endChar)); } public static bool IntersectsWith(this SnapshotSpan snapshotSpan, TextSpan textSpan) => snapshotSpan.IntersectsWith(textSpan.ToSpan()); public static bool IntersectsWith(this SnapshotSpan snapshotSpan, int position) => snapshotSpan.Span.IntersectsWith(position); } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.BodyLevelSymbolKey.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class BodyLevelSymbolKey { public static ImmutableArray<Location> GetBodyLevelSourceLocations(ISymbol symbol, CancellationToken cancellationToken) { Contract.ThrowIfFalse(IsBodyLevelSymbol(symbol)); Contract.ThrowIfTrue(symbol.DeclaringSyntaxReferences.IsEmpty && symbol.Locations.IsEmpty); using var _ = ArrayBuilder<Location>.GetInstance(out var result); foreach (var location in symbol.Locations) { if (location.IsInSource) result.Add(location); } foreach (var syntaxRef in symbol.DeclaringSyntaxReferences) result.Add(syntaxRef.GetSyntax(cancellationToken).GetLocation()); return result.ToImmutable(); } public static void Create(ISymbol symbol, SymbolKeyWriter visitor) { // Store the body level symbol in two forms. The first, a highly precise form that should find explicit // symbols for the case of resolving a symbol key back in the *same* solution snapshot it was created // from. The second, in a more query-oriented form that can allow the symbol to be found in some cases // even if the solution changed (which is a supported use case for SymbolKey). // // The first way just stores the location of the symbol, which we can then validate during resolution // maps back to the same symbol kind/name. // // The second determines the sequence of symbols of the same kind and same name in the file and keeps // track of our index in that sequence. That way, if trivial edits happen, or symbols with different // names/types are added/removed, we can still find what is likely to be this symbol after the edit. var kind = symbol.Kind; var localName = symbol.Name; visitor.WriteString(localName); visitor.WriteInteger((int)kind); // write out the locations for precision Contract.ThrowIfTrue(symbol.DeclaringSyntaxReferences.IsEmpty && symbol.Locations.IsEmpty); var locations = GetBodyLevelSourceLocations(symbol, visitor.CancellationToken); Contract.ThrowIfFalse(locations.All(loc => loc.IsInSource)); visitor.WriteLocationArray(locations.Distinct()); // and the ordinal for resilience visitor.WriteInteger(GetOrdinal()); return; int GetOrdinal() { var syntaxTree = locations[0].SourceTree; var compilation = ((ISourceAssemblySymbol)symbol.ContainingAssembly).Compilation; // Ensure that the tree we're looking at is actually in this compilation. It may not be in the // compilation in the case of work done with a speculative model. if (TryGetSemanticModel(compilation, syntaxTree, out var semanticModel)) { foreach (var possibleSymbol in EnumerateSymbols(semanticModel, kind, localName, visitor.CancellationToken)) { if (possibleSymbol.symbol.Equals(symbol)) return possibleSymbol.ordinal; } } return int.MaxValue; } } private static bool TryGetSemanticModel( Compilation compilation, SyntaxTree? syntaxTree, [NotNullWhen(true)] out SemanticModel? semanticModel) { // Ensure that the tree we're looking at is actually in this compilation. It may not be in the // compilation in the case of work done with a speculative model. if (syntaxTree != null && Contains(compilation.SyntaxTrees, syntaxTree)) { semanticModel = compilation.GetSemanticModel(syntaxTree); return true; } semanticModel = null; return false; } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var cancellationToken = reader.CancellationToken; var name = reader.ReadString()!; var kind = (SymbolKind)reader.ReadInteger(); #pragma warning disable IDE0007 // Use implicit type PooledArrayBuilder<Location> locations = reader.ReadLocationArray(out var locationsFailureReason)!; #pragma warning restore IDE0007 // Use implicit type var ordinal = reader.ReadInteger(); if (locationsFailureReason != null) { failureReason = $"({nameof(BodyLevelSymbolKey)} {nameof(locations)} failed -> {locationsFailureReason})"; return default; } // First check if we can recover the symbol just through the original location. string? totalFailureReason = null; for (var i = 0; i < locations.Count; i++) { var loc = locations[i]; if (!TryResolveLocation(loc, i, out var resolution, out var reason)) { totalFailureReason = totalFailureReason == null ? $"({reason})" : $"({totalFailureReason} -> {reason})"; continue; } failureReason = null; return resolution; } // Couldn't recover. See if we can still find a match across the textual drift. if (ordinal != int.MaxValue && TryGetSemanticModel(reader.Compilation, locations[0].SourceTree, out var semanticModel)) { foreach (var symbol in EnumerateSymbols(semanticModel, kind, name, cancellationToken)) { if (symbol.ordinal == ordinal) { failureReason = null; return new SymbolKeyResolution(symbol.symbol); } } } failureReason = $"({nameof(BodyLevelSymbolKey)} '{name}' not found -> {totalFailureReason})"; return default; bool TryResolveLocation(Location loc, int index, out SymbolKeyResolution resolution, out string? reason) { var resolutionOpt = reader.ResolveLocation(loc); if (resolutionOpt == null) { reason = $"location {index} failed to resolve"; resolution = default; return false; } resolution = resolutionOpt.Value; var symbol = resolution.GetAnySymbol(); if (symbol == null) { reason = $"location {index} did not produce any symbol"; return false; } if (symbol.Kind != kind) { reason = $"location {index} did not match kind: {symbol.Kind} != {kind}"; return false; } if (!SymbolKey.Equals(reader.Compilation, name, symbol.Name)) { reason = $"location {index} did not match name: {symbol.Name} != {name}"; return false; } reason = null; return true; } } private static IEnumerable<(ISymbol symbol, int ordinal)> EnumerateSymbols( SemanticModel semanticModel, SymbolKind kind, string localName, CancellationToken cancellationToken) { var ordinal = 0; var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); foreach (var node in root.DescendantNodes()) { var symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken); if (symbol?.Kind == kind && SymbolKey.Equals(semanticModel.Compilation, symbol.Name, localName)) { yield return (symbol, ordinal++); } } } private static bool Contains(IEnumerable<SyntaxTree> trees, SyntaxTree tree) { foreach (var current in trees) { if (current == tree) { return true; } } return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class BodyLevelSymbolKey { public static ImmutableArray<Location> GetBodyLevelSourceLocations(ISymbol symbol, CancellationToken cancellationToken) { Contract.ThrowIfFalse(IsBodyLevelSymbol(symbol)); Contract.ThrowIfTrue(symbol.DeclaringSyntaxReferences.IsEmpty && symbol.Locations.IsEmpty); using var _ = ArrayBuilder<Location>.GetInstance(out var result); foreach (var location in symbol.Locations) { if (location.IsInSource) result.Add(location); } foreach (var syntaxRef in symbol.DeclaringSyntaxReferences) result.Add(syntaxRef.GetSyntax(cancellationToken).GetLocation()); return result.ToImmutable(); } public static void Create(ISymbol symbol, SymbolKeyWriter visitor) { // Store the body level symbol in two forms. The first, a highly precise form that should find explicit // symbols for the case of resolving a symbol key back in the *same* solution snapshot it was created // from. The second, in a more query-oriented form that can allow the symbol to be found in some cases // even if the solution changed (which is a supported use case for SymbolKey). // // The first way just stores the location of the symbol, which we can then validate during resolution // maps back to the same symbol kind/name. // // The second determines the sequence of symbols of the same kind and same name in the file and keeps // track of our index in that sequence. That way, if trivial edits happen, or symbols with different // names/types are added/removed, we can still find what is likely to be this symbol after the edit. var kind = symbol.Kind; var localName = symbol.Name; visitor.WriteString(localName); visitor.WriteInteger((int)kind); // write out the locations for precision Contract.ThrowIfTrue(symbol.DeclaringSyntaxReferences.IsEmpty && symbol.Locations.IsEmpty); var locations = GetBodyLevelSourceLocations(symbol, visitor.CancellationToken); Contract.ThrowIfFalse(locations.All(loc => loc.IsInSource)); visitor.WriteLocationArray(locations.Distinct()); // and the ordinal for resilience visitor.WriteInteger(GetOrdinal()); return; int GetOrdinal() { var syntaxTree = locations[0].SourceTree; var compilation = ((ISourceAssemblySymbol)symbol.ContainingAssembly).Compilation; // Ensure that the tree we're looking at is actually in this compilation. It may not be in the // compilation in the case of work done with a speculative model. if (TryGetSemanticModel(compilation, syntaxTree, out var semanticModel)) { foreach (var possibleSymbol in EnumerateSymbols(semanticModel, kind, localName, visitor.CancellationToken)) { if (possibleSymbol.symbol.Equals(symbol)) return possibleSymbol.ordinal; } } return int.MaxValue; } } private static bool TryGetSemanticModel( Compilation compilation, SyntaxTree? syntaxTree, [NotNullWhen(true)] out SemanticModel? semanticModel) { // Ensure that the tree we're looking at is actually in this compilation. It may not be in the // compilation in the case of work done with a speculative model. if (syntaxTree != null && Contains(compilation.SyntaxTrees, syntaxTree)) { semanticModel = compilation.GetSemanticModel(syntaxTree); return true; } semanticModel = null; return false; } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var cancellationToken = reader.CancellationToken; var name = reader.ReadString()!; var kind = (SymbolKind)reader.ReadInteger(); #pragma warning disable IDE0007 // Use implicit type PooledArrayBuilder<Location> locations = reader.ReadLocationArray(out var locationsFailureReason)!; #pragma warning restore IDE0007 // Use implicit type var ordinal = reader.ReadInteger(); if (locationsFailureReason != null) { failureReason = $"({nameof(BodyLevelSymbolKey)} {nameof(locations)} failed -> {locationsFailureReason})"; return default; } // First check if we can recover the symbol just through the original location. string? totalFailureReason = null; for (var i = 0; i < locations.Count; i++) { var loc = locations[i]; if (!TryResolveLocation(loc, i, out var resolution, out var reason)) { totalFailureReason = totalFailureReason == null ? $"({reason})" : $"({totalFailureReason} -> {reason})"; continue; } failureReason = null; return resolution; } // Couldn't recover. See if we can still find a match across the textual drift. if (ordinal != int.MaxValue && TryGetSemanticModel(reader.Compilation, locations[0].SourceTree, out var semanticModel)) { foreach (var symbol in EnumerateSymbols(semanticModel, kind, name, cancellationToken)) { if (symbol.ordinal == ordinal) { failureReason = null; return new SymbolKeyResolution(symbol.symbol); } } } failureReason = $"({nameof(BodyLevelSymbolKey)} '{name}' not found -> {totalFailureReason})"; return default; bool TryResolveLocation(Location loc, int index, out SymbolKeyResolution resolution, out string? reason) { var resolutionOpt = reader.ResolveLocation(loc); if (resolutionOpt == null) { reason = $"location {index} failed to resolve"; resolution = default; return false; } resolution = resolutionOpt.Value; var symbol = resolution.GetAnySymbol(); if (symbol == null) { reason = $"location {index} did not produce any symbol"; return false; } if (symbol.Kind != kind) { reason = $"location {index} did not match kind: {symbol.Kind} != {kind}"; return false; } if (!SymbolKey.Equals(reader.Compilation, name, symbol.Name)) { reason = $"location {index} did not match name: {symbol.Name} != {name}"; return false; } reason = null; return true; } } private static IEnumerable<(ISymbol symbol, int ordinal)> EnumerateSymbols( SemanticModel semanticModel, SymbolKind kind, string localName, CancellationToken cancellationToken) { var ordinal = 0; var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); foreach (var node in root.DescendantNodes()) { var symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken); if (symbol?.Kind == kind && SymbolKey.Equals(semanticModel.Compilation, symbol.Name, localName)) { yield return (symbol, ordinal++); } } } private static bool Contains(IEnumerable<SyntaxTree> trees, SyntaxTree tree) { foreach (var current in trees) { if (current == tree) { return true; } } return false; } } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/XmlCommentHighlighter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class XmlCommentHighlighter Inherits AbstractKeywordHighlighter(Of XmlCommentSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub addHighlights(xmlComment As XmlCommentSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken) With xmlComment If Not .ContainsDiagnostics AndAlso Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then highlights.Add(.LessThanExclamationMinusMinusToken.Span) highlights.Add(.MinusMinusGreaterThanToken.Span) End If End With End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class XmlCommentHighlighter Inherits AbstractKeywordHighlighter(Of XmlCommentSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub addHighlights(xmlComment As XmlCommentSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken) With xmlComment If Not .ContainsDiagnostics AndAlso Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then highlights.Add(.LessThanExclamationMinusMinusToken.Span) highlights.Add(.MinusMinusGreaterThanToken.Span) End If End With End Sub End Class End Namespace
-1