diff --git a/src/Workspaces/Core/Portable/Classification/ClassifiedSpan.cs b/src/Workspaces/Core/Portable/Classification/ClassifiedSpan.cs index c8a8334d73f1e..1414624c6c6a2 100644 --- a/src/Workspaces/Core/Portable/Classification/ClassifiedSpan.cs +++ b/src/Workspaces/Core/Portable/Classification/ClassifiedSpan.cs @@ -8,22 +8,16 @@ namespace Microsoft.CodeAnalysis.Classification { - public readonly struct ClassifiedSpan : IEquatable + public readonly struct ClassifiedSpan(TextSpan textSpan, string classificationType) : IEquatable { - public string ClassificationType { get; } - public TextSpan TextSpan { get; } + public string ClassificationType { get; } = classificationType; + public TextSpan TextSpan { get; } = textSpan; public ClassifiedSpan(string classificationType, TextSpan textSpan) : this(textSpan, classificationType) { } - public ClassifiedSpan(TextSpan textSpan, string classificationType) - { - this.ClassificationType = classificationType; - this.TextSpan = textSpan; - } - public override int GetHashCode() => Hash.Combine(this.ClassificationType, this.TextSpan.GetHashCode()); diff --git a/src/Workspaces/Core/Portable/Classification/ClassifiedText.cs b/src/Workspaces/Core/Portable/Classification/ClassifiedText.cs index e8d7fae36d45f..223bae97bb010 100644 --- a/src/Workspaces/Core/Portable/Classification/ClassifiedText.cs +++ b/src/Workspaces/Core/Portable/Classification/ClassifiedText.cs @@ -4,15 +4,9 @@ namespace Microsoft.CodeAnalysis.Classification { - internal readonly struct ClassifiedText + internal readonly struct ClassifiedText(string classificationType, string text) { - public string ClassificationType { get; } - public string Text { get; } - - public ClassifiedText(string classificationType, string text) - { - ClassificationType = classificationType; - Text = text; - } + public string ClassificationType { get; } = classificationType; + public string Text { get; } = text; } } diff --git a/src/Workspaces/Core/Portable/Classification/IRemoteSemanticClassificationService.cs b/src/Workspaces/Core/Portable/Classification/IRemoteSemanticClassificationService.cs index dfe68ee04cb18..68036b60b4036 100644 --- a/src/Workspaces/Core/Portable/Classification/IRemoteSemanticClassificationService.cs +++ b/src/Workspaces/Core/Portable/Classification/IRemoteSemanticClassificationService.cs @@ -46,19 +46,13 @@ ValueTask GetClassificationsAsync( /// second and third ints encode the span. /// [DataContract] - internal sealed class SerializableClassifiedSpans + internal sealed class SerializableClassifiedSpans(ImmutableArray classificationTypes, ImmutableArray classificationTriples) { [DataMember(Order = 0)] - public readonly ImmutableArray ClassificationTypes; + public readonly ImmutableArray ClassificationTypes = classificationTypes; [DataMember(Order = 1)] - public readonly ImmutableArray ClassificationTriples; - - public SerializableClassifiedSpans(ImmutableArray classificationTypes, ImmutableArray classificationTriples) - { - ClassificationTypes = classificationTypes; - ClassificationTriples = classificationTriples; - } + public readonly ImmutableArray ClassificationTriples = classificationTriples; internal static SerializableClassifiedSpans Dehydrate(ImmutableArray classifiedSpans) { diff --git a/src/Workspaces/Core/Portable/CodeActions/Operations/ApplyChangesOperation.cs b/src/Workspaces/Core/Portable/CodeActions/Operations/ApplyChangesOperation.cs index aa874245f361e..1c3b4a01bc908 100644 --- a/src/Workspaces/Core/Portable/CodeActions/Operations/ApplyChangesOperation.cs +++ b/src/Workspaces/Core/Portable/CodeActions/Operations/ApplyChangesOperation.cs @@ -34,12 +34,9 @@ namespace Microsoft.CodeAnalysis.CodeActions /// /// #pragma warning restore RS0030 // Do not used banned APIs - public sealed class ApplyChangesOperation : CodeActionOperation + public sealed class ApplyChangesOperation(Solution changedSolution) : CodeActionOperation { - public Solution ChangedSolution { get; } - - public ApplyChangesOperation(Solution changedSolution) - => ChangedSolution = changedSolution ?? throw new ArgumentNullException(nameof(changedSolution)); + public Solution ChangedSolution { get; } = changedSolution ?? throw new ArgumentNullException(nameof(changedSolution)); internal override bool ApplyDuringTests => true; diff --git a/src/Workspaces/Core/Portable/CodeActions/Operations/OpenDocumentOperation.cs b/src/Workspaces/Core/Portable/CodeActions/Operations/OpenDocumentOperation.cs index 0cfdebefe00d1..2f1813154ee5a 100644 --- a/src/Workspaces/Core/Portable/CodeActions/Operations/OpenDocumentOperation.cs +++ b/src/Workspaces/Core/Portable/CodeActions/Operations/OpenDocumentOperation.cs @@ -10,16 +10,9 @@ namespace Microsoft.CodeAnalysis.CodeActions /// /// A code action operation for requesting a document be opened in the host environment. /// - public sealed class OpenDocumentOperation : CodeActionOperation + public sealed class OpenDocumentOperation(DocumentId documentId, bool activateIfAlreadyOpen = false) : CodeActionOperation { - private readonly DocumentId _documentId; - private readonly bool _activate; - - public OpenDocumentOperation(DocumentId documentId, bool activateIfAlreadyOpen = false) - { - _documentId = documentId ?? throw new ArgumentNullException(nameof(documentId)); - _activate = activateIfAlreadyOpen; - } + private readonly DocumentId _documentId = documentId ?? throw new ArgumentNullException(nameof(documentId)); public DocumentId DocumentId => _documentId; @@ -27,7 +20,7 @@ public override void Apply(Workspace workspace, CancellationToken cancellationTo { if (workspace.CanOpenDocuments) { - workspace.OpenDocument(_documentId, _activate); + workspace.OpenDocument(_documentId, activateIfAlreadyOpen); } } } diff --git a/src/Workspaces/Core/Portable/CodeCleanup/Providers/FormatCodeCleanupProvider.cs b/src/Workspaces/Core/Portable/CodeCleanup/Providers/FormatCodeCleanupProvider.cs index 5648e03677d65..0460a0aac0826 100644 --- a/src/Workspaces/Core/Portable/CodeCleanup/Providers/FormatCodeCleanupProvider.cs +++ b/src/Workspaces/Core/Portable/CodeCleanup/Providers/FormatCodeCleanupProvider.cs @@ -14,22 +14,15 @@ namespace Microsoft.CodeAnalysis.CodeCleanup.Providers { - internal sealed class FormatCodeCleanupProvider : ICodeCleanupProvider + internal sealed class FormatCodeCleanupProvider(IEnumerable? rules = null) : ICodeCleanupProvider { - private readonly IEnumerable? _rules; - - public FormatCodeCleanupProvider(IEnumerable? rules = null) - { - _rules = rules; - } - public string Name => PredefinedCodeCleanupProviderNames.Format; public async Task CleanupAsync(Document document, ImmutableArray spans, CodeCleanupOptions options, CancellationToken cancellationToken) { var formatter = document.GetRequiredLanguageService(); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var result = formatter.GetFormattingResult(root, spans, options.FormattingOptions, _rules, cancellationToken); + var result = formatter.GetFormattingResult(root, spans, options.FormattingOptions, rules, cancellationToken); // apply changes to an old text if it already exists return document.TryGetText(out var oldText) @@ -40,7 +33,7 @@ public async Task CleanupAsync(Document document, ImmutableArray CleanupAsync(SyntaxNode root, ImmutableArray spans, SyntaxFormattingOptions options, SolutionServices services, CancellationToken cancellationToken) { var formatter = services.GetRequiredLanguageService(root.Language); - var result = formatter.GetFormattingResult(root, spans, options, _rules, cancellationToken); + var result = formatter.GetFormattingResult(root, spans, options, rules, cancellationToken); // apply changes to an old text if it already exists return (root.SyntaxTree != null && root.SyntaxTree.TryGetText(out var oldText)) diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllProvider.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllProvider.cs index f947bd88320f1..7ed08d1337598 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllProvider.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllProvider.cs @@ -95,20 +95,12 @@ public static FixAllProvider Create( => this.GetFixAsync((FixAllContext)fixAllContext); #endregion - private class CallbackDocumentBasedFixAllProvider : DocumentBasedFixAllProvider + private class CallbackDocumentBasedFixAllProvider( + Func, Task> fixAllAsync, + ImmutableArray supportedFixAllScopes) : DocumentBasedFixAllProvider(supportedFixAllScopes) { - private readonly Func, Task> _fixAllAsync; - - public CallbackDocumentBasedFixAllProvider( - Func, Task> fixAllAsync, - ImmutableArray supportedFixAllScopes) - : base(supportedFixAllScopes) - { - _fixAllAsync = fixAllAsync; - } - protected override Task FixAllAsync(FixAllContext context, Document document, ImmutableArray diagnostics) - => _fixAllAsync(context, document, diagnostics); + => fixAllAsync(context, document, diagnostics); } } } diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/TextChangeMerger.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/TextChangeMerger.cs index cd45150607ab4..f5d30d43257bc 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/TextChangeMerger.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/TextChangeMerger.cs @@ -16,7 +16,7 @@ namespace Microsoft.CodeAnalysis.CodeFixes /// /// Helper to merge many disparate text changes to a single document together into a total set of changes. /// - internal class TextChangeMerger + internal class TextChangeMerger(Document document) { private readonly struct IntervalIntrospector : IIntervalIntrospector { @@ -24,29 +24,22 @@ internal class TextChangeMerger int IIntervalIntrospector.GetLength(TextChange value) => value.Span.Length; } - private readonly Document _oldDocument; - private readonly IDocumentTextDifferencingService _differenceService; + private readonly IDocumentTextDifferencingService _differenceService = document.Project.Solution.Services.GetRequiredService(); private readonly SimpleIntervalTree _totalChangesIntervalTree = SimpleIntervalTree.Create(new IntervalIntrospector(), Array.Empty()); - public TextChangeMerger(Document document) - { - _oldDocument = document; - _differenceService = document.Project.Solution.Services.GetRequiredService(); - } - /// /// Try to merge the changes made to into the tracked changes. If there is any /// conflicting change in with existing changes, then no changes are added. /// public async Task TryMergeChangesAsync(Document newDocument, CancellationToken cancellationToken) { - Debug.Assert(newDocument.Id == _oldDocument.Id); + Debug.Assert(newDocument.Id == document.Id); cancellationToken.ThrowIfCancellationRequested(); var currentChanges = await _differenceService.GetTextChangesAsync( - _oldDocument, newDocument, cancellationToken).ConfigureAwait(false); + document, newDocument, cancellationToken).ConfigureAwait(false); if (AllChangesCanBeApplied(_totalChangesIntervalTree, currentChanges)) { @@ -71,7 +64,7 @@ public async Task GetFinalMergedTextAsync(CancellationToken cancella // WithChanges requires a ordered list of TextChanges without any overlap. var changesToApply = _totalChangesIntervalTree.Distinct().OrderBy(tc => tc.Span.Start); - var oldText = await _oldDocument.GetValueTextAsync(cancellationToken).ConfigureAwait(false); + var oldText = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false); var newText = oldText.WithChanges(changesToApply); return newText; diff --git a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/FixAllProviderInfo.cs b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/FixAllProviderInfo.cs index 7c30b95ceb3df..7b8f147c8a0be 100644 --- a/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/FixAllProviderInfo.cs +++ b/src/Workspaces/Core/Portable/CodeFixesAndRefactorings/FixAllProviderInfo.cs @@ -112,49 +112,30 @@ private FixAllProviderInfo( public abstract bool CanBeFixed(Diagnostic diagnostic); - private class CodeFixerFixAllProviderInfo : FixAllProviderInfo + private class CodeFixerFixAllProviderInfo( + IFixAllProvider fixAllProvider, + IEnumerable supportedDiagnosticIds, + ImmutableArray supportedScopes) : FixAllProviderInfo(fixAllProvider, supportedScopes) { - private readonly IEnumerable _supportedDiagnosticIds; - - public CodeFixerFixAllProviderInfo( - IFixAllProvider fixAllProvider, - IEnumerable supportedDiagnosticIds, - ImmutableArray supportedScopes) - : base(fixAllProvider, supportedScopes) - { - _supportedDiagnosticIds = supportedDiagnosticIds; - } - public override bool CanBeFixed(Diagnostic diagnostic) - => _supportedDiagnosticIds.Contains(diagnostic.Id); + => supportedDiagnosticIds.Contains(diagnostic.Id); } - private class SuppressionFixerFixAllProviderInfo : FixAllProviderInfo + private class SuppressionFixerFixAllProviderInfo( + IFixAllProvider fixAllProvider, + IConfigurationFixProvider suppressionFixer, + ImmutableArray supportedScopes) : FixAllProviderInfo(fixAllProvider, supportedScopes) { - private readonly Func _canBeSuppressedOrUnsuppressed; - - public SuppressionFixerFixAllProviderInfo( - IFixAllProvider fixAllProvider, - IConfigurationFixProvider suppressionFixer, - ImmutableArray supportedScopes) - : base(fixAllProvider, supportedScopes) - { - _canBeSuppressedOrUnsuppressed = suppressionFixer.IsFixableDiagnostic; - } + private readonly Func _canBeSuppressedOrUnsuppressed = suppressionFixer.IsFixableDiagnostic; public override bool CanBeFixed(Diagnostic diagnostic) => _canBeSuppressedOrUnsuppressed(diagnostic); } - private class CodeRefactoringFixAllProviderInfo : FixAllProviderInfo + private class CodeRefactoringFixAllProviderInfo( + IFixAllProvider fixAllProvider, + ImmutableArray supportedScopes) : FixAllProviderInfo(fixAllProvider, supportedScopes) { - public CodeRefactoringFixAllProviderInfo( - IFixAllProvider fixAllProvider, - ImmutableArray supportedScopes) - : base(fixAllProvider, supportedScopes) - { - } - public override bool CanBeFixed(Diagnostic diagnostic) => throw ExceptionUtilities.Unreachable(); } diff --git a/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllProvider.cs b/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllProvider.cs index 2bb4ff04afe87..e5630334ec0de 100644 --- a/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllProvider.cs +++ b/src/Workspaces/Core/Portable/CodeRefactorings/FixAllOccurences/FixAllProvider.cs @@ -91,20 +91,12 @@ public static FixAllProvider Create( return new CallbackDocumentBasedFixAllProvider(fixAllAsync, supportedFixAllScopes); } - private sealed class CallbackDocumentBasedFixAllProvider : DocumentBasedFixAllProvider + private sealed class CallbackDocumentBasedFixAllProvider( + Func>, Task> fixAllAsync, + ImmutableArray supportedFixAllScopes) : DocumentBasedFixAllProvider(supportedFixAllScopes) { - private readonly Func>, Task> _fixAllAsync; - - public CallbackDocumentBasedFixAllProvider( - Func>, Task> fixAllAsync, - ImmutableArray supportedFixAllScopes) - : base(supportedFixAllScopes) - { - _fixAllAsync = fixAllAsync; - } - protected override Task FixAllAsync(FixAllContext context, Document document, Optional> fixAllSpans) - => _fixAllAsync(context, document, fixAllSpans); + => fixAllAsync(context, document, fixAllSpans); } } } diff --git a/src/Workspaces/Core/Portable/Diagnostics/DiagnosticAnalysisResultBuilder.cs b/src/Workspaces/Core/Portable/Diagnostics/DiagnosticAnalysisResultBuilder.cs index 542eda6177f74..b979722942bc7 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/DiagnosticAnalysisResultBuilder.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/DiagnosticAnalysisResultBuilder.cs @@ -17,30 +17,18 @@ namespace Microsoft.CodeAnalysis.Workspaces.Diagnostics /// We have this builder to avoid creating collections unnecessarily. /// Expectation is that, most of time, most of analyzers doesn't have any diagnostics. so no need to actually create any objects. /// - internal struct DiagnosticAnalysisResultBuilder + internal struct DiagnosticAnalysisResultBuilder(Project project, VersionStamp version) { - public readonly Project Project; - public readonly VersionStamp Version; + public readonly Project Project = project; + public readonly VersionStamp Version = version; - private HashSet? _lazyDocumentsWithDiagnostics; + private HashSet? _lazyDocumentsWithDiagnostics = null; - private Dictionary>? _lazySyntaxLocals; - private Dictionary>? _lazySemanticLocals; - private Dictionary>? _lazyNonLocals; + private Dictionary>? _lazySyntaxLocals = null; + private Dictionary>? _lazySemanticLocals = null; + private Dictionary>? _lazyNonLocals = null; - private List? _lazyOthers; - - public DiagnosticAnalysisResultBuilder(Project project, VersionStamp version) - { - Project = project; - Version = version; - - _lazyDocumentsWithDiagnostics = null; - _lazySyntaxLocals = null; - _lazySemanticLocals = null; - _lazyNonLocals = null; - _lazyOthers = null; - } + private List? _lazyOthers = null; public readonly ImmutableHashSet DocumentIds => _lazyDocumentsWithDiagnostics == null ? ImmutableHashSet.Empty : _lazyDocumentsWithDiagnostics.ToImmutableHashSet(); public readonly ImmutableDictionary> SyntaxLocals => Convert(_lazySyntaxLocals); diff --git a/src/Workspaces/Core/Portable/Diagnostics/DiagnosticAnalyzerInfoCache.cs b/src/Workspaces/Core/Portable/Diagnostics/DiagnosticAnalyzerInfoCache.cs index 8d425ae0f4aa5..750435e5c00bf 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/DiagnosticAnalyzerInfoCache.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/DiagnosticAnalyzerInfoCache.cs @@ -44,18 +44,11 @@ internal sealed partial class DiagnosticAnalyzerInfoCache /// private readonly ConcurrentDictionary _idToDescriptorsMap; - private sealed class DiagnosticDescriptorsInfo + private sealed class DiagnosticDescriptorsInfo(ImmutableArray supportedDescriptors, bool telemetryAllowed) { - public readonly ImmutableArray SupportedDescriptors; - public readonly bool TelemetryAllowed; - public readonly bool HasCompilationEndDescriptor; - - public DiagnosticDescriptorsInfo(ImmutableArray supportedDescriptors, bool telemetryAllowed) - { - SupportedDescriptors = supportedDescriptors; - TelemetryAllowed = telemetryAllowed; - HasCompilationEndDescriptor = supportedDescriptors.Any(DiagnosticDescriptorExtensions.IsCompilationEnd); - } + public readonly ImmutableArray SupportedDescriptors = supportedDescriptors; + public readonly bool TelemetryAllowed = telemetryAllowed; + public readonly bool HasCompilationEndDescriptor = supportedDescriptors.Any(DiagnosticDescriptorExtensions.IsCompilationEnd); } [Export, Shared] diff --git a/src/Workspaces/Core/Portable/Diagnostics/DiagnosticData.cs b/src/Workspaces/Core/Portable/Diagnostics/DiagnosticData.cs index 400f5a578188e..576cc8750fcf5 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/DiagnosticData.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/DiagnosticData.cs @@ -18,61 +18,78 @@ namespace Microsoft.CodeAnalysis.Diagnostics { [DataContract] - internal sealed class DiagnosticData : IEquatable + internal sealed class DiagnosticData( + string id, + string category, + string? message, + DiagnosticSeverity severity, + DiagnosticSeverity defaultSeverity, + bool isEnabledByDefault, + int warningLevel, + ImmutableArray customTags, + ImmutableDictionary properties, + ProjectId? projectId, + DiagnosticDataLocation location, + ImmutableArray additionalLocations = default, + string? language = null, + string? title = null, + string? description = null, + string? helpLink = null, + bool isSuppressed = false) : IEquatable { [DataMember(Order = 0)] - public readonly string Id; + public readonly string Id = id; [DataMember(Order = 1)] - public readonly string Category; + public readonly string Category = category; [DataMember(Order = 2)] - public readonly string? Message; + public readonly string? Message = message; [DataMember(Order = 3)] - public readonly DiagnosticSeverity Severity; + public readonly DiagnosticSeverity Severity = severity; [DataMember(Order = 4)] - public readonly DiagnosticSeverity DefaultSeverity; + public readonly DiagnosticSeverity DefaultSeverity = defaultSeverity; [DataMember(Order = 5)] - public readonly bool IsEnabledByDefault; + public readonly bool IsEnabledByDefault = isEnabledByDefault; [DataMember(Order = 6)] - public readonly int WarningLevel; + public readonly int WarningLevel = warningLevel; [DataMember(Order = 7)] - public readonly ImmutableArray CustomTags; + public readonly ImmutableArray CustomTags = customTags; [DataMember(Order = 8)] - public readonly ImmutableDictionary Properties; + public readonly ImmutableDictionary Properties = properties; [DataMember(Order = 9)] - public readonly ProjectId? ProjectId; + public readonly ProjectId? ProjectId = projectId; [DataMember(Order = 10)] - public readonly DiagnosticDataLocation DataLocation; + public readonly DiagnosticDataLocation DataLocation = location; [DataMember(Order = 11)] - public readonly ImmutableArray AdditionalLocations; + public readonly ImmutableArray AdditionalLocations = additionalLocations.NullToEmpty(); /// /// Language name () or null if the diagnostic is not associated with source code. /// [DataMember(Order = 12)] - public readonly string? Language; + public readonly string? Language = language; [DataMember(Order = 13)] - public readonly string? Title; + public readonly string? Title = title; [DataMember(Order = 14)] - public readonly string? Description; + public readonly string? Description = description; [DataMember(Order = 15)] - public readonly string? HelpLink; + public readonly string? HelpLink = helpLink; [DataMember(Order = 16)] - public readonly bool IsSuppressed; + public readonly bool IsSuppressed = isSuppressed; /// /// Properties for a diagnostic generated by an explicit build. @@ -80,47 +97,6 @@ internal sealed class DiagnosticData : IEquatable internal static ImmutableDictionary PropertiesForBuildDiagnostic { get; } = ImmutableDictionary.Empty.Add(WellKnownDiagnosticPropertyNames.Origin, WellKnownDiagnosticTags.Build); - public DiagnosticData( - string id, - string category, - string? message, - DiagnosticSeverity severity, - DiagnosticSeverity defaultSeverity, - bool isEnabledByDefault, - int warningLevel, - ImmutableArray customTags, - ImmutableDictionary properties, - ProjectId? projectId, - DiagnosticDataLocation location, - ImmutableArray additionalLocations = default, - string? language = null, - string? title = null, - string? description = null, - string? helpLink = null, - bool isSuppressed = false) - { - Id = id; - Category = category; - Message = message; - - Severity = severity; - DefaultSeverity = defaultSeverity; - IsEnabledByDefault = isEnabledByDefault; - WarningLevel = warningLevel; - CustomTags = customTags; - Properties = properties; - - ProjectId = projectId; - DataLocation = location; - AdditionalLocations = additionalLocations.NullToEmpty(); - - Language = language; - Title = title; - Description = description; - HelpLink = helpLink; - IsSuppressed = isSuppressed; - } - public DiagnosticData WithLocations(DiagnosticDataLocation location, ImmutableArray additionalLocations) => new(Id, Category, Message, Severity, DefaultSeverity, IsEnabledByDefault, WarningLevel, CustomTags, Properties, ProjectId, location, additionalLocations, diff --git a/src/Workspaces/Core/Portable/Diagnostics/SerializableDiagnosticAnalysisResultMap.cs b/src/Workspaces/Core/Portable/Diagnostics/SerializableDiagnosticAnalysisResultMap.cs index 905849d221f69..8ba5248e5cdb5 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/SerializableDiagnosticAnalysisResultMap.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/SerializableDiagnosticAnalysisResultMap.cs @@ -9,52 +9,38 @@ namespace Microsoft.CodeAnalysis.Diagnostics { [DataContract] - internal readonly struct SerializableDiagnosticAnalysisResults + internal readonly struct SerializableDiagnosticAnalysisResults( + ImmutableArray<(string analyzerId, SerializableDiagnosticMap diagnosticMap)> diagnostics, + ImmutableArray<(string analyzerId, AnalyzerTelemetryInfo)> telemetry) { public static readonly SerializableDiagnosticAnalysisResults Empty = new( ImmutableArray<(string, SerializableDiagnosticMap)>.Empty, ImmutableArray<(string, AnalyzerTelemetryInfo)>.Empty); [DataMember(Order = 0)] - internal readonly ImmutableArray<(string analyzerId, SerializableDiagnosticMap diagnosticMap)> Diagnostics; + internal readonly ImmutableArray<(string analyzerId, SerializableDiagnosticMap diagnosticMap)> Diagnostics = diagnostics; [DataMember(Order = 1)] - internal readonly ImmutableArray<(string analyzerId, AnalyzerTelemetryInfo telemetry)> Telemetry; - - public SerializableDiagnosticAnalysisResults( - ImmutableArray<(string analyzerId, SerializableDiagnosticMap diagnosticMap)> diagnostics, - ImmutableArray<(string analyzerId, AnalyzerTelemetryInfo)> telemetry) - { - Diagnostics = diagnostics; - Telemetry = telemetry; - } + internal readonly ImmutableArray<(string analyzerId, AnalyzerTelemetryInfo telemetry)> Telemetry = telemetry; } [DataContract] - internal readonly struct SerializableDiagnosticMap + internal readonly struct SerializableDiagnosticMap( + ImmutableArray<(DocumentId, ImmutableArray)> syntax, + ImmutableArray<(DocumentId, ImmutableArray)> semantic, + ImmutableArray<(DocumentId, ImmutableArray)> nonLocal, + ImmutableArray other) { [DataMember(Order = 0)] - public readonly ImmutableArray<(DocumentId, ImmutableArray)> Syntax; + public readonly ImmutableArray<(DocumentId, ImmutableArray)> Syntax = syntax; [DataMember(Order = 1)] - public readonly ImmutableArray<(DocumentId, ImmutableArray)> Semantic; + public readonly ImmutableArray<(DocumentId, ImmutableArray)> Semantic = semantic; [DataMember(Order = 2)] - public readonly ImmutableArray<(DocumentId, ImmutableArray)> NonLocal; + public readonly ImmutableArray<(DocumentId, ImmutableArray)> NonLocal = nonLocal; [DataMember(Order = 3)] - public readonly ImmutableArray Other; - - public SerializableDiagnosticMap( - ImmutableArray<(DocumentId, ImmutableArray)> syntax, - ImmutableArray<(DocumentId, ImmutableArray)> semantic, - ImmutableArray<(DocumentId, ImmutableArray)> nonLocal, - ImmutableArray other) - { - Syntax = syntax; - Semantic = semantic; - NonLocal = nonLocal; - Other = other; - } + public readonly ImmutableArray Other = other; } } diff --git a/src/Workspaces/Core/Portable/Diagnostics/WorkspaceAnalyzerOptions.cs b/src/Workspaces/Core/Portable/Diagnostics/WorkspaceAnalyzerOptions.cs index 24a115b519d03..0a0a8d96fbdfb 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/WorkspaceAnalyzerOptions.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/WorkspaceAnalyzerOptions.cs @@ -17,15 +17,9 @@ namespace Microsoft.CodeAnalysis.Diagnostics /// Analyzer options with workspace. /// These are used to fetch the workspace options by our internal analyzers (e.g. simplification analyzer). /// - internal sealed class WorkspaceAnalyzerOptions : AnalyzerOptions + internal sealed class WorkspaceAnalyzerOptions(AnalyzerOptions options, IdeAnalyzerOptions ideOptions) : AnalyzerOptions(options.AdditionalFiles, options.AnalyzerConfigOptionsProvider) { - public IdeAnalyzerOptions IdeOptions { get; } - - public WorkspaceAnalyzerOptions(AnalyzerOptions options, IdeAnalyzerOptions ideOptions) - : base(options.AdditionalFiles, options.AnalyzerConfigOptionsProvider) - { - IdeOptions = ideOptions; - } + public IdeAnalyzerOptions IdeOptions { get; } = ideOptions; public override bool Equals(object obj) { diff --git a/src/Workspaces/Core/Portable/Differencing/LongestCommonSubsequence.cs b/src/Workspaces/Core/Portable/Differencing/LongestCommonSubsequence.cs index 98e2356df8b6d..5e68d431a99b5 100644 --- a/src/Workspaces/Core/Portable/Differencing/LongestCommonSubsequence.cs +++ b/src/Workspaces/Core/Portable/Differencing/LongestCommonSubsequence.cs @@ -190,18 +190,11 @@ public VArray Push() } // VArray struct enables array indexing in range [-d...d]. - protected readonly struct VArray + protected readonly struct VArray(int[] buffer, int start, int length) { - private readonly int[] _buffer; - private readonly int _start; - private readonly int _length; - - public VArray(int[] buffer, int start, int length) - { - _buffer = buffer; - _start = start; - _length = length; - } + private readonly int[] _buffer = buffer; + private readonly int _start = start; + private readonly int _length = length; public void InitializeFrom(VArray other) { diff --git a/src/Workspaces/Core/Portable/Differencing/SequenceEdit.cs b/src/Workspaces/Core/Portable/Differencing/SequenceEdit.cs index 86b365d04e06b..b1b473969c917 100644 --- a/src/Workspaces/Core/Portable/Differencing/SequenceEdit.cs +++ b/src/Workspaces/Core/Portable/Differencing/SequenceEdit.cs @@ -93,15 +93,10 @@ private string GetDebuggerDisplay() internal TestAccessor GetTestAccessor() => new(this); - internal readonly struct TestAccessor + internal readonly struct TestAccessor(SequenceEdit sequenceEdit) { - private readonly SequenceEdit _sequenceEdit; - - public TestAccessor(SequenceEdit sequenceEdit) - => _sequenceEdit = sequenceEdit; - internal string GetDebuggerDisplay() - => _sequenceEdit.GetDebuggerDisplay(); + => sequenceEdit.GetDebuggerDisplay(); } } } diff --git a/src/Workspaces/Core/Portable/Editing/SolutionEditor.cs b/src/Workspaces/Core/Portable/Editing/SolutionEditor.cs index 7dc0732695bf0..e8f95c0cad5fa 100644 --- a/src/Workspaces/Core/Portable/Editing/SolutionEditor.cs +++ b/src/Workspaces/Core/Portable/Editing/SolutionEditor.cs @@ -13,20 +13,14 @@ namespace Microsoft.CodeAnalysis.Editing /// /// An editor for making changes to multiple documents in a solution. /// - public class SolutionEditor + public class SolutionEditor(Solution solution) { - private readonly Solution _solution; private readonly Dictionary _documentEditors = new(); - public SolutionEditor(Solution solution) - { - _solution = solution; - } - /// /// The that was specified when the was constructed. /// - public Solution OriginalSolution => _solution; + public Solution OriginalSolution => solution; /// /// Gets the for the corresponding . @@ -35,7 +29,7 @@ public async Task GetDocumentEditorAsync(DocumentId id, Cancella { if (!_documentEditors.TryGetValue(id, out var editor)) { - editor = await DocumentEditor.CreateAsync(_solution.GetDocument(id), cancellationToken).ConfigureAwait(false); + editor = await DocumentEditor.CreateAsync(solution.GetDocument(id), cancellationToken).ConfigureAwait(false); _documentEditors.Add(id, editor); } @@ -47,7 +41,7 @@ public async Task GetDocumentEditorAsync(DocumentId id, Cancella /// public Solution GetChangedSolution() { - var changedSolution = _solution; + var changedSolution = solution; foreach (var docEd in _documentEditors.Values) { diff --git a/src/Workspaces/Core/Portable/Editing/SyntaxEditor.cs b/src/Workspaces/Core/Portable/Editing/SyntaxEditor.cs index 1fd3be19768c8..f4f3d92dda54e 100644 --- a/src/Workspaces/Core/Portable/Editing/SyntaxEditor.cs +++ b/src/Workspaces/Core/Portable/Editing/SyntaxEditor.cs @@ -244,12 +244,9 @@ private void CheckNodeInOriginalTree(SyntaxNode node) throw new ArgumentException(WorkspacesResources.The_node_is_not_part_of_the_tree, nameof(node)); } - private abstract class Change + private abstract class Change(SyntaxNode node) { - internal readonly SyntaxNode OriginalNode; - - public Change(SyntaxNode node) - => OriginalNode = node; + internal readonly SyntaxNode OriginalNode = node; public SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { @@ -266,29 +263,16 @@ protected static SyntaxNode ValidateNewRoot(SyntaxNode? root) protected abstract SyntaxNode Apply(SyntaxNode root, SyntaxNode currentNode, SyntaxGenerator generator); } - private sealed class NoChange : Change + private sealed class NoChange(SyntaxNode node) : Change(node) { - public NoChange(SyntaxNode node) - : base(node) - { - } - protected override SyntaxNode Apply(SyntaxNode root, SyntaxNode currentNode, SyntaxGenerator generator) => root; } - private sealed class RemoveChange : Change + private sealed class RemoveChange(SyntaxNode node, SyntaxRemoveOptions options) : Change(node) { - private readonly SyntaxRemoveOptions _options; - - public RemoveChange(SyntaxNode node, SyntaxRemoveOptions options) - : base(node) - { - _options = options; - } - protected override SyntaxNode Apply(SyntaxNode root, SyntaxNode currentNode, SyntaxGenerator generator) - => ValidateNewRoot(generator.RemoveNode(root, currentNode, _options)); + => ValidateNewRoot(generator.RemoveNode(root, currentNode, options)); } private sealed class ReplaceChange : Change @@ -308,55 +292,29 @@ protected override SyntaxNode Apply(SyntaxNode root, SyntaxNode currentNode, Syn => ValidateNewRoot(generator.ReplaceNode(root, currentNode, _modifier(currentNode, generator))); } - private sealed class ReplaceWithCollectionChange : Change + private sealed class ReplaceWithCollectionChange( + SyntaxNode node, + Func> modifier) : Change(node) { - private readonly Func> _modifier; - - public ReplaceWithCollectionChange( - SyntaxNode node, - Func> modifier) - : base(node) - { - _modifier = modifier; - } - protected override SyntaxNode Apply(SyntaxNode root, SyntaxNode currentNode, SyntaxGenerator generator) - => SyntaxGenerator.ReplaceNode(root, currentNode, _modifier(currentNode, generator)); + => SyntaxGenerator.ReplaceNode(root, currentNode, modifier(currentNode, generator)); } - private sealed class ReplaceChange : Change + private sealed class ReplaceChange( + SyntaxNode node, + Func modifier, + TArgument argument) : Change(node) { - private readonly Func _modifier; - private readonly TArgument _argument; - - public ReplaceChange( - SyntaxNode node, - Func modifier, - TArgument argument) - : base(node) - { - _modifier = modifier; - _argument = argument; - } - protected override SyntaxNode Apply(SyntaxNode root, SyntaxNode currentNode, SyntaxGenerator generator) - => ValidateNewRoot(generator.ReplaceNode(root, currentNode, _modifier(currentNode, generator, _argument))); + => ValidateNewRoot(generator.ReplaceNode(root, currentNode, modifier(currentNode, generator, argument))); } - private sealed class InsertChange : Change + private sealed class InsertChange(SyntaxNode node, IEnumerable newNodes, bool isBefore) : Change(node) { - private readonly List _newNodes; - private readonly bool _isBefore; - - public InsertChange(SyntaxNode node, IEnumerable newNodes, bool isBefore) - : base(node) - { - _newNodes = newNodes.ToList(); - _isBefore = isBefore; - } + private readonly List _newNodes = newNodes.ToList(); protected override SyntaxNode Apply(SyntaxNode root, SyntaxNode currentNode, SyntaxGenerator generator) - => _isBefore + => isBefore ? generator.InsertNodesBefore(root, currentNode, _newNodes) : generator.InsertNodesAfter(root, currentNode, _newNodes); } diff --git a/src/Workspaces/Core/Portable/ExternalAccess/Pythia/Api/PythiaEditDistanceWrapper.cs b/src/Workspaces/Core/Portable/ExternalAccess/Pythia/Api/PythiaEditDistanceWrapper.cs index 115ae824a636d..04bb4d3f65b30 100644 --- a/src/Workspaces/Core/Portable/ExternalAccess/Pythia/Api/PythiaEditDistanceWrapper.cs +++ b/src/Workspaces/Core/Portable/ExternalAccess/Pythia/Api/PythiaEditDistanceWrapper.cs @@ -7,12 +7,9 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { - internal readonly struct PythiaEditDistanceWrapper : IDisposable + internal readonly struct PythiaEditDistanceWrapper(string str) : IDisposable { - private readonly EditDistance _underlyingObject; - - public PythiaEditDistanceWrapper(string str) - => _underlyingObject = new EditDistance(str); + private readonly EditDistance _underlyingObject = new EditDistance(str); public double GetEditDistance(string target) => _underlyingObject.GetEditDistance(target); diff --git a/src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingChecksumWrapper.cs b/src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingChecksumWrapper.cs index ffe61c0583912..8f34e08a577e7 100644 --- a/src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingChecksumWrapper.cs +++ b/src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingChecksumWrapper.cs @@ -6,12 +6,9 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { - internal readonly struct UnitTestingChecksumWrapper + internal readonly struct UnitTestingChecksumWrapper(Checksum underlyingObject) { - private Checksum UnderlyingObject { get; } - - public UnitTestingChecksumWrapper(Checksum underlyingObject) - => UnderlyingObject = underlyingObject ?? throw new ArgumentNullException(nameof(underlyingObject)); + private Checksum UnderlyingObject { get; } = underlyingObject ?? throw new ArgumentNullException(nameof(underlyingObject)); public bool IsEqualTo(UnitTestingChecksumWrapper other) => other.UnderlyingObject == UnderlyingObject; diff --git a/src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingTextDocumentEventArgsWrapper.cs b/src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingTextDocumentEventArgsWrapper.cs index deb86da6ad60c..563ffbf85544e 100644 --- a/src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingTextDocumentEventArgsWrapper.cs +++ b/src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingTextDocumentEventArgsWrapper.cs @@ -7,13 +7,10 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { - internal readonly struct UnitTestingTextDocumentEventArgsWrapper + internal readonly struct UnitTestingTextDocumentEventArgsWrapper(TextDocumentEventArgs underlyingObject) { - internal TextDocumentEventArgs UnderlyingObject { get; } + internal TextDocumentEventArgs UnderlyingObject { get; } = underlyingObject ?? throw new ArgumentNullException(nameof(underlyingObject)); public TextDocument Document => UnderlyingObject.Document; - - public UnitTestingTextDocumentEventArgsWrapper(TextDocumentEventArgs underlyingObject) - => UnderlyingObject = underlyingObject ?? throw new ArgumentNullException(nameof(underlyingObject)); } } diff --git a/src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/UnitTestingIncrementalAnalyzer.cs b/src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/UnitTestingIncrementalAnalyzer.cs index 073d2adfb1554..554e4e40bfaf7 100644 --- a/src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/UnitTestingIncrementalAnalyzer.cs +++ b/src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/UnitTestingIncrementalAnalyzer.cs @@ -12,46 +12,41 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting { - internal class UnitTestingIncrementalAnalyzer : IIncrementalAnalyzer + internal class UnitTestingIncrementalAnalyzer(IUnitTestingIncrementalAnalyzerImplementation implementation) : IIncrementalAnalyzer { - private readonly IUnitTestingIncrementalAnalyzerImplementation _implementation; - - public UnitTestingIncrementalAnalyzer(IUnitTestingIncrementalAnalyzerImplementation implementation) - => _implementation = implementation; - public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) - => _implementation.AnalyzeDocumentAsync(document, bodyOpt, new UnitTestingInvocationReasonsWrapper(reasons), cancellationToken); + => implementation.AnalyzeDocumentAsync(document, bodyOpt, new UnitTestingInvocationReasonsWrapper(reasons), cancellationToken); public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) - => _implementation.AnalyzeProjectAsync(project, semanticsChanged, new UnitTestingInvocationReasonsWrapper(reasons), cancellationToken); + => implementation.AnalyzeProjectAsync(project, semanticsChanged, new UnitTestingInvocationReasonsWrapper(reasons), cancellationToken); public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) - => _implementation.AnalyzeSyntaxAsync(document, new UnitTestingInvocationReasonsWrapper(reasons), cancellationToken); + => implementation.AnalyzeSyntaxAsync(document, new UnitTestingInvocationReasonsWrapper(reasons), cancellationToken); public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) - => _implementation.DocumentCloseAsync(document, cancellationToken); + => implementation.DocumentCloseAsync(document, cancellationToken); public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) - => _implementation.DocumentOpenAsync(document, cancellationToken); + => implementation.DocumentOpenAsync(document, cancellationToken); public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) - => _implementation.DocumentResetAsync(document, cancellationToken); + => implementation.DocumentResetAsync(document, cancellationToken); public Task ActiveDocumentSwitchedAsync(TextDocument document, CancellationToken cancellationToken) => Task.CompletedTask; public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) - => _implementation.NewSolutionSnapshotAsync(solution, cancellationToken); + => implementation.NewSolutionSnapshotAsync(solution, cancellationToken); public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) { - _implementation.RemoveDocument(documentId); + implementation.RemoveDocument(documentId); return Task.CompletedTask; } public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) { - _implementation.RemoveProject(projectId); + implementation.RemoveProject(projectId); return Task.CompletedTask; } diff --git a/src/Workspaces/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptDocumentationCommentWrapper.cs b/src/Workspaces/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptDocumentationCommentWrapper.cs index 3fafdaa40f90f..3cb5f12022e0c 100644 --- a/src/Workspaces/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptDocumentationCommentWrapper.cs +++ b/src/Workspaces/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptDocumentationCommentWrapper.cs @@ -6,24 +6,19 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { - internal readonly struct VSTypeScriptDocumentationCommentWrapper + internal readonly struct VSTypeScriptDocumentationCommentWrapper(DocumentationComment underlyingObject) { - private readonly DocumentationComment _underlyingObject; - - public VSTypeScriptDocumentationCommentWrapper(DocumentationComment underlyingObject) - => _underlyingObject = underlyingObject; - public static VSTypeScriptDocumentationCommentWrapper FromXmlFragment(string xml) => new(DocumentationComment.FromXmlFragment(xml)); public bool IsDefault - => _underlyingObject == null; + => underlyingObject == null; public string? SummaryTextOpt - => _underlyingObject?.SummaryText; + => underlyingObject?.SummaryText; public string? GetParameterTextOpt(string parameterName) - => _underlyingObject?.GetParameterText(parameterName); + => underlyingObject?.GetParameterText(parameterName); } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_ProjectIndex.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_ProjectIndex.cs index abb7813a4db36..22df0954414ae 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_ProjectIndex.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder_ProjectIndex.cs @@ -14,29 +14,20 @@ namespace Microsoft.CodeAnalysis.FindSymbols { internal static partial class DependentTypeFinder { - private sealed class ProjectIndex + private sealed class ProjectIndex( + MultiDictionary classesAndRecordsThatMayDeriveFromSystemObject, + MultiDictionary valueTypes, + MultiDictionary enums, + MultiDictionary delegates, + MultiDictionary namedTypes) { private static readonly ConditionalWeakTable> s_projectToIndex = new(); - public readonly MultiDictionary ClassesAndRecordsThatMayDeriveFromSystemObject; - public readonly MultiDictionary ValueTypes; - public readonly MultiDictionary Enums; - public readonly MultiDictionary Delegates; - public readonly MultiDictionary NamedTypes; - - public ProjectIndex( - MultiDictionary classesAndRecordsThatMayDeriveFromSystemObject, - MultiDictionary valueTypes, - MultiDictionary enums, - MultiDictionary delegates, - MultiDictionary namedTypes) - { - ClassesAndRecordsThatMayDeriveFromSystemObject = classesAndRecordsThatMayDeriveFromSystemObject; - ValueTypes = valueTypes; - Enums = enums; - Delegates = delegates; - NamedTypes = namedTypes; - } + public readonly MultiDictionary ClassesAndRecordsThatMayDeriveFromSystemObject = classesAndRecordsThatMayDeriveFromSystemObject; + public readonly MultiDictionary ValueTypes = valueTypes; + public readonly MultiDictionary Enums = enums; + public readonly MultiDictionary Delegates = delegates; + public readonly MultiDictionary NamedTypes = namedTypes; public static Task GetIndexAsync( Project project, CancellationToken cancellationToken) diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesDocumentState.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesDocumentState.cs index b63974b370d18..c0f6f3e18ff32 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesDocumentState.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesDocumentState.cs @@ -8,38 +8,24 @@ namespace Microsoft.CodeAnalysis.FindSymbols { - internal class FindReferencesDocumentState + internal class FindReferencesDocumentState( + Document document, + SemanticModel semanticModel, + SyntaxNode root, + FindReferenceCache cache, + HashSet? globalAliases) { private static readonly HashSet s_empty = new(); - public readonly Document Document; - public readonly SemanticModel SemanticModel; - public readonly SyntaxNode Root; - public readonly FindReferenceCache Cache; - public readonly HashSet GlobalAliases; + public readonly Document Document = document; + public readonly SemanticModel SemanticModel = semanticModel; + public readonly SyntaxNode Root = root; + public readonly FindReferenceCache Cache = cache; + public readonly HashSet GlobalAliases = globalAliases ?? s_empty; - public readonly Solution Solution; - public readonly SyntaxTree SyntaxTree; - public readonly ISyntaxFactsService SyntaxFacts; - public readonly ISemanticFactsService SemanticFacts; - - public FindReferencesDocumentState( - Document document, - SemanticModel semanticModel, - SyntaxNode root, - FindReferenceCache cache, - HashSet? globalAliases) - { - Document = document; - SemanticModel = semanticModel; - Root = root; - Cache = cache; - GlobalAliases = globalAliases ?? s_empty; - - Solution = document.Project.Solution; - SyntaxTree = semanticModel.SyntaxTree; - SyntaxFacts = document.GetRequiredLanguageService(); - SemanticFacts = document.GetRequiredLanguageService(); - } + public readonly Solution Solution = document.Project.Solution; + public readonly SyntaxTree SyntaxTree = semanticModel.SyntaxTree; + public readonly ISyntaxFactsService SyntaxFacts = document.GetRequiredLanguageService(); + public readonly ISemanticFactsService SemanticFacts = document.GetRequiredLanguageService(); } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs index 1b2de9b3250bd..9eb7677806792 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs @@ -14,12 +14,9 @@ internal partial class FindReferencesSearchEngine /// A symbol set used when the find refs caller does not want cascading. This is a trivial impl that basically /// just wraps the initial symbol provided and doesn't need to do anything beyond that. /// - private sealed class NonCascadingSymbolSet : SymbolSet + private sealed class NonCascadingSymbolSet(FindReferencesSearchEngine engine, MetadataUnifyingSymbolHashSet searchSymbols) : SymbolSet(engine) { - private readonly ImmutableArray _symbols; - - public NonCascadingSymbolSet(FindReferencesSearchEngine engine, MetadataUnifyingSymbolHashSet searchSymbols) : base(engine) - => _symbols = searchSymbols.ToImmutableArray(); + private readonly ImmutableArray _symbols = searchSymbols.ToImmutableArray(); public override ImmutableArray GetAllSymbols() => _symbols; diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.UnidirectionalSymbolSet.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.UnidirectionalSymbolSet.cs index 0ca82137e9063..f89728a31b054 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.UnidirectionalSymbolSet.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.UnidirectionalSymbolSet.cs @@ -22,32 +22,24 @@ internal partial class FindReferencesSearchEngine /// runtime. See the docs of for more /// information on this. /// - private sealed class UnidirectionalSymbolSet : SymbolSet + private sealed class UnidirectionalSymbolSet( + FindReferencesSearchEngine engine, + MetadataUnifyingSymbolHashSet initialSymbols, + MetadataUnifyingSymbolHashSet upSymbols) : SymbolSet(engine) { - private readonly MetadataUnifyingSymbolHashSet _initialAndDownSymbols; /// /// When we're doing a unidirectional find-references, the initial set of up-symbols can never change. /// That's because we have computed the up set entirely up front, and no down symbols can produce new /// up-symbols (as going down then up would not be unidirectional). /// - private readonly ImmutableHashSet _upSymbols; - - public UnidirectionalSymbolSet( - FindReferencesSearchEngine engine, - MetadataUnifyingSymbolHashSet initialSymbols, - MetadataUnifyingSymbolHashSet upSymbols) - : base(engine) - { - _initialAndDownSymbols = initialSymbols; - _upSymbols = upSymbols.ToImmutableHashSet(MetadataUnifyingEquivalenceComparer.Instance); - } + private readonly ImmutableHashSet _upSymbols = upSymbols.ToImmutableHashSet(MetadataUnifyingEquivalenceComparer.Instance); public override ImmutableArray GetAllSymbols() { var result = new MetadataUnifyingSymbolHashSet(); result.AddRange(_upSymbols); - result.AddRange(_initialAndDownSymbols); + result.AddRange(initialSymbols); return result.ToImmutableArray(); } @@ -55,7 +47,7 @@ public override async Task InheritanceCascadeAsync(Project project, Cancellation { // Start searching using the existing set of symbols found at the start (or anything found below that). var workQueue = new Stack(); - workQueue.Push(_initialAndDownSymbols); + workQueue.Push(initialSymbols); var projects = ImmutableHashSet.Create(project); @@ -64,7 +56,7 @@ public override async Task InheritanceCascadeAsync(Project project, Cancellation var current = workQueue.Pop(); // Keep adding symbols downwards in this project as long as we keep finding new symbols. - await AddDownSymbolsAsync(this.Engine, current, _initialAndDownSymbols, workQueue, projects, cancellationToken).ConfigureAwait(false); + await AddDownSymbolsAsync(this.Engine, current, initialSymbols, workQueue, projects, cancellationToken).ConfigureAwait(false); } } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/FinderLocation.cs b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/FinderLocation.cs index 7533d1f6590e3..7efa9393cd87d 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/FinderLocation.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/FinderLocation.cs @@ -4,14 +4,14 @@ namespace Microsoft.CodeAnalysis.FindSymbols.Finders { - internal readonly struct FinderLocation + internal readonly struct FinderLocation(SyntaxNode node, ReferenceLocation location) { /// /// The actual node that we found the reference on. Normally the 'Name' portion /// of any piece of syntax. Might also be something like a 'foreach' statement node /// when finding results for something like GetEnumerator. /// - public readonly SyntaxNode Node; + public readonly SyntaxNode Node = node; /// /// The location we want want to return through the FindRefs API. The location contains @@ -24,13 +24,7 @@ internal readonly struct FinderLocation /// location we will take the user to will be the zero-length position immediately preceding /// the `[` character. /// - public readonly ReferenceLocation Location; - - public FinderLocation(SyntaxNode node, ReferenceLocation location) - { - Node = node; - Location = location; - } + public readonly ReferenceLocation Location = location; public void Deconstruct(out SyntaxNode node, out ReferenceLocation location) { diff --git a/src/Workspaces/Core/Portable/FindSymbols/ReferencedSymbol.cs b/src/Workspaces/Core/Portable/FindSymbols/ReferencedSymbol.cs index 6d00873881c7c..f2a9b2753fc9a 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/ReferencedSymbol.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/ReferencedSymbol.cs @@ -55,15 +55,10 @@ private string GetDebuggerDisplay() internal TestAccessor GetTestAccessor() => new(this); - internal readonly struct TestAccessor + internal readonly struct TestAccessor(ReferencedSymbol referencedSymbol) { - private readonly ReferencedSymbol _referencedSymbol; - - public TestAccessor(ReferencedSymbol referencedSymbol) - => _referencedSymbol = referencedSymbol; - internal string GetDebuggerDisplay() - => _referencedSymbol.GetDebuggerDisplay(); + => referencedSymbol.GetDebuggerDisplay(); } } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/StreamingProgressCollector.cs b/src/Workspaces/Core/Portable/FindSymbols/StreamingProgressCollector.cs index 005c24ffff2f5..02a6c61b38482 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/StreamingProgressCollector.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/StreamingProgressCollector.cs @@ -23,26 +23,19 @@ namespace Microsoft.CodeAnalysis.FindSymbols /// APIs to return all the results at the end of the operation, as opposed to broadcasting /// the results as they are found. /// - internal class StreamingProgressCollector : IStreamingFindReferencesProgress + internal class StreamingProgressCollector( + IStreamingFindReferencesProgress underlyingProgress) : IStreamingFindReferencesProgress { private readonly object _gate = new(); - private readonly IStreamingFindReferencesProgress _underlyingProgress; - private readonly Dictionary> _symbolToLocations = new(); - public IStreamingProgressTracker ProgressTracker => _underlyingProgress.ProgressTracker; + public IStreamingProgressTracker ProgressTracker => underlyingProgress.ProgressTracker; public StreamingProgressCollector() : this(NoOpStreamingFindReferencesProgress.Instance) { } - public StreamingProgressCollector( - IStreamingFindReferencesProgress underlyingProgress) - { - _underlyingProgress = underlyingProgress; - } - public ImmutableArray GetReferencedSymbols() { lock (_gate) @@ -55,11 +48,11 @@ public ImmutableArray GetReferencedSymbols() } } - public ValueTask OnStartedAsync(CancellationToken cancellationToken) => _underlyingProgress.OnStartedAsync(cancellationToken); - public ValueTask OnCompletedAsync(CancellationToken cancellationToken) => _underlyingProgress.OnCompletedAsync(cancellationToken); + public ValueTask OnStartedAsync(CancellationToken cancellationToken) => underlyingProgress.OnStartedAsync(cancellationToken); + public ValueTask OnCompletedAsync(CancellationToken cancellationToken) => underlyingProgress.OnCompletedAsync(cancellationToken); - public ValueTask OnFindInDocumentCompletedAsync(Document document, CancellationToken cancellationToken) => _underlyingProgress.OnFindInDocumentCompletedAsync(document, cancellationToken); - public ValueTask OnFindInDocumentStartedAsync(Document document, CancellationToken cancellationToken) => _underlyingProgress.OnFindInDocumentStartedAsync(document, cancellationToken); + public ValueTask OnFindInDocumentCompletedAsync(Document document, CancellationToken cancellationToken) => underlyingProgress.OnFindInDocumentCompletedAsync(document, cancellationToken); + public ValueTask OnFindInDocumentStartedAsync(Document document, CancellationToken cancellationToken) => underlyingProgress.OnFindInDocumentStartedAsync(document, cancellationToken); public ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken cancellationToken) { @@ -71,7 +64,7 @@ public ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken can _symbolToLocations[definition] = new List(); } - return _underlyingProgress.OnDefinitionFoundAsync(group, cancellationToken); + return underlyingProgress.OnDefinitionFoundAsync(group, cancellationToken); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { @@ -86,7 +79,7 @@ public ValueTask OnReferenceFoundAsync(SymbolGroup group, ISymbol definition, Re _symbolToLocations[definition].Add(location); } - return _underlyingProgress.OnReferenceFoundAsync(group, definition, location, cancellationToken); + return underlyingProgress.OnReferenceFoundAsync(group, definition, location, cancellationToken); } } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.FindLiteralsServerCallback.cs b/src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.FindLiteralsServerCallback.cs index 1b0d8e6b7afe4..99b15be523fb7 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.FindLiteralsServerCallback.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.FindLiteralsServerCallback.cs @@ -12,29 +12,20 @@ namespace Microsoft.CodeAnalysis.FindSymbols { public static partial class SymbolFinder { - internal sealed class FindLiteralsServerCallback + internal sealed class FindLiteralsServerCallback( + Solution solution, + IStreamingFindLiteralReferencesProgress progress) { - private readonly Solution _solution; - private readonly IStreamingFindLiteralReferencesProgress _progress; - - public FindLiteralsServerCallback( - Solution solution, - IStreamingFindLiteralReferencesProgress progress) - { - _solution = solution; - _progress = progress; - } - public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) - => _progress.ProgressTracker.AddItemsAsync(count, cancellationToken); + => progress.ProgressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemsCompletedAsync(int count, CancellationToken cancellationToken) - => _progress.ProgressTracker.ItemsCompletedAsync(count, cancellationToken); + => progress.ProgressTracker.ItemsCompletedAsync(count, cancellationToken); public async ValueTask OnLiteralReferenceFoundAsync(DocumentId documentId, TextSpan span, CancellationToken cancellationToken) { - var document = _solution.GetRequiredDocument(documentId); - await _progress.OnReferenceFoundAsync(document, span, cancellationToken).ConfigureAwait(false); + var document = solution.GetRequiredDocument(documentId); + await progress.OnReferenceFoundAsync(document, span, cancellationToken).ConfigureAwait(false); } } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.FindReferencesServerCallback.cs b/src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.FindReferencesServerCallback.cs index 1c26f07869644..5bb143b0512ac 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.FindReferencesServerCallback.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.FindReferencesServerCallback.cs @@ -20,45 +20,36 @@ public static partial class SymbolFinder /// Callback object we pass to the OOP server to hear about the result /// of the FindReferencesEngine as it executes there. /// - internal sealed class FindReferencesServerCallback + internal sealed class FindReferencesServerCallback( + Solution solution, + IStreamingFindReferencesProgress progress) { - private readonly Solution _solution; - private readonly IStreamingFindReferencesProgress _progress; - private readonly object _gate = new(); private readonly Dictionary _groupMap = new(); private readonly Dictionary _definitionMap = new(); - public FindReferencesServerCallback( - Solution solution, - IStreamingFindReferencesProgress progress) - { - _solution = solution; - _progress = progress; - } - public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) - => _progress.ProgressTracker.AddItemsAsync(count, cancellationToken); + => progress.ProgressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemsCompletedAsync(int count, CancellationToken cancellationToken) - => _progress.ProgressTracker.ItemsCompletedAsync(count, cancellationToken); + => progress.ProgressTracker.ItemsCompletedAsync(count, cancellationToken); public ValueTask OnStartedAsync(CancellationToken cancellationToken) - => _progress.OnStartedAsync(cancellationToken); + => progress.OnStartedAsync(cancellationToken); public ValueTask OnCompletedAsync(CancellationToken cancellationToken) - => _progress.OnCompletedAsync(cancellationToken); + => progress.OnCompletedAsync(cancellationToken); public async ValueTask OnFindInDocumentStartedAsync(DocumentId documentId, CancellationToken cancellationToken) { - var document = await _solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); - await _progress.OnFindInDocumentStartedAsync(document, cancellationToken).ConfigureAwait(false); + var document = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); + await progress.OnFindInDocumentStartedAsync(document, cancellationToken).ConfigureAwait(false); } public async ValueTask OnFindInDocumentCompletedAsync(DocumentId documentId, CancellationToken cancellationToken) { - var document = await _solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); - await _progress.OnFindInDocumentCompletedAsync(document, cancellationToken).ConfigureAwait(false); + var document = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); + await progress.OnFindInDocumentCompletedAsync(document, cancellationToken).ConfigureAwait(false); } public async ValueTask OnDefinitionFoundAsync(SerializableSymbolGroup dehydrated, CancellationToken cancellationToken) @@ -69,7 +60,7 @@ public async ValueTask OnDefinitionFoundAsync(SerializableSymbolGroup dehydrated foreach (var symbolAndProjectId in dehydrated.Symbols) { - var symbol = await symbolAndProjectId.TryRehydrateAsync(_solution, cancellationToken).ConfigureAwait(false); + var symbol = await symbolAndProjectId.TryRehydrateAsync(solution, cancellationToken).ConfigureAwait(false); if (symbol == null) return; @@ -84,7 +75,7 @@ public async ValueTask OnDefinitionFoundAsync(SerializableSymbolGroup dehydrated _definitionMap[pair.Key] = pair.Value; } - await _progress.OnDefinitionFoundAsync(symbolGroup, cancellationToken).ConfigureAwait(false); + await progress.OnDefinitionFoundAsync(symbolGroup, cancellationToken).ConfigureAwait(false); } public async ValueTask OnReferenceFoundAsync( @@ -112,9 +103,9 @@ public async ValueTask OnReferenceFoundAsync( } var referenceLocation = await reference.RehydrateAsync( - _solution, cancellationToken).ConfigureAwait(false); + solution, cancellationToken).ConfigureAwait(false); - await _progress.OnReferenceFoundAsync(symbolGroup, symbol, referenceLocation, cancellationToken).ConfigureAwait(false); + await progress.OnReferenceFoundAsync(symbolGroup, symbol, referenceLocation, cancellationToken).ConfigureAwait(false); } } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo.Node.cs b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo.Node.cs index 4cddecc696ca7..43ba11acad848 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo.Node.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo.Node.cs @@ -22,20 +22,13 @@ internal partial class SymbolTreeInfo /// these to s. /// [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] - private readonly struct BuilderNode + private readonly struct BuilderNode(string name, int parentIndex, MultiDictionary.ValueSet parameterTypeInfos = default) { public static readonly BuilderNode RootNode = new("", RootNodeParentIndex, default); - public readonly string Name; - public readonly int ParentIndex; - public readonly MultiDictionary.ValueSet ParameterTypeInfos; - - public BuilderNode(string name, int parentIndex, MultiDictionary.ValueSet parameterTypeInfos = default) - { - Name = name; - ParentIndex = parentIndex; - ParameterTypeInfos = parameterTypeInfos; - } + public readonly string Name = name; + public readonly int ParentIndex = parentIndex; + public readonly MultiDictionary.ValueSet ParameterTypeInfos = parameterTypeInfos; public bool IsRoot => ParentIndex == RootNodeParentIndex; @@ -44,25 +37,19 @@ private string GetDebuggerDisplay() } [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] - private readonly struct Node + private readonly struct Node(string name, int parentIndex) { /// /// The Name of this Node. /// - public readonly string Name; + public readonly string Name = name; /// /// Index in of the parent Node of this Node. /// Value will be if this is the /// Node corresponding to the root symbol. /// - public readonly int ParentIndex; - - public Node(string name, int parentIndex) - { - Name = name; - ParentIndex = parentIndex; - } + public readonly int ParentIndex = parentIndex; public bool IsRoot => ParentIndex == RootNodeParentIndex; @@ -76,14 +63,14 @@ private string GetDebuggerDisplay() => Name + ", " + ParentIndex; } - private readonly struct ParameterTypeInfo + private readonly struct ParameterTypeInfo(string name, bool isComplex, bool isArray) { /// /// This is the type name of the parameter when is false. /// For array types, this is just the elemtent type name. /// e.g. `int` for `int[][,]` /// - public readonly string Name; + public readonly string Name = name; /// /// Indicate if the type of parameter is any kind of array. @@ -92,7 +79,7 @@ private readonly struct ParameterTypeInfo /// - array of complex type like T[], T[][], etc are all represented as "[]" in index, /// in contrast to just "" for non-array types. /// - public readonly bool IsArray; + public readonly bool IsArray = isArray; /// /// Similar to , we divide extension methods into @@ -106,34 +93,21 @@ private readonly struct ParameterTypeInfo /// - By reference type of any types above /// - Array types with element of any types above /// - public readonly bool IsComplexType; - - public ParameterTypeInfo(string name, bool isComplex, bool isArray) - { - Name = name; - IsComplexType = isComplex; - IsArray = isArray; - } + public readonly bool IsComplexType = isComplex; } - public readonly struct ExtensionMethodInfo + public readonly struct ExtensionMethodInfo(string fullyQualifiedContainerName, string name) { /// /// Name of the extension method. /// This can be used to retrive corresponding symbols via /// - public readonly string Name; + public readonly string Name = name; /// /// Fully qualified name for the type that contains this extension method. /// - public readonly string FullyQualifiedContainerName; - - public ExtensionMethodInfo(string fullyQualifiedContainerName, string name) - { - FullyQualifiedContainerName = fullyQualifiedContainerName; - Name = name; - } + public readonly string FullyQualifiedContainerName = fullyQualifiedContainerName; } private sealed class ParameterTypeInfoProvider : ISignatureTypeProvider diff --git a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfoCacheService.cs b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfoCacheService.cs index 859c8af0e2157..af48bb4af2848 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfoCacheService.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfoCacheService.cs @@ -236,21 +236,14 @@ private void RemoveMetadataReferences(ProjectId projectId) public TestAccessor GetTestAccessor() => new(this); - public struct TestAccessor + public struct TestAccessor(SymbolTreeInfoCacheService service) { - private readonly SymbolTreeInfoCacheService _services; - - public TestAccessor(SymbolTreeInfoCacheService service) - { - _services = service; - } - public readonly Task AnalyzeSolutionAsync() { - foreach (var projectId in _services._workspace.CurrentSolution.ProjectIds) - _services._workQueue.AddWork(projectId); + foreach (var projectId in service._workspace.CurrentSolution.ProjectIds) + service._workQueue.AddWork(projectId); - return _services._workQueue.WaitUntilCurrentBatchCompletesAsync(); + return service._workQueue.WaitUntilCurrentBatchCompletesAsync(); } } } diff --git a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfoCacheServiceFactory.cs b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfoCacheServiceFactory.cs index 85772f815bdf9..818cf4d2884f4 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfoCacheServiceFactory.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfoCacheServiceFactory.cs @@ -11,17 +11,12 @@ namespace Microsoft.CodeAnalysis.FindSymbols.SymbolTree; [ExportWorkspaceServiceFactory(typeof(ISymbolTreeInfoCacheService)), Shared] -internal sealed partial class SymbolTreeInfoCacheServiceFactory : IWorkspaceServiceFactory +[method: ImportingConstructor] +[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] +internal sealed partial class SymbolTreeInfoCacheServiceFactory( + IAsynchronousOperationListenerProvider listenerProvider) : IWorkspaceServiceFactory { - private readonly IAsynchronousOperationListener _listener; - - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public SymbolTreeInfoCacheServiceFactory( - IAsynchronousOperationListenerProvider listenerProvider) - { - _listener = listenerProvider.GetListener(FeatureAttribute.SolutionCrawlerLegacy); - } + private readonly IAsynchronousOperationListener _listener = listenerProvider.GetListener(FeatureAttribute.SolutionCrawlerLegacy); public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new SymbolTreeInfoCacheService(workspaceServices.Workspace, _listener); diff --git a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs index 17940e9387814..07b438fcceb3b 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs @@ -256,17 +256,14 @@ private static string GetMetadataKeySuffix(PortableExecutableReference reference cancellationToken); } - private struct MetadataInfoCreator : IDisposable + private struct MetadataInfoCreator( + Checksum checksum, Metadata? metadata) : IDisposable { private static readonly Predicate s_isNotNullOrEmpty = s => !string.IsNullOrEmpty(s); private static readonly ObjectPool> s_stringListPool = SharedPools.Default>(); - - private readonly Checksum _checksum; - private readonly Metadata? _metadata; - - private readonly OrderPreservingMultiDictionary _inheritanceMap; - private readonly OrderPreservingMultiDictionary _parentToChildren; - private readonly MetadataNode _rootNode; + private readonly OrderPreservingMultiDictionary _inheritanceMap = OrderPreservingMultiDictionary.GetInstance(); + private readonly OrderPreservingMultiDictionary _parentToChildren = OrderPreservingMultiDictionary.GetInstance(); + private readonly MetadataNode _rootNode = MetadataNode.Allocate(name: ""); // The set of type definitions we've read out of the current metadata reader. private readonly List _allTypeDefinitions = new(); @@ -279,19 +276,7 @@ private struct MetadataInfoCreator : IDisposable // public static bool AnotherExtensionMethod1(this bool x); // private readonly MultiDictionary _extensionMethodToParameterTypeInfo = new(); - private bool _containsExtensionsMethod; - - public MetadataInfoCreator( - Checksum checksum, Metadata? metadata) - { - _checksum = checksum; - _metadata = metadata; - _containsExtensionsMethod = false; - - _inheritanceMap = OrderPreservingMultiDictionary.GetInstance(); - _parentToChildren = OrderPreservingMultiDictionary.GetInstance(); - _rootNode = MetadataNode.Allocate(name: ""); - } + private bool _containsExtensionsMethod = false; private static ImmutableArray GetModuleMetadata(Metadata? metadata) { @@ -318,7 +303,7 @@ private static ImmutableArray GetModuleMetadata(Metadata? metada internal SymbolTreeInfo Create() { - foreach (var moduleMetadata in GetModuleMetadata(_metadata)) + foreach (var moduleMetadata in GetModuleMetadata(metadata)) { try { @@ -348,7 +333,7 @@ internal SymbolTreeInfo Create() var unsortedNodes = GenerateUnsortedNodes(receiverTypeNameToExtensionMethodMap); return CreateSymbolTreeInfo( - _checksum, unsortedNodes, _inheritanceMap, receiverTypeNameToExtensionMethodMap); + checksum, unsortedNodes, _inheritanceMap, receiverTypeNameToExtensionMethodMap); } public readonly void Dispose() @@ -842,32 +827,23 @@ private enum MetadataDefinitionKind Member, } - private readonly struct MetadataDefinition + private readonly struct MetadataDefinition( + MetadataDefinitionKind kind, + string name, + ParameterTypeInfo receiverTypeInfo = default, + NamespaceDefinition @namespace = default, + TypeDefinition type = default) { - public string Name { get; } - public MetadataDefinitionKind Kind { get; } + public string Name { get; } = name; + public MetadataDefinitionKind Kind { get; } = kind; /// /// Only applies to member kind. Represents the type info of the first parameter. /// - public ParameterTypeInfo ReceiverTypeInfo { get; } - - public NamespaceDefinition Namespace { get; } - public TypeDefinition Type { get; } + public ParameterTypeInfo ReceiverTypeInfo { get; } = receiverTypeInfo; - public MetadataDefinition( - MetadataDefinitionKind kind, - string name, - ParameterTypeInfo receiverTypeInfo = default, - NamespaceDefinition @namespace = default, - TypeDefinition type = default) - { - Kind = kind; - Name = name; - ReceiverTypeInfo = receiverTypeInfo; - Namespace = @namespace; - Type = type; - } + public NamespaceDefinition Namespace { get; } = @namespace; + public TypeDefinition Type { get; } = type; public static MetadataDefinition Create( MetadataReader reader, NamespaceDefinitionHandle namespaceHandle) diff --git a/src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex.IdentifierInfo.cs b/src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex.IdentifierInfo.cs index 4d69a45bc65f0..a664678825c56 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex.IdentifierInfo.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex.IdentifierInfo.cs @@ -10,18 +10,12 @@ namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SyntaxTreeIndex { - private readonly struct IdentifierInfo + private readonly struct IdentifierInfo( + BloomFilter identifierFilter, + BloomFilter escapedIdentifierFilter) { - private readonly BloomFilter _identifierFilter; - private readonly BloomFilter _escapedIdentifierFilter; - - public IdentifierInfo( - BloomFilter identifierFilter, - BloomFilter escapedIdentifierFilter) - { - _identifierFilter = identifierFilter ?? throw new ArgumentNullException(nameof(identifierFilter)); - _escapedIdentifierFilter = escapedIdentifierFilter ?? throw new ArgumentNullException(nameof(escapedIdentifierFilter)); - } + private readonly BloomFilter _identifierFilter = identifierFilter ?? throw new ArgumentNullException(nameof(identifierFilter)); + private readonly BloomFilter _escapedIdentifierFilter = escapedIdentifierFilter ?? throw new ArgumentNullException(nameof(escapedIdentifierFilter)); /// /// Returns true when the identifier is probably (but not guaranteed) to be within the diff --git a/src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex.LiteralInfo.cs b/src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex.LiteralInfo.cs index ce2f3f57e3f9c..fb2efa9f95e91 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex.LiteralInfo.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex.LiteralInfo.cs @@ -10,12 +10,9 @@ namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SyntaxTreeIndex { - private readonly struct LiteralInfo + private readonly struct LiteralInfo(BloomFilter literalsFilter) { - private readonly BloomFilter _literalsFilter; - - public LiteralInfo(BloomFilter literalsFilter) - => _literalsFilter = literalsFilter ?? throw new ArgumentNullException(nameof(literalsFilter)); + private readonly BloomFilter _literalsFilter = literalsFilter ?? throw new ArgumentNullException(nameof(literalsFilter)); /// /// Returns true when the identifier is probably (but not guaranteed) to be within the diff --git a/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/DeclaredSymbolInfo.cs b/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/DeclaredSymbolInfo.cs index d20e62242d597..e2b3ab9c31a01 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/DeclaredSymbolInfo.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/DeclaredSymbolInfo.cs @@ -37,19 +37,27 @@ internal enum DeclaredSymbolInfoKind : byte } [DataContract] - internal readonly struct DeclaredSymbolInfo : IEquatable + [method: Obsolete("Do not call directly. Only around for serialization. Use Create instead")] + internal readonly struct DeclaredSymbolInfo( + string name, + string? nameSuffix, + string? containerDisplayName, + string fullyQualifiedContainerName, + TextSpan span, + ImmutableArray inheritanceNames, + uint flags) : IEquatable { /// /// The name to pattern match against, and to show in a final presentation layer. /// [DataMember(Order = 0)] - public readonly string Name; + public readonly string Name = name; /// /// An optional suffix to be shown in a presentation layer appended to . /// [DataMember(Order = 1)] - public readonly string? NameSuffix; + public readonly string? NameSuffix = nameSuffix; /// /// Container of the symbol that can be shown in a final presentation layer. @@ -59,7 +67,7 @@ internal enum DeclaredSymbolInfoKind : byte /// to indicate where the symbol is located. /// [DataMember(Order = 2)] - public readonly string? ContainerDisplayName; + public readonly string? ContainerDisplayName = containerDisplayName; /// /// Dotted container name of the symbol, used for pattern matching. For example @@ -69,21 +77,21 @@ internal enum DeclaredSymbolInfoKind : byte /// match against this. This should not be shown in a presentation layer. /// [DataMember(Order = 3)] - public readonly string FullyQualifiedContainerName; + public readonly string FullyQualifiedContainerName = fullyQualifiedContainerName; [DataMember(Order = 4)] - public readonly TextSpan Span; + public readonly TextSpan Span = span; /// /// The names directly referenced in source that this type inherits from. /// [DataMember(Order = 5)] - public ImmutableArray InheritanceNames { get; } + public ImmutableArray InheritanceNames { get; } = inheritanceNames; // Store the kind (5 bits), accessibility (4 bits), parameter-count (4 bits), and type-parameter-count (4 bits) // in a single int. [DataMember(Order = 6)] - private readonly uint _flags; + private readonly uint _flags = flags; private const uint Lower4BitMask = 0b1111; private const uint Lower5BitMask = 0b11111; @@ -96,25 +104,6 @@ internal enum DeclaredSymbolInfoKind : byte public bool IsPartial => GetIsPartial(_flags); public bool HasAttributes => GetHasAttributes(_flags); - [Obsolete("Do not call directly. Only around for serialization. Use Create instead")] - public DeclaredSymbolInfo( - string name, - string? nameSuffix, - string? containerDisplayName, - string fullyQualifiedContainerName, - TextSpan span, - ImmutableArray inheritanceNames, - uint flags) - { - Name = name; - NameSuffix = nameSuffix; - ContainerDisplayName = containerDisplayName; - FullyQualifiedContainerName = fullyQualifiedContainerName; - Span = span; - InheritanceNames = inheritanceNames; - _flags = flags; - } - public static DeclaredSymbolInfo Create( StringTable stringTable, string name, diff --git a/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex.DeclarationInfo.cs b/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex.DeclarationInfo.cs index f1d7d70cccfde..d44f5ca36cee8 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex.DeclarationInfo.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex.DeclarationInfo.cs @@ -11,12 +11,9 @@ namespace Microsoft.CodeAnalysis.FindSymbols { internal sealed partial class TopLevelSyntaxTreeIndex { - private readonly struct DeclarationInfo + private readonly struct DeclarationInfo(ImmutableArray declaredSymbolInfos) { - public ImmutableArray DeclaredSymbolInfos { get; } - - public DeclarationInfo(ImmutableArray declaredSymbolInfos) - => DeclaredSymbolInfos = declaredSymbolInfos; + public ImmutableArray DeclaredSymbolInfos { get; } = declaredSymbolInfos; public void WriteTo(ObjectWriter writer) { diff --git a/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex.ExtensionMethodInfo.cs b/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex.ExtensionMethodInfo.cs index 02c956d880ca0..3e10b8d41fdbb 100644 --- a/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex.ExtensionMethodInfo.cs +++ b/src/Workspaces/Core/Portable/FindSymbols/TopLevelSyntaxTree/TopLevelSyntaxTreeIndex.ExtensionMethodInfo.cs @@ -11,7 +11,7 @@ namespace Microsoft.CodeAnalysis.FindSymbols { internal sealed partial class TopLevelSyntaxTreeIndex { - private readonly struct ExtensionMethodInfo + private readonly struct ExtensionMethodInfo(ImmutableDictionary> receiverTypeNameToExtensionMethodMap) { // We divide extension methods into two categories, simple and complex, for filtering purpose. // Whether a method is simple is determined based on if we can determine it's receiver type easily @@ -39,15 +39,10 @@ private readonly struct ExtensionMethodInfo /// T (where T is a type parameter) => "" /// T[,] (where T is a type parameter) => "T[]" /// - public readonly ImmutableDictionary> ReceiverTypeNameToExtensionMethodMap { get; } + public readonly ImmutableDictionary> ReceiverTypeNameToExtensionMethodMap { get; } = receiverTypeNameToExtensionMethodMap; public bool ContainsExtensionMethod => !ReceiverTypeNameToExtensionMethodMap.IsEmpty; - public ExtensionMethodInfo(ImmutableDictionary> receiverTypeNameToExtensionMethodMap) - { - ReceiverTypeNameToExtensionMethodMap = receiverTypeNameToExtensionMethodMap; - } - public void WriteTo(ObjectWriter writer) { writer.WriteInt32(ReceiverTypeNameToExtensionMethodMap.Count); diff --git a/src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileDiffMergingSession.cs b/src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileDiffMergingSession.cs index ae35044134a46..c41e872a776ea 100644 --- a/src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileDiffMergingSession.cs +++ b/src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileDiffMergingSession.cs @@ -17,34 +17,23 @@ namespace Microsoft.CodeAnalysis { - internal sealed class LinkedFileDiffMergingSession + internal sealed class LinkedFileDiffMergingSession(Solution oldSolution, Solution newSolution, SolutionChanges solutionChanges) { - private readonly Solution _oldSolution; - private readonly Solution _newSolution; - private readonly SolutionChanges _solutionChanges; - - public LinkedFileDiffMergingSession(Solution oldSolution, Solution newSolution, SolutionChanges solutionChanges) - { - _oldSolution = oldSolution; - _newSolution = newSolution; - _solutionChanges = solutionChanges; - } - internal async Task MergeDiffsAsync(IMergeConflictHandler mergeConflictHandler, CancellationToken cancellationToken) { var sessionInfo = new LinkedFileDiffMergingSessionInfo(); - var linkedDocumentGroupsWithChanges = _solutionChanges + var linkedDocumentGroupsWithChanges = solutionChanges .GetProjectChanges() .SelectMany(p => p.GetChangedDocuments()) - .GroupBy(d => _oldSolution.GetDocument(d).FilePath, StringComparer.OrdinalIgnoreCase); + .GroupBy(d => oldSolution.GetDocument(d).FilePath, StringComparer.OrdinalIgnoreCase); var linkedFileMergeResults = new List(); - var updatedSolution = _newSolution; + var updatedSolution = newSolution; foreach (var linkedDocumentsWithChanges in linkedDocumentGroupsWithChanges) { - var documentInNewSolution = _newSolution.GetDocument(linkedDocumentsWithChanges.First()); + var documentInNewSolution = newSolution.GetDocument(linkedDocumentsWithChanges.First()); // Ensure the first document in the group is the first in the list of var allLinkedDocuments = documentInNewSolution.GetLinkedDocumentIds().Add(documentInNewSolution.Id); @@ -62,7 +51,7 @@ internal async Task MergeDiffsAsync(IMergeConflict } else { - mergedText = await _newSolution.GetDocument(linkedDocumentsWithChanges.Single()).GetValueTextAsync(cancellationToken).ConfigureAwait(false); + mergedText = await newSolution.GetDocument(linkedDocumentsWithChanges.Single()).GetValueTextAsync(cancellationToken).ConfigureAwait(false); } foreach (var documentId in allLinkedDocuments) @@ -85,15 +74,15 @@ private async Task MergeLinkedDocumentGroupAsync( // Automatically merge non-conflicting diffs while collecting the conflicting diffs - var textDifferencingService = _oldSolution.Services.GetRequiredService(); - var appliedChanges = await textDifferencingService.GetTextChangesAsync(_oldSolution.GetDocument(linkedDocumentGroup.First()), _newSolution.GetDocument(linkedDocumentGroup.First()), cancellationToken).ConfigureAwait(false); + var textDifferencingService = oldSolution.Services.GetRequiredService(); + var appliedChanges = await textDifferencingService.GetTextChangesAsync(oldSolution.GetDocument(linkedDocumentGroup.First()), newSolution.GetDocument(linkedDocumentGroup.First()), cancellationToken).ConfigureAwait(false); var unmergedChanges = new List(); foreach (var documentId in linkedDocumentGroup.Skip(1)) { appliedChanges = await AddDocumentMergeChangesAsync( - _oldSolution.GetDocument(documentId), - _newSolution.GetDocument(documentId), + oldSolution.GetDocument(documentId), + newSolution.GetDocument(documentId), appliedChanges.ToList(), unmergedChanges, groupSessionInfo, @@ -101,7 +90,7 @@ private async Task MergeLinkedDocumentGroupAsync( cancellationToken).ConfigureAwait(false); } - var originalDocument = _oldSolution.GetDocument(linkedDocumentGroup.First()); + var originalDocument = oldSolution.GetDocument(linkedDocumentGroup.First()); var originalSourceText = await originalDocument.GetValueTextAsync(cancellationToken).ConfigureAwait(false); // Add comments in source explaining diffs that could not be merged @@ -111,7 +100,7 @@ private async Task MergeLinkedDocumentGroupAsync( if (unmergedChanges.Any()) { - mergeConflictHandler ??= _oldSolution.GetDocument(linkedDocumentGroup.First()).GetLanguageService(); + mergeConflictHandler ??= oldSolution.GetDocument(linkedDocumentGroup.First()).GetLanguageService(); var mergeConflictTextEdits = mergeConflictHandler.CreateEdits(originalSourceText, unmergedChanges); allChanges = MergeChangesWithMergeFailComments(appliedChanges, mergeConflictTextEdits, mergeConflictResolutionSpan, groupSessionInfo); @@ -121,7 +110,7 @@ private async Task MergeLinkedDocumentGroupAsync( allChanges = appliedChanges; } - groupSessionInfo.LinkedDocuments = _newSolution.GetDocumentIdsWithFilePath(originalDocument.FilePath).Length; + groupSessionInfo.LinkedDocuments = newSolution.GetDocumentIdsWithFilePath(originalDocument.FilePath).Length; groupSessionInfo.DocumentsWithChanges = linkedDocumentGroup.Count(); sessionInfo.LogLinkedFileResult(groupSessionInfo); diff --git a/src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileMergeResult.cs b/src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileMergeResult.cs index 4b068a489a9b3..772d2b1377a28 100644 --- a/src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileMergeResult.cs +++ b/src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileMergeResult.cs @@ -10,18 +10,11 @@ namespace Microsoft.CodeAnalysis { - internal sealed class LinkedFileMergeResult + internal sealed class LinkedFileMergeResult(IEnumerable documentIds, SourceText mergedSourceText, IEnumerable mergeConflictResolutionSpans) { - public IEnumerable DocumentIds { get; internal set; } - public SourceText MergedSourceText { get; internal set; } - public IEnumerable MergeConflictResolutionSpans { get; } + public IEnumerable DocumentIds { get; internal set; } = documentIds; + public SourceText MergedSourceText { get; internal set; } = mergedSourceText; + public IEnumerable MergeConflictResolutionSpans { get; } = mergeConflictResolutionSpans; public bool HasMergeConflicts { get { return MergeConflictResolutionSpans.Any(); } } - - public LinkedFileMergeResult(IEnumerable documentIds, SourceText mergedSourceText, IEnumerable mergeConflictResolutionSpans) - { - DocumentIds = documentIds; - MergedSourceText = mergedSourceText; - MergeConflictResolutionSpans = mergeConflictResolutionSpans; - } } } diff --git a/src/Workspaces/Core/Portable/LinkedFileDiffMerging/UnmergedDocumentChanges.cs b/src/Workspaces/Core/Portable/LinkedFileDiffMerging/UnmergedDocumentChanges.cs index 24641c125c941..dc556c927988c 100644 --- a/src/Workspaces/Core/Portable/LinkedFileDiffMerging/UnmergedDocumentChanges.cs +++ b/src/Workspaces/Core/Portable/LinkedFileDiffMerging/UnmergedDocumentChanges.cs @@ -9,17 +9,10 @@ namespace Microsoft.CodeAnalysis { - internal sealed class UnmergedDocumentChanges + internal sealed class UnmergedDocumentChanges(IEnumerable unmergedChanges, string projectName, DocumentId documentId) { - public IEnumerable UnmergedChanges { get; } - public string ProjectName { get; } - public DocumentId DocumentId { get; } - - public UnmergedDocumentChanges(IEnumerable unmergedChanges, string projectName, DocumentId documentId) - { - UnmergedChanges = unmergedChanges; - ProjectName = projectName; - DocumentId = documentId; - } + public IEnumerable UnmergedChanges { get; } = unmergedChanges; + public string ProjectName { get; } = projectName; + public DocumentId DocumentId { get; } = documentId; } } diff --git a/src/Workspaces/Core/Portable/Log/EtwLogger.cs b/src/Workspaces/Core/Portable/Log/EtwLogger.cs index 0221e670d55f6..b14f5ad32e9d8 100644 --- a/src/Workspaces/Core/Portable/Log/EtwLogger.cs +++ b/src/Workspaces/Core/Portable/Log/EtwLogger.cs @@ -14,19 +14,15 @@ namespace Microsoft.CodeAnalysis.Internal.Log /// /// A logger that publishes events to ETW using an EventSource. /// - internal sealed class EtwLogger : ILogger + internal sealed class EtwLogger(Func isEnabledPredicate) : ILogger { - private readonly Func _isEnabledPredicate; // Due to ETW specifics, RoslynEventSource.Instance needs to be initialized during EtwLogger construction // so that we can enable the listeners synchronously before any events are logged. private readonly RoslynEventSource _source = RoslynEventSource.Instance; - public EtwLogger(Func isEnabledPredicate) - => _isEnabledPredicate = isEnabledPredicate; - public bool IsEnabled(FunctionId functionId) - => _source.IsEnabled() && _isEnabledPredicate(functionId); + => _source.IsEnabled() && isEnabledPredicate(functionId); public void Log(FunctionId functionId, LogMessage logMessage) => _source.Log(GetMessage(logMessage), functionId); diff --git a/src/Workspaces/Core/Portable/Log/InteractionClass.cs b/src/Workspaces/Core/Portable/Log/InteractionClass.cs index 67ec23d3b1e6b..820d8bc60f0c0 100644 --- a/src/Workspaces/Core/Portable/Log/InteractionClass.cs +++ b/src/Workspaces/Core/Portable/Log/InteractionClass.cs @@ -29,13 +29,8 @@ internal enum InteractionClass } [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)] - internal class PerfGoalAttribute : Attribute + internal class PerfGoalAttribute(InteractionClass interactionClass) : Attribute { - private readonly InteractionClass _interactionClass; - - public PerfGoalAttribute(InteractionClass interactionClass) - => _interactionClass = interactionClass; - - public InteractionClass InteractionClass => _interactionClass; + public InteractionClass InteractionClass => interactionClass; } } diff --git a/src/Workspaces/Core/Portable/Log/PiiValue.cs b/src/Workspaces/Core/Portable/Log/PiiValue.cs index 775cf2227ab26..0bbac7b214613 100644 --- a/src/Workspaces/Core/Portable/Log/PiiValue.cs +++ b/src/Workspaces/Core/Portable/Log/PiiValue.cs @@ -10,12 +10,9 @@ namespace Microsoft.CodeAnalysis.Internal.Log /// /// Represents telemetry data that's classified as personally identifiable information. /// - internal sealed class PiiValue + internal sealed class PiiValue(object value) { - public readonly object Value; - - public PiiValue(object value) - => Value = value; + public readonly object Value = value; public override string? ToString() => Value.ToString(); diff --git a/src/Workspaces/Core/Portable/Log/StatisticResult.cs b/src/Workspaces/Core/Portable/Log/StatisticResult.cs index 2c8b19e495bfd..469a17e20b410 100644 --- a/src/Workspaces/Core/Portable/Log/StatisticResult.cs +++ b/src/Workspaces/Core/Portable/Log/StatisticResult.cs @@ -9,7 +9,7 @@ namespace Microsoft.CodeAnalysis.Internal.Log { - internal readonly struct StatisticResult + internal readonly struct StatisticResult(int max, int min, double mean, int range, int? mode, int count) { public static StatisticResult FromList(List values) { @@ -42,42 +42,32 @@ public static StatisticResult FromList(List values) /// /// maximum value /// - public readonly int Maximum; + public readonly int Maximum = max; /// /// minimum value /// - public readonly int Minimum; + public readonly int Minimum = min; /// /// average value of the total data set /// - public readonly double Mean; + public readonly double Mean = mean; /// /// most frequent value in the total data set /// - public readonly int? Mode; + public readonly int? Mode = mode; /// /// difference between max and min value /// - public readonly int Range; + public readonly int Range = range; /// /// number of data points in the total data set /// - public readonly int Count; - - public StatisticResult(int max, int min, double mean, int range, int? mode, int count) - { - this.Maximum = max; - this.Minimum = min; - this.Mean = mean; - this.Range = range; - this.Mode = mode; - this.Count = count; - } + public readonly int Count = count; /// /// Writes out these statistics to a property bag for sending to telemetry. diff --git a/src/Workspaces/Core/Portable/Log/TraceLogger.cs b/src/Workspaces/Core/Portable/Log/TraceLogger.cs index 1fa359d24c610..abcf3bc3391c8 100644 --- a/src/Workspaces/Core/Portable/Log/TraceLogger.cs +++ b/src/Workspaces/Core/Portable/Log/TraceLogger.cs @@ -11,17 +11,12 @@ namespace Microsoft.CodeAnalysis.Internal.Log /// /// Implementation of that produce timing debug output. /// - internal sealed class TraceLogger : ILogger + internal sealed class TraceLogger(Func? isEnabledPredicate) : ILogger { public static readonly TraceLogger Instance = new(isEnabledPredicate: null); - private readonly Func? _isEnabledPredicate; - - public TraceLogger(Func? isEnabledPredicate) - => _isEnabledPredicate = isEnabledPredicate; - public bool IsEnabled(FunctionId functionId) - => _isEnabledPredicate == null || _isEnabledPredicate(functionId); + => isEnabledPredicate == null || isEnabledPredicate(functionId); public void Log(FunctionId functionId, LogMessage logMessage) => Trace.WriteLine(string.Format("[{0}] {1} - {2}", Environment.CurrentManagedThreadId, functionId.ToString(), logMessage.GetMessage())); diff --git a/src/Workspaces/Core/Portable/Notification/AbstractGlobalOperationNotificationService.GlobalOperationRegistration.cs b/src/Workspaces/Core/Portable/Notification/AbstractGlobalOperationNotificationService.GlobalOperationRegistration.cs index d6cdf2421ccc0..1f38256b88c40 100644 --- a/src/Workspaces/Core/Portable/Notification/AbstractGlobalOperationNotificationService.GlobalOperationRegistration.cs +++ b/src/Workspaces/Core/Portable/Notification/AbstractGlobalOperationNotificationService.GlobalOperationRegistration.cs @@ -10,17 +10,12 @@ namespace Microsoft.CodeAnalysis.Notification; internal partial class AbstractGlobalOperationNotificationService { - private class GlobalOperationRegistration : IDisposable + private class GlobalOperationRegistration(AbstractGlobalOperationNotificationService service) : IDisposable { - private readonly AbstractGlobalOperationNotificationService _service; - - public GlobalOperationRegistration(AbstractGlobalOperationNotificationService service) - => _service = service; - public void Dispose() { // Inform any listeners that we're finished. - _service.Done(this); + service.Done(this); } } } diff --git a/src/Workspaces/Core/Portable/Options/GlobalOptionService.cs b/src/Workspaces/Core/Portable/Options/GlobalOptionService.cs index 6d8d8a0e1c353..86eb14e8de8ba 100644 --- a/src/Workspaces/Core/Portable/Options/GlobalOptionService.cs +++ b/src/Workspaces/Core/Portable/Options/GlobalOptionService.cs @@ -17,34 +17,25 @@ namespace Microsoft.CodeAnalysis.Options { [Export(typeof(IGlobalOptionService)), Shared] - internal sealed class GlobalOptionService : IGlobalOptionService + [method: ImportingConstructor] + [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + internal sealed class GlobalOptionService( + [Import(AllowDefault = true)] IWorkspaceThreadingService? workspaceThreadingService, + [ImportMany] IEnumerable> optionPersisters) : IGlobalOptionService { - private readonly IWorkspaceThreadingService? _workspaceThreadingService; - private readonly ImmutableArray> _optionPersisterProviders; + private readonly ImmutableArray> _optionPersisterProviders = optionPersisters.ToImmutableArray(); private readonly object _gate = new(); #region Guarded by _gate private ImmutableArray _lazyOptionPersisters; - private ImmutableDictionary _currentValues; + private ImmutableDictionary _currentValues = ImmutableDictionary.Create(); #endregion private readonly WeakEvent _optionChanged = new(); - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public GlobalOptionService( - [Import(AllowDefault = true)] IWorkspaceThreadingService? workspaceThreadingService, - [ImportMany] IEnumerable> optionPersisters) - { - _workspaceThreadingService = workspaceThreadingService; - _optionPersisterProviders = optionPersisters.ToImmutableArray(); - - _currentValues = ImmutableDictionary.Create(); - } - private ImmutableArray GetOptionPersisters() { if (_lazyOptionPersisters.IsDefault) @@ -55,7 +46,7 @@ private ImmutableArray GetOptionPersisters() ImmutableInterlocked.InterlockedInitialize( ref _lazyOptionPersisters, - GetOptionPersistersSlow(_workspaceThreadingService, _optionPersisterProviders, CancellationToken.None)); + GetOptionPersistersSlow(workspaceThreadingService, _optionPersisterProviders, CancellationToken.None)); } return _lazyOptionPersisters; diff --git a/src/Workspaces/Core/Portable/Options/LegacyGlobalCodeActionOptionsWorkspaceService.cs b/src/Workspaces/Core/Portable/Options/LegacyGlobalCodeActionOptionsWorkspaceService.cs index 20a7881d40970..3c3fdb47c529c 100644 --- a/src/Workspaces/Core/Portable/Options/LegacyGlobalCodeActionOptionsWorkspaceService.cs +++ b/src/Workspaces/Core/Portable/Options/LegacyGlobalCodeActionOptionsWorkspaceService.cs @@ -23,52 +23,42 @@ namespace Microsoft.CodeAnalysis.Options; /// Enables legacy APIs to access global options from workspace. /// [ExportWorkspaceService(typeof(ILegacyGlobalCleanCodeGenerationOptionsWorkspaceService)), Shared] -internal sealed class LegacyGlobalCleanCodeGenerationOptionsWorkspaceService : ILegacyGlobalCleanCodeGenerationOptionsWorkspaceService +[method: ImportingConstructor] +[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] +internal sealed class LegacyGlobalCleanCodeGenerationOptionsWorkspaceService(IGlobalOptionService globalOptions) : ILegacyGlobalCleanCodeGenerationOptionsWorkspaceService { - public CleanCodeGenerationOptionsProvider Provider { get; } + public CleanCodeGenerationOptionsProvider Provider { get; } = new ProviderImpl(globalOptions); - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public LegacyGlobalCleanCodeGenerationOptionsWorkspaceService(IGlobalOptionService globalOptions) + private sealed class ProviderImpl(IOptionsReader options) : CleanCodeGenerationOptionsProvider { - Provider = new ProviderImpl(globalOptions); - } - - private sealed class ProviderImpl : CleanCodeGenerationOptionsProvider - { - private readonly IOptionsReader _options; - - public ProviderImpl(IOptionsReader options) - => _options = options; - ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options.GetLineFormattingOptions(languageServices.Language, fallbackOptions: null)); + => ValueTaskFactory.FromResult(options.GetLineFormattingOptions(languageServices.Language, fallbackOptions: null)); ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options.GetDocumentFormattingOptions(fallbackOptions: null)); + => ValueTaskFactory.FromResult(options.GetDocumentFormattingOptions(fallbackOptions: null)); ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options.GetSyntaxFormattingOptions(languageServices, fallbackOptions: null)); + => ValueTaskFactory.FromResult(options.GetSyntaxFormattingOptions(languageServices, fallbackOptions: null)); ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options.GetSimplifierOptions(languageServices, fallbackOptions: null)); + => ValueTaskFactory.FromResult(options.GetSimplifierOptions(languageServices, fallbackOptions: null)); ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options.GetAddImportPlacementOptions(languageServices, allowInHiddenRegions: null, fallbackOptions: null)); + => ValueTaskFactory.FromResult(options.GetAddImportPlacementOptions(languageServices, allowInHiddenRegions: null, fallbackOptions: null)); ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options.GetCodeCleanupOptions(languageServices, allowImportsInHiddenRegions: null, fallbackOptions: null)); + => ValueTaskFactory.FromResult(options.GetCodeCleanupOptions(languageServices, allowImportsInHiddenRegions: null, fallbackOptions: null)); ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options.GetCleanCodeGenerationOptions(languageServices, allowImportsInHiddenRegions: null, fallbackOptions: null)); + => ValueTaskFactory.FromResult(options.GetCleanCodeGenerationOptions(languageServices, allowImportsInHiddenRegions: null, fallbackOptions: null)); ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options.GetCodeAndImportGenerationOptions(languageServices, allowImportsInHiddenRegions: null, fallbackOptions: null)); + => ValueTaskFactory.FromResult(options.GetCodeAndImportGenerationOptions(languageServices, allowImportsInHiddenRegions: null, fallbackOptions: null)); ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options.GetCodeGenerationOptions(languageServices, fallbackOptions: null)); + => ValueTaskFactory.FromResult(options.GetCodeGenerationOptions(languageServices, fallbackOptions: null)); ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options.GetOption(NamingStyleOptions.NamingPreferences, languageServices.Language)); + => ValueTaskFactory.FromResult(options.GetOption(NamingStyleOptions.NamingPreferences, languageServices.Language)); } } diff --git a/src/Workspaces/Core/Portable/Options/LegacyWorkspaceOptionService.cs b/src/Workspaces/Core/Portable/Options/LegacyWorkspaceOptionService.cs index c09829e856e3a..16d75f3afa5e5 100644 --- a/src/Workspaces/Core/Portable/Options/LegacyWorkspaceOptionService.cs +++ b/src/Workspaces/Core/Portable/Options/LegacyWorkspaceOptionService.cs @@ -14,37 +14,27 @@ namespace Microsoft.CodeAnalysis.Options; [Export(typeof(ILegacyGlobalOptionService)), Shared] -internal sealed class LegacyGlobalOptionService : ILegacyGlobalOptionService +[method: ImportingConstructor] +[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] +internal sealed class LegacyGlobalOptionService(IGlobalOptionService globalOptionService) : ILegacyGlobalOptionService { [ExportWorkspaceService(typeof(ILegacyWorkspaceOptionService)), Shared] - internal sealed class WorkspaceService : ILegacyWorkspaceOptionService + [method: ImportingConstructor] + [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + internal sealed class WorkspaceService(ILegacyGlobalOptionService legacyGlobalOptions) : ILegacyWorkspaceOptionService { - public ILegacyGlobalOptionService LegacyGlobalOptions { get; } - - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public WorkspaceService(ILegacyGlobalOptionService legacyGlobalOptions) - => LegacyGlobalOptions = legacyGlobalOptions; + public ILegacyGlobalOptionService LegacyGlobalOptions { get; } = legacyGlobalOptions; } - public IGlobalOptionService GlobalOptions { get; } + public IGlobalOptionService GlobalOptions { get; } = globalOptionService; // access is interlocked - private ImmutableArray> _registeredWorkspaces; + private ImmutableArray> _registeredWorkspaces = ImmutableArray>.Empty; /// /// Stores options that are not defined by Roslyn and do not implement . /// - private ImmutableDictionary _currentExternallyDefinedOptionValues; - - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public LegacyGlobalOptionService(IGlobalOptionService globalOptionService) - { - GlobalOptions = globalOptionService; - _registeredWorkspaces = ImmutableArray>.Empty; - _currentExternallyDefinedOptionValues = ImmutableDictionary.Create(); - } + private ImmutableDictionary _currentExternallyDefinedOptionValues = ImmutableDictionary.Create(); public object? GetExternallyDefinedOption(OptionKey key) { diff --git a/src/Workspaces/Core/Portable/Packaging/IPackageInstallerService.cs b/src/Workspaces/Core/Portable/Packaging/IPackageInstallerService.cs index 883ed7f7d15d5..3a2baaceebd65 100644 --- a/src/Workspaces/Core/Portable/Packaging/IPackageInstallerService.cs +++ b/src/Workspaces/Core/Portable/Packaging/IPackageInstallerService.cs @@ -45,19 +45,13 @@ Task TryInstallPackageAsync( } [DataContract] - internal readonly struct PackageSource : IEquatable + internal readonly struct PackageSource(string name, string source) : IEquatable { [DataMember(Order = 0)] - public readonly string Name; + public readonly string Name = name; [DataMember(Order = 1)] - public readonly string Source; - - public PackageSource(string name, string source) - { - Name = name; - Source = source; - } + public readonly string Source = source; public override bool Equals(object? obj) => obj is PackageSource source && Equals(source); diff --git a/src/Workspaces/Core/Portable/PatternMatching/AllLowerCamelCaseMatcher.cs b/src/Workspaces/Core/Portable/PatternMatching/AllLowerCamelCaseMatcher.cs index 9571c2b790d07..787a79e2fdcfb 100644 --- a/src/Workspaces/Core/Portable/PatternMatching/AllLowerCamelCaseMatcher.cs +++ b/src/Workspaces/Core/Portable/PatternMatching/AllLowerCamelCaseMatcher.cs @@ -21,24 +21,13 @@ internal partial class PatternMatcher /// a candidate using CamelCase matching. i.e. this code is responsible for finding the /// match between "cofipro" and "CodeFixProvider". /// - private readonly struct AllLowerCamelCaseMatcher + private readonly struct AllLowerCamelCaseMatcher( + bool includeMatchedSpans, + string candidate, + string patternChunkText, + TextInfo textInfo) { - private readonly bool _includeMatchedSpans; - private readonly string _candidate; - private readonly string _patternText; - private readonly TextInfo _textInfo; - - public AllLowerCamelCaseMatcher( - bool includeMatchedSpans, - string candidate, - string patternChunkText, - TextInfo textInfo) - { - _includeMatchedSpans = includeMatchedSpans; - _candidate = candidate; - _patternText = patternChunkText; - _textInfo = textInfo; - } + private readonly TextInfo _textInfo = textInfo; /// /// Returns null if no match was found, 1 if a contiguous match was found, 2 if a @@ -65,7 +54,7 @@ public AllLowerCamelCaseMatcher( return null; } - matchedSpans = _includeMatchedSpans && result.Value.MatchedSpansInReverse != null + matchedSpans = includeMatchedSpans && result.Value.MatchedSpansInReverse != null ? new NormalizedTextSpanCollection(result.Value.MatchedSpansInReverse).ToImmutableArray() : ImmutableArray.Empty; @@ -79,11 +68,11 @@ private static PatternMatchKind GetKind(CamelCaseResult result, in TemporaryArra private CamelCaseResult? TryMatch( int patternIndex, int candidateHumpIndex, bool? contiguous, in TemporaryArray candidateHumps) { - if (patternIndex == _patternText.Length) + if (patternIndex == patternChunkText.Length) { // We hit the end. So we were able to match against this candidate. // We are contiguous if our contiguous tracker was not set to false. - var matchedSpansInReverse = _includeMatchedSpans ? ArrayBuilder.GetInstance() : null; + var matchedSpansInReverse = includeMatchedSpans ? ArrayBuilder.GetInstance() : null; return new CamelCaseResult( fromStart: false, contiguous: contiguous != false, @@ -94,7 +83,7 @@ private static PatternMatchKind GetKind(CamelCaseResult result, in TemporaryArra var bestResult = (CamelCaseResult?)null; // Look for a hump in the candidate that matches the current letter we're on. - var patternCharacter = _patternText[patternIndex]; + var patternCharacter = patternChunkText[patternIndex]; for (int humpIndex = candidateHumpIndex, n = candidateHumps.Count; humpIndex < n; humpIndex++) { // If we've been contiguous, but we jumped past a hump, then we're no longer contiguous. @@ -104,7 +93,7 @@ private static PatternMatchKind GetKind(CamelCaseResult result, in TemporaryArra } var candidateHump = candidateHumps[humpIndex]; - if (ToLower(_candidate[candidateHump.Start], _textInfo) == patternCharacter) + if (ToLower(candidate[candidateHump.Start], _textInfo) == patternCharacter) { // Found a hump in the candidate string that matches the current pattern // character we're on. i.e. we matched the c in cofipro against the C in @@ -163,15 +152,15 @@ private static char ToLowerAsciiInvariant(char c) var candidateHump = candidateHumps[humpIndex]; - var maxPatternHumpLength = _patternText.Length - patternIndex; + var maxPatternHumpLength = patternChunkText.Length - patternIndex; var maxCandidateHumpLength = candidateHump.Length; var maxHumpMatchLength = Math.Min(maxPatternHumpLength, maxCandidateHumpLength); for (var possibleHumpMatchLength = 1; possibleHumpMatchLength <= maxHumpMatchLength; possibleHumpMatchLength++) { if (!LowercaseSubstringsMatch( - _candidate, candidateHump.Start, - _patternText, patternIndex, possibleHumpMatchLength)) + candidate, candidateHump.Start, + patternChunkText, patternIndex, possibleHumpMatchLength)) { // Stop trying to consume once the pattern contents no longer matches // against the current candidate hump. diff --git a/src/Workspaces/Core/Portable/PatternMatching/PatternMatcher.PatternSegment.cs b/src/Workspaces/Core/Portable/PatternMatching/PatternMatcher.PatternSegment.cs index 5f0df83552c97..5f912cea3b674 100644 --- a/src/Workspaces/Core/Portable/PatternMatching/PatternMatcher.PatternSegment.cs +++ b/src/Workspaces/Core/Portable/PatternMatching/PatternMatcher.PatternSegment.cs @@ -18,24 +18,18 @@ internal partial class PatternMatcher /// can break the segment into. /// [NonCopyable] - private struct PatternSegment : IDisposable + private struct PatternSegment(string text, bool allowFuzzyMatching) : IDisposable { // Information about the entire piece of text between the dots. For example, if the // text between the dots is 'Get-Keyword', then TotalTextChunk.Text will be 'Get-Keyword' and // TotalTextChunk.CharacterSpans will correspond to 'G', 'et', 'K' and 'eyword'. - public TextChunk TotalTextChunk; + public TextChunk TotalTextChunk = new TextChunk(text, allowFuzzyMatching); // Information about the subwords compromising the total word. For example, if the // text between the dots is 'Get-Keyword', then the subwords will be 'Get' and 'Keyword' // Those individual words will have CharacterSpans of ('G' and 'et') and ('K' and 'eyword') // respectively. - public readonly TextChunk[] SubWordTextChunks; - - public PatternSegment(string text, bool allowFuzzyMatching) - { - this.TotalTextChunk = new TextChunk(text, allowFuzzyMatching); - this.SubWordTextChunks = BreakPatternIntoSubWords(text, allowFuzzyMatching); - } + public readonly TextChunk[] SubWordTextChunks = BreakPatternIntoSubWords(text, allowFuzzyMatching); public void Dispose() { diff --git a/src/Workspaces/Core/Portable/Recommendations/IRecommendationService.cs b/src/Workspaces/Core/Portable/Recommendations/IRecommendationService.cs index 9227fe209690c..ce16806bbaf03 100644 --- a/src/Workspaces/Core/Portable/Recommendations/IRecommendationService.cs +++ b/src/Workspaces/Core/Portable/Recommendations/IRecommendationService.cs @@ -17,32 +17,24 @@ RecommendedSymbols GetRecommendedSymbolsInContext( CancellationToken cancellationToken); } - internal readonly struct RecommendedSymbols + internal readonly struct RecommendedSymbols( + ImmutableArray namedSymbols, + ImmutableArray unnamedSymbols = default) { - private readonly ImmutableArray _namedSymbols; - private readonly ImmutableArray _unnamedSymbols; /// /// The named symbols to recommend. /// - public ImmutableArray NamedSymbols => _namedSymbols.NullToEmpty(); + public ImmutableArray NamedSymbols => namedSymbols.NullToEmpty(); /// /// The unnamed symbols to recommend. For example, operators, conversions and indexers. /// - public ImmutableArray UnnamedSymbols => _unnamedSymbols.NullToEmpty(); + public ImmutableArray UnnamedSymbols => unnamedSymbols.NullToEmpty(); public RecommendedSymbols(ImmutableArray namedSymbols) : this(namedSymbols, default) { } - - public RecommendedSymbols( - ImmutableArray namedSymbols, - ImmutableArray unnamedSymbols = default) - { - _namedSymbols = namedSymbols; - _unnamedSymbols = unnamedSymbols; - } } } diff --git a/src/Workspaces/Core/Portable/Remote/RemoteArguments.cs b/src/Workspaces/Core/Portable/Remote/RemoteArguments.cs index b049cf47751ff..de37b47ad66e8 100644 --- a/src/Workspaces/Core/Portable/Remote/RemoteArguments.cs +++ b/src/Workspaces/Core/Portable/Remote/RemoteArguments.cs @@ -21,19 +21,13 @@ namespace Microsoft.CodeAnalysis.Remote #region FindReferences [DataContract] - internal sealed class SerializableSymbolAndProjectId : IEquatable + internal sealed class SerializableSymbolAndProjectId(string symbolKeyData, ProjectId projectId) : IEquatable { [DataMember(Order = 0)] - public readonly string SymbolKeyData; + public readonly string SymbolKeyData = symbolKeyData; [DataMember(Order = 1)] - public readonly ProjectId ProjectId; - - public SerializableSymbolAndProjectId(string symbolKeyData, ProjectId projectId) - { - SymbolKeyData = symbolKeyData; - ProjectId = projectId; - } + public readonly ProjectId ProjectId = projectId; public override bool Equals(object? obj) => Equals(obj as SerializableSymbolAndProjectId); @@ -132,46 +126,35 @@ public static bool TryCreate( } [DataContract] - internal readonly struct SerializableReferenceLocation + internal readonly struct SerializableReferenceLocation( + DocumentId document, + SerializableSymbolAndProjectId? alias, + TextSpan location, + bool isImplicit, + SymbolUsageInfo symbolUsageInfo, + ImmutableDictionary additionalProperties, + CandidateReason candidateReason) { [DataMember(Order = 0)] - public readonly DocumentId Document; + public readonly DocumentId Document = document; [DataMember(Order = 1)] - public readonly SerializableSymbolAndProjectId? Alias; + public readonly SerializableSymbolAndProjectId? Alias = alias; [DataMember(Order = 2)] - public readonly TextSpan Location; + public readonly TextSpan Location = location; [DataMember(Order = 3)] - public readonly bool IsImplicit; + public readonly bool IsImplicit = isImplicit; [DataMember(Order = 4)] - public readonly SymbolUsageInfo SymbolUsageInfo; + public readonly SymbolUsageInfo SymbolUsageInfo = symbolUsageInfo; [DataMember(Order = 5)] - public readonly ImmutableDictionary AdditionalProperties; + public readonly ImmutableDictionary AdditionalProperties = additionalProperties; [DataMember(Order = 6)] - public readonly CandidateReason CandidateReason; - - public SerializableReferenceLocation( - DocumentId document, - SerializableSymbolAndProjectId? alias, - TextSpan location, - bool isImplicit, - SymbolUsageInfo symbolUsageInfo, - ImmutableDictionary additionalProperties, - CandidateReason candidateReason) - { - Document = document; - Alias = alias; - Location = location; - IsImplicit = isImplicit; - SymbolUsageInfo = symbolUsageInfo; - AdditionalProperties = additionalProperties; - CandidateReason = candidateReason; - } + public readonly CandidateReason CandidateReason = candidateReason; public static SerializableReferenceLocation Dehydrate( ReferenceLocation referenceLocation, CancellationToken cancellationToken) @@ -215,18 +198,13 @@ public async ValueTask RehydrateAsync( } [DataContract] - internal class SerializableSymbolGroup : IEquatable + internal class SerializableSymbolGroup(HashSet symbols) : IEquatable { [DataMember(Order = 0)] - public readonly HashSet Symbols; + public readonly HashSet Symbols = new HashSet(symbols); private int _hashCode; - public SerializableSymbolGroup(HashSet symbols) - { - Symbols = new HashSet(symbols); - } - public override bool Equals(object? obj) => obj is SerializableSymbolGroup group && Equals(group); diff --git a/src/Workspaces/Core/Portable/Remote/RemoteOptionsProvider.cs b/src/Workspaces/Core/Portable/Remote/RemoteOptionsProvider.cs index 0a04ed87b04c8..4c76bad83736c 100644 --- a/src/Workspaces/Core/Portable/Remote/RemoteOptionsProvider.cs +++ b/src/Workspaces/Core/Portable/Remote/RemoteOptionsProvider.cs @@ -14,17 +14,8 @@ namespace Microsoft.CodeAnalysis.Remote; /// Can be used when the remote API does not have an existing callback. If it does it can implement /// itself. /// -internal sealed class RemoteOptionsProvider +internal sealed class RemoteOptionsProvider(SolutionServices services, OptionsProvider optionsProvider) { - private readonly SolutionServices _services; - private readonly OptionsProvider _optionsProvider; - - public RemoteOptionsProvider(SolutionServices services, OptionsProvider optionsProvider) - { - _services = services; - _optionsProvider = optionsProvider; - } - internal ValueTask GetOptionsAsync(string language, CancellationToken cancellationToken) - => _optionsProvider.GetOptionsAsync(_services.GetLanguageServices(language), cancellationToken); + => optionsProvider.GetOptionsAsync(services.GetLanguageServices(language), cancellationToken); } diff --git a/src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackDispatcher.cs b/src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackDispatcher.cs index 4ed51833c319c..a9dfef4c69798 100644 --- a/src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackDispatcher.cs +++ b/src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackDispatcher.cs @@ -16,20 +16,13 @@ internal interface IRemoteServiceCallbackDispatcher internal class RemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher { - internal readonly struct Handle : IDisposable + internal readonly struct Handle(ConcurrentDictionary callbackInstances, RemoteServiceCallbackId callbackId) : IDisposable { - private readonly ConcurrentDictionary _callbackInstances; - public readonly RemoteServiceCallbackId Id; - - public Handle(ConcurrentDictionary callbackInstances, RemoteServiceCallbackId callbackId) - { - _callbackInstances = callbackInstances; - Id = callbackId; - } + public readonly RemoteServiceCallbackId Id = callbackId; public void Dispose() { - Contract.ThrowIfTrue(_callbackInstances?.TryRemove(Id, out _) == false); + Contract.ThrowIfTrue(callbackInstances?.TryRemove(Id, out _) == false); } } diff --git a/src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackDispatchers.cs b/src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackDispatchers.cs index 47e8fb1ccaeff..4b582470786d4 100644 --- a/src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackDispatchers.cs +++ b/src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackDispatchers.cs @@ -9,7 +9,7 @@ namespace Microsoft.CodeAnalysis.Remote { - internal sealed class RemoteServiceCallbackDispatcherRegistry : IRemoteServiceCallbackDispatcherProvider + internal sealed class RemoteServiceCallbackDispatcherRegistry(IEnumerable> dispatchers) : IRemoteServiceCallbackDispatcherProvider { public sealed class ExportMetadata { @@ -26,10 +26,7 @@ public ExportMetadata(IDictionary data) } } - private readonly ImmutableDictionary> _callbackDispatchers; - - public RemoteServiceCallbackDispatcherRegistry(IEnumerable> dispatchers) - => _callbackDispatchers = dispatchers.ToImmutableDictionary(d => d.Metadata.ServiceInterface); + private readonly ImmutableDictionary> _callbackDispatchers = dispatchers.ToImmutableDictionary(d => d.Metadata.ServiceInterface); public IRemoteServiceCallbackDispatcher GetDispatcher(Type serviceType) => _callbackDispatchers[serviceType].Value; diff --git a/src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackId.cs b/src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackId.cs index 04108ca36efbc..d1277acb9f0da 100644 --- a/src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackId.cs +++ b/src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackId.cs @@ -8,13 +8,10 @@ namespace Microsoft.CodeAnalysis.Remote { [DataContract] - internal readonly struct RemoteServiceCallbackId : IEquatable + internal readonly struct RemoteServiceCallbackId(int id) : IEquatable { [DataMember(Order = 0)] - public readonly int Id; - - public RemoteServiceCallbackId(int id) - => Id = id; + public readonly int Id = id; public override bool Equals(object? obj) => obj is RemoteServiceCallbackId id && Equals(id); diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ComplexifiedSpan.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ComplexifiedSpan.cs index a807d161e7a35..56970e4161422 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ComplexifiedSpan.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ComplexifiedSpan.cs @@ -9,22 +9,15 @@ namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { [DataContract] - internal readonly struct ComplexifiedSpan + internal readonly struct ComplexifiedSpan(TextSpan originalSpan, TextSpan newSpan, ImmutableArray<(TextSpan oldSpan, TextSpan newSpan)> modifiedSubSpans) { [DataMember(Order = 0)] - public readonly TextSpan OriginalSpan; + public readonly TextSpan OriginalSpan = originalSpan; [DataMember(Order = 1)] - public readonly TextSpan NewSpan; + public readonly TextSpan NewSpan = newSpan; [DataMember(Order = 2)] - public readonly ImmutableArray<(TextSpan oldSpan, TextSpan newSpan)> ModifiedSubSpans; - - public ComplexifiedSpan(TextSpan originalSpan, TextSpan newSpan, ImmutableArray<(TextSpan oldSpan, TextSpan newSpan)> modifiedSubSpans) - { - OriginalSpan = originalSpan; - NewSpan = newSpan; - ModifiedSubSpans = modifiedSubSpans; - } + public readonly ImmutableArray<(TextSpan oldSpan, TextSpan newSpan)> ModifiedSubSpans = modifiedSubSpans; } } diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs index 6172053574f17..a9e4e59f61fe3 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs @@ -28,50 +28,24 @@ internal static partial class ConflictResolver /// Helper class to track the state necessary for finding/resolving conflicts in a /// rename session. /// - private class Session + private class Session( + SymbolicRenameLocations renameLocationSet, + Location renameSymbolDeclarationLocation, + string replacementText, + ImmutableArray nonConflictSymbolKeys, + CancellationToken cancellationToken) { - // Set of All Locations that will be renamed (does not include non-reference locations that need to be checked for conflicts) - private readonly SymbolicRenameLocations _renameLocationSet; - - // Rename Symbol's Source Location - private readonly Location _renameSymbolDeclarationLocation; - private readonly DocumentId _documentIdOfRenameSymbolDeclaration; - private readonly string _originalText; - private readonly string _replacementText; - private readonly ImmutableArray _nonConflictSymbolKeys; - private readonly CancellationToken _cancellationToken; - + private readonly DocumentId _documentIdOfRenameSymbolDeclaration = renameLocationSet.Solution.GetRequiredDocument(renameSymbolDeclarationLocation.SourceTree!).Id; + private readonly string _originalText = renameLocationSet.Symbol.Name; private readonly RenameAnnotation _renamedSymbolDeclarationAnnotation = new(); - private readonly AnnotationTable _renameAnnotations; + private readonly AnnotationTable _renameAnnotations = new AnnotationTable(RenameAnnotation.Kind); - private bool _replacementTextValid; + private bool _replacementTextValid = true; private bool _documentOfRenameSymbolHasBeenRenamed; - public Session( - SymbolicRenameLocations renameLocationSet, - Location renameSymbolDeclarationLocation, - string replacementText, - ImmutableArray nonConflictSymbolKeys, - CancellationToken cancellationToken) - { - _renameLocationSet = renameLocationSet; - _renameSymbolDeclarationLocation = renameSymbolDeclarationLocation; - _originalText = renameLocationSet.Symbol.Name; - _replacementText = replacementText; - _nonConflictSymbolKeys = nonConflictSymbolKeys; - _cancellationToken = cancellationToken; - - _replacementTextValid = true; - - // only process documents which possibly contain the identifiers. - _documentIdOfRenameSymbolDeclaration = renameLocationSet.Solution.GetRequiredDocument(renameSymbolDeclarationLocation.SourceTree!).Id; - - _renameAnnotations = new AnnotationTable(RenameAnnotation.Kind); - } - - private SymbolRenameOptions RenameOptions => _renameLocationSet.Options; - private CodeCleanupOptionsProvider FallbackOptions => _renameLocationSet.FallbackOptions; + private SymbolRenameOptions RenameOptions => renameLocationSet.Options; + private CodeCleanupOptionsProvider FallbackOptions => renameLocationSet.FallbackOptions; private readonly struct ConflictLocationInfo { @@ -97,19 +71,19 @@ public async Task ResolveConflictsAsync() try { var (documentsIdsToBeCheckedForConflict, possibleNameConflicts) = await FindDocumentsAndPossibleNameConflictsAsync().ConfigureAwait(false); - var baseSolution = _renameLocationSet.Solution; + var baseSolution = renameLocationSet.Solution; var dependencyGraph = baseSolution.GetProjectDependencyGraph(); - var topologicallySortedProjects = dependencyGraph.GetTopologicallySortedProjects(_cancellationToken).ToList(); + var topologicallySortedProjects = dependencyGraph.GetTopologicallySortedProjects(cancellationToken).ToList(); // Process rename one project at a time to improve caching and reduce syntax tree serialization. var documentsGroupedByTopologicallySortedProjectId = documentsIdsToBeCheckedForConflict .GroupBy(d => d.ProjectId) .OrderBy(g => topologicallySortedProjects.IndexOf(g.Key)); - _replacementTextValid = IsIdentifierValid_Worker(baseSolution, _replacementText, documentsGroupedByTopologicallySortedProjectId.Select(g => g.Key)); + _replacementTextValid = IsIdentifierValid_Worker(baseSolution, replacementText, documentsGroupedByTopologicallySortedProjectId.Select(g => g.Key)); var renamedSpansTracker = new RenamedSpansTracker(); - var conflictResolution = new MutableConflictResolution(baseSolution, renamedSpansTracker, _replacementText, _replacementTextValid); + var conflictResolution = new MutableConflictResolution(baseSolution, renamedSpansTracker, replacementText, _replacementTextValid); var intermediateSolution = conflictResolution.OldSolution; foreach (var documentsByProject in documentsGroupedByTopologicallySortedProjectId) @@ -138,7 +112,7 @@ public async Task ResolveConflictsAsync() baseSolution, conflictResolution.CurrentSolution, documentIdsThatGetsAnnotatedAndRenamed, - _renameLocationSet.Locations, + renameLocationSet.Locations, renamedSpansTracker, _replacementTextValid, conflictLocations, @@ -202,9 +176,9 @@ public async Task ResolveConflictsAsync() } // Step 3: Simplify the project - conflictResolution.UpdateCurrentSolution(await renamedSpansTracker.SimplifyAsync(conflictResolution.CurrentSolution, documentsByProject, _replacementTextValid, _renameAnnotations, FallbackOptions, _cancellationToken).ConfigureAwait(false)); + conflictResolution.UpdateCurrentSolution(await renamedSpansTracker.SimplifyAsync(conflictResolution.CurrentSolution, documentsByProject, _replacementTextValid, _renameAnnotations, FallbackOptions, cancellationToken).ConfigureAwait(false)); intermediateSolution = await conflictResolution.RemoveAllRenameAnnotationsAsync( - intermediateSolution, documentsByProject, _renameAnnotations, _cancellationToken).ConfigureAwait(false); + intermediateSolution, documentsByProject, _renameAnnotations, cancellationToken).ConfigureAwait(false); conflictResolution.UpdateCurrentSolution(intermediateSolution); } @@ -216,13 +190,13 @@ public async Task ResolveConflictsAsync() { await AddImplicitConflictsAsync( renamedSymbolInNewSolution, - _renameLocationSet.Symbol, - _renameLocationSet.ImplicitLocations, - await conflictResolution.CurrentSolution.GetRequiredDocument(_documentIdOfRenameSymbolDeclaration).GetRequiredSemanticModelAsync(_cancellationToken).ConfigureAwait(false), - _renameSymbolDeclarationLocation, - renamedSpansTracker.GetAdjustedPosition(_renameSymbolDeclarationLocation.SourceSpan.Start, _documentIdOfRenameSymbolDeclaration), + renameLocationSet.Symbol, + renameLocationSet.ImplicitLocations, + await conflictResolution.CurrentSolution.GetRequiredDocument(_documentIdOfRenameSymbolDeclaration).GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false), + renameSymbolDeclarationLocation, + renamedSpansTracker.GetAdjustedPosition(renameSymbolDeclarationLocation.SourceSpan.Start, _documentIdOfRenameSymbolDeclaration), conflictResolution, - _cancellationToken).ConfigureAwait(false); + cancellationToken).ConfigureAwait(false); } for (var i = 0; i < conflictResolution.RelatedLocations.Count; i++) @@ -239,7 +213,7 @@ await conflictResolution.CurrentSolution.GetRequiredDocument(_documentIdOfRename // Step 5: Rename declaration files if (_replacementTextValid && RenameOptions.RenameFile) { - var definitionLocations = _renameLocationSet.Symbol.Locations; + var definitionLocations = renameLocationSet.Symbol.Locations; var definitionDocuments = definitionLocations .Select(l => conflictResolution.OldSolution.GetRequiredDocument(l.SourceTree!)) .Distinct(); @@ -270,7 +244,7 @@ private async Task DebugVerifyNoErrorsAsync(MutableConflictResolution conflictRe { // remember if there were issues in the document prior to renaming it. var originalDoc = conflictResolution.OldSolution.GetRequiredDocument(documentId); - documentIdErrorStateLookup.Add(documentId, await originalDoc.HasAnyErrorsAsync(_cancellationToken).ConfigureAwait(false)); + documentIdErrorStateLookup.Add(documentId, await originalDoc.HasAnyErrorsAsync(cancellationToken).ConfigureAwait(false)); } // We want to ignore few error message introduced by rename because the user is wantedly doing it. @@ -287,9 +261,9 @@ private async Task DebugVerifyNoErrorsAsync(MutableConflictResolution conflictRe // fixed them because of rename). Also, don't bother checking if a custom // callback was provided. The caller might be ok with a rename that introduces // errors. - if (!documentIdErrorStateLookup[documentId] && _nonConflictSymbolKeys.IsDefault) + if (!documentIdErrorStateLookup[documentId] && nonConflictSymbolKeys.IsDefault) { - await conflictResolution.CurrentSolution.GetRequiredDocument(documentId).VerifyNoErrorsAsync("Rename introduced errors in error-free code", _cancellationToken, ignoreErrorCodes).ConfigureAwait(false); + await conflictResolution.CurrentSolution.GetRequiredDocument(documentId).VerifyNoErrorsAsync("Rename introduced errors in error-free code", cancellationToken, ignoreErrorCodes).ConfigureAwait(false); } } } @@ -321,7 +295,7 @@ private async Task IdentifyConflictsAsync( foreach (var documentId in documentIdsForConflictResolution) { var newDocument = conflictResolution.CurrentSolution.GetRequiredDocument(documentId); - var syntaxRoot = await newDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); + var syntaxRoot = await newDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var nodesOrTokensWithConflictCheckAnnotations = GetNodesOrTokensToCheckForConflicts(syntaxRoot); foreach (var (syntax, annotation) in nodesOrTokensWithConflictCheckAnnotations) @@ -347,10 +321,10 @@ private async Task IdentifyConflictsAsync( foreach (var documentId in documentIdsForConflictResolution) { var newDocument = conflictResolution.CurrentSolution.GetRequiredDocument(documentId); - var syntaxRoot = await newDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); + var syntaxRoot = await newDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var baseDocument = conflictResolution.OldSolution.GetRequiredDocument(documentId); - var baseSyntaxTree = await baseDocument.GetRequiredSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false); - var baseRoot = await baseDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); + var baseSyntaxTree = await baseDocument.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); + var baseRoot = await baseDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); SemanticModel? newDocumentSemanticModel = null; var syntaxFactsService = newDocument.Project.Services.GetRequiredService(); @@ -373,7 +347,7 @@ private async Task IdentifyConflictsAsync( var hasConflict = _renameAnnotations.HasAnnotation(tokenOrNode, RenameInvalidIdentifierAnnotation.Instance); if (!hasConflict) { - newDocumentSemanticModel ??= await newDocument.GetRequiredSemanticModelAsync(_cancellationToken).ConfigureAwait(false); + newDocumentSemanticModel ??= await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); newReferencedSymbols = GetSymbolsInNewSolution(newDocument, newDocumentSemanticModel, conflictAnnotation, tokenOrNode); // The semantic correctness, after rename, for each token of interest in the @@ -439,9 +413,9 @@ private async Task IdentifyConflictsAsync( foreach (var unprocessedDocumentIdWithPotentialDeclarationConflicts in allDocumentIdsInProject.Where(d => !documentIdsForConflictResolution.Contains(d))) { var newDocument = conflictResolution.CurrentSolution.GetRequiredDocument(unprocessedDocumentIdWithPotentialDeclarationConflicts); - var syntaxRoot = await newDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); + var syntaxRoot = await newDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var baseDocument = conflictResolution.OldSolution.GetRequiredDocument(unprocessedDocumentIdWithPotentialDeclarationConflicts); - var baseSyntaxTree = await baseDocument.GetRequiredSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false); + var baseSyntaxTree = await baseDocument.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var nodesOrTokensWithConflictCheckAnnotations = GetNodesOrTokensToCheckForConflicts(syntaxRoot); foreach (var (syntax, annotation) in nodesOrTokensWithConflictCheckAnnotations) @@ -452,10 +426,10 @@ private async Task IdentifyConflictsAsync( } } - var referencedSymbols = _renameLocationSet.ReferencedSymbols; - var renameSymbol = _renameLocationSet.Symbol; + var referencedSymbols = renameLocationSet.ReferencedSymbols; + var renameSymbol = renameLocationSet.Symbol; await AddDeclarationConflictsAsync( - renamedSymbolInNewSolution, renameSymbol, referencedSymbols, conflictResolution, reverseMappedLocations, _cancellationToken).ConfigureAwait(false); + renamedSymbolInNewSolution, renameSymbol, referencedSymbols, conflictResolution, reverseMappedLocations, cancellationToken).ConfigureAwait(false); } return conflictResolution.RelatedLocations.Any(r => r.Type == RelatedLocationType.PossiblyResolvableConflict); @@ -468,12 +442,12 @@ await AddDeclarationConflictsAsync( private async Task?> GetNonConflictSymbolsAsync(Project currentProject) { - if (_nonConflictSymbolKeys.IsDefault) + if (nonConflictSymbolKeys.IsDefault) return null; - var compilation = await currentProject.GetRequiredCompilationAsync(_cancellationToken).ConfigureAwait(false); + var compilation = await currentProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); return ImmutableHashSet.CreateRange( - _nonConflictSymbolKeys.Select(s => s.Resolve(compilation).GetAnySymbol()).WhereNotNull()); + nonConflictSymbolKeys.Select(s => s.Resolve(compilation).GetAnySymbol()).WhereNotNull()); } private static bool IsConflictFreeChange( @@ -532,7 +506,7 @@ private async Task CheckForConflictAsync( hasConflict = true; - var newLocationTasks = newReferencedSymbols.Select(async symbol => await GetSymbolLocationAsync(solution, symbol, _cancellationToken).ConfigureAwait(false)); + var newLocationTasks = newReferencedSymbols.Select(async symbol => await GetSymbolLocationAsync(solution, symbol, cancellationToken).ConfigureAwait(false)); var newLocations = (await Task.WhenAll(newLocationTasks).ConfigureAwait(false)).WhereNotNull().Where(loc => loc.IsInSource); foreach (var originalReference in conflictAnnotation.RenameDeclarationLocationReferences.Where(loc => loc.IsSourceLocation)) { @@ -574,7 +548,7 @@ private async Task CheckForConflictAsync( break; } - var newLocation = await GetSymbolLocationAsync(solution, symbol, _cancellationToken).ConfigureAwait(false); + var newLocation = await GetSymbolLocationAsync(solution, symbol, cancellationToken).ConfigureAwait(false); if (newLocation != null && conflictAnnotation.RenameDeclarationLocationReferences[symbolIndex].IsSourceLocation) { @@ -595,7 +569,7 @@ private async Task CheckForConflictAsync( if (conflictAnnotation.RenameDeclarationLocationReferences[symbolIndex].IsOverriddenFromMetadata) { - var overridingSymbol = await SymbolFinder.FindSymbolAtPositionAsync(solution.GetRequiredDocument(newLocation.SourceTree), newLocation.SourceSpan.Start, cancellationToken: _cancellationToken).ConfigureAwait(false); + var overridingSymbol = await SymbolFinder.FindSymbolAtPositionAsync(solution.GetRequiredDocument(newLocation.SourceTree), newLocation.SourceSpan.Start, cancellationToken: cancellationToken).ConfigureAwait(false); if (overridingSymbol != null && !Equals(renamedSymbolInNewSolution, overridingSymbol)) { if (!overridingSymbol.IsOverride) @@ -625,7 +599,7 @@ private async Task CheckForConflictAsync( oldMetadataName, newMetadataName, _originalText, - _replacementText)) + replacementText)) { hasConflict = true; break; @@ -646,13 +620,13 @@ private async Task CheckForConflictAsync( private ImmutableArray GetSymbolsInNewSolution(Document newDocument, SemanticModel newDocumentSemanticModel, RenameActionAnnotation conflictAnnotation, SyntaxNodeOrToken tokenOrNode) { - var newReferencedSymbols = RenameUtilities.GetSymbolsTouchingPosition(tokenOrNode.Span.Start, newDocumentSemanticModel, newDocument.Project.Solution.Services, _cancellationToken); + var newReferencedSymbols = RenameUtilities.GetSymbolsTouchingPosition(tokenOrNode.Span.Start, newDocumentSemanticModel, newDocument.Project.Solution.Services, cancellationToken); if (conflictAnnotation.IsInvocationExpression) { if (tokenOrNode.IsNode) { - var invocationReferencedSymbols = SymbolsForEnclosingInvocationExpressionWorker((SyntaxNode)tokenOrNode!, newDocumentSemanticModel, _cancellationToken); + var invocationReferencedSymbols = SymbolsForEnclosingInvocationExpressionWorker((SyntaxNode)tokenOrNode!, newDocumentSemanticModel, cancellationToken); if (!invocationReferencedSymbols.IsDefault) newReferencedSymbols = invocationReferencedSymbols; } @@ -673,11 +647,11 @@ private async Task GetRenamedSymbolInCurrentSolutionAsync(MutableConfli { // get the renamed symbol in complexified new solution var start = _documentOfRenameSymbolHasBeenRenamed - ? conflictResolution.GetAdjustedTokenStartingPosition(_renameSymbolDeclarationLocation.SourceSpan.Start, _documentIdOfRenameSymbolDeclaration) - : _renameSymbolDeclarationLocation.SourceSpan.Start; + ? conflictResolution.GetAdjustedTokenStartingPosition(renameSymbolDeclarationLocation.SourceSpan.Start, _documentIdOfRenameSymbolDeclaration) + : renameSymbolDeclarationLocation.SourceSpan.Start; var document = conflictResolution.CurrentSolution.GetRequiredDocument(_documentIdOfRenameSymbolDeclaration); - var newSymbol = await SymbolFinder.FindSymbolAtPositionAsync(document, start, cancellationToken: _cancellationToken).ConfigureAwait(false); + var newSymbol = await SymbolFinder.FindSymbolAtPositionAsync(document, start, cancellationToken: cancellationToken).ConfigureAwait(false); return newSymbol; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, ErrorSeverity.Critical)) @@ -698,17 +672,17 @@ private async Task GetRenamedSymbolInCurrentSolutionAsync(MutableConfli var documentIds = new HashSet(); var possibleNameConflictsList = new List(); - var symbol = _renameLocationSet.Symbol; - var solution = _renameLocationSet.Solution; + var symbol = renameLocationSet.Symbol; + var solution = renameLocationSet.Solution; - var allRenamedDocuments = _renameLocationSet.Locations.Select(loc => loc.Location.SourceTree!).Distinct().Select(solution.GetRequiredDocument); + var allRenamedDocuments = renameLocationSet.Locations.Select(loc => loc.Location.SourceTree!).Distinct().Select(solution.GetRequiredDocument); documentIds.AddRange(allRenamedDocuments.Select(d => d.Id)); - var documentsFromAffectedProjects = RenameUtilities.GetDocumentsAffectedByRename(symbol, solution, _renameLocationSet.Locations); + var documentsFromAffectedProjects = RenameUtilities.GetDocumentsAffectedByRename(symbol, solution, renameLocationSet.Locations); foreach (var language in documentsFromAffectedProjects.Select(d => d.Project.Language).Distinct()) { solution.Services.GetLanguageServices(language).GetService() - ?.TryAddPossibleNameConflicts(symbol, _replacementText, possibleNameConflictsList); + ?.TryAddPossibleNameConflicts(symbol, replacementText, possibleNameConflictsList); } var possibleNameConflicts = possibleNameConflictsList.ToImmutableArray(); @@ -736,14 +710,14 @@ private async Task AddDocumentsWithPotentialConflictsAsync( if (!document.SupportsSyntaxTree) continue; - var info = await SyntaxTreeIndex.GetRequiredIndexAsync(document, _cancellationToken).ConfigureAwait(false); + var info = await SyntaxTreeIndex.GetRequiredIndexAsync(document, cancellationToken).ConfigureAwait(false); if (info.ProbablyContainsEscapedIdentifier(_originalText)) { documentIds.Add(document.Id); continue; } - if (info.ProbablyContainsIdentifier(_replacementText)) + if (info.ProbablyContainsIdentifier(replacementText)) { documentIds.Add(document.Id); continue; @@ -780,11 +754,11 @@ private async Task AnnotateAndRename_WorkerAsync( { foreach (var documentId in documentIdsToRename.ToList()) { - _cancellationToken.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); var document = originalSolution.GetRequiredDocument(documentId); - var semanticModel = await document.GetRequiredSemanticModelAsync(_cancellationToken).ConfigureAwait(false); - var originalSyntaxRoot = await semanticModel.SyntaxTree.GetRootAsync(_cancellationToken).ConfigureAwait(false); + var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); + var originalSyntaxRoot = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); // Get all rename locations for the current document. var allTextSpansInSingleSourceTree = renameLocations @@ -811,20 +785,20 @@ private async Task AnnotateAndRename_WorkerAsync( document, semanticModel, originalSyntaxRoot, - _replacementText, + replacementText, _originalText, possibleNameConflicts, allTextSpansInSingleSourceTree, stringAndCommentTextSpansInSingleSourceTree, conflictLocationSpans, originalSolution, - _renameLocationSet.Symbol, + renameLocationSet.Symbol, replacementTextValid, renameSpansTracker, RenameOptions.RenameInStrings, RenameOptions.RenameInComments, _renameAnnotations, - _cancellationToken); + cancellationToken); var renameRewriterLanguageService = document.GetRequiredLanguageService(); var newRoot = renameRewriterLanguageService.AnnotateAndRename(parameters); diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictingIdentifierTracker.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictingIdentifierTracker.cs index 432875ac8efe4..b950cbf186d25 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictingIdentifierTracker.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictingIdentifierTracker.cs @@ -6,22 +6,15 @@ namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { - internal sealed class ConflictingIdentifierTracker + internal sealed class ConflictingIdentifierTracker(SyntaxToken tokenBeingRenamed, IEqualityComparer identifierComparer) { /// /// The core data structure of the tracker. This is a dictionary of variable name to the /// current identifier tokens that are declaring variables. This should only ever be updated /// via the AddIdentifier and RemoveIdentifier helpers. /// - private readonly Dictionary> _currentIdentifiersInScope; + private readonly Dictionary> _currentIdentifiersInScope = new Dictionary>(identifierComparer); private readonly HashSet _conflictingTokensToReport = new(); - private readonly SyntaxToken _tokenBeingRenamed; - - public ConflictingIdentifierTracker(SyntaxToken tokenBeingRenamed, IEqualityComparer identifierComparer) - { - _currentIdentifiersInScope = new Dictionary>(identifierComparer); - _tokenBeingRenamed = tokenBeingRenamed; - } public IEnumerable ConflictingTokens => _conflictingTokensToReport; @@ -41,11 +34,11 @@ public void AddIdentifier(SyntaxToken token) // If at least one of the identifiers is the one we're renaming, // track it. This means that conflicts unrelated to our rename (that // were there when we started) we won't flag. - if (conflictingTokens.Contains(_tokenBeingRenamed)) + if (conflictingTokens.Contains(tokenBeingRenamed)) { foreach (var conflictingToken in conflictingTokens) { - if (conflictingToken != _tokenBeingRenamed) + if (conflictingToken != tokenBeingRenamed) { // conflictingTokensToReport is a set, so we won't get duplicates _conflictingTokensToReport.Add(conflictingToken); diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/MutableConflictResolution.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/MutableConflictResolution.cs index f65e659e3654a..61a17c0b2c2a5 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/MutableConflictResolution.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/MutableConflictResolution.cs @@ -18,55 +18,43 @@ namespace Microsoft.CodeAnalysis.Rename.ConflictEngine /// /// The result of the conflict engine. Can be made immutable by calling . /// - internal sealed class MutableConflictResolution + internal sealed class MutableConflictResolution( + Solution oldSolution, + RenamedSpansTracker renamedSpansTracker, + string replacementText, + bool replacementTextValid) { - // Used to map spans from oldSolution to the newSolution - private readonly RenamedSpansTracker _renamedSpansTracker; // List of All the Locations that were renamed and conflict-complexified - public readonly List RelatedLocations; + public readonly List RelatedLocations = new List(); /// /// The base workspace snapshot /// - public readonly Solution OldSolution; + public readonly Solution OldSolution = oldSolution; /// /// Whether the text that was resolved with was even valid. This may be false if the /// identifier was not valid in some language that was involved in the rename. /// - public readonly bool ReplacementTextValid; + public readonly bool ReplacementTextValid = replacementTextValid; /// /// The original text that is the rename replacement. /// - public readonly string ReplacementText; + public readonly string ReplacementText = replacementText; /// /// The solution snapshot as it is being updated with specific rename steps. /// - public Solution CurrentSolution { get; private set; } + public Solution CurrentSolution { get; private set; } = oldSolution; private (DocumentId documentId, string newName) _renamedDocument; - public MutableConflictResolution( - Solution oldSolution, - RenamedSpansTracker renamedSpansTracker, - string replacementText, - bool replacementTextValid) - { - OldSolution = oldSolution; - CurrentSolution = oldSolution; - _renamedSpansTracker = renamedSpansTracker; - ReplacementText = replacementText; - ReplacementTextValid = replacementTextValid; - RelatedLocations = new List(); - } - internal void ClearDocuments(IEnumerable conflictLocationDocumentIds) { RelatedLocations.RemoveAll(r => conflictLocationDocumentIds.Contains(r.DocumentId)); - _renamedSpansTracker.ClearDocuments(conflictLocationDocumentIds); + renamedSpansTracker.ClearDocuments(conflictLocationDocumentIds); } internal void UpdateCurrentSolution(Solution solution) @@ -80,7 +68,7 @@ internal async Task RemoveAllRenameAnnotationsAsync( { foreach (var documentId in documentWithRenameAnnotations) { - if (_renamedSpansTracker.IsDocumentChanged(documentId)) + if (renamedSpansTracker.IsDocumentChanged(documentId)) { var document = CurrentSolution.GetRequiredDocument(documentId); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); @@ -139,7 +127,7 @@ internal void RenameDocumentToMatchNewSymbol(Document document) } public int GetAdjustedTokenStartingPosition(int startingPosition, DocumentId documentId) - => _renamedSpansTracker.GetAdjustedPosition(startingPosition, documentId); + => renamedSpansTracker.GetAdjustedPosition(startingPosition, documentId); internal void AddRelatedLocation(RelatedLocation location) => RelatedLocations.Add(location); @@ -155,13 +143,13 @@ internal void AddOrReplaceRelatedLocation(RelatedLocation location) public ConflictResolution ToConflictResolution() { - var documentIds = _renamedSpansTracker.DocumentIds.Concat( + var documentIds = renamedSpansTracker.DocumentIds.Concat( this.RelatedLocations.Select(l => l.DocumentId)).Distinct().ToImmutableArray(); var relatedLocations = this.RelatedLocations.ToImmutableArray(); - var documentToModifiedSpansMap = _renamedSpansTracker.GetDocumentToModifiedSpansMap(); - var documentToComplexifiedSpansMap = _renamedSpansTracker.GetDocumentToComplexifiedSpansMap(); + var documentToModifiedSpansMap = renamedSpansTracker.GetDocumentToModifiedSpansMap(); + var documentToComplexifiedSpansMap = renamedSpansTracker.GetDocumentToComplexifiedSpansMap(); var documentToRelatedLocationsMap = this.RelatedLocations.GroupBy(loc => loc.DocumentId).ToImmutableDictionary( g => g.Key, g => g.ToImmutableArray()); diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/RelatedLocation.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/RelatedLocation.cs index 4ea108faea20a..de591f335e514 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/RelatedLocation.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/RelatedLocation.cs @@ -13,39 +13,30 @@ namespace Microsoft.CodeAnalysis.Rename.ConflictEngine /// Gives information about an identifier span that was affected by Rename (Reference or Non reference) /// [DataContract] - internal readonly struct RelatedLocation : IEquatable + internal readonly struct RelatedLocation(TextSpan conflictCheckSpan, DocumentId documentId, RelatedLocationType type, bool isReference = false, TextSpan complexifiedTargetSpan = default) : IEquatable { /// /// The Span of the original identifier if it was in source, otherwise the span to check for implicit /// references. /// [DataMember(Order = 0)] - public readonly TextSpan ConflictCheckSpan; + public readonly TextSpan ConflictCheckSpan = conflictCheckSpan; [DataMember(Order = 1)] - public readonly DocumentId DocumentId; + public readonly DocumentId DocumentId = documentId; [DataMember(Order = 2)] - public readonly RelatedLocationType Type; + public readonly RelatedLocationType Type = type; [DataMember(Order = 3)] - public readonly bool IsReference; + public readonly bool IsReference = isReference; /// /// If there was a conflict at ConflictCheckSpan during rename, then the next phase in rename uses /// ComplexifiedTargetSpan span to be expanded to resolve the conflict. /// [DataMember(Order = 4)] - public readonly TextSpan ComplexifiedTargetSpan; - - public RelatedLocation(TextSpan conflictCheckSpan, DocumentId documentId, RelatedLocationType type, bool isReference = false, TextSpan complexifiedTargetSpan = default) - { - ConflictCheckSpan = conflictCheckSpan; - Type = type; - IsReference = isReference; - DocumentId = documentId; - ComplexifiedTargetSpan = complexifiedTargetSpan; - } + public readonly TextSpan ComplexifiedTargetSpan = complexifiedTargetSpan; public RelatedLocation WithType(RelatedLocationType type) => new(ConflictCheckSpan, DocumentId, type, IsReference, ComplexifiedTargetSpan); diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/RenamedSpansTracker.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/RenamedSpansTracker.cs index bf0f680d53c00..a8e02caeb0f55 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/RenamedSpansTracker.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/RenamedSpansTracker.cs @@ -118,19 +118,12 @@ internal int GetAdjustedPosition(int startingPosition, DocumentId documentId) /// "a", "NS3.a" /// /// - private class MutableComplexifiedSpan + private class MutableComplexifiedSpan( + TextSpan originalSpan, TextSpan newSpan, List<(TextSpan oldSpan, TextSpan newSpan)> modifiedSubSpans) { - public TextSpan OriginalSpan; - public TextSpan NewSpan; - public List<(TextSpan oldSpan, TextSpan newSpan)> ModifiedSubSpans; - - public MutableComplexifiedSpan( - TextSpan originalSpan, TextSpan newSpan, List<(TextSpan oldSpan, TextSpan newSpan)> modifiedSubSpans) - { - OriginalSpan = originalSpan; - NewSpan = newSpan; - ModifiedSubSpans = modifiedSubSpans; - } + public TextSpan OriginalSpan = originalSpan; + public TextSpan NewSpan = newSpan; + public List<(TextSpan oldSpan, TextSpan newSpan)> ModifiedSubSpans = modifiedSubSpans; } internal void ClearDocuments(IEnumerable conflictLocationDocumentIds) diff --git a/src/Workspaces/Core/Portable/Rename/IRemoteRenamerService.cs b/src/Workspaces/Core/Portable/Rename/IRemoteRenamerService.cs index a99489336a6fb..2efb2693e5883 100644 --- a/src/Workspaces/Core/Portable/Rename/IRemoteRenamerService.cs +++ b/src/Workspaces/Core/Portable/Rename/IRemoteRenamerService.cs @@ -73,46 +73,35 @@ public ValueTask GetOptionsAsync(RemoteServiceCallbackId cal } [DataContract] - internal readonly struct SerializableRenameLocation + internal readonly struct SerializableRenameLocation( + TextSpan location, + DocumentId documentId, + CandidateReason candidateReason, + bool isRenamableAliasUsage, + bool isRenamableAccessor, + TextSpan containingLocationForStringOrComment, + bool isWrittenTo) { [DataMember(Order = 0)] - public readonly TextSpan Location; + public readonly TextSpan Location = location; [DataMember(Order = 1)] - public readonly DocumentId DocumentId; + public readonly DocumentId DocumentId = documentId; [DataMember(Order = 2)] - public readonly CandidateReason CandidateReason; + public readonly CandidateReason CandidateReason = candidateReason; [DataMember(Order = 3)] - public readonly bool IsRenamableAliasUsage; + public readonly bool IsRenamableAliasUsage = isRenamableAliasUsage; [DataMember(Order = 4)] - public readonly bool IsRenamableAccessor; + public readonly bool IsRenamableAccessor = isRenamableAccessor; [DataMember(Order = 5)] - public readonly TextSpan ContainingLocationForStringOrComment; + public readonly TextSpan ContainingLocationForStringOrComment = containingLocationForStringOrComment; [DataMember(Order = 6)] - public readonly bool IsWrittenTo; - - public SerializableRenameLocation( - TextSpan location, - DocumentId documentId, - CandidateReason candidateReason, - bool isRenamableAliasUsage, - bool isRenamableAccessor, - TextSpan containingLocationForStringOrComment, - bool isWrittenTo) - { - Location = location; - DocumentId = documentId; - CandidateReason = candidateReason; - IsRenamableAliasUsage = isRenamableAliasUsage; - IsRenamableAccessor = isRenamableAccessor; - ContainingLocationForStringOrComment = containingLocationForStringOrComment; - IsWrittenTo = isWrittenTo; - } + public readonly bool IsWrittenTo = isWrittenTo; public static SerializableRenameLocation Dehydrate(RenameLocation location) => new(location.Location.SourceSpan, @@ -179,31 +168,23 @@ internal partial class SymbolicRenameLocations } [DataContract] - internal sealed class SerializableRenameLocations + internal sealed class SerializableRenameLocations( + SymbolRenameOptions options, + ImmutableArray locations, + ImmutableArray implicitLocations, + ImmutableArray referencedSymbols) { [DataMember(Order = 0)] - public readonly SymbolRenameOptions Options; + public readonly SymbolRenameOptions Options = options; [DataMember(Order = 1)] - public readonly ImmutableArray Locations; + public readonly ImmutableArray Locations = locations; [DataMember(Order = 2)] - public readonly ImmutableArray ImplicitLocations; + public readonly ImmutableArray ImplicitLocations = implicitLocations; [DataMember(Order = 3)] - public readonly ImmutableArray ReferencedSymbols; - - public SerializableRenameLocations( - SymbolRenameOptions options, - ImmutableArray locations, - ImmutableArray implicitLocations, - ImmutableArray referencedSymbols) - { - Options = options; - Locations = locations; - ImplicitLocations = implicitLocations; - ReferencedSymbols = referencedSymbols; - } + public readonly ImmutableArray ReferencedSymbols = referencedSymbols; public async ValueTask> RehydrateLocationsAsync( Solution solution, CancellationToken cancellationToken) @@ -217,19 +198,13 @@ public async ValueTask> RehydrateLocationsAsync( } [DataContract] - internal sealed class SerializableConflictResolution + internal sealed class SerializableConflictResolution(string? errorMessage, SuccessfulConflictResolution? resolution) { [DataMember(Order = 0)] - public readonly string? ErrorMessage; + public readonly string? ErrorMessage = errorMessage; [DataMember(Order = 1)] - public readonly SuccessfulConflictResolution? Resolution; - - public SerializableConflictResolution(string? errorMessage, SuccessfulConflictResolution? resolution) - { - ErrorMessage = errorMessage; - Resolution = resolution; - } + public readonly SuccessfulConflictResolution? Resolution = resolution; public async Task RehydrateAsync(Solution oldSolution, CancellationToken cancellationToken) { @@ -255,51 +230,39 @@ public async Task RehydrateAsync(Solution oldSolution, Cance } [DataContract] - internal sealed class SuccessfulConflictResolution + internal sealed class SuccessfulConflictResolution( + bool replacementTextValid, + (DocumentId documentId, string newName) renamedDocument, + ImmutableArray documentIds, + ImmutableArray relatedLocations, + ImmutableArray<(DocumentId, ImmutableArray)> documentTextChanges, + ImmutableDictionary> documentToModifiedSpansMap, + ImmutableDictionary> documentToComplexifiedSpansMap, + ImmutableDictionary> documentToRelatedLocationsMap) { [DataMember(Order = 0)] - public readonly bool ReplacementTextValid; + public readonly bool ReplacementTextValid = replacementTextValid; [DataMember(Order = 1)] - public readonly (DocumentId documentId, string newName) RenamedDocument; + public readonly (DocumentId documentId, string newName) RenamedDocument = renamedDocument; [DataMember(Order = 2)] - public readonly ImmutableArray DocumentIds; + public readonly ImmutableArray DocumentIds = documentIds; [DataMember(Order = 3)] - public readonly ImmutableArray RelatedLocations; + public readonly ImmutableArray RelatedLocations = relatedLocations; [DataMember(Order = 4)] - public readonly ImmutableArray<(DocumentId, ImmutableArray)> DocumentTextChanges; + public readonly ImmutableArray<(DocumentId, ImmutableArray)> DocumentTextChanges = documentTextChanges; [DataMember(Order = 5)] - public readonly ImmutableDictionary> DocumentToModifiedSpansMap; + public readonly ImmutableDictionary> DocumentToModifiedSpansMap = documentToModifiedSpansMap; [DataMember(Order = 6)] - public readonly ImmutableDictionary> DocumentToComplexifiedSpansMap; + public readonly ImmutableDictionary> DocumentToComplexifiedSpansMap = documentToComplexifiedSpansMap; [DataMember(Order = 7)] - public readonly ImmutableDictionary> DocumentToRelatedLocationsMap; - - public SuccessfulConflictResolution( - bool replacementTextValid, - (DocumentId documentId, string newName) renamedDocument, - ImmutableArray documentIds, - ImmutableArray relatedLocations, - ImmutableArray<(DocumentId, ImmutableArray)> documentTextChanges, - ImmutableDictionary> documentToModifiedSpansMap, - ImmutableDictionary> documentToComplexifiedSpansMap, - ImmutableDictionary> documentToRelatedLocationsMap) - { - ReplacementTextValid = replacementTextValid; - RenamedDocument = renamedDocument; - DocumentIds = documentIds; - RelatedLocations = relatedLocations; - DocumentTextChanges = documentTextChanges; - DocumentToModifiedSpansMap = documentToModifiedSpansMap; - DocumentToComplexifiedSpansMap = documentToComplexifiedSpansMap; - DocumentToRelatedLocationsMap = documentToRelatedLocationsMap; - } + public readonly ImmutableDictionary> DocumentToRelatedLocationsMap = documentToRelatedLocationsMap; } internal partial struct ConflictResolution diff --git a/src/Workspaces/Core/Portable/Rename/RenameLocation.cs b/src/Workspaces/Core/Portable/Rename/RenameLocation.cs index 52b7fca387f53..61163be1d4994 100644 --- a/src/Workspaces/Core/Portable/Rename/RenameLocation.cs +++ b/src/Workspaces/Core/Portable/Rename/RenameLocation.cs @@ -8,36 +8,25 @@ namespace Microsoft.CodeAnalysis.Rename { - internal readonly struct RenameLocation : IEquatable + internal readonly struct RenameLocation( + Location location, + DocumentId documentId, + CandidateReason candidateReason = CandidateReason.None, + bool isRenamableAliasUsage = false, + bool isRenamableAccessor = false, + bool isWrittenTo = false, + TextSpan containingLocationForStringOrComment = default) : IEquatable { - public readonly Location Location; - public readonly DocumentId DocumentId; - public readonly CandidateReason CandidateReason; - public readonly bool IsRenamableAliasUsage; - public readonly bool IsRenamableAccessor; - public readonly TextSpan ContainingLocationForStringOrComment; - public readonly bool IsWrittenTo; + public readonly Location Location = location; + public readonly DocumentId DocumentId = documentId; + public readonly CandidateReason CandidateReason = candidateReason; + public readonly bool IsRenamableAliasUsage = isRenamableAliasUsage; + public readonly bool IsRenamableAccessor = isRenamableAccessor; + public readonly TextSpan ContainingLocationForStringOrComment = containingLocationForStringOrComment; + public readonly bool IsWrittenTo = isWrittenTo; public bool IsRenameInStringOrComment => ContainingLocationForStringOrComment != default; - public RenameLocation( - Location location, - DocumentId documentId, - CandidateReason candidateReason = CandidateReason.None, - bool isRenamableAliasUsage = false, - bool isRenamableAccessor = false, - bool isWrittenTo = false, - TextSpan containingLocationForStringOrComment = default) - { - Location = location; - DocumentId = documentId; - CandidateReason = candidateReason; - IsRenamableAliasUsage = isRenamableAliasUsage; - IsRenamableAccessor = isRenamableAccessor; - IsWrittenTo = isWrittenTo; - ContainingLocationForStringOrComment = containingLocationForStringOrComment; - } - public RenameLocation(ReferenceLocation referenceLocation, DocumentId documentId) : this(referenceLocation.Location, documentId, candidateReason: referenceLocation.CandidateReason, diff --git a/src/Workspaces/Core/Portable/Rename/RenameRewriterParameters.cs b/src/Workspaces/Core/Portable/Rename/RenameRewriterParameters.cs index 1d077cb4f7008..d527438758c54 100644 --- a/src/Workspaces/Core/Portable/Rename/RenameRewriterParameters.cs +++ b/src/Workspaces/Core/Portable/Rename/RenameRewriterParameters.cs @@ -11,67 +11,44 @@ namespace Microsoft.CodeAnalysis.Rename { - internal class RenameRewriterParameters + internal class RenameRewriterParameters( + RenameAnnotation renamedSymbolDeclarationAnnotation, + Document document, + SemanticModel semanticModel, + SyntaxNode syntaxRoot, + string replacementText, + string originalText, + ImmutableArray possibleNameConflicts, + ImmutableDictionary renameLocations, + ImmutableDictionary?> stringAndCommentTextSpans, + ImmutableHashSet conflictLocationSpans, + Solution originalSolution, + ISymbol renameSymbol, + bool replacementTextValid, + RenamedSpansTracker renameSpansTracker, + bool isRenamingInStrings, + bool isRenamingInComments, + AnnotationTable renameAnnotations, + CancellationToken cancellationToken) { - internal readonly CancellationToken CancellationToken; - internal readonly ImmutableHashSet ConflictLocationSpans; - internal readonly bool IsRenamingInStrings; - internal readonly bool IsRenamingInComments; - internal readonly Solution OriginalSolution; - internal readonly SyntaxTree OriginalSyntaxTree; - internal readonly string OriginalText; - internal readonly ImmutableArray PossibleNameConflicts; - internal readonly RenameAnnotation RenamedSymbolDeclarationAnnotation; - internal readonly ImmutableDictionary RenameLocations; - internal readonly RenamedSpansTracker RenameSpansTracker; - internal readonly ISymbol RenameSymbol; - internal readonly string ReplacementText; - internal readonly bool ReplacementTextValid; - internal readonly ImmutableDictionary?> StringAndCommentTextSpans; - internal readonly SyntaxNode SyntaxRoot; - internal readonly Document Document; - internal readonly SemanticModel SemanticModel; - internal readonly AnnotationTable RenameAnnotations; - - public RenameRewriterParameters( - RenameAnnotation renamedSymbolDeclarationAnnotation, - Document document, - SemanticModel semanticModel, - SyntaxNode syntaxRoot, - string replacementText, - string originalText, - ImmutableArray possibleNameConflicts, - ImmutableDictionary renameLocations, - ImmutableDictionary?> stringAndCommentTextSpans, - ImmutableHashSet conflictLocationSpans, - Solution originalSolution, - ISymbol renameSymbol, - bool replacementTextValid, - RenamedSpansTracker renameSpansTracker, - bool isRenamingInStrings, - bool isRenamingInComments, - AnnotationTable renameAnnotations, - CancellationToken cancellationToken) - { - RenamedSymbolDeclarationAnnotation = renamedSymbolDeclarationAnnotation; - Document = document; - SemanticModel = semanticModel; - SyntaxRoot = syntaxRoot; - OriginalSyntaxTree = semanticModel.SyntaxTree; - ReplacementText = replacementText; - OriginalText = originalText; - PossibleNameConflicts = possibleNameConflicts; - RenameLocations = renameLocations; - StringAndCommentTextSpans = stringAndCommentTextSpans; - ConflictLocationSpans = conflictLocationSpans; - OriginalSolution = originalSolution; - RenameSymbol = renameSymbol; - ReplacementTextValid = replacementTextValid; - CancellationToken = cancellationToken; - RenameSpansTracker = renameSpansTracker; - IsRenamingInStrings = isRenamingInStrings; - IsRenamingInComments = isRenamingInComments; - RenameAnnotations = renameAnnotations; - } + internal readonly CancellationToken CancellationToken = cancellationToken; + internal readonly ImmutableHashSet ConflictLocationSpans = conflictLocationSpans; + internal readonly bool IsRenamingInStrings = isRenamingInStrings; + internal readonly bool IsRenamingInComments = isRenamingInComments; + internal readonly Solution OriginalSolution = originalSolution; + internal readonly SyntaxTree OriginalSyntaxTree = semanticModel.SyntaxTree; + internal readonly string OriginalText = originalText; + internal readonly ImmutableArray PossibleNameConflicts = possibleNameConflicts; + internal readonly RenameAnnotation RenamedSymbolDeclarationAnnotation = renamedSymbolDeclarationAnnotation; + internal readonly ImmutableDictionary RenameLocations = renameLocations; + internal readonly RenamedSpansTracker RenameSpansTracker = renameSpansTracker; + internal readonly ISymbol RenameSymbol = renameSymbol; + internal readonly string ReplacementText = replacementText; + internal readonly bool ReplacementTextValid = replacementTextValid; + internal readonly ImmutableDictionary?> StringAndCommentTextSpans = stringAndCommentTextSpans; + internal readonly SyntaxNode SyntaxRoot = syntaxRoot; + internal readonly Document Document = document; + internal readonly SemanticModel SemanticModel = semanticModel; + internal readonly AnnotationTable RenameAnnotations = renameAnnotations; } } diff --git a/src/Workspaces/Core/Portable/Rename/Renamer.RenameDocumentAction.cs b/src/Workspaces/Core/Portable/Rename/Renamer.RenameDocumentAction.cs index c3b122458e520..e32368c8e5028 100644 --- a/src/Workspaces/Core/Portable/Rename/Renamer.RenameDocumentAction.cs +++ b/src/Workspaces/Core/Portable/Rename/Renamer.RenameDocumentAction.cs @@ -43,16 +43,10 @@ public ImmutableArray GetErrors(CultureInfo? culture = null) internal abstract Task GetModifiedSolutionAsync(Document document, DocumentRenameOptions options, CancellationToken cancellationToken); - internal readonly struct ErrorResource + internal readonly struct ErrorResource(string formatString, object[] arguments) { - public string FormatString { get; } - public object[] Arguments { get; } - - public ErrorResource(string formatString, object[] arguments) - { - FormatString = formatString; - Arguments = arguments; - } + public string FormatString { get; } = formatString; + public object[] Arguments { get; } = arguments; } } } diff --git a/src/Workspaces/Core/Portable/Rename/Renamer.RenameSymbolDocumentAction.cs b/src/Workspaces/Core/Portable/Rename/Renamer.RenameSymbolDocumentAction.cs index 66faad591827e..be197e6ad7fec 100644 --- a/src/Workspaces/Core/Portable/Rename/Renamer.RenameSymbolDocumentAction.cs +++ b/src/Workspaces/Core/Portable/Rename/Renamer.RenameSymbolDocumentAction.cs @@ -120,39 +120,31 @@ internal override async Task GetModifiedSolutionAsync(Document documen symbol.Name); } - private readonly struct AnalysisResult + private readonly struct AnalysisResult( + Document document, + string newDocumentName, + string newSymbolName, + string originalSymbolName) { /// /// Name of the document that the action was produced for. /// - public string OriginalDocumentName { get; } + public string OriginalDocumentName { get; } = document.Name; /// /// The new document name that will be used. /// - public string NewDocumentName { get; } + public string NewDocumentName { get; } = newDocumentName; /// /// The original name of the symbol that will be changed. /// - public string OriginalSymbolName { get; } + public string OriginalSymbolName { get; } = originalSymbolName; /// /// The new name for the symbol. /// - public string NewSymbolName { get; } - - public AnalysisResult( - Document document, - string newDocumentName, - string newSymbolName, - string originalSymbolName) - { - OriginalDocumentName = document.Name; - NewDocumentName = newDocumentName; - NewSymbolName = newSymbolName; - OriginalSymbolName = originalSymbolName; - } + public string NewSymbolName { get; } = newSymbolName; } } } diff --git a/src/Workspaces/Core/Portable/Rename/Renamer.SyncNamespaceDocumentAction.cs b/src/Workspaces/Core/Portable/Rename/Renamer.SyncNamespaceDocumentAction.cs index 1cf0290d24749..4071b58f02393 100644 --- a/src/Workspaces/Core/Portable/Rename/Renamer.SyncNamespaceDocumentAction.cs +++ b/src/Workspaces/Core/Portable/Rename/Renamer.SyncNamespaceDocumentAction.cs @@ -87,14 +87,9 @@ internal override async Task GetModifiedSolutionAsync(Document documen } } - private readonly struct AnalysisResult + private readonly struct AnalysisResult(string targetNamespace) { - public string TargetNamespace { get; } - - public AnalysisResult(string targetNamespace) - { - TargetNamespace = targetNamespace; - } + public string TargetNamespace { get; } = targetNamespace; } } } diff --git a/src/Workspaces/Core/Portable/Rename/TokenRenameInfo.cs b/src/Workspaces/Core/Portable/Rename/TokenRenameInfo.cs index f8ca1c5c9f08e..5e243864d2b86 100644 --- a/src/Workspaces/Core/Portable/Rename/TokenRenameInfo.cs +++ b/src/Workspaces/Core/Portable/Rename/TokenRenameInfo.cs @@ -7,18 +7,11 @@ namespace Microsoft.CodeAnalysis.Rename { - internal sealed class TokenRenameInfo + internal sealed class TokenRenameInfo(bool hasSymbols, IEnumerable symbols, bool isMemberGroup) { - public bool HasSymbols { get; private set; } - public IEnumerable Symbols { get; private set; } - public bool IsMemberGroup { get; private set; } - - public TokenRenameInfo(bool hasSymbols, IEnumerable symbols, bool isMemberGroup) - { - HasSymbols = hasSymbols; - Symbols = symbols; - IsMemberGroup = isMemberGroup; - } + public bool HasSymbols { get; private set; } = hasSymbols; + public IEnumerable Symbols { get; private set; } = symbols; + public bool IsMemberGroup { get; private set; } = isMemberGroup; public static TokenRenameInfo CreateMemberGroupTokenInfo(IEnumerable symbols) { diff --git a/src/Workspaces/Core/Portable/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs b/src/Workspaces/Core/Portable/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs index 8f2cf482d46ef..34783eac77aca 100644 --- a/src/Workspaces/Core/Portable/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs +++ b/src/Workspaces/Core/Portable/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs @@ -124,20 +124,8 @@ protected SyntaxNode GetPreviousBodyNode(SyntaxNode previousRoot, SyntaxNode cur } } - private sealed class NonEquivalentTreeException : Exception + private sealed class NonEquivalentTreeException(string message, SyntaxTree originalSyntaxTree, SyntaxTree updatedSyntaxTree) : Exception(message) { - // Used for analyzing dumps -#pragma warning disable IDE0052 // Remove unread private members - private readonly SyntaxTree _originalSyntaxTree; - private readonly SyntaxTree _updatedSyntaxTree; -#pragma warning restore IDE0052 // Remove unread private members - - public NonEquivalentTreeException(string message, SyntaxTree originalSyntaxTree, SyntaxTree updatedSyntaxTree) - : base(message) - { - _originalSyntaxTree = originalSyntaxTree; - _updatedSyntaxTree = updatedSyntaxTree; - } } } } diff --git a/src/Workspaces/Core/Portable/SemanticModelReuse/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.cs b/src/Workspaces/Core/Portable/SemanticModelReuse/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.cs index 77c43c63b86ae..e36b1e874423b 100644 --- a/src/Workspaces/Core/Portable/SemanticModelReuse/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.cs +++ b/src/Workspaces/Core/Portable/SemanticModelReuse/SemanticModelWorkspaceServiceFactory.SemanticModelWorkspaceService.cs @@ -13,37 +13,29 @@ namespace Microsoft.CodeAnalysis.SemanticModelReuse { - internal readonly struct SemanticModelReuseInfo + internal readonly struct SemanticModelReuseInfo(SemanticModel previousNonSpeculativeSemanticModel, SemanticModel currentSemanticModel, SyntaxNode bodyNode, VersionStamp topLevelSementicVersion) { /// /// The original non-speculative semantic model we retrieved for this document at some point. /// - public readonly SemanticModel PreviousNonSpeculativeSemanticModel; + public readonly SemanticModel PreviousNonSpeculativeSemanticModel = previousNonSpeculativeSemanticModel; /// /// The current semantic model we retrieved for the . Could /// be speculative or non-speculative. /// - public readonly SemanticModel CurrentSemanticModel; + public readonly SemanticModel CurrentSemanticModel = currentSemanticModel; /// /// The current method body we retrieved the for. /// - public readonly SyntaxNode BodyNode; + public readonly SyntaxNode BodyNode = bodyNode; /// /// The top level version of the project when we retrieved . As long as this is the /// same we can continue getting speculative models to use. /// - public readonly VersionStamp TopLevelSemanticVersion; - - public SemanticModelReuseInfo(SemanticModel previousNonSpeculativeSemanticModel, SemanticModel currentSemanticModel, SyntaxNode bodyNode, VersionStamp topLevelSementicVersion) - { - PreviousNonSpeculativeSemanticModel = previousNonSpeculativeSemanticModel; - CurrentSemanticModel = currentSemanticModel; - BodyNode = bodyNode; - TopLevelSemanticVersion = topLevelSementicVersion; - } + public readonly VersionStamp TopLevelSemanticVersion = topLevelSementicVersion; } internal partial class SemanticModelReuseWorkspaceServiceFactory : IWorkspaceServiceFactory diff --git a/src/Workspaces/Core/Portable/Serialization/SerializerService_Reference.cs b/src/Workspaces/Core/Portable/Serialization/SerializerService_Reference.cs index bc4ffd25e83ee..8dfb3f69fd3a0 100644 --- a/src/Workspaces/Core/Portable/Serialization/SerializerService_Reference.cs +++ b/src/Workspaces/Core/Portable/Serialization/SerializerService_Reference.cs @@ -564,13 +564,10 @@ private static void WriteUnresolvedAnalyzerReferenceTo(AnalyzerReference referen } } - private sealed class PinnedObject : IDisposable + private sealed class PinnedObject(byte[] array) : IDisposable { // shouldn't be read-only since GCHandle is a mutable struct - private GCHandle _gcHandle; - - public PinnedObject(byte[] array) - => _gcHandle = GCHandle.Alloc(array, GCHandleType.Pinned); + private GCHandle _gcHandle = GCHandle.Alloc(array, GCHandleType.Pinned); internal IntPtr GetPointer() => _gcHandle.AddrOfPinnedObject(); @@ -593,18 +590,9 @@ public void Dispose() } } - private sealed class MissingMetadataReference : PortableExecutableReference + private sealed class MissingMetadataReference( + MetadataReferenceProperties properties, string? fullPath, DocumentationProvider initialDocumentation) : PortableExecutableReference(properties, fullPath, initialDocumentation) { - private readonly DocumentationProvider _provider; - - public MissingMetadataReference( - MetadataReferenceProperties properties, string? fullPath, DocumentationProvider initialDocumentation) - : base(properties, fullPath, initialDocumentation) - { - // TODO: doc comment provider is a bit weird. - _provider = initialDocumentation; - } - protected override DocumentationProvider CreateDocumentationProvider() { // TODO: properly implement this @@ -623,27 +611,14 @@ protected override Metadata GetMetadataImpl() } protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) - => new MissingMetadataReference(properties, FilePath, _provider); + => new MissingMetadataReference(properties, FilePath, initialDocumentation); } [DebuggerDisplay("{" + nameof(Display) + ",nq}")] - private sealed class SerializedMetadataReference : PortableExecutableReference, ISupportTemporaryStorage + private sealed class SerializedMetadataReference( + MetadataReferenceProperties properties, string? fullPath, + Metadata metadata, ImmutableArray storagesOpt, DocumentationProvider initialDocumentation) : PortableExecutableReference(properties, fullPath, initialDocumentation), ISupportTemporaryStorage { - private readonly Metadata _metadata; - private readonly ImmutableArray _storagesOpt; - private readonly DocumentationProvider _provider; - - public SerializedMetadataReference( - MetadataReferenceProperties properties, string? fullPath, - Metadata metadata, ImmutableArray storagesOpt, DocumentationProvider initialDocumentation) - : base(properties, fullPath, initialDocumentation) - { - _metadata = metadata; - _storagesOpt = storagesOpt; - - _provider = initialDocumentation; - } - protected override DocumentationProvider CreateDocumentationProvider() { // this uses documentation provider given at the constructor @@ -651,13 +626,13 @@ protected override DocumentationProvider CreateDocumentationProvider() } protected override Metadata GetMetadataImpl() - => _metadata; + => metadata; protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) - => new SerializedMetadataReference(properties, FilePath, _metadata, _storagesOpt, _provider); + => new SerializedMetadataReference(properties, FilePath, metadata, storagesOpt, initialDocumentation); public IReadOnlyList? GetStorages() - => _storagesOpt.IsDefault ? null : _storagesOpt; + => storagesOpt.IsDefault ? null : storagesOpt; } } } diff --git a/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.AnonymousTypeRemover.cs b/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.AnonymousTypeRemover.cs index ced1df3aff99d..c83b1180019c1 100644 --- a/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.AnonymousTypeRemover.cs +++ b/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.AnonymousTypeRemover.cs @@ -11,13 +11,8 @@ namespace Microsoft.CodeAnalysis.Shared.Extensions { internal partial class ITypeSymbolExtensions { - private class AnonymousTypeRemover : SymbolVisitor + private class AnonymousTypeRemover(Compilation compilation) : SymbolVisitor { - private readonly Compilation _compilation; - - public AnonymousTypeRemover(Compilation compilation) - => _compilation = compilation; - public override ITypeSymbol DefaultVisit(ISymbol node) => throw new NotImplementedException(); @@ -32,7 +27,7 @@ public override ITypeSymbol VisitArrayType(IArrayTypeSymbol symbol) return symbol; } - return _compilation.CreateArrayTypeSymbol(elementType, symbol.Rank); + return compilation.CreateArrayTypeSymbol(elementType, symbol.Rank); } public override ITypeSymbol VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) @@ -46,7 +41,7 @@ public override ITypeSymbol VisitFunctionPointerType(IFunctionPointerTypeSymbol public override ITypeSymbol VisitNamedType(INamedTypeSymbol symbol) { if (symbol.IsAnonymousType()) - return _compilation.ObjectType; + return compilation.ObjectType; var arguments = symbol.TypeArguments.Select(t => t.Accept(this)).ToArray(); if (arguments.SequenceEqual(symbol.TypeArguments)) @@ -63,7 +58,7 @@ public override ITypeSymbol VisitPointerType(IPointerTypeSymbol symbol) return symbol; } - return _compilation.CreatePointerTypeSymbol(elementType); + return compilation.CreatePointerTypeSymbol(elementType); } public override ITypeSymbol VisitTypeParameter(ITypeParameterSymbol symbol) diff --git a/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.CompilationTypeGenerator.cs b/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.CompilationTypeGenerator.cs index dec289b3a5c72..66268e730ea36 100644 --- a/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.CompilationTypeGenerator.cs +++ b/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.CompilationTypeGenerator.cs @@ -8,18 +8,13 @@ namespace Microsoft.CodeAnalysis.Shared.Extensions { internal partial class ITypeSymbolExtensions { - private class CompilationTypeGenerator : ITypeGenerator + private class CompilationTypeGenerator(Compilation compilation) : ITypeGenerator { - private readonly Compilation _compilation; - - public CompilationTypeGenerator(Compilation compilation) - => _compilation = compilation; - public ITypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank) - => _compilation.CreateArrayTypeSymbol(elementType, rank); + => compilation.CreateArrayTypeSymbol(elementType, rank); public ITypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType) - => _compilation.CreatePointerTypeSymbol(pointedAtType); + => compilation.CreatePointerTypeSymbol(pointedAtType); public ITypeSymbol Construct(INamedTypeSymbol namedType, ITypeSymbol[] typeArguments) => namedType.Construct(typeArguments); diff --git a/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.UnavailableTypeParameterRemover.cs b/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.UnavailableTypeParameterRemover.cs index e2a93fc44e4df..25aea3e8c24aa 100644 --- a/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.UnavailableTypeParameterRemover.cs +++ b/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.UnavailableTypeParameterRemover.cs @@ -12,17 +12,8 @@ namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ITypeSymbolExtensions { - private class UnavailableTypeParameterRemover : SymbolVisitor + private class UnavailableTypeParameterRemover(Compilation compilation, ISet availableTypeParameterNames) : SymbolVisitor { - private readonly Compilation _compilation; - private readonly ISet _availableTypeParameterNames; - - public UnavailableTypeParameterRemover(Compilation compilation, ISet availableTypeParameterNames) - { - _compilation = compilation; - _availableTypeParameterNames = availableTypeParameterNames; - } - public override ITypeSymbol DefaultVisit(ISymbol node) => throw new NotImplementedException(); @@ -37,7 +28,7 @@ public override ITypeSymbol VisitArrayType(IArrayTypeSymbol symbol) return symbol; } - return _compilation.CreateArrayTypeSymbol(elementType, symbol.Rank); + return compilation.CreateArrayTypeSymbol(elementType, symbol.Rank); } public override ITypeSymbol VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) @@ -65,17 +56,17 @@ public override ITypeSymbol VisitPointerType(IPointerTypeSymbol symbol) return symbol; } - return _compilation.CreatePointerTypeSymbol(elementType); + return compilation.CreatePointerTypeSymbol(elementType); } public override ITypeSymbol VisitTypeParameter(ITypeParameterSymbol symbol) { - if (_availableTypeParameterNames.Contains(symbol.Name)) + if (availableTypeParameterNames.Contains(symbol.Name)) { return symbol; } - return _compilation.ObjectType; + return compilation.ObjectType; } } } diff --git a/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.UnnamedErrorTypeRemover.cs b/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.UnnamedErrorTypeRemover.cs index 851680b25423e..43f24f015381d 100644 --- a/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.UnnamedErrorTypeRemover.cs +++ b/src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.UnnamedErrorTypeRemover.cs @@ -11,13 +11,8 @@ namespace Microsoft.CodeAnalysis.Shared.Extensions { internal partial class ITypeSymbolExtensions { - private class UnnamedErrorTypeRemover : SymbolVisitor + private class UnnamedErrorTypeRemover(Compilation compilation) : SymbolVisitor { - private readonly Compilation _compilation; - - public UnnamedErrorTypeRemover(Compilation compilation) - => _compilation = compilation; - public override ITypeSymbol DefaultVisit(ISymbol node) => throw new NotImplementedException(); @@ -32,7 +27,7 @@ public override ITypeSymbol VisitArrayType(IArrayTypeSymbol symbol) return symbol; } - return _compilation.CreateArrayTypeSymbol(elementType, symbol.Rank); + return compilation.CreateArrayTypeSymbol(elementType, symbol.Rank); } public override ITypeSymbol VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) @@ -45,7 +40,7 @@ public override ITypeSymbol VisitNamedType(INamedTypeSymbol symbol) { if (symbol.IsErrorType() && symbol.Name == string.Empty) { - return _compilation.ObjectType; + return compilation.ObjectType; } var arguments = symbol.TypeArguments.Select(t => t.Accept(this)).ToArray(); @@ -65,7 +60,7 @@ public override ITypeSymbol VisitPointerType(IPointerTypeSymbol symbol) return symbol; } - return _compilation.CreatePointerTypeSymbol(elementType); + return compilation.CreatePointerTypeSymbol(elementType); } public override ITypeSymbol VisitTypeParameter(ITypeParameterSymbol symbol) diff --git a/src/Workspaces/Core/Portable/Shared/Extensions/TokenSemanticInfo.cs b/src/Workspaces/Core/Portable/Shared/Extensions/TokenSemanticInfo.cs index a21d810cf958b..a02fcdba4fcf4 100644 --- a/src/Workspaces/Core/Portable/Shared/Extensions/TokenSemanticInfo.cs +++ b/src/Workspaces/Core/Portable/Shared/Extensions/TokenSemanticInfo.cs @@ -11,33 +11,23 @@ namespace Microsoft.CodeAnalysis.Shared.Extensions { - internal readonly struct TokenSemanticInfo + internal readonly struct TokenSemanticInfo( + ISymbol declaredSymbol, + IAliasSymbol aliasSymbol, + ImmutableArray referencedSymbols, + ITypeSymbol type, + ITypeSymbol convertedType, + TextSpan span) { public static readonly TokenSemanticInfo Empty = new( null, null, ImmutableArray.Empty, null, null, default); - public readonly ISymbol DeclaredSymbol; - public readonly IAliasSymbol AliasSymbol; - public readonly ImmutableArray ReferencedSymbols; - public readonly ITypeSymbol Type; - public readonly ITypeSymbol ConvertedType; - public readonly TextSpan Span; - - public TokenSemanticInfo( - ISymbol declaredSymbol, - IAliasSymbol aliasSymbol, - ImmutableArray referencedSymbols, - ITypeSymbol type, - ITypeSymbol convertedType, - TextSpan span) - { - DeclaredSymbol = declaredSymbol; - AliasSymbol = aliasSymbol; - ReferencedSymbols = referencedSymbols; - Type = type; - ConvertedType = convertedType; - Span = span; - } + public readonly ISymbol DeclaredSymbol = declaredSymbol; + public readonly IAliasSymbol AliasSymbol = aliasSymbol; + public readonly ImmutableArray ReferencedSymbols = referencedSymbols; + public readonly ITypeSymbol Type = type; + public readonly ITypeSymbol ConvertedType = convertedType; + public readonly TextSpan Span = span; public ImmutableArray GetSymbols(bool includeType) { diff --git a/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener+DiagnosticAsyncToken.cs b/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener+DiagnosticAsyncToken.cs index f84e807da3fd6..c87396b2c4e3e 100644 --- a/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener+DiagnosticAsyncToken.cs +++ b/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener+DiagnosticAsyncToken.cs @@ -13,28 +13,19 @@ internal sealed partial class AsynchronousOperationListener /// Stores the source information for an value. Helpful when /// tracking down tokens which aren't properly disposed. /// - internal sealed class DiagnosticAsyncToken : AsyncToken + internal sealed class DiagnosticAsyncToken( + AsynchronousOperationListener listener, + string name, + object? tag, + string filePath, + int lineNumber) : AsyncToken(listener) { - public string Name { get; } - public string FilePath { get; } - public int LineNumber { get; } - public object? Tag { get; } + public string Name { get; } = name; + public string FilePath { get; } = filePath; + public int LineNumber { get; } = lineNumber; + public object? Tag { get; } = tag; public Task? Task { get; set; } - public DiagnosticAsyncToken( - AsynchronousOperationListener listener, - string name, - object? tag, - string filePath, - int lineNumber) - : base(listener) - { - Name = name; - Tag = tag; - FilePath = filePath; - LineNumber = lineNumber; - } - internal void AssociateWithTask(Task task) => Task = task; diff --git a/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs b/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs index f06a431ed9270..fdc1d3dc29e6b 100644 --- a/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs +++ b/src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.cs @@ -13,16 +13,13 @@ namespace Microsoft.CodeAnalysis.Shared.TestHooks { - internal sealed partial class AsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter + internal sealed partial class AsynchronousOperationListener(string featureName, bool enableDiagnosticTokens) : IAsynchronousOperationListener, IAsynchronousOperationWaiter { private readonly NonReentrantLock _gate = new(); - -#pragma warning disable IDE0052 // Remove unread private members - Can this field be removed? - private readonly string _featureName; #pragma warning restore IDE0052 // Remove unread private members private readonly HashSet> _pendingTasks = new(); - private CancellationTokenSource _expeditedDelayCancellationTokenSource; + private CancellationTokenSource _expeditedDelayCancellationTokenSource = new CancellationTokenSource(); private List _diagnosticTokenList = new(); private int _counter; @@ -33,13 +30,6 @@ public AsynchronousOperationListener() { } - public AsynchronousOperationListener(string featureName, bool enableDiagnosticTokens) - { - _featureName = featureName; - _expeditedDelayCancellationTokenSource = new CancellationTokenSource(); - TrackActiveTokens = Debugger.IsAttached || enableDiagnosticTokens; - } - [PerformanceSensitive( "https://github.com/dotnet/roslyn/pull/58646", Constraint = "Cannot use async/await because it produces large numbers of first-chance cancellation exceptions.")] @@ -213,7 +203,7 @@ public bool TrackActiveTokens _diagnosticTokenList = new List(); } } - } + } = Debugger.IsAttached || enableDiagnosticTokens; public bool HasPendingWork { diff --git a/src/Workspaces/Core/Portable/Shared/Utilities/AsyncBatchingWorkQueue`0.cs b/src/Workspaces/Core/Portable/Shared/Utilities/AsyncBatchingWorkQueue`0.cs index ad7914453c8c5..24b266705dabc 100644 --- a/src/Workspaces/Core/Portable/Shared/Utilities/AsyncBatchingWorkQueue`0.cs +++ b/src/Workspaces/Core/Portable/Shared/Utilities/AsyncBatchingWorkQueue`0.cs @@ -12,17 +12,12 @@ namespace Roslyn.Utilities { /// - internal class AsyncBatchingWorkQueue : AsyncBatchingWorkQueue + internal class AsyncBatchingWorkQueue( + TimeSpan delay, + Func processBatchAsync, + IAsynchronousOperationListener asyncListener, + CancellationToken cancellationToken) : AsyncBatchingWorkQueue(delay, Convert(processBatchAsync), EqualityComparer.Default, asyncListener, cancellationToken) { - public AsyncBatchingWorkQueue( - TimeSpan delay, - Func processBatchAsync, - IAsynchronousOperationListener asyncListener, - CancellationToken cancellationToken) - : base(delay, Convert(processBatchAsync), EqualityComparer.Default, asyncListener, cancellationToken) - { - } - private static Func, CancellationToken, ValueTask> Convert(Func processBatchAsync) => (items, ct) => processBatchAsync(ct); diff --git a/src/Workspaces/Core/Portable/Shared/Utilities/AsyncBatchingWorkQueue`1.cs b/src/Workspaces/Core/Portable/Shared/Utilities/AsyncBatchingWorkQueue`1.cs index e0e31db4c4770..49aa45138199e 100644 --- a/src/Workspaces/Core/Portable/Shared/Utilities/AsyncBatchingWorkQueue`1.cs +++ b/src/Workspaces/Core/Portable/Shared/Utilities/AsyncBatchingWorkQueue`1.cs @@ -12,7 +12,12 @@ namespace Roslyn.Utilities { /// - internal class AsyncBatchingWorkQueue : AsyncBatchingWorkQueue + internal class AsyncBatchingWorkQueue( + TimeSpan delay, + Func, CancellationToken, ValueTask> processBatchAsync, + IEqualityComparer? equalityComparer, + IAsynchronousOperationListener asyncListener, + CancellationToken cancellationToken) : AsyncBatchingWorkQueue(delay, Convert(processBatchAsync), equalityComparer, asyncListener, cancellationToken) { public AsyncBatchingWorkQueue( TimeSpan delay, @@ -27,16 +32,6 @@ public AsyncBatchingWorkQueue( { } - public AsyncBatchingWorkQueue( - TimeSpan delay, - Func, CancellationToken, ValueTask> processBatchAsync, - IEqualityComparer? equalityComparer, - IAsynchronousOperationListener asyncListener, - CancellationToken cancellationToken) - : base(delay, Convert(processBatchAsync), equalityComparer, asyncListener, cancellationToken) - { - } - private static Func, CancellationToken, ValueTask> Convert(Func, CancellationToken, ValueTask> processBatchAsync) => async (items, ct) => { diff --git a/src/Workspaces/Core/Portable/Shared/Utilities/EditorBrowsableHelpers.cs b/src/Workspaces/Core/Portable/Shared/Utilities/EditorBrowsableHelpers.cs index e2a7aa1eefd3f..bd3ee13658e80 100644 --- a/src/Workspaces/Core/Portable/Shared/Utilities/EditorBrowsableHelpers.cs +++ b/src/Workspaces/Core/Portable/Shared/Utilities/EditorBrowsableHelpers.cs @@ -11,25 +11,15 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class EditorBrowsableHelpers { - public readonly struct EditorBrowsableInfo + public readonly struct EditorBrowsableInfo(Compilation compilation) { - public Compilation Compilation { get; } - public INamedTypeSymbol? HideModuleNameAttribute { get; } - public IMethodSymbol? EditorBrowsableAttributeConstructor { get; } - public ImmutableArray TypeLibTypeAttributeConstructors { get; } - public ImmutableArray TypeLibFuncAttributeConstructors { get; } - public ImmutableArray TypeLibVarAttributeConstructors { get; } + public Compilation Compilation { get; } = compilation; + public INamedTypeSymbol? HideModuleNameAttribute { get; } = compilation.HideModuleNameAttribute(); + public IMethodSymbol? EditorBrowsableAttributeConstructor { get; } = GetSpecialEditorBrowsableAttributeConstructor(compilation); + public ImmutableArray TypeLibTypeAttributeConstructors { get; } = GetSpecialTypeLibTypeAttributeConstructors(compilation); + public ImmutableArray TypeLibFuncAttributeConstructors { get; } = GetSpecialTypeLibFuncAttributeConstructors(compilation); + public ImmutableArray TypeLibVarAttributeConstructors { get; } = GetSpecialTypeLibVarAttributeConstructors(compilation); public bool IsDefault => Compilation == null; - - public EditorBrowsableInfo(Compilation compilation) - { - Compilation = compilation; - HideModuleNameAttribute = compilation.HideModuleNameAttribute(); - EditorBrowsableAttributeConstructor = GetSpecialEditorBrowsableAttributeConstructor(compilation); - TypeLibTypeAttributeConstructors = GetSpecialTypeLibTypeAttributeConstructors(compilation); - TypeLibFuncAttributeConstructors = GetSpecialTypeLibFuncAttributeConstructors(compilation); - TypeLibVarAttributeConstructors = GetSpecialTypeLibVarAttributeConstructors(compilation); - } } /// diff --git a/src/Workspaces/Core/Portable/Shared/Utilities/ExtensionOrderer.Node.cs b/src/Workspaces/Core/Portable/Shared/Utilities/ExtensionOrderer.Node.cs index 4bcbb3a4bb768..9ab267f4ff034 100644 --- a/src/Workspaces/Core/Portable/Shared/Utilities/ExtensionOrderer.Node.cs +++ b/src/Workspaces/Core/Portable/Shared/Utilities/ExtensionOrderer.Node.cs @@ -11,14 +11,11 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class ExtensionOrderer { - private class Node + private class Node(Lazy extension) { - public readonly Lazy Extension; + public readonly Lazy Extension = extension; public readonly HashSet> ExtensionsBeforeMeSet = new(); - public Node(Lazy extension) - => this.Extension = extension; - public void CheckForCycles() => this.CheckForCycles(new HashSet>()); diff --git a/src/Workspaces/Core/Portable/Shared/Utilities/IStreamingProgressTrackerExtensions.cs b/src/Workspaces/Core/Portable/Shared/Utilities/IStreamingProgressTrackerExtensions.cs index 87544727ed625..961da5739654a 100644 --- a/src/Workspaces/Core/Portable/Shared/Utilities/IStreamingProgressTrackerExtensions.cs +++ b/src/Workspaces/Core/Portable/Shared/Utilities/IStreamingProgressTrackerExtensions.cs @@ -23,19 +23,10 @@ public static async Task AddSingleItemAsync(this IStreamingPro public static ValueTask ItemCompletedAsync(this IStreamingProgressTracker tracker, CancellationToken cancellationToken) => tracker.ItemsCompletedAsync(1, cancellationToken); - private class StreamingProgressDisposer : IAsyncDisposable + private class StreamingProgressDisposer(IStreamingProgressTracker progressTracker, CancellationToken cancellationToken) : IAsyncDisposable { - private readonly IStreamingProgressTracker _progressTracker; - private readonly CancellationToken _cancellationToken; - - public StreamingProgressDisposer(IStreamingProgressTracker progressTracker, CancellationToken cancellationToken) - { - _progressTracker = progressTracker; - _cancellationToken = cancellationToken; - } - public async ValueTask DisposeAsync() - => await _progressTracker.ItemCompletedAsync(_cancellationToken).ConfigureAwait(false); + => await progressTracker.ItemCompletedAsync(cancellationToken).ConfigureAwait(false); } } } diff --git a/src/Workspaces/Core/Portable/Shared/Utilities/ProgressTracker.cs b/src/Workspaces/Core/Portable/Shared/Utilities/ProgressTracker.cs index 55f00ab8bd1bf..acac99ae440bb 100644 --- a/src/Workspaces/Core/Portable/Shared/Utilities/ProgressTracker.cs +++ b/src/Workspaces/Core/Portable/Shared/Utilities/ProgressTracker.cs @@ -12,22 +12,17 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities /// /// Utility class that can be used to track the progress of an operation in a threadsafe manner. /// - internal class ProgressTracker : IProgressTracker + internal class ProgressTracker(Action updateActionOpt) : IProgressTracker { private string _description; private int _completedItems; private int _totalItems; - private readonly Action _updateActionOpt; - public ProgressTracker() : this(null) { } - public ProgressTracker(Action updateActionOpt) - => _updateActionOpt = updateActionOpt; - public string Description { get => _description; @@ -63,6 +58,6 @@ public void Clear() } private void Update() - => _updateActionOpt?.Invoke(_description, _completedItems, _totalItems); + => updateActionOpt?.Invoke(_description, _completedItems, _totalItems); } } diff --git a/src/Workspaces/Core/Portable/Shared/Utilities/SemanticMap.Walker.cs b/src/Workspaces/Core/Portable/Shared/Utilities/SemanticMap.Walker.cs index 25317e9d4ae17..5daea7dddbb28 100644 --- a/src/Workspaces/Core/Portable/Shared/Utilities/SemanticMap.Walker.cs +++ b/src/Workspaces/Core/Portable/Shared/Utilities/SemanticMap.Walker.cs @@ -11,26 +11,14 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class SemanticMap { - private class Walker : SyntaxWalker + private class Walker(SemanticModel semanticModel, SemanticMap map, CancellationToken cancellationToken) : SyntaxWalker(SyntaxWalkerDepth.Token) { - private readonly SemanticModel _semanticModel; - private readonly SemanticMap _map; - private readonly CancellationToken _cancellationToken; - - public Walker(SemanticModel semanticModel, SemanticMap map, CancellationToken cancellationToken) - : base(SyntaxWalkerDepth.Token) - { - _semanticModel = semanticModel; - _map = map; - _cancellationToken = cancellationToken; - } - public override void Visit(SyntaxNode node) { - var info = _semanticModel.GetSymbolInfo(node); + var info = semanticModel.GetSymbolInfo(node); if (!IsNone(info)) { - _map._expressionToInfoMap.Add(node, info); + map._expressionToInfoMap.Add(node, info); } base.Visit(node); @@ -38,10 +26,10 @@ public override void Visit(SyntaxNode node) protected override void VisitToken(SyntaxToken token) { - var info = _semanticModel.GetSymbolInfo(token, _cancellationToken); + var info = semanticModel.GetSymbolInfo(token, cancellationToken); if (!IsNone(info)) { - _map._tokenToInfoMap.Add(token, info); + map._tokenToInfoMap.Add(token, info); } base.VisitToken(token); diff --git a/src/Workspaces/Core/Portable/Shared/Utilities/StreamingProgressTracker.cs b/src/Workspaces/Core/Portable/Shared/Utilities/StreamingProgressTracker.cs index 69f59ccf8382f..6a06dbd703d51 100644 --- a/src/Workspaces/Core/Portable/Shared/Utilities/StreamingProgressTracker.cs +++ b/src/Workspaces/Core/Portable/Shared/Utilities/StreamingProgressTracker.cs @@ -11,16 +11,11 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities /// /// Utility class that can be used to track the progress of an operation in a threadsafe manner. /// - internal sealed class StreamingProgressTracker : IStreamingProgressTracker + internal sealed class StreamingProgressTracker(Func? updateAction = null) : IStreamingProgressTracker { private int _completedItems; private int _totalItems; - private readonly Func? _updateAction; - - public StreamingProgressTracker(Func? updateAction = null) - => _updateAction = updateAction; - public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) { Interlocked.Add(ref _totalItems, count); @@ -34,6 +29,6 @@ public ValueTask ItemsCompletedAsync(int count, CancellationToken cancellationTo } private ValueTask UpdateAsync(CancellationToken cancellationToken) - => _updateAction?.Invoke(Volatile.Read(ref _completedItems), Volatile.Read(ref _totalItems), cancellationToken) ?? default; + => updateAction?.Invoke(Volatile.Read(ref _completedItems), Volatile.Read(ref _totalItems), cancellationToken) ?? default; } } diff --git a/src/Workspaces/Core/Portable/SolutionCrawler/ExportIncrementalAnalyzerProviderAttribute.cs b/src/Workspaces/Core/Portable/SolutionCrawler/ExportIncrementalAnalyzerProviderAttribute.cs index bd535cbcaad1b..8ee2c1f742cb7 100644 --- a/src/Workspaces/Core/Portable/SolutionCrawler/ExportIncrementalAnalyzerProviderAttribute.cs +++ b/src/Workspaces/Core/Portable/SolutionCrawler/ExportIncrementalAnalyzerProviderAttribute.cs @@ -11,19 +11,11 @@ namespace Microsoft.CodeAnalysis.SolutionCrawler { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] - internal class ExportIncrementalAnalyzerProviderAttribute : ExportAttribute + internal class ExportIncrementalAnalyzerProviderAttribute(string name, string[] workspaceKinds) : ExportAttribute(typeof(IIncrementalAnalyzerProvider)) { - public bool HighPriorityForActiveFile { get; } - public string Name { get; } - public string[] WorkspaceKinds { get; } - - public ExportIncrementalAnalyzerProviderAttribute(string name, string[] workspaceKinds) - : base(typeof(IIncrementalAnalyzerProvider)) - { - this.WorkspaceKinds = workspaceKinds; - this.Name = name ?? throw new ArgumentNullException(nameof(name)); - this.HighPriorityForActiveFile = false; - } + public bool HighPriorityForActiveFile { get; } = false; + public string Name { get; } = name ?? throw new ArgumentNullException(nameof(name)); + public string[] WorkspaceKinds { get; } = workspaceKinds; public ExportIncrementalAnalyzerProviderAttribute(bool highPriorityForActiveFile, string name, string[] workspaceKinds) : this(name, workspaceKinds) diff --git a/src/Workspaces/Core/Portable/SolutionCrawler/InvocationReasons.cs b/src/Workspaces/Core/Portable/SolutionCrawler/InvocationReasons.cs index 9bfd6168b6b75..a1a33340e065a 100644 --- a/src/Workspaces/Core/Portable/SolutionCrawler/InvocationReasons.cs +++ b/src/Workspaces/Core/Portable/SolutionCrawler/InvocationReasons.cs @@ -10,21 +10,18 @@ namespace Microsoft.CodeAnalysis.SolutionCrawler { [DataContract] - internal partial struct InvocationReasons : IEnumerable + internal partial struct InvocationReasons(ImmutableHashSet reasons) : IEnumerable { public static readonly InvocationReasons Empty = new(ImmutableHashSet.Empty); [DataMember(Order = 0)] - private readonly ImmutableHashSet _reasons; + private readonly ImmutableHashSet _reasons = reasons ?? ImmutableHashSet.Empty; public InvocationReasons(string reason) : this(ImmutableHashSet.Create(reason)) { } - public InvocationReasons(ImmutableHashSet reasons) - => _reasons = reasons ?? ImmutableHashSet.Empty; - public bool IsEmpty => _reasons.IsEmpty; public bool Contains(string reason) diff --git a/src/Workspaces/Core/Portable/Storage/AbstractPersistentStorageService.cs b/src/Workspaces/Core/Portable/Storage/AbstractPersistentStorageService.cs index 69ee4e874a597..fd3ea452678a8 100644 --- a/src/Workspaces/Core/Portable/Storage/AbstractPersistentStorageService.cs +++ b/src/Workspaces/Core/Portable/Storage/AbstractPersistentStorageService.cs @@ -167,15 +167,10 @@ private void Shutdown() internal TestAccessor GetTestAccessor() => new(this); - internal readonly struct TestAccessor + internal readonly struct TestAccessor(AbstractPersistentStorageService service) { - private readonly AbstractPersistentStorageService _service; - - public TestAccessor(AbstractPersistentStorageService service) - => _service = service; - public void Shutdown() - => _service.Shutdown(); + => service.Shutdown(); } /// diff --git a/src/Workspaces/Core/Portable/Storage/SQLite/Interop/SqlException.cs b/src/Workspaces/Core/Portable/Storage/SQLite/Interop/SqlException.cs index 27dc41ad6970a..fbab320358318 100644 --- a/src/Workspaces/Core/Portable/Storage/SQLite/Interop/SqlException.cs +++ b/src/Workspaces/Core/Portable/Storage/SQLite/Interop/SqlException.cs @@ -6,14 +6,8 @@ namespace Microsoft.CodeAnalysis.SQLite.Interop { - internal class SqlException : Exception + internal class SqlException(Result result, string message) : Exception(message) { - public readonly Result Result; - - public SqlException(Result result, string message) - : base(message) - { - this.Result = result; - } + public readonly Result Result = result; } } diff --git a/src/Workspaces/Core/Portable/Storage/SQLite/v2/Interop/ResettableSqlStatement.cs b/src/Workspaces/Core/Portable/Storage/SQLite/v2/Interop/ResettableSqlStatement.cs index 6815b7559f2eb..5bac6cea63203 100644 --- a/src/Workspaces/Core/Portable/Storage/SQLite/v2/Interop/ResettableSqlStatement.cs +++ b/src/Workspaces/Core/Portable/Storage/SQLite/v2/Interop/ResettableSqlStatement.cs @@ -24,12 +24,9 @@ namespace Microsoft.CodeAnalysis.SQLite.v2.Interop /// as it will happen to all prepared statemnets when the is /// d. /// - internal readonly struct ResettableSqlStatement : IDisposable + internal readonly struct ResettableSqlStatement(SqlStatement statement) : IDisposable { - public readonly SqlStatement Statement; - - public ResettableSqlStatement(SqlStatement statement) - => Statement = statement; + public readonly SqlStatement Statement = statement; public void Dispose() { diff --git a/src/Workspaces/Core/Portable/Storage/SQLite/v2/Interop/SqlStatement.cs b/src/Workspaces/Core/Portable/Storage/SQLite/v2/Interop/SqlStatement.cs index c012eca753301..431c3c23f17cb 100644 --- a/src/Workspaces/Core/Portable/Storage/SQLite/v2/Interop/SqlStatement.cs +++ b/src/Workspaces/Core/Portable/Storage/SQLite/v2/Interop/SqlStatement.cs @@ -27,29 +27,20 @@ namespace Microsoft.CodeAnalysis.SQLite.v2.Interop /// Finalization/destruction of the underlying raw sqlite statement is handled /// by . /// - internal readonly struct SqlStatement + internal readonly struct SqlStatement(SqlConnection connection, SafeSqliteStatementHandle statement) { - private readonly SqlConnection _connection; - private readonly SafeSqliteStatementHandle _rawStatement; - - public SqlStatement(SqlConnection connection, SafeSqliteStatementHandle statement) - { - _connection = connection; - _rawStatement = statement; - } - internal void Close_OnlyForUseBySqlConnection() - => _rawStatement.Dispose(); + => statement.Dispose(); public void ClearBindings() - => _connection.ThrowIfNotOk(NativeMethods.sqlite3_clear_bindings(_rawStatement)); + => connection.ThrowIfNotOk(NativeMethods.sqlite3_clear_bindings(statement)); public void Reset() - => _connection.ThrowIfNotOk(NativeMethods.sqlite3_reset(_rawStatement)); + => connection.ThrowIfNotOk(NativeMethods.sqlite3_reset(statement)); public Result Step(bool throwOnError = true) { - var stepResult = NativeMethods.sqlite3_step(_rawStatement); + var stepResult = NativeMethods.sqlite3_step(statement); // Anything other than DONE or ROW is an error when stepping. // throw if the caller wants that, or just return the value @@ -58,7 +49,7 @@ public Result Step(bool throwOnError = true) { if (throwOnError) { - _connection.Throw(stepResult); + connection.Throw(stepResult); throw ExceptionUtilities.Unreachable(); } } @@ -101,27 +92,27 @@ internal void BindStringParameter(int parameterIndex, string value) } } #endif - _connection.ThrowIfNotOk(NativeMethods.sqlite3_bind_text(_rawStatement, parameterIndex, bytes)); + connection.ThrowIfNotOk(NativeMethods.sqlite3_bind_text(statement, parameterIndex, bytes)); return; } } - _connection.ThrowIfNotOk(NativeMethods.sqlite3_bind_text(_rawStatement, parameterIndex, value)); + connection.ThrowIfNotOk(NativeMethods.sqlite3_bind_text(statement, parameterIndex, value)); } internal void BindInt64Parameter(int parameterIndex, long value) - => _connection.ThrowIfNotOk(NativeMethods.sqlite3_bind_int64(_rawStatement, parameterIndex, value)); + => connection.ThrowIfNotOk(NativeMethods.sqlite3_bind_int64(statement, parameterIndex, value)); internal void BindBlobParameter(int parameterIndex, ReadOnlySpan bytes) - => _connection.ThrowIfNotOk(NativeMethods.sqlite3_bind_blob(_rawStatement, parameterIndex, bytes)); + => connection.ThrowIfNotOk(NativeMethods.sqlite3_bind_blob(statement, parameterIndex, bytes)); internal int GetInt32At(int columnIndex) - => NativeMethods.sqlite3_column_int(_rawStatement, columnIndex); + => NativeMethods.sqlite3_column_int(statement, columnIndex); internal long GetInt64At(int columnIndex) - => NativeMethods.sqlite3_column_int64(_rawStatement, columnIndex); + => NativeMethods.sqlite3_column_int64(statement, columnIndex); internal string GetStringAt(int columnIndex) - => NativeMethods.sqlite3_column_text(_rawStatement, columnIndex); + => NativeMethods.sqlite3_column_text(statement, columnIndex); } } diff --git a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPool+PooledConnection.cs b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPool+PooledConnection.cs index 0c37cdf95d740..282225e30c551 100644 --- a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPool+PooledConnection.cs +++ b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPool+PooledConnection.cs @@ -9,19 +9,12 @@ namespace Microsoft.CodeAnalysis.SQLite.v2 { internal partial class SQLiteConnectionPool { - internal readonly struct PooledConnection : IDisposable + internal readonly struct PooledConnection(SQLiteConnectionPool connectionPool, SqlConnection sqlConnection) : IDisposable { - private readonly SQLiteConnectionPool _connectionPool; - public readonly SqlConnection Connection; - - public PooledConnection(SQLiteConnectionPool connectionPool, SqlConnection sqlConnection) - { - _connectionPool = connectionPool; - Connection = sqlConnection; - } + public readonly SqlConnection Connection = sqlConnection; public void Dispose() - => _connectionPool.ReleaseConnection(Connection); + => connectionPool.ReleaseConnection(Connection); } } } diff --git a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPool.cs b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPool.cs index 19f6d981ebaf9..aa3ef1fe45322 100644 --- a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPool.cs +++ b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPool.cs @@ -11,7 +11,7 @@ namespace Microsoft.CodeAnalysis.SQLite.v2 { - internal sealed partial class SQLiteConnectionPool : IDisposable + internal sealed partial class SQLiteConnectionPool(SQLiteConnectionPoolService connectionPoolService, IPersistentStorageFaultInjector? faultInjector, string databasePath, IDisposable ownershipLock) : IDisposable { // We pool connections to the DB so that we don't have to take the hit of // reconnecting. The connections also cache the prepared statements used @@ -22,19 +22,6 @@ internal sealed partial class SQLiteConnectionPool : IDisposable private readonly CancellationTokenSource _shutdownTokenSource = new(); - private readonly SQLiteConnectionPoolService _connectionPoolService; - private readonly IPersistentStorageFaultInjector? _faultInjector; - private readonly string _databasePath; - private readonly IDisposable _ownershipLock; - - public SQLiteConnectionPool(SQLiteConnectionPoolService connectionPoolService, IPersistentStorageFaultInjector? faultInjector, string databasePath, IDisposable ownershipLock) - { - _connectionPoolService = connectionPoolService; - _faultInjector = faultInjector; - _databasePath = databasePath; - _ownershipLock = ownershipLock; - } - internal void Initialize( Action initializer, CancellationToken cancellationToken) @@ -58,7 +45,7 @@ public void Dispose() finally { // let the lock go - _ownershipLock.Dispose(); + ownershipLock.Dispose(); } } @@ -96,7 +83,7 @@ private PooledConnection GetPooledConnection(bool checkScheduler, out SqlConnect if (checkScheduler) { var scheduler = TaskScheduler.Current; - if (scheduler != _connectionPoolService.Scheduler.ConcurrentScheduler && scheduler != _connectionPoolService.Scheduler.ExclusiveScheduler) + if (scheduler != connectionPoolService.Scheduler.ConcurrentScheduler && scheduler != connectionPoolService.Scheduler.ExclusiveScheduler) throw new InvalidOperationException($"Cannot get a connection to the DB unless running on one of {nameof(SQLiteConnectionPoolService)}'s schedulers"); } @@ -117,7 +104,7 @@ private SqlConnection GetConnection() } // Otherwise create a new connection. - return SqlConnection.Create(_faultInjector, _databasePath); + return SqlConnection.Create(faultInjector, databasePath); } private void ReleaseConnection(SqlConnection connection) diff --git a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorageService.cs b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorageService.cs index a08a98b5d9273..113726cce4838 100644 --- a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorageService.cs +++ b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorageService.cs @@ -16,26 +16,22 @@ namespace Microsoft.CodeAnalysis.SQLite.v2 { - internal sealed class SQLitePersistentStorageService : AbstractPersistentStorageService, IWorkspaceService + internal sealed class SQLitePersistentStorageService( + SQLiteConnectionPoolService connectionPoolService, + IPersistentStorageConfiguration configuration, + IAsynchronousOperationListener asyncListener) : AbstractPersistentStorageService(configuration), IWorkspaceService { [ExportWorkspaceServiceFactory(typeof(SQLitePersistentStorageService)), Shared] - internal sealed class ServiceFactory : IWorkspaceServiceFactory + [method: ImportingConstructor] + [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + internal sealed class ServiceFactory( + SQLiteConnectionPoolService connectionPoolService, + IAsynchronousOperationListenerProvider asyncOperationListenerProvider) : IWorkspaceServiceFactory { - private readonly SQLiteConnectionPoolService _connectionPoolService; - private readonly IAsynchronousOperationListener _asyncListener; - - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public ServiceFactory( - SQLiteConnectionPoolService connectionPoolService, - IAsynchronousOperationListenerProvider asyncOperationListenerProvider) - { - _connectionPoolService = connectionPoolService; - _asyncListener = asyncOperationListenerProvider.GetListener(FeatureAttribute.PersistentStorage); - } + private readonly IAsynchronousOperationListener _asyncListener = asyncOperationListenerProvider.GetListener(FeatureAttribute.PersistentStorage); public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) - => new SQLitePersistentStorageService(_connectionPoolService, workspaceServices.GetRequiredService(), _asyncListener); + => new SQLitePersistentStorageService(connectionPoolService, workspaceServices.GetRequiredService(), _asyncListener); } private const string StorageExtension = "sqlite3"; @@ -65,20 +61,8 @@ private static bool TryInitializeLibrariesLazy() return true; } - private readonly SQLiteConnectionPoolService _connectionPoolService; - private readonly IAsynchronousOperationListener _asyncListener; private readonly IPersistentStorageFaultInjector? _faultInjector; - public SQLitePersistentStorageService( - SQLiteConnectionPoolService connectionPoolService, - IPersistentStorageConfiguration configuration, - IAsynchronousOperationListener asyncListener) - : base(configuration) - { - _connectionPoolService = connectionPoolService; - _asyncListener = asyncListener; - } - public SQLitePersistentStorageService( SQLiteConnectionPoolService connectionPoolService, IPersistentStorageConfiguration configuration, @@ -108,11 +92,11 @@ protected override string GetDatabaseFilePath(string workingFolderPath) return new(NoOpPersistentStorage.GetOrThrow(Configuration.ThrowOnFailure)); return new(SQLitePersistentStorage.TryCreate( - _connectionPoolService, + connectionPoolService, solutionKey, workingFolderPath, databaseFilePath, - _asyncListener, + asyncListener, _faultInjector)); } diff --git a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_DocumentSerialization.cs b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_DocumentSerialization.cs index 5e3c1a5cf5074..13d50c5c11c2c 100644 --- a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_DocumentSerialization.cs +++ b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_DocumentSerialization.cs @@ -30,18 +30,13 @@ protected override Task WriteStreamAsync(DocumentKey documentKey, Document /// responsible for storing and /// retrieving data from . /// - private sealed class DocumentAccessor : Accessor + private sealed class DocumentAccessor(SQLitePersistentStorage storage) : Accessor(Table.Document, + storage, + (ProjectPathIdColumnName, SQLiteIntegerType), + (ProjectNameIdColumnName, SQLiteIntegerType), + (DocumentFolderIdColumnName, SQLiteIntegerType), + (DocumentNameIdColumnName, SQLiteIntegerType)) { - public DocumentAccessor(SQLitePersistentStorage storage) - : base(Table.Document, - storage, - (ProjectPathIdColumnName, SQLiteIntegerType), - (ProjectNameIdColumnName, SQLiteIntegerType), - (DocumentFolderIdColumnName, SQLiteIntegerType), - (DocumentNameIdColumnName, SQLiteIntegerType)) - { - } - protected override DocumentPrimaryKey? TryGetDatabaseKey(SqlConnection connection, DocumentKey key, bool allowWrite) => Storage.TryGetDocumentPrimaryKey(connection, key, allowWrite); diff --git a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_ProjectSerialization.cs b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_ProjectSerialization.cs index 4da91b2910ed8..44177bdec1766 100644 --- a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_ProjectSerialization.cs +++ b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_ProjectSerialization.cs @@ -30,16 +30,11 @@ protected override Task WriteStreamAsync(ProjectKey projectKey, Project? p /// responsible for storing and /// retrieving data from . /// - private sealed class ProjectAccessor : Accessor + private sealed class ProjectAccessor(SQLitePersistentStorage storage) : Accessor(Table.Project, + storage, + (ProjectPathIdColumnName, SQLiteIntegerType), + (ProjectNameIdColumnName, SQLiteIntegerType)) { - public ProjectAccessor(SQLitePersistentStorage storage) - : base(Table.Project, - storage, - (ProjectPathIdColumnName, SQLiteIntegerType), - (ProjectNameIdColumnName, SQLiteIntegerType)) - { - } - protected override ProjectPrimaryKey? TryGetDatabaseKey(SqlConnection connection, ProjectKey projectKey, bool allowWrite) => Storage.TryGetProjectPrimaryKey(connection, projectKey, allowWrite); diff --git a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_SolutionSerialization.cs b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_SolutionSerialization.cs index cf52ab79a3437..da2eded2ff706 100644 --- a/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_SolutionSerialization.cs +++ b/src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_SolutionSerialization.cs @@ -31,13 +31,9 @@ public override Task WriteStreamAsync(string name, Stream stream, Checksum /// retrieving data from . Note that with the Solution /// table there is no need for key->id translation. i.e. the key acts as the ID itself. /// - private sealed class SolutionAccessor : Accessor + private sealed class SolutionAccessor(SQLitePersistentStorage storage) : Accessor(Table.Solution, + storage) { - public SolutionAccessor(SQLitePersistentStorage storage) - : base(Table.Solution, - storage) - { - } // For the SolutionDataTable the key itself acts as the data-id. protected override SolutionPrimaryKey? TryGetDatabaseKey(SqlConnection connection, SolutionKey key, bool allowWrite) diff --git a/src/Workspaces/Core/Portable/SymbolSearch/ISymbolSearchService.cs b/src/Workspaces/Core/Portable/SymbolSearch/ISymbolSearchService.cs index 5f1cf8d3bb7c0..83d019f780d9e 100644 --- a/src/Workspaces/Core/Portable/SymbolSearch/ISymbolSearchService.cs +++ b/src/Workspaces/Core/Portable/SymbolSearch/ISymbolSearchService.cs @@ -70,45 +70,31 @@ protected PackageResult(string packageName, int rank) } [DataContract] - internal sealed class PackageWithTypeResult : PackageResult + internal sealed class PackageWithTypeResult( + string packageName, + int rank, + string typeName, + string? version, + ImmutableArray containingNamespaceNames) : PackageResult(packageName, rank) { [DataMember(Order = 2)] - public readonly string TypeName; + public readonly string TypeName = typeName; [DataMember(Order = 3)] - public readonly string? Version; + public readonly string? Version = version; [DataMember(Order = 4)] - public readonly ImmutableArray ContainingNamespaceNames; - - public PackageWithTypeResult( - string packageName, - int rank, - string typeName, - string? version, - ImmutableArray containingNamespaceNames) - : base(packageName, rank) - { - TypeName = typeName; - Version = version; - ContainingNamespaceNames = containingNamespaceNames; - } + public readonly ImmutableArray ContainingNamespaceNames = containingNamespaceNames; } [DataContract] - internal sealed class PackageWithAssemblyResult : PackageResult, IEquatable, IComparable + internal sealed class PackageWithAssemblyResult( + string packageName, + int rank, + string version) : PackageResult(packageName, rank), IEquatable, IComparable { [DataMember(Order = 2)] - public readonly string? Version; - - public PackageWithAssemblyResult( - string packageName, - int rank, - string version) - : base(packageName, rank) - { - Version = version; - } + public readonly string? Version = version; public override int GetHashCode() => PackageName.GetHashCode(); @@ -132,26 +118,19 @@ public int CompareTo(PackageWithAssemblyResult? other) } [DataContract] - internal sealed class ReferenceAssemblyWithTypeResult + internal sealed class ReferenceAssemblyWithTypeResult( + string assemblyName, + string typeName, + ImmutableArray containingNamespaceNames) { [DataMember(Order = 0)] - public readonly string AssemblyName; + public readonly string AssemblyName = assemblyName; [DataMember(Order = 1)] - public readonly string TypeName; + public readonly string TypeName = typeName; [DataMember(Order = 2)] - public readonly ImmutableArray ContainingNamespaceNames; - - public ReferenceAssemblyWithTypeResult( - string assemblyName, - string typeName, - ImmutableArray containingNamespaceNames) - { - AssemblyName = assemblyName; - TypeName = typeName; - ContainingNamespaceNames = containingNamespaceNames; - } + public readonly ImmutableArray ContainingNamespaceNames = containingNamespaceNames; } [ExportWorkspaceService(typeof(ISymbolSearchService)), Shared] diff --git a/src/Workspaces/Core/Portable/TaskList/TaskListItemDescriptor.cs b/src/Workspaces/Core/Portable/TaskList/TaskListItemDescriptor.cs index 4e15badad56ec..644aa4ea0463f 100644 --- a/src/Workspaces/Core/Portable/TaskList/TaskListItemDescriptor.cs +++ b/src/Workspaces/Core/Portable/TaskList/TaskListItemDescriptor.cs @@ -20,18 +20,12 @@ internal enum TaskListItemPriority /// Description of a TODO comment type to find in a user's comments. /// [DataContract] - internal readonly struct TaskListItemDescriptor + internal readonly struct TaskListItemDescriptor(string text, TaskListItemPriority priority) { [DataMember(Order = 0)] - public string Text { get; } + public string Text { get; } = text; [DataMember(Order = 1)] - public TaskListItemPriority Priority { get; } - - public TaskListItemDescriptor(string text, TaskListItemPriority priority) - { - Text = text; - Priority = priority; - } + public TaskListItemPriority Priority { get; } = priority; public static ImmutableArray Parse(ImmutableArray items) { diff --git a/src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageService.Factory.cs b/src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageService.Factory.cs index 90d90f98035a8..1fd7e36878ea7 100644 --- a/src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageService.Factory.cs +++ b/src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageService.Factory.cs @@ -13,18 +13,11 @@ namespace Microsoft.CodeAnalysis.Host internal partial class TemporaryStorageService { [ExportWorkspaceServiceFactory(typeof(ITemporaryStorageServiceInternal), ServiceLayer.Default), Shared] - internal partial class Factory : IWorkspaceServiceFactory + [method: ImportingConstructor] + [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + internal partial class Factory( + [Import(AllowDefault = true)] IWorkspaceThreadingService? workspaceThreadingService) : IWorkspaceServiceFactory { - private readonly IWorkspaceThreadingService? _workspaceThreadingService; - - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public Factory( - [Import(AllowDefault = true)] IWorkspaceThreadingService? workspaceThreadingService) - { - _workspaceThreadingService = workspaceThreadingService; - } - [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { @@ -34,7 +27,7 @@ public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) // and .NET Core Windows. For non-Windows .NET Core scenarios, we can return the TrivialTemporaryStorageService // until https://github.com/dotnet/runtime/issues/30878 is fixed. return PlatformInformation.IsWindows || PlatformInformation.IsRunningOnMono - ? new TemporaryStorageService(_workspaceThreadingService, textFactory) + ? new TemporaryStorageService(workspaceThreadingService, textFactory) : TrivialTemporaryStorageService.Instance; } } diff --git a/src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageService.MemoryMappedInfo.cs b/src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageService.MemoryMappedInfo.cs index aaf83a633bd54..f496a63624d0b 100644 --- a/src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageService.MemoryMappedInfo.cs +++ b/src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageService.MemoryMappedInfo.cs @@ -34,7 +34,7 @@ internal partial class TemporaryStorageService /// Update: Dispose, Finalization, and Resource Management. Additional notes regarding operating system /// behavior leveraged for efficiency are given in comments. /// - internal sealed class MemoryMappedInfo : IDisposable + internal sealed class MemoryMappedInfo(ReferenceCountedDisposable memoryMappedFile, string name, long offset, long size) : IDisposable { /// /// The memory mapped file. @@ -44,7 +44,7 @@ internal sealed class MemoryMappedInfo : IDisposable /// However, the operating system does not actually close the views which are in use until the file handles /// are closed as well, even if the file is disposed first. /// - private readonly ReferenceCountedDisposable _memoryMappedFile; + private readonly ReferenceCountedDisposable _memoryMappedFile = memoryMappedFile; /// /// A weak reference to a read-only view for the memory mapped file. @@ -61,14 +61,6 @@ internal sealed class MemoryMappedInfo : IDisposable /// private ReferenceCountedDisposable.WeakReference _weakReadAccessor; - public MemoryMappedInfo(ReferenceCountedDisposable memoryMappedFile, string name, long offset, long size) - { - _memoryMappedFile = memoryMappedFile; - Name = name; - Offset = offset; - Size = size; - } - public MemoryMappedInfo(string name, long offset, long size) : this(new ReferenceCountedDisposable(MemoryMappedFile.OpenExisting(name)), name, offset, size) { @@ -77,19 +69,19 @@ public MemoryMappedInfo(string name, long offset, long size) /// /// The name of the memory mapped file. /// - public string Name { get; } + public string Name { get; } = name; /// /// The offset into the memory mapped file of the region described by the current /// . /// - public long Offset { get; } + public long Offset { get; } = offset; /// /// The size of the region of the memory mapped file described by the current /// . /// - public long Size { get; } + public long Size { get; } = size; /// /// Caller is responsible for disposing the returned stream. diff --git a/src/Workspaces/Core/Portable/Utilities/Documentation/DeferredDocumentationProvider.cs b/src/Workspaces/Core/Portable/Utilities/Documentation/DeferredDocumentationProvider.cs index 0ab3f5eb7f582..c9e4f0bcaaf69 100644 --- a/src/Workspaces/Core/Portable/Utilities/Documentation/DeferredDocumentationProvider.cs +++ b/src/Workspaces/Core/Portable/Utilities/Documentation/DeferredDocumentationProvider.cs @@ -21,16 +21,9 @@ namespace Microsoft.CodeAnalysis /// symbols in practice, this should not be expensive to hold onto. Importantly, semantic models and /// complex method binding/caching should never really happen with this compilation. /// - internal class DeferredDocumentationProvider : DocumentationProvider + internal class DeferredDocumentationProvider(Compilation compilation) : DocumentationProvider { - private readonly Compilation _compilation; - - public DeferredDocumentationProvider(Compilation compilation) - { - // Ensure we are getting a clone of this compilation so that we are only holding onto the decl table and - // not rooting a full compilation that might be quite expensive. - _compilation = compilation.Clone(); - } + private readonly Compilation _compilation = compilation.Clone(); protected override string? GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default) { diff --git a/src/Workspaces/Core/Portable/Utilities/FlowControlHelper.cs b/src/Workspaces/Core/Portable/Utilities/FlowControlHelper.cs index d0d283ee26f52..7cd654ac8a783 100644 --- a/src/Workspaces/Core/Portable/Utilities/FlowControlHelper.cs +++ b/src/Workspaces/Core/Portable/Utilities/FlowControlHelper.cs @@ -12,20 +12,13 @@ internal static class FlowControlHelper public static AsyncFlowControlHelper TrySuppressFlow() => new(ExecutionContext.IsFlowSuppressed() ? default : ExecutionContext.SuppressFlow()); - public readonly struct AsyncFlowControlHelper : IDisposable + public readonly struct AsyncFlowControlHelper(AsyncFlowControl asyncFlowControl) : IDisposable { - private readonly AsyncFlowControl _asyncFlowControl; - - public AsyncFlowControlHelper(AsyncFlowControl asyncFlowControl) - { - _asyncFlowControl = asyncFlowControl; - } - public void Dispose() { - if (_asyncFlowControl != default) + if (asyncFlowControl != default) { - _asyncFlowControl.Dispose(); + asyncFlowControl.Dispose(); } } } diff --git a/src/Workspaces/Core/Portable/Utilities/SpellChecker.cs b/src/Workspaces/Core/Portable/Utilities/SpellChecker.cs index 2c8385707d516..1790c2d349e7b 100644 --- a/src/Workspaces/Core/Portable/Utilities/SpellChecker.cs +++ b/src/Workspaces/Core/Portable/Utilities/SpellChecker.cs @@ -10,19 +10,11 @@ namespace Roslyn.Utilities { - internal readonly struct SpellChecker : IObjectWritable, IChecksummedObject + internal readonly struct SpellChecker(Checksum checksum, BKTree bKTree) : IObjectWritable, IChecksummedObject { private const string SerializationFormat = "3"; - public Checksum Checksum { get; } - - private readonly BKTree _bkTree; - - public SpellChecker(Checksum checksum, BKTree bKTree) - { - Checksum = checksum; - _bkTree = bKTree; - } + public Checksum Checksum { get; } = checksum; public SpellChecker(Checksum checksum, IEnumerable corpus) : this(checksum, BKTree.Create(corpus)) @@ -34,7 +26,7 @@ public void FindSimilarWords(ref TemporaryArray similarWords, string val using var result = TemporaryArray.Empty; using var checker = new WordSimilarityChecker(value, substringsAreSimilar); - _bkTree.Find(ref result.AsRef(), value, threshold: null); + bKTree.Find(ref result.AsRef(), value, threshold: null); foreach (var current in result) { @@ -49,7 +41,7 @@ public void WriteTo(ObjectWriter writer) { writer.WriteString(SerializationFormat); Checksum.WriteTo(writer); - _bkTree.WriteTo(writer); + bKTree.WriteTo(writer); } internal static SpellChecker? TryReadFrom(ObjectReader reader) diff --git a/src/Workspaces/Core/Portable/Workspace/AdhocWorkspace.cs b/src/Workspaces/Core/Portable/Workspace/AdhocWorkspace.cs index 4f846b8cd017b..806dc1e0eed47 100644 --- a/src/Workspaces/Core/Portable/Workspace/AdhocWorkspace.cs +++ b/src/Workspaces/Core/Portable/Workspace/AdhocWorkspace.cs @@ -16,13 +16,8 @@ namespace Microsoft.CodeAnalysis /// A workspace that allows full manipulation of projects and documents, /// but does not persist changes. /// - public sealed class AdhocWorkspace : Workspace + public sealed class AdhocWorkspace(HostServices host, string workspaceKind = WorkspaceKind.Custom) : Workspace(host, workspaceKind) { - public AdhocWorkspace(HostServices host, string workspaceKind = WorkspaceKind.Custom) - : base(host, workspaceKind) - { - } - public AdhocWorkspace() : this(Host.Mef.MefHostServices.DefaultHost) { diff --git a/src/Workspaces/Core/Portable/Workspace/Host/DocumentService/IDocumentExcerptService.cs b/src/Workspaces/Core/Portable/Workspace/Host/DocumentService/IDocumentExcerptService.cs index 52c539408ef1a..df88e069b4558 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/DocumentService/IDocumentExcerptService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/DocumentService/IDocumentExcerptService.cs @@ -37,45 +37,35 @@ internal enum ExcerptMode /// /// Result of excerpt /// - internal readonly struct ExcerptResult + internal readonly struct ExcerptResult(SourceText content, TextSpan mappedSpan, ImmutableArray classifiedSpans, Document document, TextSpan span) { /// /// excerpt content /// - public readonly SourceText Content; + public readonly SourceText Content = content; /// /// span on that given got mapped to /// - public readonly TextSpan MappedSpan; + public readonly TextSpan MappedSpan = mappedSpan; /// /// classification information on the /// - public readonly ImmutableArray ClassifiedSpans; + public readonly ImmutableArray ClassifiedSpans = classifiedSpans; /// /// this excerpt is from /// /// should be same document in /// - public readonly Document Document; + public readonly Document Document = document; /// /// span on this excerpt is from /// /// should be same text span in /// - public readonly TextSpan Span; - - public ExcerptResult(SourceText content, TextSpan mappedSpan, ImmutableArray classifiedSpans, Document document, TextSpan span) - { - Content = content; - MappedSpan = mappedSpan; - ClassifiedSpans = classifiedSpans; - - Document = document; - Span = span; - } + public readonly TextSpan Span = span; } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/EventListener/EventListenerTracker.cs b/src/Workspaces/Core/Portable/Workspace/Host/EventListener/EventListenerTracker.cs index 1040b76535ff5..c32d599d17db6 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/EventListener/EventListenerTracker.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/EventListener/EventListenerTracker.cs @@ -17,19 +17,14 @@ namespace Microsoft.CodeAnalysis.Host /// currently, this helper only supports services whose lifetime is same as Host (ex, VS) /// /// TService for - internal class EventListenerTracker + internal class EventListenerTracker( + IEnumerable> eventListeners, string kind) { /// /// Workspace kind this event listener is initialized for /// private readonly HashSet _eventListenerInitialized = new(); - private readonly ImmutableArray> _eventListeners; - - public EventListenerTracker( - IEnumerable> eventListeners, string kind) - { - _eventListeners = eventListeners.Where(el => el.Metadata.Service == kind).ToImmutableArray(); - } + private readonly ImmutableArray> _eventListeners = eventListeners.Where(el => el.Metadata.Service == kind).ToImmutableArray(); public void EnsureEventListener(Workspace workspace, TService serviceOpt) { diff --git a/src/Workspaces/Core/Portable/Workspace/Host/EventListener/IWorkspaceEventListenerProvider.cs b/src/Workspaces/Core/Portable/Workspace/Host/EventListener/IWorkspaceEventListenerProvider.cs index 11300a9a106db..d657e0592da95 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/EventListener/IWorkspaceEventListenerProvider.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/EventListener/IWorkspaceEventListenerProvider.cs @@ -22,41 +22,22 @@ internal interface IWorkspaceEventListenerService : IWorkspaceService } [ExportWorkspaceServiceFactory(typeof(IWorkspaceEventListenerService), layer: ServiceLayer.Default), Shared] - internal class DefaultWorkspaceEventListenerServiceFactory : IWorkspaceServiceFactory + [method: ImportingConstructor] + [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + internal class DefaultWorkspaceEventListenerServiceFactory( + [ImportMany] IEnumerable> eventListeners) : IWorkspaceServiceFactory { - private readonly IEnumerable> _eventListeners; - - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public DefaultWorkspaceEventListenerServiceFactory( - [ImportMany] IEnumerable> eventListeners) - { - // we use this indirect abstraction to deliver IEventLister to workspace. - // otherwise, each Workspace implementation need to explicitly tell base event listeners either through - // constructor or through virtual property. - // taking indirect approach since i dont believe all workspaces need to know about this. - _eventListeners = eventListeners; - } - public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { var workspace = workspaceServices.Workspace; - return new Service(workspace, EventListenerTracker.GetListeners(workspace, _eventListeners)); + return new Service(workspace, EventListenerTracker.GetListeners(workspace, eventListeners)); } - private class Service : IWorkspaceEventListenerService + private class Service(Workspace workspace, IEnumerable> eventListeners) : IWorkspaceEventListenerService { private readonly object _gate = new(); private bool _initialized = false; - - private readonly Workspace _workspace; - private readonly ImmutableArray> _eventListeners; - - public Service(Workspace workspace, IEnumerable> eventListeners) - { - _workspace = workspace; - _eventListeners = eventListeners.ToImmutableArray(); - } + private readonly ImmutableArray> _eventListeners = eventListeners.ToImmutableArray(); public void EnsureListeners() { @@ -73,7 +54,7 @@ public void EnsureListeners() foreach (var listener in _eventListeners) { - listener.StartListening(_workspace, serviceOpt: null); + listener.StartListening(workspace, serviceOpt: null); } } @@ -89,7 +70,7 @@ public void Stop() foreach (var listener in _eventListeners.OfType()) { - listener.StopListening(_workspace); + listener.StopListening(workspace); } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/ISupportedChangesService.cs b/src/Workspaces/Core/Portable/Workspace/Host/ISupportedChangesService.cs index a9614ea147523..d2a7a95ecf38c 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/ISupportedChangesService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/ISupportedChangesService.cs @@ -36,23 +36,16 @@ public DefaultSupportedChangesServiceFactory() public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new DefaultSupportedChangesService(workspaceServices.Workspace); - private sealed class DefaultSupportedChangesService : ISupportedChangesService + private sealed class DefaultSupportedChangesService(Workspace workspace) : ISupportedChangesService { - private readonly Workspace _workspace; - - public DefaultSupportedChangesService(Workspace workspace) - { - _workspace = workspace; - } - public bool CanApplyChange(ApplyChangesKind kind) - => _workspace.CanApplyChange(kind); + => workspace.CanApplyChange(kind); public bool CanApplyCompilationOptionChange(CompilationOptions oldOptions, CompilationOptions newOptions, Project project) - => _workspace.CanApplyCompilationOptionChange(oldOptions, newOptions, project); + => workspace.CanApplyCompilationOptionChange(oldOptions, newOptions, project); public bool CanApplyParseOptionChange(ParseOptions oldOptions, ParseOptions newOptions, Project project) - => _workspace.CanApplyParseOptionChange(oldOptions, newOptions, project); + => workspace.CanApplyParseOptionChange(oldOptions, newOptions, project); } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/Mef/MefHostServices.cs b/src/Workspaces/Core/Portable/Workspace/Host/Mef/MefHostServices.cs index f6143fcb5fd5a..fac07e578c2af 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/Mef/MefHostServices.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/Mef/MefHostServices.cs @@ -15,7 +15,7 @@ namespace Microsoft.CodeAnalysis.Host.Mef { - public class MefHostServices : HostServices, IMefHostExportProvider + public class MefHostServices(CompositionContext compositionContext) : HostServices, IMefHostExportProvider { internal delegate MefHostServices CreationHook(IEnumerable assemblies); @@ -25,11 +25,6 @@ public class MefHostServices : HostServices, IMefHostExportProvider /// private static CreationHook s_creationHook; - private readonly CompositionContext _compositionContext; - - public MefHostServices(CompositionContext compositionContext) - => _compositionContext = compositionContext; - public static MefHostServices Create(CompositionContext compositionContext) { if (compositionContext == null) @@ -61,12 +56,12 @@ protected internal override HostWorkspaceServices CreateWorkspaceServices(Worksp => new MefWorkspaceServices(this, workspace); IEnumerable> IMefHostExportProvider.GetExports() - => _compositionContext.GetExports().Select(e => new Lazy(() => e)); + => compositionContext.GetExports().Select(e => new Lazy(() => e)); IEnumerable> IMefHostExportProvider.GetExports() { var importer = new WithMetadataImporter(); - _compositionContext.SatisfyImports(importer); + compositionContext.SatisfyImports(importer); return importer.Exports; } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/Metadata/AnalyzerAssemblyLoaderOptions.cs b/src/Workspaces/Core/Portable/Workspace/Host/Metadata/AnalyzerAssemblyLoaderOptions.cs index 4e4f0c5beee46..64f8ff2e9b5f4 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/Metadata/AnalyzerAssemblyLoaderOptions.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/Metadata/AnalyzerAssemblyLoaderOptions.cs @@ -4,13 +4,8 @@ namespace Microsoft.CodeAnalysis.Host { - internal readonly struct AnalyzerAssemblyLoaderOptions + internal readonly struct AnalyzerAssemblyLoaderOptions(bool shadowCopy) { - public bool ShadowCopy { get; } - - public AnalyzerAssemblyLoaderOptions(bool shadowCopy) - { - ShadowCopy = shadowCopy; - } + public bool ShadowCopy { get; } = shadowCopy; } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/Metadata/MetadataReferenceCache.cs b/src/Workspaces/Core/Portable/Workspace/Host/Metadata/MetadataReferenceCache.cs index 0c1e5b7b889fc..a30b508146aca 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/Metadata/MetadataReferenceCache.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/Metadata/MetadataReferenceCache.cs @@ -14,15 +14,12 @@ namespace Microsoft.CodeAnalysis.Host /// /// A cache for metadata references. /// - internal class MetadataReferenceCache + internal class MetadataReferenceCache(Func createReference) { private ImmutableDictionary _referenceSets = ImmutableDictionary.Empty; - private readonly Func _createReference; - - public MetadataReferenceCache(Func createReference) - => _createReference = createReference ?? throw new ArgumentNullException(nameof(createReference)); + private readonly Func _createReference = createReference ?? throw new ArgumentNullException(nameof(createReference)); public MetadataReference GetReference(string path, MetadataReferenceProperties properties) { @@ -37,19 +34,14 @@ public MetadataReference GetReference(string path, MetadataReferenceProperties p /// /// A collection of references to the same underlying metadata, each with different properties. /// - private class ReferenceSet + private class ReferenceSet(MetadataReferenceCache cache) { - private readonly MetadataReferenceCache _cache; - private readonly NonReentrantLock _gate = new(); // metadata references are held weakly, so even though this is a cache that enables reuse, it does not control lifetime. private readonly Dictionary> _references = new(); - public ReferenceSet(MetadataReferenceCache cache) - => _cache = cache; - public MetadataReference GetAddOrUpdate(string path, MetadataReferenceProperties properties) { using (_gate.DisposableWait()) @@ -67,7 +59,7 @@ public MetadataReference GetAddOrUpdate(string path, MetadataReferenceProperties } } - mref ??= _cache._createReference(path, properties); + mref ??= cache._createReference(path, properties); _references[properties] = new WeakReference(mref); } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/Metadata/MetadataServiceFactory.cs b/src/Workspaces/Core/Portable/Workspace/Host/Metadata/MetadataServiceFactory.cs index 21d7384dab987..dbc4e87e8b737 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/Metadata/MetadataServiceFactory.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/Metadata/MetadataServiceFactory.cs @@ -22,15 +22,10 @@ public MetadataServiceFactory() public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new Service(workspaceServices.GetService()); - private sealed class Service : IMetadataService + private sealed class Service(IDocumentationProviderService documentationService) : IMetadataService { - private readonly MetadataReferenceCache _metadataCache; - - public Service(IDocumentationProviderService documentationService) - { - _metadataCache = new MetadataReferenceCache((path, properties) => + private readonly MetadataReferenceCache _metadataCache = new MetadataReferenceCache((path, properties) => MetadataReference.CreateFromFile(path, properties, documentationService.GetDocumentationProvider(path))); - } public PortableExecutableReference GetReference(string resolvedPath, MetadataReferenceProperties properties) => (PortableExecutableReference)_metadataCache.GetReference(resolvedPath, properties); diff --git a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/DocumentKey.cs b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/DocumentKey.cs index 677ee89e21db2..87f947bc5c3ba 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/DocumentKey.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/DocumentKey.cs @@ -16,27 +16,19 @@ namespace Microsoft.CodeAnalysis.Storage /// solution load), but querying the data is still desired. /// [DataContract] - internal readonly struct DocumentKey : IEqualityComparer, IEquatable + internal readonly struct DocumentKey(ProjectKey project, DocumentId id, string? filePath, string name) : IEqualityComparer, IEquatable { [DataMember(Order = 0)] - public readonly ProjectKey Project; + public readonly ProjectKey Project = project; [DataMember(Order = 1)] - public readonly DocumentId Id; + public readonly DocumentId Id = id; [DataMember(Order = 2)] - public readonly string? FilePath; + public readonly string? FilePath = filePath; [DataMember(Order = 3)] - public readonly string Name; - - public DocumentKey(ProjectKey project, DocumentId id, string? filePath, string name) - { - Project = project; - Id = id; - FilePath = filePath; - Name = name; - } + public readonly string Name = name; public static DocumentKey ToDocumentKey(Document document) => ToDocumentKey(ProjectKey.ToProjectKey(document.Project), document.State); diff --git a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/ProjectKey.cs b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/ProjectKey.cs index 74ee810b5a2f9..fa5a3f4585c94 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/ProjectKey.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/ProjectKey.cs @@ -14,31 +14,22 @@ namespace Microsoft.CodeAnalysis.Storage /// solution load), but querying the data is still desired. /// [DataContract] - internal readonly struct ProjectKey + internal readonly struct ProjectKey(SolutionKey solution, ProjectId id, string? filePath, string name, Checksum parseOptionsChecksum) { [DataMember(Order = 0)] - public readonly SolutionKey Solution; + public readonly SolutionKey Solution = solution; [DataMember(Order = 1)] - public readonly ProjectId Id; + public readonly ProjectId Id = id; [DataMember(Order = 2)] - public readonly string? FilePath; + public readonly string? FilePath = filePath; [DataMember(Order = 3)] - public readonly string Name; + public readonly string Name = name; [DataMember(Order = 4)] - public readonly Checksum ParseOptionsChecksum; - - public ProjectKey(SolutionKey solution, ProjectId id, string? filePath, string name, Checksum parseOptionsChecksum) - { - Solution = solution; - Id = id; - FilePath = filePath; - Name = name; - ParseOptionsChecksum = parseOptionsChecksum; - } + public readonly Checksum ParseOptionsChecksum = parseOptionsChecksum; public static ProjectKey ToProjectKey(Project project) => ToProjectKey(project.Solution.State, project.State); diff --git a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/SolutionKey.cs b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/SolutionKey.cs index 5a9cc440d96b6..70fcd8ecc31cc 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/SolutionKey.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/SolutionKey.cs @@ -14,19 +14,13 @@ namespace Microsoft.CodeAnalysis.Storage /// solution load), but querying the data is still desired. /// [DataContract] - internal readonly struct SolutionKey + internal readonly struct SolutionKey(SolutionId id, string? filePath) { [DataMember(Order = 0)] - public readonly SolutionId Id; + public readonly SolutionId Id = id; [DataMember(Order = 1)] - public readonly string? FilePath; - - public SolutionKey(SolutionId id, string? filePath) - { - Id = id; - FilePath = filePath; - } + public readonly string? FilePath = filePath; public static SolutionKey ToSolutionKey(Solution solution) => ToSolutionKey(solution.State); diff --git a/src/Workspaces/Core/Portable/Workspace/Host/SourceFiles/DynamicFileInfo.cs b/src/Workspaces/Core/Portable/Workspace/Host/SourceFiles/DynamicFileInfo.cs index 51d128bb56531..723cadd92a958 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/SourceFiles/DynamicFileInfo.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/SourceFiles/DynamicFileInfo.cs @@ -10,41 +10,33 @@ namespace Microsoft.CodeAnalysis.Host /// this will be used to provide dynamic content such as generated content from cshtml to workspace /// we acquire this from exposed from external components such as razor for cshtml /// - internal sealed class DynamicFileInfo + internal sealed class DynamicFileInfo(string filePath, SourceCodeKind sourceCodeKind, TextLoader textLoader, bool designTimeOnly, IDocumentServiceProvider? documentServiceProvider) { - public DynamicFileInfo(string filePath, SourceCodeKind sourceCodeKind, TextLoader textLoader, bool designTimeOnly, IDocumentServiceProvider? documentServiceProvider) - { - FilePath = filePath; - SourceCodeKind = sourceCodeKind; - TextLoader = textLoader; - DocumentServiceProvider = documentServiceProvider; - DesignTimeOnly = designTimeOnly; - } /// /// The path to the generated file. in future, we will use this to get right options from editorconfig /// - public string FilePath { get; } + public string FilePath { get; } = filePath; /// /// return for this file /// - public SourceCodeKind SourceCodeKind { get; } + public SourceCodeKind SourceCodeKind { get; } = sourceCodeKind; /// /// return to load content for the dynamic file /// - public TextLoader TextLoader { get; } + public TextLoader TextLoader { get; } = textLoader; /// /// True if the source code contained in the document is only used in design-time (e.g. for completion), /// but is not passed to the compiler when the containing project is built, e.g. a Razor view. /// - public bool DesignTimeOnly { get; } + public bool DesignTimeOnly { get; } = designTimeOnly; /// /// return for the content it provided /// - public IDocumentServiceProvider? DocumentServiceProvider { get; } + public IDocumentServiceProvider? DocumentServiceProvider { get; } = documentServiceProvider; } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/WorkspaceAsynchronousOperationListenerProvider.cs b/src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/WorkspaceAsynchronousOperationListenerProvider.cs index 431161c07ebb8..83bd04517ff9c 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/WorkspaceAsynchronousOperationListenerProvider.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/WorkspaceAsynchronousOperationListenerProvider.cs @@ -11,14 +11,11 @@ namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceService(typeof(IWorkspaceAsynchronousOperationListenerProvider), ServiceLayer.Default)] [Shared] - internal sealed class WorkspaceAsynchronousOperationListenerProvider : IWorkspaceAsynchronousOperationListenerProvider + [method: ImportingConstructor] + [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + internal sealed class WorkspaceAsynchronousOperationListenerProvider(IAsynchronousOperationListenerProvider listenerProvider) : IWorkspaceAsynchronousOperationListenerProvider { - private readonly IAsynchronousOperationListener _listener; - - [ImportingConstructor] - [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public WorkspaceAsynchronousOperationListenerProvider(IAsynchronousOperationListenerProvider listenerProvider) - => _listener = listenerProvider.GetListener(FeatureAttribute.Workspace); + private readonly IAsynchronousOperationListener _listener = listenerProvider.GetListener(FeatureAttribute.Workspace); public IAsynchronousOperationListener GetListener() => _listener; diff --git a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs index 916231184d82f..eef980314b980 100644 --- a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs +++ b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.BatchingDocumentCollection.cs @@ -27,9 +27,13 @@ internal sealed partial class ProjectSystemProject /// /// This class should be free-threaded, and any synchronization is done via . /// This class is otherwise free to operate on private members of if needed. - private sealed class BatchingDocumentCollection + private sealed class BatchingDocumentCollection(ProjectSystemProject project, + Func documentAlreadyInWorkspace, + Action documentAddAction, + Action documentRemoveAction, + Func documentTextLoaderChangedAction, + WorkspaceChangeKind documentChangedWorkspaceKind) { - private readonly ProjectSystemProject _project; /// /// The map of file paths to the underlying . This document may exist in or has been @@ -63,27 +67,6 @@ private sealed class BatchingDocumentCollection /// private ImmutableList? _orderedDocumentsInBatch = null; - private readonly Func _documentAlreadyInWorkspace; - private readonly Action _documentAddAction; - private readonly Action _documentRemoveAction; - private readonly Func _documentTextLoaderChangedAction; - private readonly WorkspaceChangeKind _documentChangedWorkspaceKind; - - public BatchingDocumentCollection(ProjectSystemProject project, - Func documentAlreadyInWorkspace, - Action documentAddAction, - Action documentRemoveAction, - Func documentTextLoaderChangedAction, - WorkspaceChangeKind documentChangedWorkspaceKind) - { - _project = project; - _documentAlreadyInWorkspace = documentAlreadyInWorkspace; - _documentAddAction = documentAddAction; - _documentRemoveAction = documentRemoveAction; - _documentTextLoaderChangedAction = documentTextLoaderChangedAction; - _documentChangedWorkspaceKind = documentChangedWorkspaceKind; - } - public DocumentId AddFile(string fullPath, SourceCodeKind sourceCodeKind, ImmutableArray folders) { if (string.IsNullOrEmpty(fullPath)) @@ -91,8 +74,8 @@ public DocumentId AddFile(string fullPath, SourceCodeKind sourceCodeKind, Immuta throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } - var documentId = DocumentId.CreateNewId(_project.Id, fullPath); - var textLoader = new WorkspaceFileTextLoader(_project._projectSystemProjectFactory.Workspace.Services.SolutionServices, fullPath, defaultEncoding: null); + var documentId = DocumentId.CreateNewId(project.Id, fullPath); + var textLoader = new WorkspaceFileTextLoader(project._projectSystemProjectFactory.Workspace.Services.SolutionServices, fullPath, defaultEncoding: null); var documentInfo = DocumentInfo.Create( documentId, name: FileNameUtilities.GetFileName(fullPath), @@ -101,7 +84,7 @@ public DocumentId AddFile(string fullPath, SourceCodeKind sourceCodeKind, Immuta loader: textLoader, filePath: fullPath); - using (_project._gate.DisposableWait()) + using (project._gate.DisposableWait()) { if (_documentPathsToDocumentIds.ContainsKey(fullPath)) { @@ -112,16 +95,16 @@ public DocumentId AddFile(string fullPath, SourceCodeKind sourceCodeKind, Immuta _orderedDocumentsInBatch = _orderedDocumentsInBatch?.Add(documentId); _documentPathsToDocumentIds.Add(fullPath, documentId); - _project._documentWatchedFiles.Add(documentId, _project._documentFileChangeContext.EnqueueWatchingFile(fullPath)); + project._documentWatchedFiles.Add(documentId, project._documentFileChangeContext.EnqueueWatchingFile(fullPath)); - if (_project._activeBatchScopes > 0) + if (project._activeBatchScopes > 0) { _documentsAddedInBatch.Add(documentInfo); } else { - _project._projectSystemProjectFactory.ApplyChangeToWorkspace(w => _documentAddAction(w, documentInfo)); - _project._projectSystemProjectFactory.RaiseOnDocumentsAddedMaybeAsync(useAsync: false, ImmutableArray.Create(fullPath)).VerifyCompleted(); + project._projectSystemProjectFactory.ApplyChangeToWorkspace(w => documentAddAction(w, documentInfo)); + project._projectSystemProjectFactory.RaiseOnDocumentsAddedMaybeAsync(useAsync: false, ImmutableArray.Create(fullPath)).VerifyCompleted(); } } @@ -141,7 +124,7 @@ public DocumentId AddTextContainer( throw new ArgumentNullException(nameof(textContainer)); } - var documentId = DocumentId.CreateNewId(_project.Id, fullPath); + var documentId = DocumentId.CreateNewId(project.Id, fullPath); var textLoader = new SourceTextLoader(textContainer, fullPath); var documentInfo = DocumentInfo.Create( documentId, @@ -153,7 +136,7 @@ public DocumentId AddTextContainer( .WithDesignTimeOnly(designTimeOnly) .WithDocumentServiceProvider(documentServiceProvider); - using (_project._gate.DisposableWait()) + using (project._gate.DisposableWait()) { if (_sourceTextContainersToDocumentIds.ContainsKey(textContainer)) { @@ -172,16 +155,16 @@ public DocumentId AddTextContainer( _sourceTextContainersToDocumentIds = _sourceTextContainersToDocumentIds.Add(textContainer, documentInfo.Id); - if (_project._activeBatchScopes > 0) + if (project._activeBatchScopes > 0) { _documentsAddedInBatch.Add(documentInfo); } else { - _project._projectSystemProjectFactory.ApplyChangeToWorkspace(w => + project._projectSystemProjectFactory.ApplyChangeToWorkspace(w => { - _project._projectSystemProjectFactory.AddDocumentToDocumentsNotFromFiles_NoLock(documentInfo.Id); - _documentAddAction(w, documentInfo); + project._projectSystemProjectFactory.AddDocumentToDocumentsNotFromFiles_NoLock(documentInfo.Id); + documentAddAction(w, documentInfo); w.OnDocumentOpened(documentInfo.Id, textContainer); }); } @@ -192,7 +175,7 @@ public DocumentId AddTextContainer( public void AddDynamicFile_NoLock(IDynamicFileInfoProvider fileInfoProvider, DynamicFileInfo fileInfo, ImmutableArray folders) { - Debug.Assert(_project._gate.CurrentCount == 0); + Debug.Assert(project._gate.CurrentCount == 0); var documentInfo = CreateDocumentInfoFromFileInfo(fileInfo, folders.NullToEmpty()); @@ -213,26 +196,26 @@ public void AddDynamicFile_NoLock(IDynamicFileInfoProvider fileInfoProvider, Dyn _documentIdToDynamicFileInfoProvider.Add(documentId, fileInfoProvider); - if (_project._eventSubscriptionTracker.Add(fileInfoProvider)) + if (project._eventSubscriptionTracker.Add(fileInfoProvider)) { // subscribe to the event when we use this provider the first time - fileInfoProvider.Updated += _project.OnDynamicFileInfoUpdated; + fileInfoProvider.Updated += project.OnDynamicFileInfoUpdated; } - if (_project._activeBatchScopes > 0) + if (project._activeBatchScopes > 0) { _documentsAddedInBatch.Add(documentInfo); } else { // right now, assumption is dynamically generated file can never be opened in editor - _project._projectSystemProjectFactory.ApplyChangeToWorkspace(w => _documentAddAction(w, documentInfo)); + project._projectSystemProjectFactory.ApplyChangeToWorkspace(w => documentAddAction(w, documentInfo)); } } public IDynamicFileInfoProvider RemoveDynamicFile_NoLock(string fullPath) { - Debug.Assert(_project._gate.CurrentCount == 0); + Debug.Assert(project._gate.CurrentCount == 0); if (string.IsNullOrEmpty(fullPath)) { @@ -259,15 +242,15 @@ public void RemoveFile(string fullPath) throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } - using (_project._gate.DisposableWait()) + using (project._gate.DisposableWait()) { if (!_documentPathsToDocumentIds.TryGetValue(fullPath, out var documentId)) { throw new ArgumentException($"'{fullPath}' is not a source file of this project."); } - _project._documentWatchedFiles[documentId].Dispose(); - _project._documentWatchedFiles.Remove(documentId); + project._documentWatchedFiles[documentId].Dispose(); + project._documentWatchedFiles.Remove(documentId); RemoveFileInternal(documentId, fullPath); } @@ -283,15 +266,15 @@ private void RemoveFileInternal(DocumentId documentId, string fullPath) // 1. This file is actually been pushed to the workspace, and we need to remove it (either // as a part of the active batch or immediately) // 2. It hasn't been pushed yet, but is contained in _documentsAddedInBatch - if (_documentAlreadyInWorkspace(_project._projectSystemProjectFactory.Workspace.CurrentSolution, documentId)) + if (documentAlreadyInWorkspace(project._projectSystemProjectFactory.Workspace.CurrentSolution, documentId)) { - if (_project._activeBatchScopes > 0) + if (project._activeBatchScopes > 0) { _documentsRemovedInBatch.Add(documentId); } else { - _project._projectSystemProjectFactory.ApplyChangeToWorkspace(w => _documentRemoveAction(w, documentId)); + project._projectSystemProjectFactory.ApplyChangeToWorkspace(w => documentRemoveAction(w, documentId)); } } else @@ -314,7 +297,7 @@ public void RemoveTextContainer(SourceTextContainer textContainer) throw new ArgumentNullException(nameof(textContainer)); } - using (_project._gate.DisposableWait()) + using (project._gate.DisposableWait()) { if (!_sourceTextContainersToDocumentIds.TryGetValue(textContainer, out var documentId)) { @@ -335,23 +318,23 @@ public void RemoveTextContainer(SourceTextContainer textContainer) // 1. This file is actually been pushed to the workspace, and we need to remove it (either // as a part of the active batch or immediately) // 2. It hasn't been pushed yet, but is contained in _documentsAddedInBatch - if (_project._projectSystemProjectFactory.Workspace.CurrentSolution.GetDocument(documentId) != null) + if (project._projectSystemProjectFactory.Workspace.CurrentSolution.GetDocument(documentId) != null) { - if (_project._activeBatchScopes > 0) + if (project._activeBatchScopes > 0) { _documentsRemovedInBatch.Add(documentId); } else { - _project._projectSystemProjectFactory.ApplyChangeToWorkspace(w => + project._projectSystemProjectFactory.ApplyChangeToWorkspace(w => { // Just pass null for the filePath, since this document is immediately being removed // anyways -- whatever we set won't really be read since the next change will // come through. // TODO: Can't we just remove the document without closing it? w.OnDocumentClosed(documentId, new SourceTextLoader(textContainer, filePath: null)); - _documentRemoveAction(w, documentId); - _project._projectSystemProjectFactory.RemoveDocumentToDocumentsNotFromFiles_NoLock(documentId); + documentRemoveAction(w, documentId); + project._projectSystemProjectFactory.RemoveDocumentToDocumentsNotFromFiles_NoLock(documentId); }); } } @@ -376,7 +359,7 @@ public bool ContainsFile(string fullPath) throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath)); } - using (_project._gate.DisposableWait()) + using (project._gate.DisposableWait()) { return _documentPathsToDocumentIds.ContainsKey(fullPath); } @@ -384,10 +367,10 @@ public bool ContainsFile(string fullPath) public async ValueTask ProcessRegularFileChangesAsync(ImmutableSegmentedList filePaths) { - using (await _project._gate.DisposableWaitAsync().ConfigureAwait(false)) + using (await project._gate.DisposableWaitAsync().ConfigureAwait(false)) { // If our project has already been removed, this is a stale notification, and we can disregard. - if (_project.HasBeenRemoved) + if (project.HasBeenRemoved) { return; } @@ -405,7 +388,7 @@ public async ValueTask ProcessRegularFileChangesAsync(ImmutableSegmentedList d.Id == documentId)) { - documentsToChange.Add((documentId, new WorkspaceFileTextLoader(_project._projectSystemProjectFactory.Workspace.Services.SolutionServices, filePath, defaultEncoding: null))); + documentsToChange.Add((documentId, new WorkspaceFileTextLoader(project._projectSystemProjectFactory.Workspace.Services.SolutionServices, filePath, defaultEncoding: null))); } } } @@ -416,15 +399,15 @@ public async ValueTask ProcessRegularFileChangesAsync(ImmutableSegmentedList + await project._projectSystemProjectFactory.ApplyBatchChangeToWorkspaceAsync(solutionChanges => { foreach (var (documentId, textLoader) in documentsToChange) { - if (!_project._projectSystemProjectFactory.Workspace.IsDocumentOpen(documentId)) + if (!project._projectSystemProjectFactory.Workspace.IsDocumentOpen(documentId)) { solutionChanges.UpdateSolutionForDocumentAction( - _documentTextLoaderChangedAction(solutionChanges.Solution, documentId, textLoader), - _documentChangedWorkspaceKind, + documentTextLoaderChangedAction(solutionChanges.Solution, documentId, textLoader), + documentChangedWorkspaceKind, SpecializedCollections.SingletonEnumerable(documentId)); } } @@ -441,10 +424,10 @@ await _project._projectSystemProjectFactory.ApplyBatchChangeToWorkspaceAsync(sol /// filepath used in workspace. it might be different than projectSystemFilePath public void ProcessDynamicFileChange(string projectSystemFilePath, string workspaceFilePath) { - using (_project._gate.DisposableWait()) + using (project._gate.DisposableWait()) { // If our project has already been removed, this is a stale notification, and we can disregard. - if (_project.HasBeenRemoved) + if (project.HasBeenRemoved) { return; } @@ -463,7 +446,7 @@ public void ProcessDynamicFileChange(string projectSystemFilePath, string worksp Contract.ThrowIfFalse(_documentIdToDynamicFileInfoProvider.TryGetValue(documentId, out var fileInfoProvider)); - _project._projectSystemProjectFactory.ApplyChangeToWorkspace(w => + project._projectSystemProjectFactory.ApplyChangeToWorkspace(w => { if (w.IsDocumentOpen(documentId)) { @@ -474,7 +457,7 @@ public void ProcessDynamicFileChange(string projectSystemFilePath, string worksp // meaning it can't use JTF to go back to UI thread. // so, it is okay for us to call regular ".Result" on a task here. var fileInfo = fileInfoProvider.GetDynamicFileInfoAsync( - _project.Id, _project._filePath, projectSystemFilePath, CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None); + project.Id, project._filePath, projectSystemFilePath, CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None); Contract.ThrowIfNull(fileInfo, "We previously received a dynamic file for this path, and we're responding to a change, so we expect to get a new one."); @@ -496,7 +479,7 @@ public void ReorderFiles(ImmutableArray filePaths) throw new ArgumentOutOfRangeException("The specified files are empty.", nameof(filePaths)); } - using (_project._gate.DisposableWait()) + using (project._gate.DisposableWait()) { if (_documentPathsToDocumentIds.Count != filePaths.Length) { @@ -517,13 +500,13 @@ public void ReorderFiles(ImmutableArray filePaths) } } - if (_project._activeBatchScopes > 0) + if (project._activeBatchScopes > 0) { _orderedDocumentsInBatch = documentIds.ToImmutable(); } else { - _project._projectSystemProjectFactory.ApplyChangeToWorkspace(_project.Id, solution => solution.WithProjectDocumentsOrder(_project.Id, documentIds.ToImmutable())); + project._projectSystemProjectFactory.ApplyChangeToWorkspace(project.Id, solution => solution.WithProjectDocumentsOrder(project.Id, documentIds.ToImmutable())); } } } @@ -567,8 +550,8 @@ internal void UpdateSolutionForBatch( if (_orderedDocumentsInBatch != null) { solutionChanges.UpdateSolutionForProjectAction( - _project.Id, - solutionChanges.Solution.WithProjectDocumentsOrder(_project.Id, _orderedDocumentsInBatch)); + project.Id, + solutionChanges.Solution.WithProjectDocumentsOrder(project.Id, _orderedDocumentsInBatch)); _orderedDocumentsInBatch = null; } } @@ -581,7 +564,7 @@ private DocumentInfo CreateDocumentInfoFromFileInfo(DynamicFileInfo fileInfo, Im var filePath = fileInfo.FilePath; var name = FileNameUtilities.GetFileName(filePath); - var documentId = DocumentId.CreateNewId(_project.Id, filePath); + var documentId = DocumentId.CreateNewId(project.Id, filePath); return DocumentInfo.Create( documentId, @@ -595,19 +578,10 @@ private DocumentInfo CreateDocumentInfoFromFileInfo(DynamicFileInfo fileInfo, Im .WithDocumentServiceProvider(fileInfo.DocumentServiceProvider); } - private sealed class SourceTextLoader : TextLoader + private sealed class SourceTextLoader(SourceTextContainer textContainer, string? filePath) : TextLoader { - private readonly SourceTextContainer _textContainer; - private readonly string? _filePath; - - public SourceTextLoader(SourceTextContainer textContainer, string? filePath) - { - _textContainer = textContainer; - _filePath = filePath; - } - public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - => Task.FromResult(TextAndVersion.Create(_textContainer.CurrentText, VersionStamp.Create(), _filePath)); + => Task.FromResult(TextAndVersion.Create(textContainer.CurrentText, VersionStamp.Create(), filePath)); } } } diff --git a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/SolutionChangeAccumulator.cs b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/SolutionChangeAccumulator.cs index eedd91579f77f..b83b44a793eb7 100644 --- a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/SolutionChangeAccumulator.cs +++ b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/SolutionChangeAccumulator.cs @@ -10,7 +10,7 @@ namespace Microsoft.CodeAnalysis.Workspaces.ProjectSystem /// A little helper type to hold onto the being updated in a batch, which also /// keeps track of the right to raise when we are done. /// - internal sealed class SolutionChangeAccumulator + internal sealed class SolutionChangeAccumulator(Solution startingSolution) { /// /// The kind that encompasses all the changes we've made. It's null if no changes have been made, @@ -20,10 +20,7 @@ internal sealed class SolutionChangeAccumulator private WorkspaceChangeKind? _workspaceChangeKind; private readonly List _documentIdsRemoved = new(); - public SolutionChangeAccumulator(Solution startingSolution) - => Solution = startingSolution; - - public Solution Solution { get; private set; } + public Solution Solution { get; private set; } = startingSolution; public IEnumerable DocumentIdsRemoved => _documentIdsRemoved; public bool HasChange => _workspaceChangeKind.HasValue; diff --git a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/VisualStudioAnalyzer.cs b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/VisualStudioAnalyzer.cs index 2b41f36c0219e..a4cd344d9b472 100644 --- a/src/Workspaces/Core/Portable/Workspace/ProjectSystem/VisualStudioAnalyzer.cs +++ b/src/Workspaces/Core/Portable/Workspace/ProjectSystem/VisualStudioAnalyzer.cs @@ -11,7 +11,7 @@ namespace Microsoft.CodeAnalysis.Workspaces.ProjectSystem { // TODO: Remove. This is only needed to support Solution Explorer Analyzer node population. // Analyzers should not be loaded in devenv process (see https://github.com/dotnet/roslyn/issues/43008). - internal sealed class ProjectAnalyzerReference : IDisposable + internal sealed class ProjectAnalyzerReference(string fullPath, IProjectSystemDiagnosticSource projectSystemDiagnosticSource, ProjectId projectId, string language) : IDisposable { // Shadow copy analyzer files coming from packages to avoid locking the files in NuGet cache. // NOTE: It is important that we share the same shadow copy assembly loader for all VisualStudioAnalyzer instances. @@ -19,24 +19,12 @@ internal sealed class ProjectAnalyzerReference : IDisposable private static readonly IAnalyzerAssemblyLoader s_analyzerAssemblyLoader = new ShadowCopyAnalyzerAssemblyLoader(Path.Combine(Path.GetTempPath(), "VS", "AnalyzerAssemblyLoader")); - private readonly ProjectId _projectId; - private readonly IProjectSystemDiagnosticSource _projectSystemDiagnosticSource; - private readonly string _language; - // these 2 are mutable states that must be guarded under the _gate. private readonly object _gate = new(); private AnalyzerReference? _analyzerReference; private ImmutableArray _analyzerLoadErrors = ImmutableArray.Empty; - public ProjectAnalyzerReference(string fullPath, IProjectSystemDiagnosticSource projectSystemDiagnosticSource, ProjectId projectId, string language) - { - FullPath = fullPath; - _projectSystemDiagnosticSource = projectSystemDiagnosticSource; - _projectId = projectId; - _language = language; - } - - public string FullPath { get; } + public string FullPath { get; } = fullPath; public AnalyzerReference GetReference() { @@ -58,12 +46,12 @@ public AnalyzerReference GetReference() private void OnAnalyzerLoadError(object? sender, AnalyzerLoadFailureEventArgs e) { - var data = _projectSystemDiagnosticSource.CreateAnalyzerLoadFailureDiagnostic(e, FullPath, _projectId, _language); + var data = projectSystemDiagnosticSource.CreateAnalyzerLoadFailureDiagnostic(e, FullPath, projectId, language); lock (_gate) { _analyzerLoadErrors = _analyzerLoadErrors.Add(data); - _projectSystemDiagnosticSource.UpdateDiagnosticsForProject(_projectId, this, _analyzerLoadErrors); + projectSystemDiagnosticSource.UpdateDiagnosticsForProject(projectId, this, _analyzerLoadErrors); } } @@ -77,10 +65,10 @@ public void Dispose() if (!loadErrors.IsEmpty) { - _projectSystemDiagnosticSource.ClearDiagnosticsForProject(_projectId, this); + projectSystemDiagnosticSource.ClearDiagnosticsForProject(projectId, this); } - _projectSystemDiagnosticSource.ClearAnalyzerReferenceDiagnostics(fileReference, _language, _projectId); + projectSystemDiagnosticSource.ClearAnalyzerReferenceDiagnostics(fileReference, language, projectId); } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/AdditionalTextWithState.cs b/src/Workspaces/Core/Portable/Workspace/Solution/AdditionalTextWithState.cs index bd2c335acc41f..dc204f1d87207 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/AdditionalTextWithState.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/AdditionalTextWithState.cs @@ -11,15 +11,12 @@ namespace Microsoft.CodeAnalysis.Diagnostics /// /// An implementation of for the compiler that wraps a . /// - internal sealed class AdditionalTextWithState : AdditionalText + /// + /// Create a from a . + /// + internal sealed class AdditionalTextWithState(AdditionalDocumentState documentState) : AdditionalText { - private readonly AdditionalDocumentState _documentState; - - /// - /// Create a from a . - /// - public AdditionalTextWithState(AdditionalDocumentState documentState) - => _documentState = documentState ?? throw new ArgumentNullException(nameof(documentState)); + private readonly AdditionalDocumentState _documentState = documentState ?? throw new ArgumentNullException(nameof(documentState)); /// /// Resolved path of the document. diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/AnalyzerConfigData.cs b/src/Workspaces/Core/Portable/Workspace/Solution/AnalyzerConfigData.cs index 99371f49965bb..1555df3765c3c 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/AnalyzerConfigData.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/AnalyzerConfigData.cs @@ -10,16 +10,9 @@ namespace Microsoft.CodeAnalysis; /// /// Aggregate analyzer config options for a specific path. /// -internal readonly struct AnalyzerConfigData +internal readonly struct AnalyzerConfigData(AnalyzerConfigOptionsResult result) { - public readonly StructuredAnalyzerConfigOptions ConfigOptions; - public readonly ImmutableDictionary AnalyzerOptions; - public readonly ImmutableDictionary TreeOptions; - - public AnalyzerConfigData(AnalyzerConfigOptionsResult result) - { - ConfigOptions = StructuredAnalyzerConfigOptions.Create(result.AnalyzerOptions); - AnalyzerOptions = result.AnalyzerOptions; - TreeOptions = result.TreeOptions; - } + public readonly StructuredAnalyzerConfigOptions ConfigOptions = StructuredAnalyzerConfigOptions.Create(result.AnalyzerOptions); + public readonly ImmutableDictionary AnalyzerOptions = result.AnalyzerOptions; + public readonly ImmutableDictionary TreeOptions = result.TreeOptions; } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Checksum.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Checksum.cs index c3ae1f521642b..c3264c8baab64 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Checksum.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Checksum.cs @@ -21,7 +21,7 @@ namespace Microsoft.CodeAnalysis /// without actually comparing data itself /// [DataContract] - internal sealed partial class Checksum : IObjectWritable, IEquatable + internal sealed partial class Checksum(HashData hash) : IObjectWritable, IEquatable { /// /// The intended size of the structure. @@ -31,10 +31,7 @@ internal sealed partial class Checksum : IObjectWritable, IEquatable public static readonly Checksum Null = new(default); [DataMember(Order = 0)] - private readonly HashData _checksum; - - public Checksum(HashData hash) - => _checksum = hash; + private readonly HashData _checksum = hash; /// /// Create Checksum from given byte array. if byte array is bigger than , it will be @@ -137,23 +134,16 @@ public static Checksum ReadFrom(ObjectReader reader) /// [DataContract] [StructLayout(LayoutKind.Explicit, Size = HashSize)] - public readonly struct HashData : IEquatable + public readonly struct HashData(long data1, long data2, int data3) : IEquatable { [FieldOffset(0), DataMember(Order = 0)] - private readonly long Data1; + private readonly long Data1 = data1; [FieldOffset(8), DataMember(Order = 1)] - private readonly long Data2; + private readonly long Data2 = data2; [FieldOffset(16), DataMember(Order = 2)] - private readonly int Data3; - - public HashData(long data1, long data2, int data3) - { - Data1 = data1; - Data2 = data2; - Data3 = data3; - } + private readonly int Data3 = data3; public static bool operator ==(HashData x, HashData y) => x.Equals(y); diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ChecksumCollection.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ChecksumCollection.cs index e68ae66ea7978..b4495a9b4c5c5 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ChecksumCollection.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ChecksumCollection.cs @@ -17,16 +17,12 @@ namespace Microsoft.CodeAnalysis.Serialization /// /// collection which children is checksum. /// - internal class ChecksumCollection : ChecksumWithChildren, IReadOnlyCollection + internal class ChecksumCollection(ImmutableArray checksums) : ChecksumWithChildren(checksums), IReadOnlyCollection { public ChecksumCollection(ImmutableArray checksums) : this(checksums.CastArray()) { } - public ChecksumCollection(ImmutableArray checksums) : base(checksums) - { - } - public int Count => Children.Length; public Checksum this[int index] => (Checksum)Children[index]; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ChecksumWithChildren.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ChecksumWithChildren.cs index e459e21006ba6..bf2d02a802d19 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ChecksumWithChildren.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ChecksumWithChildren.cs @@ -11,17 +11,11 @@ namespace Microsoft.CodeAnalysis.Serialization /// /// this is a collection that has its own checksum and contains only checksum or checksum collection as its children. /// - internal abstract class ChecksumWithChildren : IChecksummedObject + internal abstract class ChecksumWithChildren(ImmutableArray children) : IChecksummedObject { - public ChecksumWithChildren(ImmutableArray children) - { - Checksum = CreateChecksum(children); - Children = children; - } - - public Checksum Checksum { get; } + public Checksum Checksum { get; } = CreateChecksum(children); - public ImmutableArray Children { get; } + public ImmutableArray Children { get; } = children; private static Checksum CreateChecksum(ImmutableArray children) { diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ConstantTextAndVersionSource.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ConstantTextAndVersionSource.cs index 1b7268ac8f73b..44b43280d7d8c 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ConstantTextAndVersionSource.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ConstantTextAndVersionSource.cs @@ -12,14 +12,9 @@ namespace Microsoft.CodeAnalysis; /// /// This value source keeps a strong reference to a value. /// -internal sealed class ConstantTextAndVersionSource : ValueSource, ITextAndVersionSource +internal sealed class ConstantTextAndVersionSource(TextAndVersion value) : ValueSource, ITextAndVersionSource { - private readonly TextAndVersion _value; - - public ConstantTextAndVersionSource(TextAndVersion value) - { - _value = value; - } + private readonly TextAndVersion _value = value; public bool CanReloadText => false; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentDiagnostic.cs b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentDiagnostic.cs index ec11511cf57f7..19eb5a9c2e937 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentDiagnostic.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentDiagnostic.cs @@ -6,14 +6,8 @@ namespace Microsoft.CodeAnalysis { - public class DocumentDiagnostic : WorkspaceDiagnostic + public class DocumentDiagnostic(WorkspaceDiagnosticKind kind, string message, DocumentId documentId) : WorkspaceDiagnostic(kind, message) { - public DocumentId DocumentId { get; } - - public DocumentDiagnostic(WorkspaceDiagnosticKind kind, string message, DocumentId documentId) - : base(kind, message) - { - this.DocumentId = documentId; - } + public DocumentId DocumentId { get; } = documentId; } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentInfo.cs b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentInfo.cs index de436542b7c4a..99f39147215aa 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentInfo.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentInfo.cs @@ -147,63 +147,52 @@ private string GetDebuggerDisplay() /// type that contains information regarding this document itself but /// no tree information such as document info /// - internal sealed class DocumentAttributes : IChecksummedObject, IObjectWritable + internal sealed class DocumentAttributes( + DocumentId id, + string name, + IReadOnlyList folders, + SourceCodeKind sourceCodeKind, + string? filePath, + bool isGenerated, + bool designTimeOnly) : IChecksummedObject, IObjectWritable { private Checksum? _lazyChecksum; /// /// The Id of the document. /// - public DocumentId Id { get; } + public DocumentId Id { get; } = id; /// /// The name of the document. /// - public string Name { get; } + public string Name { get; } = name; /// /// The names of the logical nested folders the document is contained in. /// - public IReadOnlyList Folders { get; } + public IReadOnlyList Folders { get; } = folders; /// /// The kind of the source code. /// - public SourceCodeKind SourceCodeKind { get; } + public SourceCodeKind SourceCodeKind { get; } = sourceCodeKind; /// /// The file path of the document. /// - public string? FilePath { get; } + public string? FilePath { get; } = filePath; /// /// True if the document is a side effect of the build. /// - public bool IsGenerated { get; } + public bool IsGenerated { get; } = isGenerated; /// /// True if the source code contained in the document is only used in design-time (e.g. for completion), /// but is not passed to the compiler when the containing project is built, e.g. a Razor view /// - public bool DesignTimeOnly { get; } - - public DocumentAttributes( - DocumentId id, - string name, - IReadOnlyList folders, - SourceCodeKind sourceCodeKind, - string? filePath, - bool isGenerated, - bool designTimeOnly) - { - Id = id; - Name = name; - Folders = folders; - SourceCodeKind = sourceCodeKind; - FilePath = filePath; - IsGenerated = isGenerated; - DesignTimeOnly = designTimeOnly; - } + public bool DesignTimeOnly { get; } = designTimeOnly; public DocumentAttributes With( DocumentId? id = null, diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState.EquivalenceResult.cs b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState.EquivalenceResult.cs index 01ff61f58d22f..60543ea086cb9 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState.EquivalenceResult.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState.EquivalenceResult.cs @@ -8,16 +8,10 @@ namespace Microsoft.CodeAnalysis { internal partial class DocumentState { - internal class EquivalenceResult + internal class EquivalenceResult(bool topLevelEquivalent, bool interiorEquivalent) { - public readonly bool TopLevelEquivalent; - public readonly bool InteriorEquivalent; - - public EquivalenceResult(bool topLevelEquivalent, bool interiorEquivalent) - { - this.TopLevelEquivalent = topLevelEquivalent; - this.InteriorEquivalent = interiorEquivalent; - } + public readonly bool TopLevelEquivalent = topLevelEquivalent; + public readonly bool InteriorEquivalent = interiorEquivalent; } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState_TreeTextSource.cs b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState_TreeTextSource.cs index 941cb267fc1de..25a94da69406d 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState_TreeTextSource.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/DocumentState_TreeTextSource.cs @@ -15,35 +15,28 @@ internal partial class DocumentState /// /// A source for constructed from an syntax tree. /// - private sealed class TreeTextSource : ITextAndVersionSource + private sealed class TreeTextSource(ValueSource textSource, VersionStamp version) : ITextAndVersionSource { - private readonly ValueSource _textSource; - private readonly VersionStamp _version; + private readonly VersionStamp _version = version; public bool CanReloadText => false; - public TreeTextSource(ValueSource textSource, VersionStamp version) - { - _textSource = textSource; - _version = version; - } - public async Task GetValueAsync(LoadTextOptions options, CancellationToken cancellationToken) { - var text = await _textSource.GetValueAsync(cancellationToken).ConfigureAwait(false); + var text = await textSource.GetValueAsync(cancellationToken).ConfigureAwait(false); return TextAndVersion.Create(text, _version); } public TextAndVersion GetValue(LoadTextOptions options, CancellationToken cancellationToken) { - var text = _textSource.GetValue(cancellationToken); + var text = textSource.GetValue(cancellationToken); return TextAndVersion.Create(text, _version); } public bool TryGetValue(LoadTextOptions options, [NotNullWhen(true)] out TextAndVersion? value) { - if (_textSource.TryGetValue(out var text)) + if (textSource.TryGetValue(out var text)) { value = TextAndVersion.Create(text, _version); return true; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/LoadTextOptions.cs b/src/Workspaces/Core/Portable/Workspace/Solution/LoadTextOptions.cs index 5f01a2368766a..a64ded278c05c 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/LoadTextOptions.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/LoadTextOptions.cs @@ -11,12 +11,9 @@ namespace Microsoft.CodeAnalysis; /// /// Options used to load . /// -public readonly struct LoadTextOptions : IEquatable +public readonly struct LoadTextOptions(SourceHashAlgorithm checksumAlgorithm) : IEquatable { - public SourceHashAlgorithm ChecksumAlgorithm { get; } - - public LoadTextOptions(SourceHashAlgorithm checksumAlgorithm) - => ChecksumAlgorithm = checksumAlgorithm; + public SourceHashAlgorithm ChecksumAlgorithm { get; } = checksumAlgorithm; public bool Equals(LoadTextOptions other) => ChecksumAlgorithm == other.ChecksumAlgorithm; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/LoadableTextAndVersionSource.cs b/src/Workspaces/Core/Portable/Workspace/Solution/LoadableTextAndVersionSource.cs index 94b3467cdf651..70417d9b9dbad 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/LoadableTextAndVersionSource.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/LoadableTextAndVersionSource.cs @@ -10,12 +10,12 @@ namespace Microsoft.CodeAnalysis; -internal sealed class LoadableTextAndVersionSource : ITextAndVersionSource +internal sealed class LoadableTextAndVersionSource(TextLoader loader, bool cacheResult) : ITextAndVersionSource { - private sealed class LazyValueWithOptions + private sealed class LazyValueWithOptions(LoadableTextAndVersionSource source, LoadTextOptions options) { - public readonly LoadableTextAndVersionSource Source; - public readonly LoadTextOptions Options; + public readonly LoadableTextAndVersionSource Source = source; + public readonly LoadTextOptions Options = options; private readonly SemaphoreSlim _gate = new(initialCount: 1); @@ -34,12 +34,6 @@ private sealed class LazyValueWithOptions /// private WeakReference? _weakInstance; - public LazyValueWithOptions(LoadableTextAndVersionSource source, LoadTextOptions options) - { - Source = source; - Options = options; - } - private Task LoadAsync(CancellationToken cancellationToken) => Source.Loader.LoadTextAsync(Options, cancellationToken); @@ -108,17 +102,11 @@ private void UpdateWeakAndStrongReferences_NoLock(TextAndVersion textAndVersion) } } - public readonly TextLoader Loader; - public readonly bool CacheResult; + public readonly TextLoader Loader = loader; + public readonly bool CacheResult = cacheResult; private LazyValueWithOptions? _lazyValue; - public LoadableTextAndVersionSource(TextLoader loader, bool cacheResult) - { - Loader = loader; - CacheResult = cacheResult; - } - public bool CanReloadText => Loader.CanReloadText; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Project.EquivalenceResult.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Project.EquivalenceResult.cs index 281fa15ae1f9f..73361de7fe833 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Project.EquivalenceResult.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Project.EquivalenceResult.cs @@ -8,16 +8,10 @@ namespace Microsoft.CodeAnalysis { public partial class Project { - private class EquivalenceResult + private class EquivalenceResult(bool publiclyEquivalent, bool privatelyEquivalent) { - public readonly bool PubliclyEquivalent; - public readonly bool PrivatelyEquivalent; - - public EquivalenceResult(bool publiclyEquivalent, bool privatelyEquivalent) - { - this.PubliclyEquivalent = publiclyEquivalent; - this.PrivatelyEquivalent = privatelyEquivalent; - } + public readonly bool PubliclyEquivalent = publiclyEquivalent; + public readonly bool PrivatelyEquivalent = privatelyEquivalent; } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph.cs index 4593d8b9c5c70..2e007ad813eca 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph.cs @@ -512,12 +512,8 @@ private static void ValidateReverseReferences( internal TestAccessor GetTestAccessor() => new(this); - internal readonly struct TestAccessor + internal readonly struct TestAccessor(ProjectDependencyGraph instance) { - private readonly ProjectDependencyGraph _instance; - - public TestAccessor(ProjectDependencyGraph instance) - => _instance = instance; /// /// Gets the list of projects that directly or transitively depend on this project, if it has already been @@ -530,7 +526,7 @@ public TestAccessor(ProjectDependencyGraph instance) throw new ArgumentNullException(nameof(projectId)); } - _instance._reverseTransitiveReferencesMap.TryGetValue(projectId, out var projects); + instance._reverseTransitiveReferencesMap.TryGetValue(projectId, out var projects); return projects; } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDiagnostic.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDiagnostic.cs index 00a253b11a6ef..5853ea69fd651 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDiagnostic.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectDiagnostic.cs @@ -6,14 +6,8 @@ namespace Microsoft.CodeAnalysis { - public class ProjectDiagnostic : WorkspaceDiagnostic + public class ProjectDiagnostic(WorkspaceDiagnosticKind kind, string message, ProjectId projectId) : WorkspaceDiagnostic(kind, message) { - public ProjectId ProjectId { get; } - - public ProjectDiagnostic(WorkspaceDiagnosticKind kind, string message, ProjectId projectId) - : base(kind, message) - { - this.ProjectId = projectId; - } + public ProjectId ProjectId { get; } = projectId; } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectInfo.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectInfo.cs index e5e764550992c..7cb79c6d61aaa 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectInfo.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectInfo.cs @@ -399,7 +399,22 @@ internal string GetDebuggerDisplay() /// type that contains information regarding this project itself but /// no tree information such as document info /// - internal sealed class ProjectAttributes : IChecksummedObject, IObjectWritable + internal sealed class ProjectAttributes( + ProjectId id, + VersionStamp version, + string name, + string assemblyName, + string language, + CompilationOutputInfo compilationOutputFilePaths, + SourceHashAlgorithm checksumAlgorithm, + string? defaultNamespace = null, + string? filePath = null, + string? outputFilePath = null, + string? outputRefFilePath = null, + Guid telemetryId = default, + bool isSubmission = false, + bool hasAllInformation = true, + bool runAnalyzers = true) : IChecksummedObject, IObjectWritable { /// /// Matches names like: Microsoft.CodeAnalysis.Features (netcoreapp3.1) @@ -409,79 +424,79 @@ internal sealed class ProjectAttributes : IChecksummedObject, IObjectWritable /// /// The unique Id of the project. /// - public ProjectId Id { get; } + public ProjectId Id { get; } = id; /// /// The version of the project. /// - public VersionStamp Version { get; } + public VersionStamp Version { get; } = version; /// /// The name of the project. This may differ from the project's filename. /// - public string Name { get; } + public string Name { get; } = name; /// /// The name of the assembly that this project will create, without file extension. /// , - public string AssemblyName { get; } + public string AssemblyName { get; } = assemblyName; /// /// The language of the project. /// - public string Language { get; } + public string Language { get; } = language; /// /// The path to the project file or null if there is no project file. /// - public string? FilePath { get; } + public string? FilePath { get; } = filePath; /// /// The path to the output file (module or assembly). /// - public string? OutputFilePath { get; } + public string? OutputFilePath { get; } = outputFilePath; /// /// The path to the reference assembly output file. /// - public string? OutputRefFilePath { get; } + public string? OutputRefFilePath { get; } = outputRefFilePath; /// /// Paths to the compiler output files. /// - public CompilationOutputInfo CompilationOutputInfo { get; } + public CompilationOutputInfo CompilationOutputInfo { get; } = compilationOutputFilePaths; /// /// The default namespace of the project. /// - public string? DefaultNamespace { get; } + public string? DefaultNamespace { get; } = defaultNamespace; /// /// Algorithm to calculate content checksum for debugging purposes. /// - public SourceHashAlgorithm ChecksumAlgorithm { get; } + public SourceHashAlgorithm ChecksumAlgorithm { get; } = checksumAlgorithm; /// /// True if this is a submission project for interactive sessions. /// - public bool IsSubmission { get; } + public bool IsSubmission { get; } = isSubmission; /// /// True if project information is complete. In some workspace hosts, it is possible /// a project only has partial information. In such cases, a project might not have all /// information on its files or references. /// - public bool HasAllInformation { get; } + public bool HasAllInformation { get; } = hasAllInformation; /// /// True if we should run analyzers for this project. /// - public bool RunAnalyzers { get; } + public bool RunAnalyzers { get; } = runAnalyzers; /// /// The id report during telemetry events. /// - public Guid TelemetryId { get; } + public Guid TelemetryId { get; } = telemetryId; private StrongBox<(string?, string?)>? _lazyNameAndFlavor; private Checksum? _lazyChecksum; @@ -506,41 +521,6 @@ internal sealed class ProjectAttributes : IChecksummedObject, IObjectWritable } } - public ProjectAttributes( - ProjectId id, - VersionStamp version, - string name, - string assemblyName, - string language, - CompilationOutputInfo compilationOutputFilePaths, - SourceHashAlgorithm checksumAlgorithm, - string? defaultNamespace = null, - string? filePath = null, - string? outputFilePath = null, - string? outputRefFilePath = null, - Guid telemetryId = default, - bool isSubmission = false, - bool hasAllInformation = true, - bool runAnalyzers = true) - { - Id = id; - Name = name; - Language = language; - AssemblyName = assemblyName; - - Version = version; - FilePath = filePath; - OutputFilePath = outputFilePath; - OutputRefFilePath = outputRefFilePath; - CompilationOutputInfo = compilationOutputFilePaths; - DefaultNamespace = defaultNamespace; - ChecksumAlgorithm = checksumAlgorithm; - IsSubmission = isSubmission; - HasAllInformation = hasAllInformation; - RunAnalyzers = runAnalyzers; - TelemetryId = telemetryId; - } - public ProjectAttributes With( VersionStamp? version = null, string? name = null, diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs index e1f3658a71a26..bacd0287a65f2 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs @@ -291,16 +291,12 @@ public AnalyzerConfigData GetAnalyzerOptionsForPath(string path, CancellationTok return GetAnalyzerOptionsForPath(sourceFilePath, CancellationToken.None); } - internal sealed class ProjectAnalyzerConfigOptionsProvider : AnalyzerConfigOptionsProvider + internal sealed class ProjectAnalyzerConfigOptionsProvider(ProjectState projectState) : AnalyzerConfigOptionsProvider { - private readonly ProjectState _projectState; private RazorDesignTimeAnalyzerConfigOptions? _lazyRazorDesignTimeOptions = null; - public ProjectAnalyzerConfigOptionsProvider(ProjectState projectState) - => _projectState = projectState; - private AnalyzerConfigOptionsCache GetCache() - => _projectState._lazyAnalyzerConfigOptions.GetValue(CancellationToken.None); + => projectState._lazyAnalyzerConfigOptions.GetValue(CancellationToken.None); public override AnalyzerConfigOptions GlobalOptions => GetCache().GlobalConfigOptions.ConfigOptions; @@ -309,7 +305,7 @@ public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) { var documentId = DocumentState.GetDocumentIdForTree(tree); var cache = GetCache(); - if (documentId != null && _projectState.DocumentStates.TryGetState(documentId, out var documentState)) + if (documentId != null && projectState.DocumentStates.TryGetState(documentId, out var documentState)) { return GetOptions(cache, documentState); } @@ -319,13 +315,13 @@ public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) internal async ValueTask GetOptionsAsync(DocumentState documentState, CancellationToken cancellationToken) { - var cache = await _projectState._lazyAnalyzerConfigOptions.GetValueAsync(cancellationToken).ConfigureAwait(false); + var cache = await projectState._lazyAnalyzerConfigOptions.GetValueAsync(cancellationToken).ConfigureAwait(false); return GetOptions(cache, documentState); } private StructuredAnalyzerConfigOptions GetOptions(in AnalyzerConfigOptionsCache cache, DocumentState documentState) { - var services = _projectState.LanguageServices.SolutionServices; + var services = projectState.LanguageServices.SolutionServices; if (documentState.IsRazorDocument()) { @@ -341,7 +337,7 @@ private StructuredAnalyzerConfigOptions GetOptions(in AnalyzerConfigOptionsCache var legacyDocumentOptionsProvider = services.GetService(); if (legacyDocumentOptionsProvider != null) { - return StructuredAnalyzerConfigOptions.Create(legacyDocumentOptionsProvider.GetOptions(_projectState.Id, filePath)); + return StructuredAnalyzerConfigOptions.Create(legacyDocumentOptionsProvider.GetOptions(projectState.Id, filePath)); } return GetOptionsForSourcePath(cache, filePath); @@ -366,7 +362,7 @@ private static StructuredAnalyzerConfigOptions GetOptionsForSourcePath(in Analyz // We need to work out path to this document. Documents may not have a "real" file path if they're something created // as a part of a code action, but haven't been written to disk yet. - var projectFilePath = _projectState.FilePath; + var projectFilePath = projectState.FilePath; if (documentState.Name != null && projectFilePath != null) { @@ -389,15 +385,9 @@ private static StructuredAnalyzerConfigOptions GetOptionsForSourcePath(in Analyz /// are only available in-proc and the same for all Razor design-time documents. /// This type emulates these options as analyzer config options. /// - private sealed class RazorDesignTimeAnalyzerConfigOptions : StructuredAnalyzerConfigOptions + private sealed class RazorDesignTimeAnalyzerConfigOptions(SolutionServices services) : StructuredAnalyzerConfigOptions { - private readonly ILegacyGlobalOptionsWorkspaceService? _globalOptions; - - public RazorDesignTimeAnalyzerConfigOptions(SolutionServices services) - { - // not available OOP: - _globalOptions = services.GetService(); - } + private readonly ILegacyGlobalOptionsWorkspaceService? _globalOptions = services.GetService(); public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) { @@ -437,12 +427,9 @@ public override NamingStylePreferences GetNamingStylePreferences() => NamingStylePreferences.Empty; } - private sealed class ProjectSyntaxTreeOptionsProvider : SyntaxTreeOptionsProvider + private sealed class ProjectSyntaxTreeOptionsProvider(ValueSource lazyAnalyzerConfigSet) : SyntaxTreeOptionsProvider { - private readonly ValueSource _lazyAnalyzerConfigSet; - - public ProjectSyntaxTreeOptionsProvider(ValueSource lazyAnalyzerConfigSet) - => _lazyAnalyzerConfigSet = lazyAnalyzerConfigSet; + private readonly ValueSource _lazyAnalyzerConfigSet = lazyAnalyzerConfigSet; public override GeneratedKind IsGenerated(SyntaxTree tree, CancellationToken cancellationToken) { @@ -493,17 +480,11 @@ private static ValueSource ComputeAnalyzerConfigOpti }); } - private readonly struct AnalyzerConfigOptionsCache + private readonly struct AnalyzerConfigOptionsCache(AnalyzerConfigSet configSet) { private readonly ConcurrentDictionary _sourcePathToResult = new(); - private readonly Func _computeFunction; - private readonly Lazy _global; - - public AnalyzerConfigOptionsCache(AnalyzerConfigSet configSet) - { - _global = new Lazy(() => new AnalyzerConfigData(configSet.GlobalConfigOptions)); - _computeFunction = path => new AnalyzerConfigData(configSet.GetOptionsForSourcePath(path)); - } + private readonly Func _computeFunction = path => new AnalyzerConfigData(configSet.GetOptionsForSourcePath(path)); + private readonly Lazy _global = new Lazy(() => new AnalyzerConfigData(configSet.GlobalConfigOptions)); public AnalyzerConfigData GlobalConfigOptions => _global.Value; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/RecoverableTextAndVersion.cs b/src/Workspaces/Core/Portable/Workspace/Solution/RecoverableTextAndVersion.cs index 6b0c04e45ea91..b553b69887c2c 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/RecoverableTextAndVersion.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/RecoverableTextAndVersion.cs @@ -15,22 +15,10 @@ namespace Microsoft.CodeAnalysis /// /// A recoverable TextAndVersion source that saves its text to temporary storage. /// - internal sealed class RecoverableTextAndVersion : ITextAndVersionSource + internal sealed class RecoverableTextAndVersion(ITextAndVersionSource initialSource, SolutionServices services) : ITextAndVersionSource { - private readonly SolutionServices _services; - // Starts as ITextAndVersionSource and is replaced with RecoverableText when the TextAndVersion value is requested. - // At that point the initial source is no longer referenced and can be garbage collected. - private object _initialSourceOrRecoverableText; - - public bool CanReloadText { get; } - - public RecoverableTextAndVersion(ITextAndVersionSource initialSource, SolutionServices services) - { - _initialSourceOrRecoverableText = initialSource; - _services = services; - CanReloadText = initialSource.CanReloadText; - } + public bool CanReloadText { get; } = initialSource.CanReloadText; /// /// True if the is available, false if is returned. @@ -38,7 +26,7 @@ public RecoverableTextAndVersion(ITextAndVersionSource initialSource, SolutionSe private bool TryGetInitialSourceOrRecoverableText([NotNullWhen(true)] out ITextAndVersionSource? source, [NotNullWhen(false)] out RecoverableText? text) { // store to local to avoid race: - var sourceOrRecoverableText = _initialSourceOrRecoverableText; + var sourceOrRecoverableText = initialSource; source = sourceOrRecoverableText as ITextAndVersionSource; if (source != null) @@ -52,7 +40,7 @@ private bool TryGetInitialSourceOrRecoverableText([NotNullWhen(true)] out ITextA } public ITemporaryTextStorageInternal? Storage - => (_initialSourceOrRecoverableText as RecoverableText)?.Storage; + => (initialSource as RecoverableText)?.Storage; public bool TryGetValue(LoadTextOptions options, [MaybeNullWhen(false)] out TextAndVersion value) { @@ -87,7 +75,7 @@ public bool TryGetVersion(LoadTextOptions options, out VersionStamp version) private async ValueTask GetRecoverableTextAsync( bool useAsync, LoadTextOptions options, CancellationToken cancellationToken) { - if (_initialSourceOrRecoverableText is ITextAndVersionSource source) + if (initialSource is ITextAndVersionSource source) { // replace initial source with recoverable text if it hasn't been replaced already: var textAndVersion = useAsync @@ -95,25 +83,25 @@ private async ValueTask GetRecoverableTextAsync( : source.GetValue(options, cancellationToken); Interlocked.CompareExchange( - ref _initialSourceOrRecoverableText, - value: new RecoverableText(source, textAndVersion, options, _services), + ref initialSource, + value: new RecoverableText(source, textAndVersion, options, services), comparand: source); } // If we have a recoverable text but the options it was created for do not match the current options // and the initial source supports reloading, reload and replace the recoverable text. - var recoverableText = (RecoverableText)_initialSourceOrRecoverableText; + var recoverableText = (RecoverableText)initialSource; if (recoverableText.LoadTextOptions != options && recoverableText.InitialSource != null) { var textAndVersion = useAsync ? await recoverableText.InitialSource.GetValueAsync(options, cancellationToken).ConfigureAwait(false) : recoverableText.InitialSource.GetValue(options, cancellationToken); Interlocked.Exchange( - ref _initialSourceOrRecoverableText, - new RecoverableText(recoverableText.InitialSource, textAndVersion, options, _services)); + ref initialSource, + new RecoverableText(recoverableText.InitialSource, textAndVersion, options, services)); } - return (RecoverableText)_initialSourceOrRecoverableText; + return (RecoverableText)initialSource; } public TextAndVersion GetValue(LoadTextOptions options, CancellationToken cancellationToken) diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionInfo.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionInfo.cs index 4119d66a3f197..a70e6a0abd6eb 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionInfo.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionInfo.cs @@ -94,37 +94,29 @@ internal SolutionInfo WithTelemetryId(Guid telemetryId) /// type that contains information regarding this solution itself but /// no tree information such as project info /// - internal sealed class SolutionAttributes : IChecksummedObject, IObjectWritable + internal sealed class SolutionAttributes(SolutionId id, VersionStamp version, string? filePath, Guid telemetryId) : IChecksummedObject, IObjectWritable { private Checksum? _lazyChecksum; /// /// The unique Id of the solution. /// - public SolutionId Id { get; } + public SolutionId Id { get; } = id; /// /// The version of the solution. /// - public VersionStamp Version { get; } + public VersionStamp Version { get; } = version; /// /// The path to the solution file, or null if there is no solution file. /// - public string? FilePath { get; } + public string? FilePath { get; } = filePath; /// /// The id report during telemetry events. /// - public Guid TelemetryId { get; } - - public SolutionAttributes(SolutionId id, VersionStamp version, string? filePath, Guid telemetryId) - { - Id = id; - Version = version; - FilePath = filePath; - TelemetryId = telemetryId; - } + public Guid TelemetryId { get; } = telemetryId; public SolutionAttributes With( VersionStamp? version = null, diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationAndGeneratorDriverTranslationAction_Actions.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationAndGeneratorDriverTranslationAction_Actions.cs index 636d8676cdaa1..6e6e2d359417b 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationAndGeneratorDriverTranslationAction_Actions.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationAndGeneratorDriverTranslationAction_Actions.cs @@ -18,16 +18,10 @@ internal partial class SolutionState { private abstract partial class CompilationAndGeneratorDriverTranslationAction { - internal sealed class TouchDocumentAction : CompilationAndGeneratorDriverTranslationAction + internal sealed class TouchDocumentAction(DocumentState oldState, DocumentState newState) : CompilationAndGeneratorDriverTranslationAction { - private readonly DocumentState _oldState; - private readonly DocumentState _newState; - - public TouchDocumentAction(DocumentState oldState, DocumentState newState) - { - _oldState = oldState; - _newState = newState; - } + private readonly DocumentState _oldState = oldState; + private readonly DocumentState _newState = newState; public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { @@ -52,16 +46,10 @@ public override Task TransformCompilationAsync(Compilation oldCompi } } - internal sealed class TouchAdditionalDocumentAction : CompilationAndGeneratorDriverTranslationAction + internal sealed class TouchAdditionalDocumentAction(AdditionalDocumentState oldState, AdditionalDocumentState newState) : CompilationAndGeneratorDriverTranslationAction { - private readonly AdditionalDocumentState _oldState; - private readonly AdditionalDocumentState _newState; - - public TouchAdditionalDocumentAction(AdditionalDocumentState oldState, AdditionalDocumentState newState) - { - _oldState = oldState; - _newState = newState; - } + private readonly AdditionalDocumentState _oldState = oldState; + private readonly AdditionalDocumentState _newState = newState; // Changing an additional document doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping @@ -88,19 +76,12 @@ public TouchAdditionalDocumentAction(AdditionalDocumentState oldState, Additiona } } - internal sealed class RemoveDocumentsAction : CompilationAndGeneratorDriverTranslationAction + internal sealed class RemoveDocumentsAction(ImmutableArray documents) : CompilationAndGeneratorDriverTranslationAction { - private readonly ImmutableArray _documents; - - public RemoveDocumentsAction(ImmutableArray documents) - { - _documents = documents; - } - public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { - var syntaxTrees = new List(_documents.Length); - foreach (var document in _documents) + var syntaxTrees = new List(documents.Length); + foreach (var document in documents) { cancellationToken.ThrowIfCancellationRequested(); syntaxTrees.Add(await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); @@ -113,19 +94,12 @@ public override async Task TransformCompilationAsync(Compilation ol public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; } - internal sealed class AddDocumentsAction : CompilationAndGeneratorDriverTranslationAction + internal sealed class AddDocumentsAction(ImmutableArray documents) : CompilationAndGeneratorDriverTranslationAction { - private readonly ImmutableArray _documents; - - public AddDocumentsAction(ImmutableArray documents) - { - _documents = documents; - } - public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { - var syntaxTrees = new List(capacity: _documents.Length); - foreach (var document in _documents) + var syntaxTrees = new List(capacity: documents.Length); + foreach (var document in documents) { cancellationToken.ThrowIfCancellationRequested(); syntaxTrees.Add(await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); @@ -138,22 +112,13 @@ public override async Task TransformCompilationAsync(Compilation ol public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; } - internal sealed class ReplaceAllSyntaxTreesAction : CompilationAndGeneratorDriverTranslationAction + internal sealed class ReplaceAllSyntaxTreesAction(ProjectState state, bool isParseOptionChange) : CompilationAndGeneratorDriverTranslationAction { - private readonly ProjectState _state; - private readonly bool _isParseOptionChange; - - public ReplaceAllSyntaxTreesAction(ProjectState state, bool isParseOptionChange) - { - _state = state; - _isParseOptionChange = isParseOptionChange; - } - public override async Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { - var syntaxTrees = new List(capacity: _state.DocumentStates.Count); + var syntaxTrees = new List(capacity: state.DocumentStates.Count); - foreach (var documentState in _state.DocumentStates.GetStatesInCompilationOrder()) + foreach (var documentState in state.DocumentStates.GetStatesInCompilationOrder()) { cancellationToken.ThrowIfCancellationRequested(); syntaxTrees.Add(await documentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); @@ -167,10 +132,10 @@ public override async Task TransformCompilationAsync(Compilation ol public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { - if (_isParseOptionChange) + if (isParseOptionChange) { - RoslynDebug.AssertNotNull(_state.ParseOptions); - return generatorDriver.WithUpdatedParseOptions(_state.ParseOptions); + RoslynDebug.AssertNotNull(state.ParseOptions); + return generatorDriver.WithUpdatedParseOptions(state.ParseOptions); } else { @@ -181,21 +146,12 @@ public override async Task TransformCompilationAsync(Compilation ol } } - internal sealed class ProjectCompilationOptionsAction : CompilationAndGeneratorDriverTranslationAction + internal sealed class ProjectCompilationOptionsAction(ProjectState state, bool isAnalyzerConfigChange) : CompilationAndGeneratorDriverTranslationAction { - private readonly ProjectState _state; - private readonly bool _isAnalyzerConfigChange; - - public ProjectCompilationOptionsAction(ProjectState state, bool isAnalyzerConfigChange) - { - _state = state; - _isAnalyzerConfigChange = isAnalyzerConfigChange; - } - public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { - RoslynDebug.AssertNotNull(_state.CompilationOptions); - return Task.FromResult(oldCompilation.WithOptions(_state.CompilationOptions)); + RoslynDebug.AssertNotNull(state.CompilationOptions); + return Task.FromResult(oldCompilation.WithOptions(state.CompilationOptions)); } // Updating the options of a compilation doesn't require us to reparse trees, so we can use this to update @@ -204,9 +160,9 @@ public override Task TransformCompilationAsync(Compilation oldCompi public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { - if (_isAnalyzerConfigChange) + if (isAnalyzerConfigChange) { - return generatorDriver.WithUpdatedAnalyzerConfigOptions(_state.AnalyzerOptions.AnalyzerConfigOptionsProvider); + return generatorDriver.WithUpdatedAnalyzerConfigOptions(state.AnalyzerOptions.AnalyzerConfigOptionsProvider); } else { @@ -217,18 +173,11 @@ public override Task TransformCompilationAsync(Compilation oldCompi } } - internal sealed class ProjectAssemblyNameAction : CompilationAndGeneratorDriverTranslationAction + internal sealed class ProjectAssemblyNameAction(string assemblyName) : CompilationAndGeneratorDriverTranslationAction { - private readonly string _assemblyName; - - public ProjectAssemblyNameAction(string assemblyName) - { - _assemblyName = assemblyName; - } - public override Task TransformCompilationAsync(Compilation oldCompilation, CancellationToken cancellationToken) { - return Task.FromResult(oldCompilation.WithAssemblyName(_assemblyName)); + return Task.FromResult(oldCompilation.WithAssemblyName(assemblyName)); } // Updating the options of a compilation doesn't require us to reparse trees, so we can use this to update @@ -236,18 +185,8 @@ public override Task TransformCompilationAsync(Compilation oldCompi public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; } - internal sealed class AddOrRemoveAnalyzerReferencesAction : CompilationAndGeneratorDriverTranslationAction + internal sealed class AddOrRemoveAnalyzerReferencesAction(string language, ImmutableArray referencesToAdd = default, ImmutableArray referencesToRemove = default) : CompilationAndGeneratorDriverTranslationAction { - private readonly string _language; - private readonly ImmutableArray _referencesToAdd; - private readonly ImmutableArray _referencesToRemove; - - public AddOrRemoveAnalyzerReferencesAction(string language, ImmutableArray referencesToAdd = default, ImmutableArray referencesToRemove = default) - { - _language = language; - _referencesToAdd = referencesToAdd; - _referencesToRemove = referencesToRemove; - } // Changing analyzer references doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping @@ -256,28 +195,22 @@ public AddOrRemoveAnalyzerReferencesAction(string language, ImmutableArray r.GetGenerators(_language)).ToImmutableArray()); + generatorDriver = generatorDriver.RemoveGenerators(referencesToRemove.SelectMany(r => r.GetGenerators(language)).ToImmutableArray()); } - if (!_referencesToAdd.IsDefaultOrEmpty) + if (!referencesToAdd.IsDefaultOrEmpty) { - generatorDriver = generatorDriver.AddGenerators(_referencesToAdd.SelectMany(r => r.GetGenerators(_language)).ToImmutableArray()); + generatorDriver = generatorDriver.AddGenerators(referencesToAdd.SelectMany(r => r.GetGenerators(language)).ToImmutableArray()); } return generatorDriver; } } - internal sealed class AddAdditionalDocumentsAction : CompilationAndGeneratorDriverTranslationAction + internal sealed class AddAdditionalDocumentsAction(ImmutableArray additionalDocuments) : CompilationAndGeneratorDriverTranslationAction { - private readonly ImmutableArray _additionalDocuments; - - public AddAdditionalDocumentsAction(ImmutableArray additionalDocuments) - { - _additionalDocuments = additionalDocuments; - } // Changing an additional document doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping @@ -286,18 +219,12 @@ public AddAdditionalDocumentsAction(ImmutableArray addi public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { - return generatorDriver.AddAdditionalTexts(_additionalDocuments.SelectAsArray(static documentState => documentState.AdditionalText)); + return generatorDriver.AddAdditionalTexts(additionalDocuments.SelectAsArray(static documentState => documentState.AdditionalText)); } } - internal sealed class RemoveAdditionalDocumentsAction : CompilationAndGeneratorDriverTranslationAction + internal sealed class RemoveAdditionalDocumentsAction(ImmutableArray additionalDocuments) : CompilationAndGeneratorDriverTranslationAction { - private readonly ImmutableArray _additionalDocuments; - - public RemoveAdditionalDocumentsAction(ImmutableArray additionalDocuments) - { - _additionalDocuments = additionalDocuments; - } // Changing an additional document doesn't change the compilation directly, so we can "apply" the // translation (which is a no-op). Since we use a 'false' here to mean that it's not worth keeping @@ -306,31 +233,22 @@ public RemoveAdditionalDocumentsAction(ImmutableArray a public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver generatorDriver) { - return generatorDriver.RemoveAdditionalTexts(_additionalDocuments.SelectAsArray(static documentState => documentState.AdditionalText)); + return generatorDriver.RemoveAdditionalTexts(additionalDocuments.SelectAsArray(static documentState => documentState.AdditionalText)); } } - internal sealed class ReplaceGeneratorDriverAction : CompilationAndGeneratorDriverTranslationAction + internal sealed class ReplaceGeneratorDriverAction(GeneratorDriver oldGeneratorDriver, ProjectState newProjectState) : CompilationAndGeneratorDriverTranslationAction { - private readonly GeneratorDriver _oldGeneratorDriver; - private readonly ProjectState _newProjectState; - - public ReplaceGeneratorDriverAction(GeneratorDriver oldGeneratorDriver, ProjectState newProjectState) - { - _oldGeneratorDriver = oldGeneratorDriver; - _newProjectState = newProjectState; - } - public override bool CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput => true; public override GeneratorDriver? TransformGeneratorDriver(GeneratorDriver _) { // The GeneratorDriver that we have here is from a prior version of the Project, it may be missing state changes due // to changes to the project. We'll update everything here. - var generatorDriver = _oldGeneratorDriver.ReplaceAdditionalTexts(_newProjectState.AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText)) - .WithUpdatedParseOptions(_newProjectState.ParseOptions!) - .WithUpdatedAnalyzerConfigOptions(_newProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider) - .ReplaceGenerators(_newProjectState.SourceGenerators.ToImmutableArray()); + var generatorDriver = oldGeneratorDriver.ReplaceAdditionalTexts(newProjectState.AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText)) + .WithUpdatedParseOptions(newProjectState.ParseOptions!) + .WithUpdatedAnalyzerConfigOptions(newProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider) + .ReplaceGenerators(newProjectState.SourceGenerators.ToImmutableArray()); return generatorDriver; } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.CompilationTrackerState.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.CompilationTrackerState.cs index 933e96fa4a16c..a868673465012 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.CompilationTrackerState.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.CompilationTrackerState.cs @@ -171,12 +171,8 @@ public static CompilationTrackerState Create( /// State used when we potentially have some information (like prior generated documents) /// but no compilation. /// - private sealed class NoCompilationState : CompilationTrackerState + private sealed class NoCompilationState(CompilationTrackerGeneratorInfo generatorInfo) : CompilationTrackerState(compilationWithoutGeneratedDocuments: null, generatorInfo) { - public NoCompilationState(CompilationTrackerGeneratorInfo generatorInfo) - : base(compilationWithoutGeneratedDocuments: null, generatorInfo) - { - } } /// @@ -219,12 +215,8 @@ public InProgressState( /// A built compilation for the tracker that contains the fully built DeclarationTable, /// but may not have references initialized /// - private sealed class AllSyntaxTreesParsedState : CompilationTrackerState + private sealed class AllSyntaxTreesParsedState(Compilation declarationCompilation, CompilationTrackerGeneratorInfo generatorInfo) : CompilationTrackerState(declarationCompilation, generatorInfo) { - public AllSyntaxTreesParsedState(Compilation declarationCompilation, CompilationTrackerGeneratorInfo generatorInfo) - : base(declarationCompilation, generatorInfo) - { - } } /// diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.cs index 271fc07a31363..66ba400688187 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.cs @@ -670,18 +670,11 @@ private async Task BuildFinalStateFromInProgressStateAsync( } } - private readonly struct CompilationInfo + private readonly struct CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, CompilationTrackerGeneratorInfo generatorInfo) { - public Compilation Compilation { get; } - public bool HasSuccessfullyLoaded { get; } - public CompilationTrackerGeneratorInfo GeneratorInfo { get; } - - public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, CompilationTrackerGeneratorInfo generatorInfo) - { - Compilation = compilation; - HasSuccessfullyLoaded = hasSuccessfullyLoaded; - GeneratorInfo = generatorInfo; - } + public Compilation Compilation { get; } = compilation; + public bool HasSuccessfullyLoaded { get; } = hasSuccessfullyLoaded; + public CompilationTrackerGeneratorInfo GeneratorInfo { get; } = generatorInfo; } /// diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.GeneratedFileReplacingCompilationTracker.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.GeneratedFileReplacingCompilationTracker.cs index 7bd4c264c810f..f61dddd18e496 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.GeneratedFileReplacingCompilationTracker.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.GeneratedFileReplacingCompilationTracker.cs @@ -19,10 +19,8 @@ internal partial class SolutionState /// to return a generated document with a specific content, regardless of what the generator actually produces. In other words, it says /// "take the compilation this other thing produced, and pretend the generator gave this content, even if it wouldn't." /// - private class GeneratedFileReplacingCompilationTracker : ICompilationTracker + private class GeneratedFileReplacingCompilationTracker(ICompilationTracker underlyingTracker, SourceGeneratedDocumentState replacementDocumentState) : ICompilationTracker { - private readonly SourceGeneratedDocumentState _replacedGeneratedDocumentState; - private AsyncLazy? _lazyDependentChecksum; /// @@ -32,17 +30,10 @@ private class GeneratedFileReplacingCompilationTracker : ICompilationTracker [DisallowNull] private Compilation? _compilationWithReplacement; - public ICompilationTracker UnderlyingTracker { get; } - public SkeletonReferenceCache SkeletonReferenceCache { get; } + public ICompilationTracker UnderlyingTracker { get; } = underlyingTracker; + public SkeletonReferenceCache SkeletonReferenceCache { get; } = underlyingTracker.SkeletonReferenceCache.Clone(); public ProjectState ProjectState => UnderlyingTracker.ProjectState; - public GeneratedFileReplacingCompilationTracker(ICompilationTracker underlyingTracker, SourceGeneratedDocumentState replacementDocumentState) - { - UnderlyingTracker = underlyingTracker; - _replacedGeneratedDocumentState = replacementDocumentState; - SkeletonReferenceCache = underlyingTracker.SkeletonReferenceCache.Clone(); - } - public GeneratorDriver? GeneratorDriver => UnderlyingTracker.GeneratorDriver; public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) @@ -83,11 +74,11 @@ public async Task GetCompilationAsync(SolutionState solution, Cance var underlyingCompilation = await UnderlyingTracker.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); var underlyingSourceGeneratedDocuments = await UnderlyingTracker.GetSourceGeneratedDocumentStatesAsync(solution, cancellationToken).ConfigureAwait(false); - underlyingSourceGeneratedDocuments.TryGetState(_replacedGeneratedDocumentState.Id, out var existingState); + underlyingSourceGeneratedDocuments.TryGetState(replacementDocumentState.Id, out var existingState); Compilation newCompilation; - var newSyntaxTree = await _replacedGeneratedDocumentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); + var newSyntaxTree = await replacementDocumentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (existingState != null) { @@ -131,7 +122,7 @@ public Task GetDependentChecksumAsync(SolutionState solution, Cancella private async Task ComputeDependentChecksumAsync(SolutionState solution, CancellationToken cancellationToken) => Checksum.Create( await UnderlyingTracker.GetDependentChecksumAsync(solution, cancellationToken).ConfigureAwait(false), - await _replacedGeneratedDocumentState.GetChecksumAsync(cancellationToken).ConfigureAwait(false)); + await replacementDocumentState.GetChecksumAsync(cancellationToken).ConfigureAwait(false)); public MetadataReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference) { @@ -149,11 +140,11 @@ public async ValueTask> GetSour { var underlyingGeneratedDocumentStates = await UnderlyingTracker.GetSourceGeneratedDocumentStatesAsync(solution, cancellationToken).ConfigureAwait(false); - if (underlyingGeneratedDocumentStates.Contains(_replacedGeneratedDocumentState.Id)) + if (underlyingGeneratedDocumentStates.Contains(replacementDocumentState.Id)) { // The generated file still exists in the underlying compilation, but the contents may not match the open file if the open file // is stale. Replace the syntax tree so we have a tree that matches the text. - return underlyingGeneratedDocumentStates.SetState(_replacedGeneratedDocumentState.Id, _replacedGeneratedDocumentState); + return underlyingGeneratedDocumentStates.SetState(replacementDocumentState.Id, replacementDocumentState); } else { @@ -161,7 +152,7 @@ public async ValueTask> GetSour // an edit which would cause this file to no longer exist, but they're still operating on an open representation // of that file. To ensure that this snapshot is still usable, we'll just add this document back in. This is not a // semantically correct operation, but working on stale snapshots never has that guarantee. - return underlyingGeneratedDocumentStates.AddRange(ImmutableArray.Create(_replacedGeneratedDocumentState)); + return underlyingGeneratedDocumentStates.AddRange(ImmutableArray.Create(replacementDocumentState)); } } @@ -178,9 +169,9 @@ public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { - if (documentId == _replacedGeneratedDocumentState.Id) + if (documentId == replacementDocumentState.Id) { - return _replacedGeneratedDocumentState; + return replacementDocumentState; } else { diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.SkeletonReferenceSet.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.SkeletonReferenceSet.cs index f54584e3a3341..87b1baf85b295 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.SkeletonReferenceSet.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.SkeletonReferenceSet.cs @@ -12,21 +12,19 @@ namespace Microsoft.CodeAnalysis; internal partial class SolutionState { - private sealed class SkeletonReferenceSet + /// + /// The actual assembly metadata produced from another compilation. + /// + /// + /// The documentation provider used to lookup xml docs for any metadata reference we pass out. See + /// docs on for why this is safe to hold onto despite it + /// rooting a compilation internally. + /// + private sealed class SkeletonReferenceSet( + AssemblyMetadata metadata, + string? assemblyName, + DeferredDocumentationProvider documentationProvider) { - /// - /// The actual assembly metadata produced from another compilation. - /// - private readonly AssemblyMetadata _metadata; - - private readonly string? _assemblyName; - - /// - /// The documentation provider used to lookup xml docs for any metadata reference we pass out. See - /// docs on for why this is safe to hold onto despite it - /// rooting a compilation internally. - /// - private readonly DeferredDocumentationProvider _documentationProvider; /// /// Lock this object while reading/writing from it. Used so we can return the same reference for the same @@ -36,27 +34,17 @@ private sealed class SkeletonReferenceSet /// private readonly Dictionary _referenceMap = new(); - public SkeletonReferenceSet( - AssemblyMetadata metadata, - string? assemblyName, - DeferredDocumentationProvider documentationProvider) - { - _metadata = metadata; - _assemblyName = assemblyName; - _documentationProvider = documentationProvider; - } - public PortableExecutableReference GetOrCreateMetadataReference(MetadataReferenceProperties properties) { lock (_referenceMap) { if (!_referenceMap.TryGetValue(properties, out var value)) { - value = _metadata.GetReference( - _documentationProvider, + value = metadata.GetReference( + documentationProvider, aliases: properties.Aliases, embedInteropTypes: properties.EmbedInteropTypes, - display: _assemblyName); + display: assemblyName); _referenceMap.Add(properties, value); } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs index 8fa7462502662..521d27cefea23 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs @@ -2059,18 +2059,11 @@ internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toP internal TestAccessor GetTestAccessor() => new TestAccessor(this); - internal readonly struct TestAccessor + internal readonly struct TestAccessor(SolutionState solutionState) { - private readonly SolutionState _solutionState; - - public TestAccessor(SolutionState solutionState) - { - _solutionState = solutionState; - } - public GeneratorDriver? GetGeneratorDriver(Project project) { - return project.SupportsCompilation ? _solutionState.GetCompilationTracker(project.Id).GeneratorDriver : null; + return project.SupportsCompilation ? solutionState.GetCompilationTracker(project.Id).GeneratorDriver : null; } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/StateChecksums.cs b/src/Workspaces/Core/Portable/Workspace/Solution/StateChecksums.cs index 3105296413193..ca676f26d73c8 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/StateChecksums.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/StateChecksums.cs @@ -13,7 +13,7 @@ namespace Microsoft.CodeAnalysis.Serialization { - internal sealed class SolutionStateChecksums : ChecksumWithChildren + internal sealed class SolutionStateChecksums(ImmutableArray children) : ChecksumWithChildren(children) { public SolutionStateChecksums( Checksum attributesChecksum, @@ -25,10 +25,6 @@ public SolutionStateChecksums( { } - public SolutionStateChecksums(ImmutableArray children) : base(children) - { - } - public Checksum Attributes => (Checksum)Children[0]; public ChecksumCollection Projects => (ChecksumCollection)Children[1]; public ChecksumCollection AnalyzerReferences => (ChecksumCollection)Children[2]; @@ -89,7 +85,7 @@ public async Task FindAsync( } } - internal class ProjectStateChecksums : ChecksumWithChildren + internal class ProjectStateChecksums(ImmutableArray children) : ChecksumWithChildren(children) { public ProjectStateChecksums( Checksum infoChecksum, @@ -114,10 +110,6 @@ public ProjectStateChecksums( { } - public ProjectStateChecksums(ImmutableArray children) : base(children) - { - } - public Checksum Info => (Checksum)Children[0]; public Checksum CompilationOptions => (Checksum)Children[1]; public Checksum ParseOptions => (Checksum)Children[2]; @@ -207,17 +199,13 @@ public async Task FindAsync( } } - internal class DocumentStateChecksums : ChecksumWithChildren + internal class DocumentStateChecksums(ImmutableArray children) : ChecksumWithChildren(children) { public DocumentStateChecksums(Checksum infoChecksum, Checksum textChecksum) : this(ImmutableArray.Create(infoChecksum, textChecksum)) { } - public DocumentStateChecksums(ImmutableArray children) : base(children) - { - } - public Checksum Info => (Checksum)Children[0]; public Checksum Text => (Checksum)Children[1]; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/TreeAndVersion.cs b/src/Workspaces/Core/Portable/Workspace/Solution/TreeAndVersion.cs index fc6b7e6928be0..9b50046ccd383 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/TreeAndVersion.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/TreeAndVersion.cs @@ -10,22 +10,16 @@ namespace Microsoft.CodeAnalysis /// /// A class that represents both a tree and its top level signature version /// - internal sealed class TreeAndVersion + internal sealed class TreeAndVersion(SyntaxTree tree, VersionStamp version) { /// /// The syntax tree /// - public SyntaxTree Tree { get; } + public SyntaxTree Tree { get; } = tree; /// /// The version of the top level signature of the tree /// - public VersionStamp Version { get; } - - public TreeAndVersion(SyntaxTree tree, VersionStamp version) - { - Tree = tree; - Version = version; - } + public VersionStamp Version { get; } = version; } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/VersionStamp.cs b/src/Workspaces/Core/Portable/Workspace/Solution/VersionStamp.cs index b69c7a9afaa2a..c14b21c0264ff 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/VersionStamp.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/VersionStamp.cs @@ -232,26 +232,22 @@ private static int GetNextGlobalVersion() internal TestAccessor GetTestAccessor() => new(this); - internal readonly struct TestAccessor + internal readonly struct TestAccessor(in VersionStamp versionStamp) { - private readonly VersionStamp _versionStamp; - - public TestAccessor(in VersionStamp versionStamp) - => _versionStamp = versionStamp; /// /// True if this VersionStamp is newer than the specified one. /// internal bool IsNewerThan(in VersionStamp version) { - if (_versionStamp._utcLastModified > version._utcLastModified) + if (versionStamp._utcLastModified > version._utcLastModified) { return true; } - if (_versionStamp._utcLastModified == version._utcLastModified) + if (versionStamp._utcLastModified == version._utcLastModified) { - return GetGlobalVersion(_versionStamp) > GetGlobalVersion(version); + return GetGlobalVersion(versionStamp) > GetGlobalVersion(version); } return false; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/WeaklyCachedRecoverableValueSource.cs b/src/Workspaces/Core/Portable/Workspace/Solution/WeaklyCachedRecoverableValueSource.cs index 3b1e6a543ba56..5028820a2abae 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/WeaklyCachedRecoverableValueSource.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/WeaklyCachedRecoverableValueSource.cs @@ -17,7 +17,11 @@ namespace Microsoft.CodeAnalysis.Host /// or is called. At that point, it will be dumped to secondary storage, and retrieved /// and weakly held from that point on in the future. /// - internal abstract class WeaklyCachedRecoverableValueSource : ValueSource where T : class + /// + /// Initial strong value that this value source is initialized with. Will be used to respond to the first + /// request to get the value, at which point it will be dumped into secondary storage. + /// + internal abstract class WeaklyCachedRecoverableValueSource(T initialValue) : ValueSource where T : class { // enforce saving in a queue so save's don't overload the thread pool. private static Task s_latestTask = Task.CompletedTask; @@ -33,21 +37,12 @@ internal abstract class WeaklyCachedRecoverableValueSource : ValueSource w /// private bool _saved; - /// - /// Initial strong value that this value source is initialized with. Will be used to respond to the first - /// request to get the value, at which point it will be dumped into secondary storage. - /// - private T? _initialValue; - /// /// Weak reference to the value last returned from this value source. Will thus return the same value as long /// as something external is holding onto it. /// private WeakReference? _weakReference; - public WeaklyCachedRecoverableValueSource(T initialValue) - => _initialValue = initialValue; - /// /// Override this to save the state of the instance so it can be recovered. /// This method will only ever be called once. @@ -85,7 +80,7 @@ private bool TryGetWeakValue([NotNullWhen(true)] out T? value) private bool TryGetStrongOrWeakValue([NotNullWhen(true)] out T? value) { // See if we still have the constant value stored. If so, we can trivially return that. - value = _initialValue; + value = initialValue; if (value != null) return true; @@ -166,7 +161,7 @@ private void UpdateWeakReferenceAndEnqueueSaveTask_NoLock(T instance) // we want to keep it around to service future requests. Once we do clear out this value, then all // future request will either retrieve the value from the weak reference (if anyone else is holding onto // it), or will recover from underlying storage. - _initialValue = null; + initialValue = null; }, CancellationToken.None, // Ensure we run continuations asynchronously so that we don't start running the continuation while diff --git a/src/Workspaces/Core/Portable/Workspace/TextDocumentEventArgs.cs b/src/Workspaces/Core/Portable/Workspace/TextDocumentEventArgs.cs index 9ed3305bcbf14..9c382c57019f3 100644 --- a/src/Workspaces/Core/Portable/Workspace/TextDocumentEventArgs.cs +++ b/src/Workspaces/Core/Portable/Workspace/TextDocumentEventArgs.cs @@ -7,13 +7,8 @@ namespace Microsoft.CodeAnalysis { - public sealed class TextDocumentEventArgs : EventArgs + public sealed class TextDocumentEventArgs(TextDocument document) : EventArgs { - public TextDocument Document { get; } - - public TextDocumentEventArgs(TextDocument document) - { - this.Document = document ?? throw new ArgumentNullException(nameof(document)); - } + public TextDocument Document { get; } = document ?? throw new ArgumentNullException(nameof(document)); } } diff --git a/src/Workspaces/Core/Portable/Workspace/WorkspaceDiagnostic.cs b/src/Workspaces/Core/Portable/Workspace/WorkspaceDiagnostic.cs index 8e5acbcbf8cb6..abd3b4e0289b2 100644 --- a/src/Workspaces/Core/Portable/Workspace/WorkspaceDiagnostic.cs +++ b/src/Workspaces/Core/Portable/Workspace/WorkspaceDiagnostic.cs @@ -8,16 +8,10 @@ namespace Microsoft.CodeAnalysis { - public class WorkspaceDiagnostic + public class WorkspaceDiagnostic(WorkspaceDiagnosticKind kind, string message) { - public WorkspaceDiagnosticKind Kind { get; } - public string Message { get; } - - public WorkspaceDiagnostic(WorkspaceDiagnosticKind kind, string message) - { - this.Kind = kind; - this.Message = message; - } + public WorkspaceDiagnosticKind Kind { get; } = kind; + public string Message { get; } = message; public override string ToString() { diff --git a/src/Workspaces/Core/Portable/Workspace/WorkspaceDiagnosticEventArgs.cs b/src/Workspaces/Core/Portable/Workspace/WorkspaceDiagnosticEventArgs.cs index 8ba3626eddfbe..2303b7cde9223 100644 --- a/src/Workspaces/Core/Portable/Workspace/WorkspaceDiagnosticEventArgs.cs +++ b/src/Workspaces/Core/Portable/Workspace/WorkspaceDiagnosticEventArgs.cs @@ -8,11 +8,8 @@ namespace Microsoft.CodeAnalysis { - public class WorkspaceDiagnosticEventArgs : EventArgs + public class WorkspaceDiagnosticEventArgs(WorkspaceDiagnostic diagnostic) : EventArgs { - public WorkspaceDiagnostic Diagnostic { get; } - - public WorkspaceDiagnosticEventArgs(WorkspaceDiagnostic diagnostic) - => this.Diagnostic = diagnostic; + public WorkspaceDiagnostic Diagnostic { get; } = diagnostic; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeGeneration/CodeGenerationOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeGeneration/CodeGenerationOptions.cs index 4e5151fad0a49..39332a9f6ceee 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeGeneration/CodeGenerationOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeGeneration/CodeGenerationOptions.cs @@ -65,24 +65,19 @@ internal static CodeAndImportGenerationOptions GetDefault(LanguageServices langu internal CodeAndImportGenerationOptionsProvider CreateProvider() => new Provider(this); - private sealed class Provider : CodeAndImportGenerationOptionsProvider + private sealed class Provider(CodeAndImportGenerationOptions options) : CodeAndImportGenerationOptionsProvider { - private readonly CodeAndImportGenerationOptions _options; - - public Provider(CodeAndImportGenerationOptions options) - => _options = options; - ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options); + => ValueTaskFactory.FromResult(options); ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options.GenerationOptions); + => ValueTaskFactory.FromResult(options.GenerationOptions); ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options.GenerationOptions.NamingStyle); + => ValueTaskFactory.FromResult(options.GenerationOptions.NamingStyle); ValueTask OptionsProvider.GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken) - => ValueTaskFactory.FromResult(_options.AddImportOptions); + => ValueTaskFactory.FromResult(options.AddImportOptions); } #endif } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs index 7b2ec42c9ce3d..91818de8f2687 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs @@ -75,7 +75,7 @@ public static CodeStyleOption2 GetCodeStyle(bool value, NotificationOption /// then those values will write back as false/true. /// [DataContract] - internal sealed partial class CodeStyleOption2 : ICodeStyleOption2, IEquatable?> + internal sealed partial class CodeStyleOption2(T value, NotificationOption2 notification) : ICodeStyleOption2, IEquatable?> { public static readonly CodeStyleOption2 Default = new(default!, NotificationOption2.Silent); @@ -88,16 +88,10 @@ internal sealed partial class CodeStyleOption2 : ICodeStyleOption2, IEquatabl private const string XmlAttribute_DiagnosticSeverity = "DiagnosticSeverity"; [DataMember(Order = 0)] - public T Value { get; } + public T Value { get; } = value; [DataMember(Order = 1)] - public NotificationOption2 Notification { get; } - - public CodeStyleOption2(T value, NotificationOption2 notification) - { - Value = value; - Notification = notification; - } + public NotificationOption2 Notification { get; } = notification; object? ICodeStyleOption.Value => this.Value; ICodeStyleOption ICodeStyleOption.WithValue(object value) => WithValue((T)value); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EditorConfig/Parsing/Sections/SectionMatcher.Lexer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EditorConfig/Parsing/Sections/SectionMatcher.Lexer.cs index 32f53af3097bb..c6d2cbfa302e0 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EditorConfig/Parsing/Sections/SectionMatcher.Lexer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EditorConfig/Parsing/Sections/SectionMatcher.Lexer.cs @@ -8,29 +8,22 @@ namespace Microsoft.CodeAnalysis.EditorConfig.Parsing { internal readonly partial struct SectionMatcher { - private struct Lexer + private struct Lexer(string headerText) { - private readonly string _headerText; - public int Position { get; set; } + public int Position { get; set; } = 0; - public Lexer(string headerText) - { - _headerText = headerText; - Position = 0; - } - - public readonly bool IsDone => Position >= _headerText.Length; + public readonly bool IsDone => Position >= headerText.Length; public TokenKind Lex() { - var tokenKind = GetTokenKindAtPosition(_headerText, Position); + var tokenKind = GetTokenKindAtPosition(headerText, Position); switch (tokenKind) { case TokenKind.StarStar: Position += 2; break; case TokenKind.SimpleCharacter: - if (_headerText[Position] == '\\') + if (headerText[Position] == '\\') { // Backslash escapes the next character Position++; @@ -58,9 +51,9 @@ public readonly bool TryPeekNext(out TokenKind kind) { var position = Position; position++; - if (position < _headerText.Length) + if (position < headerText.Length) { - kind = GetTokenKindAtPosition(_headerText, position); + kind = GetTokenKindAtPosition(headerText, position); return true; } @@ -74,7 +67,7 @@ public readonly bool TryPeekPrevious(out TokenKind kind) position--; if (position >= 0) { - kind = GetTokenKindAtPosition(_headerText, position); + kind = GetTokenKindAtPosition(headerText, position); return true; } @@ -128,9 +121,9 @@ private static TokenKind GetTokenKindAtPosition(string headerText, int position) } } - public readonly char CurrentCharacter => _headerText[Position]; + public readonly char CurrentCharacter => headerText[Position]; - public char EatCurrentCharacter() => _headerText[Position++]; + public char EatCurrentCharacter() => headerText[Position++]; public bool TryEatCurrentCharacter(out char nextChar) { @@ -146,7 +139,7 @@ public bool TryEatCurrentCharacter(out char nextChar) } } - public readonly char this[int position] => _headerText[position]; + public readonly char this[int position] => headerText[position]; public string? TryLexNumber() { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/Common/EmbeddedSeparatedSyntaxNodeList.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/Common/EmbeddedSeparatedSyntaxNodeList.cs index 4cd837cabae59..9981de119896b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/Common/EmbeddedSeparatedSyntaxNodeList.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/Common/EmbeddedSeparatedSyntaxNodeList.cs @@ -76,30 +76,22 @@ public TDerivedNode this[int index] public Enumerator GetEnumerator() => new(this); - public struct Enumerator + public struct Enumerator(EmbeddedSeparatedSyntaxNodeList list) { - private readonly EmbeddedSeparatedSyntaxNodeList _list; - private int _currentIndex; + private int _currentIndex = -1; - public Enumerator(EmbeddedSeparatedSyntaxNodeList list) - { - _list = list; - _currentIndex = -1; - Current = null!; - } - - public TDerivedNode Current { get; private set; } + public TDerivedNode Current { get; private set; } = null!; public bool MoveNext() { _currentIndex++; - if (_currentIndex >= _list.Length) + if (_currentIndex >= list.Length) { Current = null!; return false; } - Current = _list[_currentIndex]; + Current = list[_currentIndex]; return true; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Chunks.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Chunks.cs index 0db80681639a7..5382f40499196 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Chunks.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Chunks.cs @@ -34,25 +34,20 @@ protected Chunk() /// This will be the common construct we generate when getting the /// for a string token that has escapes in it. /// - private class ImmutableSegmentedListChunk : Chunk + private class ImmutableSegmentedListChunk(ImmutableSegmentedList array) : Chunk { - private readonly ImmutableSegmentedList _array; - - public ImmutableSegmentedListChunk(ImmutableSegmentedList array) - => _array = array; - - public override int Length => _array.Count; - public override VirtualChar this[int index] => _array[index]; + public override int Length => array.Count; + public override VirtualChar this[int index] => array[index]; public override VirtualChar? Find(int position) { - if (_array.IsEmpty) + if (array.IsEmpty) return null; - if (position < _array[0].Span.Start || position >= _array[^1].Span.End) + if (position < array[0].Span.Start || position >= array[^1].Span.End) return null; - var index = _array.BinarySearch(position, static (ch, position) => + var index = array.BinarySearch(position, static (ch, position) => { if (position < ch.Span.Start) return 1; @@ -68,7 +63,7 @@ public ImmutableSegmentedListChunk(ImmutableSegmentedList array) if (index < 0) return null; - return _array[index]; + return array[index]; } } @@ -77,30 +72,20 @@ public ImmutableSegmentedListChunk(ImmutableSegmentedList array) /// string. This is the common case of the type of the sequence we would /// create for a normal string token without any escapes in it. /// - private class StringChunk : Chunk + /// + /// The underlying string that we're returning virtual chars from. Note: + /// this will commonly include things like quote characters. Clients who + /// do not want that should then ask for an appropriate + /// back that does not include those characters. + /// + private class StringChunk(int firstVirtualCharPosition, string data) : Chunk { - private readonly int _firstVirtualCharPosition; - - /// - /// The underlying string that we're returning virtual chars from. Note: - /// this will commonly include things like quote characters. Clients who - /// do not want that should then ask for an appropriate - /// back that does not include those characters. - /// - private readonly string _underlyingData; - - public StringChunk(int firstVirtualCharPosition, string data) - { - _firstVirtualCharPosition = firstVirtualCharPosition; - _underlyingData = data; - } - - public override int Length => _underlyingData.Length; + public override int Length => data.Length; public override VirtualChar? Find(int position) { - var stringIndex = position - _firstVirtualCharPosition; - if (stringIndex < 0 || stringIndex >= _underlyingData.Length) + var stringIndex = position - firstVirtualCharPosition; + if (stringIndex < 0 || stringIndex >= data.Length) return null; return this[stringIndex]; @@ -113,15 +98,15 @@ public override VirtualChar this[int index] #if DEBUG // We should never have a properly paired high/low surrogate in a StringChunk. We are only created // when the string has the same number of chars as there are VirtualChars. - if (char.IsHighSurrogate(_underlyingData[index])) + if (char.IsHighSurrogate(data[index])) { - Debug.Assert(index + 1 >= _underlyingData.Length || - !char.IsLowSurrogate(_underlyingData[index + 1])); + Debug.Assert(index + 1 >= data.Length || + !char.IsLowSurrogate(data[index + 1])); } #endif - var span = new TextSpan(_firstVirtualCharPosition + index, length: 1); - var ch = _underlyingData[index]; + var span = new TextSpan(firstVirtualCharPosition + index, length: 1); + var ch = data[index]; return char.IsSurrogate(ch) ? VirtualChar.Create(ch, span) : VirtualChar.Create(new Rune(ch), span); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Enumerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Enumerator.cs index 512cb7012c4c1..22b01647fe044 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Enumerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Enumerator.cs @@ -10,19 +10,12 @@ namespace Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars { internal partial struct VirtualCharSequence { - public struct Enumerator : IEnumerator + public struct Enumerator(VirtualCharSequence virtualCharSequence) : IEnumerator { - private readonly VirtualCharSequence _virtualCharSequence; - private int _position; + private int _position = -1; - public Enumerator(VirtualCharSequence virtualCharSequence) - { - _virtualCharSequence = virtualCharSequence; - _position = -1; - } - - public bool MoveNext() => ++_position < _virtualCharSequence.Length; - public readonly VirtualChar Current => _virtualCharSequence[_position]; + public bool MoveNext() => ++_position < virtualCharSequence.Length; + public readonly VirtualChar Current => virtualCharSequence[_position]; public void Reset() => _position = -1; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxNodeExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxNodeExtensions.cs index 17a95ff67d789..9963ed2ebe96f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxNodeExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxNodeExtensions.cs @@ -834,37 +834,18 @@ public static SyntaxToken WithoutTrailingTrivia(this SyntaxToken token) public static ValueAncestorsAndSelfEnumerable ValueAncestorsAndSelf(this SyntaxNode syntaxNode, bool ascendOutOfTrivia = true) => new(syntaxNode, ascendOutOfTrivia); - public readonly struct ValueAncestorsAndSelfEnumerable + public readonly struct ValueAncestorsAndSelfEnumerable(SyntaxNode syntaxNode, bool ascendOutOfTrivia) { - private readonly SyntaxNode _syntaxNode; - private readonly bool _ascendOutOfTrivia; - - public ValueAncestorsAndSelfEnumerable(SyntaxNode syntaxNode, bool ascendOutOfTrivia) - { - _syntaxNode = syntaxNode; - _ascendOutOfTrivia = ascendOutOfTrivia; - } - public Enumerator GetEnumerator() - => new(_syntaxNode, _ascendOutOfTrivia); + => new(syntaxNode, ascendOutOfTrivia); - public struct Enumerator + public struct Enumerator(SyntaxNode syntaxNode, bool ascendOutOfTrivia) { - private readonly SyntaxNode _start; - private readonly bool _ascendOutOfTrivia; - - public Enumerator(SyntaxNode syntaxNode, bool ascendOutOfTrivia) - { - _start = syntaxNode; - _ascendOutOfTrivia = ascendOutOfTrivia; - Current = null!; - } - - public SyntaxNode Current { get; private set; } + public SyntaxNode Current { get; private set; } = null!; public bool MoveNext() { - Current = Current == null ? _start : GetParent(Current, _ascendOutOfTrivia)!; + Current = Current == null ? syntaxNode : GetParent(Current, ascendOutOfTrivia)!; return Current != null; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageResult.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageResult.cs index b7c930e30ddab..ce542a5c0dfe2 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageResult.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageResult.cs @@ -11,15 +11,10 @@ namespace Microsoft.CodeAnalysis.FlowAnalysis.SymbolUsageAnalysis { - internal readonly struct SymbolUsageResult + internal readonly struct SymbolUsageResult( + ImmutableDictionary<(ISymbol symbol, IOperation write), bool> symbolWritesMap, + ImmutableHashSet symbolsRead) { - public SymbolUsageResult( - ImmutableDictionary<(ISymbol symbol, IOperation write), bool> symbolWritesMap, - ImmutableHashSet symbolsRead) - { - SymbolWritesMap = symbolWritesMap; - SymbolsRead = symbolsRead; - } /// /// Map from each symbol write to a boolean indicating if the value assinged @@ -37,12 +32,12 @@ public SymbolUsageResult( /// Value = 'true', because value assigned to 'x' here **may be** read on /// some control flow path. /// - public ImmutableDictionary<(ISymbol symbol, IOperation write), bool> SymbolWritesMap { get; } + public ImmutableDictionary<(ISymbol symbol, IOperation write), bool> SymbolWritesMap { get; } = symbolWritesMap; /// /// Set of locals/parameters that are read at least once. /// - public ImmutableHashSet SymbolsRead { get; } + public ImmutableHashSet SymbolsRead { get; } = symbolsRead; public bool HasUnreadSymbolWrites() => SymbolWritesMap.Values.Any(value => !value); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.AnchorData.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.AnchorData.cs index 01de97733daff..62af62c742900 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.AnchorData.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.AnchorData.cs @@ -13,26 +13,17 @@ internal partial class FormattingContext /// /// data that will be used in an interval tree related to Anchor. /// - private class AnchorData + private class AnchorData(AnchorIndentationOperation operation, SyntaxToken anchorToken, int originalColumn) { - private readonly AnchorIndentationOperation _operation; + public TextSpan TextSpan => operation.TextSpan; - public AnchorData(AnchorIndentationOperation operation, SyntaxToken anchorToken, int originalColumn) - { - _operation = operation; - this.AnchorToken = anchorToken; - this.OriginalColumn = originalColumn; - } + public SyntaxToken StartToken => operation.StartToken; - public TextSpan TextSpan => _operation.TextSpan; + public SyntaxToken EndToken => operation.EndToken; - public SyntaxToken StartToken => _operation.StartToken; + public SyntaxToken AnchorToken { get; } = anchorToken; - public SyntaxToken EndToken => _operation.EndToken; - - public SyntaxToken AnchorToken { get; } - - public int OriginalColumn { get; } + public int OriginalColumn { get; } = originalColumn; } private readonly struct FormattingContextIntervalIntrospector diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.IndentationData.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.IndentationData.cs index 6b15b8f849ebf..da8240ae2202d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.IndentationData.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.IndentationData.cs @@ -15,12 +15,9 @@ internal partial class FormattingContext /// /// data that will be used in an interval tree related to indentation. /// - private abstract class IndentationData + private abstract class IndentationData(TextSpan textSpan) { - public IndentationData(TextSpan textSpan) - => this.TextSpan = textSpan; - - public TextSpan TextSpan { get; } + public TextSpan TextSpan { get; } = textSpan; public abstract int Indentation { get; } public IndentationData WithTextSpan(TextSpan span) @@ -29,21 +26,13 @@ public IndentationData WithTextSpan(TextSpan span) protected abstract IndentationData WithTextSpanCore(TextSpan span); } - private sealed class SimpleIndentationData : IndentationData + private sealed class SimpleIndentationData(TextSpan textSpan, int indentation) : IndentationData(textSpan) { - private readonly int _indentation; - - public SimpleIndentationData(TextSpan textSpan, int indentation) - : base(textSpan) - { - _indentation = indentation; - } - - public override int Indentation => _indentation; + public override int Indentation => indentation; protected override IndentationData WithTextSpanCore(TextSpan span) { - return new SimpleIndentationData(span, _indentation); + return new SimpleIndentationData(span, indentation); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/SuppressSpacingData.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/SuppressSpacingData.cs index ba581c7170ff7..9885f30e55c7d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/SuppressSpacingData.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/SuppressSpacingData.cs @@ -9,11 +9,8 @@ namespace Microsoft.CodeAnalysis.Formatting /// /// data that will be used in an interval tree related to suppressing spacing operations. /// - internal class SuppressSpacingData + internal class SuppressSpacingData(TextSpan textSpan) { - public SuppressSpacingData(TextSpan textSpan) - => this.TextSpan = textSpan; - - public TextSpan TextSpan { get; } + public TextSpan TextSpan { get; } = textSpan; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/SuppressWrappingData.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/SuppressWrappingData.cs index 7962b620a5fd2..89d537eb155c5 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/SuppressWrappingData.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/SuppressWrappingData.cs @@ -9,16 +9,10 @@ namespace Microsoft.CodeAnalysis.Formatting /// /// data that will be used in an interval tree related to suppressing wrapping operations. /// - internal class SuppressWrappingData + internal class SuppressWrappingData(TextSpan textSpan, bool ignoreElastic) { - public SuppressWrappingData(TextSpan textSpan, bool ignoreElastic) - { - this.TextSpan = textSpan; - this.IgnoreElastic = ignoreElastic; - } - - public TextSpan TextSpan { get; } - public bool IgnoreElastic { get; } + public TextSpan TextSpan { get; } = textSpan; + public bool IgnoreElastic { get; } = ignoreElastic; #if DEBUG public override string ToString() diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractFormatEngine.OperationApplier.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractFormatEngine.OperationApplier.cs index f97724d36fe85..c6ea71d1661ec 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractFormatEngine.OperationApplier.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractFormatEngine.OperationApplier.cs @@ -18,17 +18,8 @@ internal abstract partial class AbstractFormatEngine /// /// this actually applies formatting operations to trivia between two tokens /// - private class OperationApplier + private class OperationApplier(FormattingContext context, ChainedFormattingRules formattingRules) { - private readonly FormattingContext _context; - private readonly ChainedFormattingRules _formattingRules; - - public OperationApplier(FormattingContext context, ChainedFormattingRules formattingRules) - { - _context = context; - _formattingRules = formattingRules; - } - public bool Apply(AdjustSpacesOperation operation, int pairIndex) { if (operation.Option == AdjustSpacesOption.PreserveSpaces) @@ -51,7 +42,7 @@ public bool Apply(AdjustSpacesOperation operation, int pairIndex) private bool ApplyDynamicSpacesOperation(AdjustSpacesOperation operation, int pairIndex) { - var triviaInfo = _context.TokenStream.GetTriviaData(pairIndex); + var triviaInfo = context.TokenStream.GetTriviaData(pairIndex); if (triviaInfo.SecondTokenIsFirstTokenOnLine) { @@ -60,20 +51,20 @@ private bool ApplyDynamicSpacesOperation(AdjustSpacesOperation operation, int pa Contract.ThrowIfFalse(triviaInfo.LineBreaks == 0); - var indentation = _context.GetBaseIndentation(_context.TokenStream.GetToken(pairIndex + 1)); + var indentation = context.GetBaseIndentation(context.TokenStream.GetToken(pairIndex + 1)); - var previousToken = _context.TokenStream.GetToken(pairIndex); - _context.TokenStream.GetTokenLength(previousToken, out var tokenLength, out var multipleLines); + var previousToken = context.TokenStream.GetToken(pairIndex); + context.TokenStream.GetTokenLength(previousToken, out var tokenLength, out var multipleLines); // get end column of previous token - var endColumnOfPreviousToken = multipleLines ? tokenLength : _context.TokenStream.GetCurrentColumn(previousToken) + tokenLength; + var endColumnOfPreviousToken = multipleLines ? tokenLength : context.TokenStream.GetCurrentColumn(previousToken) + tokenLength; // check whether current position is less than indentation if (endColumnOfPreviousToken < indentation) { - Debug.Assert(!_context.IsFormattingDisabled(pairIndex)); + Debug.Assert(!context.IsFormattingDisabled(pairIndex)); - _context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithSpace(indentation - endColumnOfPreviousToken, _context, _formattingRules)); + context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithSpace(indentation - endColumnOfPreviousToken, context, formattingRules)); return true; } @@ -83,7 +74,7 @@ private bool ApplyDynamicSpacesOperation(AdjustSpacesOperation operation, int pa private bool ApplyPreserveSpacesOperation(AdjustSpacesOperation operation, int pairIndex) { - var triviaInfo = _context.TokenStream.GetTriviaData(pairIndex); + var triviaInfo = context.TokenStream.GetTriviaData(pairIndex); var space = operation.Space; if (triviaInfo.SecondTokenIsFirstTokenOnLine) @@ -98,30 +89,30 @@ private bool ApplyPreserveSpacesOperation(AdjustSpacesOperation operation, int p return false; } - Debug.Assert(!_context.IsFormattingDisabled(pairIndex)); + Debug.Assert(!context.IsFormattingDisabled(pairIndex)); - _context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithSpace(space, _context, _formattingRules)); + context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithSpace(space, context, formattingRules)); return true; } public bool ApplyForceSpacesOperation(AdjustSpacesOperation operation, int pairIndex) { - var triviaInfo = _context.TokenStream.GetTriviaData(pairIndex); + var triviaInfo = context.TokenStream.GetTriviaData(pairIndex); if (triviaInfo.LineBreaks == 0 && triviaInfo.Spaces == operation.Space) { return false; } - Debug.Assert(!_context.IsFormattingDisabled(pairIndex)); + Debug.Assert(!context.IsFormattingDisabled(pairIndex)); - _context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithSpace(operation.Space, _context, _formattingRules)); + context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithSpace(operation.Space, context, formattingRules)); return true; } private bool ApplySpaceIfSingleLine(AdjustSpacesOperation operation, int pairIndex) { - var triviaInfo = _context.TokenStream.GetTriviaData(pairIndex); + var triviaInfo = context.TokenStream.GetTriviaData(pairIndex); var space = operation.Space; if (triviaInfo.SecondTokenIsFirstTokenOnLine) @@ -136,9 +127,9 @@ private bool ApplySpaceIfSingleLine(AdjustSpacesOperation operation, int pairInd return false; } - Debug.Assert(!_context.IsFormattingDisabled(pairIndex)); + Debug.Assert(!context.IsFormattingDisabled(pairIndex)); - _context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithSpace(space, _context, _formattingRules)); + context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithSpace(space, context, formattingRules)); return true; } @@ -160,8 +151,8 @@ public bool Apply(AdjustNewLinesOperation operation, int pairIndex, Cancellation // else we leave the tokens as it is (Note: We should not preserve too. If we // we do, then that will be counted as a line operation and the indentation of // the second token will be modified) - if (_context.TokenStream.TwoTokensOnSameLine(_context.TokenStream.GetToken(pairIndex), - _context.TokenStream.GetToken(pairIndex + 1))) + if (context.TokenStream.TwoTokensOnSameLine(context.TokenStream.GetToken(pairIndex), + context.TokenStream.GetToken(pairIndex + 1))) { return ApplyForceLinesOperation(operation, pairIndex, cancellationToken); } @@ -174,9 +165,9 @@ public bool Apply(AdjustNewLinesOperation operation, int pairIndex, Cancellation private bool ApplyForceLinesOperation(AdjustNewLinesOperation operation, int pairIndex, CancellationToken cancellationToken) { - var triviaInfo = _context.TokenStream.GetTriviaData(pairIndex); + var triviaInfo = context.TokenStream.GetTriviaData(pairIndex); - var indentation = _context.GetBaseIndentation(_context.TokenStream.GetToken(pairIndex + 1)); + var indentation = context.GetBaseIndentation(context.TokenStream.GetToken(pairIndex + 1)); if (triviaInfo.LineBreaks == operation.Line && triviaInfo.Spaces == indentation && !triviaInfo.TreatAsElastic) { // things are already in the shape we want, so we don't actually need to do @@ -184,27 +175,27 @@ private bool ApplyForceLinesOperation(AdjustNewLinesOperation operation, int pai return true; } - Debug.Assert(!_context.IsFormattingDisabled(pairIndex)); + Debug.Assert(!context.IsFormattingDisabled(pairIndex)); // well, force it regardless original content - _context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithLine(operation.Line, indentation, _context, _formattingRules, cancellationToken)); + context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithLine(operation.Line, indentation, context, formattingRules, cancellationToken)); return true; } public bool ApplyPreserveLinesOperation( AdjustNewLinesOperation operation, int pairIndex, CancellationToken cancellationToken) { - var triviaInfo = _context.TokenStream.GetTriviaData(pairIndex); + var triviaInfo = context.TokenStream.GetTriviaData(pairIndex); // okay, check whether there is line between token more than we want // check whether we should force it if it is less than given number - var indentation = _context.GetBaseIndentation(_context.TokenStream.GetToken(pairIndex + 1)); + var indentation = context.GetBaseIndentation(context.TokenStream.GetToken(pairIndex + 1)); if (operation.Line > triviaInfo.LineBreaks) { - Debug.Assert(!_context.IsFormattingDisabled(pairIndex)); + Debug.Assert(!context.IsFormattingDisabled(pairIndex)); // alright force them - _context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithLine(operation.Line, indentation, _context, _formattingRules, cancellationToken)); + context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithLine(operation.Line, indentation, context, formattingRules, cancellationToken)); return true; } @@ -215,9 +206,9 @@ public bool ApplyPreserveLinesOperation( // Formatting can only be disabled for entire lines. This block only modifies the line containing // the second token of the current pair, so we only need to check for disabled formatting at the // starting position of the second token of the pair. - Debug.Assert(!_context.IsFormattingDisabled(new TextSpan(_context.TokenStream.GetToken(pairIndex + 1).SpanStart, 0))); + Debug.Assert(!context.IsFormattingDisabled(new TextSpan(context.TokenStream.GetToken(pairIndex + 1).SpanStart, 0))); - _context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithIndentation(indentation, _context, _formattingRules, cancellationToken)); + context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithIndentation(indentation, context, formattingRules, cancellationToken)); return true; } @@ -283,7 +274,7 @@ public bool ApplyAlignment( break; case AlignTokensOption.AlignIndentationOfTokensToFirstTokenOfBaseTokenLine: - if (!ApplyAlignment(_context.TokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken), operation.Tokens, previousChangesMap, out tokenData, cancellationToken)) + if (!ApplyAlignment(context.TokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken), operation.Tokens, previousChangesMap, out tokenData, cancellationToken)) { return false; } @@ -307,14 +298,14 @@ private void ApplyIndentationToAlignWithGivenToken( { // rather than having external new changes map, having snapshot concept // in token stream might be easier to understand. - var baseSpaceOrIndentation = _context.TokenStream.GetCurrentColumn(token); + var baseSpaceOrIndentation = context.TokenStream.GetCurrentColumn(token); for (var i = 0; i < list.Count; i++) { var currentToken = list[i]; - var previousToken = _context.TokenStream.GetPreviousTokenData(currentToken); + var previousToken = context.TokenStream.GetPreviousTokenData(currentToken); - var triviaInfo = _context.TokenStream.GetTriviaData(previousToken, currentToken); + var triviaInfo = context.TokenStream.GetTriviaData(previousToken, currentToken); if (!triviaInfo.SecondTokenIsFirstTokenOnLine) { continue; @@ -344,20 +335,20 @@ private void ApplyIndentationToGivenPosition( // before make any change, check whether spacing is allowed var spanBetweenTokens = TextSpan.FromBounds(previousToken.Token.Span.End, currentToken.Token.SpanStart); - if (_context.IsSpacingSuppressed(spanBetweenTokens, triviaInfo.TreatAsElastic)) + if (context.IsSpacingSuppressed(spanBetweenTokens, triviaInfo.TreatAsElastic)) { return; } - if (_context.IsFormattingDisabled(spanBetweenTokens)) + if (context.IsFormattingDisabled(spanBetweenTokens)) { return; } // okay, update indentation - _context.TokenStream.ApplyChange( + context.TokenStream.ApplyChange( previousToken.IndexInStream, - triviaInfo.WithIndentation(baseSpaceOrIndentation, _context, _formattingRules, cancellationToken)); + triviaInfo.WithIndentation(baseSpaceOrIndentation, context, formattingRules, cancellationToken)); } private IList GetTokenWithIndices(IEnumerable tokens) @@ -371,7 +362,7 @@ private IList GetTokenWithIndices(IEnumerable tokens) continue; } - var tokenWithIndex = _context.TokenStream.GetTokenData(token); + var tokenWithIndex = context.TokenStream.GetTokenData(token); if (tokenWithIndex.IndexInStream < 0) { // this token is not inside of the formatting span, ignore @@ -394,7 +385,7 @@ private bool ApplyIndentationChangesToDependentTokens( // first check whether the token moved by alignment operation have affected an anchor token. if it has, // then find the last token of that anchor span. - var endAnchorToken = _context.GetEndTokenForAnchorSpan(firstToken); + var endAnchorToken = context.GetEndTokenForAnchorSpan(firstToken); if (endAnchorToken.RawKind == 0) { // this means given token is not anchor token, no need to do anything @@ -402,10 +393,10 @@ private bool ApplyIndentationChangesToDependentTokens( } // first token was anchor token, now find last token with index - var lastToken = _context.TokenStream.GetTokenData(endAnchorToken); + var lastToken = context.TokenStream.GetTokenData(endAnchorToken); if (lastToken.IndexInStream < 0) { - lastToken = _context.TokenStream.LastTokenInStream; + lastToken = context.TokenStream.LastTokenInStream; } ApplyBaseTokenIndentationChangesFromTo(firstToken, firstToken, lastToken, newChangesMap, cancellationToken); @@ -424,14 +415,14 @@ private void ApplyIndentationDeltaFromTo( // can this run parallel? at least finding out all first token on line. for (var pairIndex = firstToken.IndexInStream; pairIndex < lastToken.IndexInStream; pairIndex++) { - var triviaInfo = _context.TokenStream.GetTriviaData(pairIndex); + var triviaInfo = context.TokenStream.GetTriviaData(pairIndex); if (!triviaInfo.SecondTokenIsFirstTokenOnLine) { continue; } // spacing is suppressed. don't change any spacing - if (_context.IsSpacingSuppressed(pairIndex)) + if (context.IsSpacingSuppressed(pairIndex)) { continue; } @@ -439,7 +430,7 @@ private void ApplyIndentationDeltaFromTo( // bail fast here. // if an entity is in the map, then it means indentation has been applied to the token pair already. // no reason to do same work again. - var currentToken = _context.TokenStream.GetToken(pairIndex + 1); + var currentToken = context.TokenStream.GetToken(pairIndex + 1); if (previousChangesMap.ContainsKey(currentToken)) { continue; @@ -467,14 +458,14 @@ private void ApplyIndentationDelta( return; } - Debug.Assert(!_context.IsFormattingDisabled(pairIndex)); + Debug.Assert(!context.IsFormattingDisabled(pairIndex)); // record the fact that this pair has been moved Debug.Assert(!previousChangesMap.ContainsKey(currentToken)); previousChangesMap.Add(currentToken, triviaInfo.Spaces); // okay, update indentation - _context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithIndentation(indentation, _context, _formattingRules, cancellationToken)); + context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithIndentation(indentation, context, formattingRules, cancellationToken)); } public bool ApplyBaseTokenIndentationChangesFromTo( @@ -486,9 +477,9 @@ public bool ApplyBaseTokenIndentationChangesFromTo( { Contract.ThrowIfFalse(baseToken.RawKind != 0 && startToken.RawKind != 0 && endToken.RawKind != 0); - var baseTokenWithIndex = _context.TokenStream.GetTokenData(baseToken); - var firstTokenWithIndex = _context.TokenStream.GetTokenData(startToken).GetPreviousTokenData(); - var lastTokenWithIndex = _context.TokenStream.GetTokenData(endToken); + var baseTokenWithIndex = context.TokenStream.GetTokenData(baseToken); + var firstTokenWithIndex = context.TokenStream.GetTokenData(startToken).GetPreviousTokenData(); + var lastTokenWithIndex = context.TokenStream.GetTokenData(endToken); return ApplyBaseTokenIndentationChangesFromTo( baseTokenWithIndex, firstTokenWithIndex, lastTokenWithIndex, previousChangesMap, cancellationToken); @@ -521,7 +512,7 @@ private bool ApplyBaseTokenIndentationChangesFromTo( // okay, this token is not moved, check one before me as long as it is on the same line var tokenPairIndex = tokenWithIndex.IndexInStream - 1; if (tokenPairIndex < 0 || - _context.TokenStream.GetTriviaData(tokenPairIndex).SecondTokenIsFirstTokenOnLine) + context.TokenStream.GetTriviaData(tokenPairIndex).SecondTokenIsFirstTokenOnLine) { return false; } @@ -536,14 +527,14 @@ private bool ApplyBaseTokenIndentationChangesFromTo( } // we are not moved - var indentationDelta = _context.GetDeltaFromPreviousChangesMap(tokenWithIndex.Token, previousChangesMap); + var indentationDelta = context.GetDeltaFromPreviousChangesMap(tokenWithIndex.Token, previousChangesMap); if (indentationDelta == 0) { return false; } - startToken = startToken.IndexInStream < 0 ? _context.TokenStream.FirstTokenInStream : startToken; - endToken = endToken.IndexInStream < 0 ? _context.TokenStream.LastTokenInStream : endToken; + startToken = startToken.IndexInStream < 0 ? context.TokenStream.FirstTokenInStream : startToken; + endToken = endToken.IndexInStream < 0 ? context.TokenStream.LastTokenInStream : endToken; ApplyIndentationDeltaFromTo(startToken, endToken, indentationDelta, previousChangesMap, cancellationToken); return true; @@ -552,7 +543,7 @@ private bool ApplyBaseTokenIndentationChangesFromTo( public bool ApplyAnchorIndentation( int pairIndex, Dictionary previousChangesMap, CancellationToken cancellationToken) { - var triviaInfo = _context.TokenStream.GetTriviaData(pairIndex); + var triviaInfo = context.TokenStream.GetTriviaData(pairIndex); if (!triviaInfo.SecondTokenIsFirstTokenOnLine) { @@ -560,13 +551,13 @@ public bool ApplyAnchorIndentation( } // don't apply anchor is spacing is suppressed - if (_context.IsSpacingSuppressed(pairIndex)) + if (context.IsSpacingSuppressed(pairIndex)) { return false; } - var firstTokenOnLine = _context.TokenStream.GetToken(pairIndex + 1); - var indentation = triviaInfo.Spaces + _context.GetAnchorDeltaFromOriginalColumn(firstTokenOnLine); + var firstTokenOnLine = context.TokenStream.GetToken(pairIndex + 1); + var indentation = triviaInfo.Spaces + context.GetAnchorDeltaFromOriginalColumn(firstTokenOnLine); if (triviaInfo.Spaces != indentation) { @@ -574,7 +565,7 @@ public bool ApplyAnchorIndentation( previousChangesMap.Add(firstTokenOnLine, triviaInfo.Spaces); // okay, update indentation - _context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithIndentation(indentation, _context, _formattingRules, cancellationToken)); + context.TokenStream.ApplyChange(pairIndex, triviaInfo.WithIndentation(indentation, context, formattingRules, cancellationToken)); return true; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TokenStream.Iterator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TokenStream.Iterator.cs index fd8fc491ce50a..8fb0772a22df5 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TokenStream.Iterator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TokenStream.Iterator.cs @@ -10,15 +10,10 @@ internal partial class TokenStream { // gain of having hand written iterator seems about 50-100ms over auto generated one. // not sure whether it is worth it. but I already wrote it to test, so going to just keep it. - public readonly struct Iterator + public readonly struct Iterator(SegmentedList tokensIncludingZeroWidth) { - private readonly SegmentedList _tokensIncludingZeroWidth; - - public Iterator(SegmentedList tokensIncludingZeroWidth) - => _tokensIncludingZeroWidth = tokensIncludingZeroWidth; - public Enumerator GetEnumerator() - => new(_tokensIncludingZeroWidth); + => new(tokensIncludingZeroWidth); public struct Enumerator { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TreeData.Debug.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TreeData.Debug.cs index ccceb9b050a82..be6a6589db203 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TreeData.Debug.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TreeData.Debug.cs @@ -9,15 +9,9 @@ namespace Microsoft.CodeAnalysis.Formatting { internal abstract partial class TreeData { - private class Debug : NodeAndText + private class Debug(SyntaxNode root, SourceText text) : NodeAndText(root, text) { - private readonly TreeData _debugNodeData; - - public Debug(SyntaxNode root, SourceText text) - : base(root, text) - { - _debugNodeData = new Node(root); - } + private readonly TreeData _debugNodeData = new Node(root); public override string GetTextBetween(SyntaxToken token1, SyntaxToken token2) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TriviaDataWithList.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TriviaDataWithList.cs index 6355f59d66642..e16791e971edc 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TriviaDataWithList.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TriviaDataWithList.cs @@ -7,13 +7,8 @@ namespace Microsoft.CodeAnalysis.Formatting { - internal abstract class TriviaDataWithList : TriviaData + internal abstract class TriviaDataWithList(SyntaxFormattingOptions options, string language) : TriviaData(options, language) { - public TriviaDataWithList(SyntaxFormattingOptions options, string language) - : base(options, language) - { - } - public abstract SyntaxTriviaList GetTriviaList(CancellationToken cancellationToken); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextAlignTokensOperationAction.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextAlignTokensOperationAction.cs index 809441ee6f8b6..5ea039b6f9105 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextAlignTokensOperationAction.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextAlignTokensOperationAction.cs @@ -9,39 +9,26 @@ namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] - internal readonly struct NextAlignTokensOperationAction + internal readonly struct NextAlignTokensOperationAction( + ImmutableArray formattingRules, + int index, + SyntaxNode node, + List list) { - private readonly ImmutableArray _formattingRules; - private readonly int _index; - private readonly SyntaxNode _node; - private readonly List _list; - - public NextAlignTokensOperationAction( - ImmutableArray formattingRules, - int index, - SyntaxNode node, - List list) - { - _formattingRules = formattingRules; - _index = index; - _node = node; - _list = list; - } - private NextAlignTokensOperationAction NextAction - => new(_formattingRules, _index + 1, _node, _list); + => new(formattingRules, index + 1, node, list); public void Invoke() { // If we have no remaining handlers to execute, then we'll execute our last handler - if (_index >= _formattingRules.Length) + if (index >= formattingRules.Length) { return; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 - _formattingRules[_index].AddAlignTokensOperations(_list, _node, NextAction); + formattingRules[index].AddAlignTokensOperations(list, node, NextAction); return; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextAnchorIndentationOperationAction.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextAnchorIndentationOperationAction.cs index 977d195e43940..570c300709fba 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextAnchorIndentationOperationAction.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextAnchorIndentationOperationAction.cs @@ -9,39 +9,26 @@ namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] - internal readonly struct NextAnchorIndentationOperationAction + internal readonly struct NextAnchorIndentationOperationAction( + ImmutableArray formattingRules, + int index, + SyntaxNode node, + List list) { - private readonly ImmutableArray _formattingRules; - private readonly int _index; - private readonly SyntaxNode _node; - private readonly List _list; - - public NextAnchorIndentationOperationAction( - ImmutableArray formattingRules, - int index, - SyntaxNode node, - List list) - { - _formattingRules = formattingRules; - _index = index; - _node = node; - _list = list; - } - private NextAnchorIndentationOperationAction NextAction - => new(_formattingRules, _index + 1, _node, _list); + => new(formattingRules, index + 1, node, list); public void Invoke() { // If we have no remaining handlers to execute, then we'll execute our last handler - if (_index >= _formattingRules.Length) + if (index >= formattingRules.Length) { return; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 - _formattingRules[_index].AddAnchorIndentationOperations(_list, _node, NextAction); + formattingRules[index].AddAnchorIndentationOperations(list, node, NextAction); return; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextGetAdjustNewLinesOperation.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextGetAdjustNewLinesOperation.cs index 8867ee98cf217..c410167abbde6 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextGetAdjustNewLinesOperation.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextGetAdjustNewLinesOperation.cs @@ -8,33 +8,24 @@ namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] - internal readonly struct NextGetAdjustNewLinesOperation + internal readonly struct NextGetAdjustNewLinesOperation( + ImmutableArray formattingRules, + int index) { - private readonly ImmutableArray _formattingRules; - private readonly int _index; - - public NextGetAdjustNewLinesOperation( - ImmutableArray formattingRules, - int index) - { - _formattingRules = formattingRules; - _index = index; - } - private NextGetAdjustNewLinesOperation NextOperation - => new(_formattingRules, _index + 1); + => new(formattingRules, index + 1); public AdjustNewLinesOperation? Invoke(in SyntaxToken previousToken, in SyntaxToken currentToken) { // If we have no remaining handlers to execute, then we'll execute our last handler - if (_index >= _formattingRules.Length) + if (index >= formattingRules.Length) { return null; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 - return _formattingRules[_index].GetAdjustNewLinesOperation(in previousToken, in currentToken, NextOperation); + return formattingRules[index].GetAdjustNewLinesOperation(in previousToken, in currentToken, NextOperation); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextGetAdjustSpacesOperation.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextGetAdjustSpacesOperation.cs index 7642c2d665312..8fc77ca50da25 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextGetAdjustSpacesOperation.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextGetAdjustSpacesOperation.cs @@ -8,33 +8,24 @@ namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] - internal readonly struct NextGetAdjustSpacesOperation + internal readonly struct NextGetAdjustSpacesOperation( + ImmutableArray formattingRules, + int index) { - private readonly ImmutableArray _formattingRules; - private readonly int _index; - - public NextGetAdjustSpacesOperation( - ImmutableArray formattingRules, - int index) - { - _formattingRules = formattingRules; - _index = index; - } - private NextGetAdjustSpacesOperation NextOperation - => new(_formattingRules, _index + 1); + => new(formattingRules, index + 1); public AdjustSpacesOperation? Invoke(in SyntaxToken previousToken, in SyntaxToken currentToken) { // If we have no remaining handlers to execute, then we'll execute our last handler - if (_index >= _formattingRules.Length) + if (index >= formattingRules.Length) { return null; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 - return _formattingRules[_index].GetAdjustSpacesOperation(in previousToken, in currentToken, NextOperation); + return formattingRules[index].GetAdjustSpacesOperation(in previousToken, in currentToken, NextOperation); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextIndentBlockOperationAction.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextIndentBlockOperationAction.cs index 43c5495f1319d..1daa18b2606d8 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextIndentBlockOperationAction.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextIndentBlockOperationAction.cs @@ -9,39 +9,26 @@ namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] - internal readonly struct NextIndentBlockOperationAction + internal readonly struct NextIndentBlockOperationAction( + ImmutableArray formattingRules, + int index, + SyntaxNode node, + List list) { - private readonly ImmutableArray _formattingRules; - private readonly int _index; - private readonly SyntaxNode _node; - private readonly List _list; - - public NextIndentBlockOperationAction( - ImmutableArray formattingRules, - int index, - SyntaxNode node, - List list) - { - _formattingRules = formattingRules; - _index = index; - _node = node; - _list = list; - } - private NextIndentBlockOperationAction NextAction - => new(_formattingRules, _index + 1, _node, _list); + => new(formattingRules, index + 1, node, list); public void Invoke() { // If we have no remaining handlers to execute, then we'll execute our last handler - if (_index >= _formattingRules.Length) + if (index >= formattingRules.Length) { return; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 - _formattingRules[_index].AddIndentBlockOperations(_list, _node, NextAction); + formattingRules[index].AddIndentBlockOperations(list, node, NextAction); return; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextSuppressOperationAction.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextSuppressOperationAction.cs index 349dbda54f592..5c1e18873bc8a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextSuppressOperationAction.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextSuppressOperationAction.cs @@ -9,39 +9,26 @@ namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] - internal readonly struct NextSuppressOperationAction + internal readonly struct NextSuppressOperationAction( + ImmutableArray formattingRules, + int index, + SyntaxNode node, + List list) { - private readonly ImmutableArray _formattingRules; - private readonly int _index; - private readonly SyntaxNode _node; - private readonly List _list; - - public NextSuppressOperationAction( - ImmutableArray formattingRules, - int index, - SyntaxNode node, - List list) - { - _formattingRules = formattingRules; - _index = index; - _node = node; - _list = list; - } - private NextSuppressOperationAction NextAction - => new(_formattingRules, _index + 1, _node, _list); + => new(formattingRules, index + 1, node, list); public void Invoke() { // If we have no remaining handlers to execute, then we'll execute our last handler - if (_index >= _formattingRules.Length) + if (index >= formattingRules.Length) { return; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 - _formattingRules[_index].AddSuppressOperations(_list, _node, NextAction); + formattingRules[index].AddSuppressOperations(list, node, NextAction); return; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/LineColumn.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/LineColumn.cs index 1d2eba6d515da..134aba94b6fac 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/LineColumn.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/LineColumn.cs @@ -4,31 +4,24 @@ namespace Microsoft.CodeAnalysis.Formatting { - internal readonly struct LineColumn + internal readonly struct LineColumn(int line, int column, bool whitespaceOnly) { public static LineColumn Default = new(line: 0, column: 0, whitespaceOnly: true); /// /// absolute line number from first token /// - public readonly int Line; + public readonly int Line = line; /// /// absolute column from beginning of a line /// - public readonly int Column; + public readonly int Column = column; /// /// there is only whitespace on this line /// - public readonly bool WhitespaceOnly; - - public LineColumn(int line, int column, bool whitespaceOnly) - { - Line = line; - Column = column; - WhitespaceOnly = whitespaceOnly; - } + public readonly bool WhitespaceOnly = whitespaceOnly; public LineColumn With(LineColumnDelta delta) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/LineColumnDelta.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/LineColumnDelta.cs index 727539bbae0ef..df4107cab8ce7 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/LineColumnDelta.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/LineColumnDelta.cs @@ -4,38 +4,29 @@ namespace Microsoft.CodeAnalysis.Formatting { - internal readonly struct LineColumnDelta + internal readonly struct LineColumnDelta(int lines, int spaces) { public static LineColumnDelta Default = new(lines: 0, spaces: 0, whitespaceOnly: true, forceUpdate: false); /// /// relative line number between calls /// - public readonly int Lines; + public readonly int Lines = lines; /// /// relative spaces between calls /// - public readonly int Spaces; + public readonly int Spaces = spaces; /// /// there is only whitespace in this space /// - public readonly bool WhitespaceOnly; + public readonly bool WhitespaceOnly = true; /// /// force text change regardless line and space changes /// - public readonly bool ForceUpdate; - - public LineColumnDelta(int lines, int spaces) - { - this.Lines = lines; - this.Spaces = spaces; - - this.WhitespaceOnly = true; - this.ForceUpdate = false; - } + public readonly bool ForceUpdate = false; public LineColumnDelta(int lines, int spaces, bool whitespaceOnly) : this(lines, spaces) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/LineColumnRule.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/LineColumnRule.cs index 998497b4e439a..31622f70f71bf 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/LineColumnRule.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/LineColumnRule.cs @@ -4,31 +4,21 @@ namespace Microsoft.CodeAnalysis.Formatting { - internal readonly struct LineColumnRule + internal readonly struct LineColumnRule( + SpaceOperations spaceOperation, + LineOperations lineOperation, + IndentationOperations indentationOperation, + int lines, + int spaces, + int indentation) { - public readonly SpaceOperations SpaceOperation; - public readonly LineOperations LineOperation; - public readonly IndentationOperations IndentationOperation; - - public readonly int Lines; - public readonly int Spaces; - public readonly int Indentation; - - public LineColumnRule( - SpaceOperations spaceOperation, - LineOperations lineOperation, - IndentationOperations indentationOperation, - int lines, - int spaces, - int indentation) - { - SpaceOperation = spaceOperation; - LineOperation = lineOperation; - IndentationOperation = indentationOperation; - Lines = lines; - Spaces = spaces; - Indentation = indentation; - } + public readonly SpaceOperations SpaceOperation = spaceOperation; + public readonly LineOperations LineOperation = lineOperation; + public readonly IndentationOperations IndentationOperation = indentationOperation; + + public readonly int Lines = lines; + public readonly int Spaces = spaces; + public readonly int Indentation = indentation; public LineColumnRule With(int? lines = null, int? spaces = null, int? indentation = null, LineOperations? lineOperation = null, SpaceOperations? spaceOperation = null, IndentationOperations? indentationOperation = null) => new( diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/TriviaList.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/TriviaList.cs index a567feed689f9..0d222cddb7375 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/TriviaList.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/TriviaList.cs @@ -4,21 +4,12 @@ namespace Microsoft.CodeAnalysis.Formatting { - internal readonly struct TriviaList + internal readonly struct TriviaList(SyntaxTriviaList list1, SyntaxTriviaList list2) { - private readonly SyntaxTriviaList _list1; - private readonly SyntaxTriviaList _list2; - - public TriviaList(SyntaxTriviaList list1, SyntaxTriviaList list2) - { - _list1 = list1; - _list2 = list2; - } - - public int Count => _list1.Count + _list2.Count; + public int Count => list1.Count + list2.Count; public SyntaxTrivia this[int index] - => index < _list1.Count ? _list1[index] : _list2[index - _list1.Count]; + => index < list1.Count ? list1[index] : list2[index - list1.Count]; public Enumerator GetEnumerator() => new(this); @@ -33,8 +24,8 @@ public struct Enumerator internal Enumerator(TriviaList triviaList) { - _list1 = triviaList._list1; - _list2 = triviaList._list2; + _list1 = list1; + _list2 = list2; _index = -1; _enumerator = _list1.GetEnumerator(); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/Logger.LogBlock.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/Logger.LogBlock.cs index 84f2be87c7de4..4a81d3c1207b1 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/Logger.LogBlock.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/Logger.LogBlock.cs @@ -29,9 +29,8 @@ private static IDisposable CreateLogBlock(FunctionId functionId, LogMessage mess /// This tracks the logged message. On instantiation, it logs 'Started block' with other event data. /// On dispose, it logs 'Ended block' with the same event data so we can track which block started and ended when looking at logs. /// - private class RoslynLogBlock : IDisposable + private class RoslynLogBlock(ObjectPool pool) : IDisposable { - private readonly ObjectPool _pool; // these need to be cleared before putting back to pool private ILogger? _logger; @@ -42,9 +41,6 @@ private class RoslynLogBlock : IDisposable private int _tick; private int _blockId; - public RoslynLogBlock(ObjectPool pool) - => _pool = pool; - public void Construct(ILogger logger, FunctionId functionId, LogMessage logMessage, int blockId, CancellationToken cancellationToken) { _logger = logger; @@ -77,7 +73,7 @@ public void Dispose() _logger = null; _cancellationToken = default; - _pool.Free(this); + pool.Free(this); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingRule.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingRule.cs index bd378ffe4efd1..2094e21802731 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingRule.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingRule.cs @@ -8,17 +8,10 @@ namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { - internal readonly struct NamingRule + internal readonly struct NamingRule(SymbolSpecification symbolSpecification, NamingStyle namingStyle, ReportDiagnostic enforcementLevel) { - public readonly SymbolSpecification SymbolSpecification; - public readonly NamingStyle NamingStyle; - public readonly ReportDiagnostic EnforcementLevel; - - public NamingRule(SymbolSpecification symbolSpecification, NamingStyle namingStyle, ReportDiagnostic enforcementLevel) - { - SymbolSpecification = symbolSpecification; - NamingStyle = namingStyle; - EnforcementLevel = enforcementLevel; - } + public readonly SymbolSpecification SymbolSpecification = symbolSpecification; + public readonly NamingStyle NamingStyle = namingStyle; + public readonly ReportDiagnostic EnforcementLevel = enforcementLevel; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyle.WordSpanEnumerable.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyle.WordSpanEnumerable.cs index 002f122a32965..35185d8055050 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyle.WordSpanEnumerable.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyle.WordSpanEnumerable.cs @@ -10,21 +10,10 @@ namespace Microsoft.CodeAnalysis.NamingStyles { internal partial record struct NamingStyle { - private readonly struct WordSpanEnumerable + private readonly struct WordSpanEnumerable(string name, TextSpan nameSpan, string wordSeparator) { - private readonly string _name; - private readonly TextSpan _nameSpan; - private readonly string _wordSeparator; - - public WordSpanEnumerable(string name, TextSpan nameSpan, string wordSeparator) - { - _name = name; - _nameSpan = nameSpan; - _wordSeparator = wordSeparator; - } - public WordSpanEnumerator GetEnumerator() - => new(_name, _nameSpan, _wordSeparator); + => new(name, nameSpan, wordSeparator); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyleRules.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyleRules.cs index b03ed854586c5..6903f5d38b352 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyleRules.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyleRules.cs @@ -10,9 +10,9 @@ namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { - internal class NamingStyleRules + internal class NamingStyleRules(ImmutableArray namingRules) { - public ImmutableArray NamingRules { get; } + public ImmutableArray NamingRules { get; } = namingRules; private readonly ImmutableArray _symbolKindsThatCanBeOverridden = ImmutableArray.Create( @@ -20,9 +20,6 @@ internal class NamingStyleRules SymbolKind.Property, SymbolKind.Event); - public NamingStyleRules(ImmutableArray namingRules) - => NamingRules = namingRules; - internal bool TryGetApplicableRule(ISymbol symbol, out NamingRule applicableRule) { if (NamingRules != null && diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/MutableNamingStyle.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/MutableNamingStyle.cs index b1a28c50f8db9..403ec5d491c62 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/MutableNamingStyle.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/MutableNamingStyle.cs @@ -9,9 +9,9 @@ namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { - internal class MutableNamingStyle + internal class MutableNamingStyle(NamingStyle namingStyle) { - public NamingStyle NamingStyle { get; private set; } + public NamingStyle NamingStyle { get; private set; } = namingStyle; public Guid ID => NamingStyle.ID; @@ -50,9 +50,6 @@ public MutableNamingStyle() { } - public MutableNamingStyle(NamingStyle namingStyle) - => NamingStyle = namingStyle; - internal MutableNamingStyle Clone() => new(NamingStyle); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/SymbolSpecification.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/SymbolSpecification.cs index c25c355f299ac..43b2ef40ad160 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/SymbolSpecification.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/SymbolSpecification.cs @@ -25,38 +25,29 @@ namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { [DataContract] [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] - internal sealed class SymbolSpecification : IEquatable, IObjectWritable + internal sealed class SymbolSpecification( + Guid id, + string name, + ImmutableArray symbolKindList, + ImmutableArray accessibilityList = default, + ImmutableArray modifiers = default) : IEquatable, IObjectWritable { private static readonly SymbolSpecification DefaultSymbolSpecificationTemplate = CreateDefaultSymbolSpecification(); [DataMember(Order = 0)] - public Guid ID { get; } + public Guid ID { get; } = id; [DataMember(Order = 1)] - public string Name { get; } + public string Name { get; } = name; [DataMember(Order = 2)] - public ImmutableArray ApplicableSymbolKindList { get; } + public ImmutableArray ApplicableSymbolKindList { get; } = symbolKindList.IsDefault ? DefaultSymbolSpecificationTemplate.ApplicableSymbolKindList : symbolKindList; [DataMember(Order = 3)] - public ImmutableArray ApplicableAccessibilityList { get; } + public ImmutableArray ApplicableAccessibilityList { get; } = accessibilityList.IsDefault ? DefaultSymbolSpecificationTemplate.ApplicableAccessibilityList : accessibilityList; [DataMember(Order = 4)] - public ImmutableArray RequiredModifierList { get; } - - public SymbolSpecification( - Guid id, - string name, - ImmutableArray symbolKindList, - ImmutableArray accessibilityList = default, - ImmutableArray modifiers = default) - { - ID = id; - Name = name; - ApplicableSymbolKindList = symbolKindList.IsDefault ? DefaultSymbolSpecificationTemplate.ApplicableSymbolKindList : symbolKindList; - ApplicableAccessibilityList = accessibilityList.IsDefault ? DefaultSymbolSpecificationTemplate.ApplicableAccessibilityList : accessibilityList; - RequiredModifierList = modifiers.IsDefault ? DefaultSymbolSpecificationTemplate.RequiredModifierList : modifiers; - } + public ImmutableArray RequiredModifierList { get; } = modifiers.IsDefault ? DefaultSymbolSpecificationTemplate.RequiredModifierList : modifiers; private string GetDebuggerDisplay() => Name; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/ObjectPools/PooledDisposer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/ObjectPools/PooledDisposer.cs index 337358e4cda92..0f7c919e026e1 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/ObjectPools/PooledDisposer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/ObjectPools/PooledDisposer.cs @@ -8,15 +8,10 @@ namespace Microsoft.CodeAnalysis.PooledObjects { [NonCopyable] - internal readonly struct PooledDisposer : IDisposable + internal readonly struct PooledDisposer(TPoolable instance) : IDisposable where TPoolable : class, IPooled { - private readonly TPoolable _pooledObject; - - public PooledDisposer(TPoolable instance) - => _pooledObject = instance; - void IDisposable.Dispose() - => _pooledObject?.Free(); + => instance?.Free(); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfigValueSerializer`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfigValueSerializer`1.cs index cfb2d1fc095ad..e1083e0e40f95 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfigValueSerializer`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfigValueSerializer`1.cs @@ -12,25 +12,15 @@ namespace Microsoft.CodeAnalysis.Options /// /// Specifies that an option should be read from an .editorconfig file. /// - internal sealed class EditorConfigValueSerializer : IEditorConfigValueSerializer + internal sealed class EditorConfigValueSerializer( + Func> parseValue, + Func serializeValue) : IEditorConfigValueSerializer { public static readonly EditorConfigValueSerializer Unsupported = new( parseValue: _ => throw new NotSupportedException("Option does not support serialization to editorconfig format"), serializeValue: _ => throw new NotSupportedException("Option does not support serialization to editorconfig format")); - - private readonly Func> _parseValue; - private readonly Func _serializeValue; - private readonly ConcurrentDictionary> _cachedValues = new(); - public EditorConfigValueSerializer( - Func> parseValue, - Func serializeValue) - { - _parseValue = parseValue; - _serializeValue = serializeValue; - } - bool IEditorConfigValueSerializer.TryParse(string value, out object? result) { if (TryParseValue(value, out var typedResult)) @@ -45,7 +35,7 @@ bool IEditorConfigValueSerializer.TryParse(string value, out object? result) internal bool TryParseValue(string value, [MaybeNullWhen(false)] out T result) { - var optionalValue = _cachedValues.GetOrAdd(value, _parseValue); + var optionalValue = _cachedValues.GetOrAdd(value, parseValue); if (optionalValue.HasValue) { result = optionalValue.Value; @@ -60,7 +50,7 @@ internal bool TryParseValue(string value, [MaybeNullWhen(false)] out T result) public string GetEditorConfigStringValue(T value) { - var editorConfigStringForValue = _serializeValue(value); + var editorConfigStringForValue = serializeValue(value); Contract.ThrowIfTrue(RoslynString.IsNullOrEmpty(editorConfigStringForValue)); return editorConfigStringForValue; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOptionReader.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOptionReader.cs index 1d3a60418f6c8..249b399bd8c17 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOptionReader.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOptionReader.cs @@ -16,14 +16,9 @@ internal interface IOptionsReader bool TryGetOption(OptionKey2 optionKey, out T value); } -internal sealed class AnalyzerConfigOptionsReader : IOptionsReader +internal sealed class AnalyzerConfigOptionsReader(AnalyzerConfigOptions options) : IOptionsReader { - public readonly AnalyzerConfigOptions Options; - - public AnalyzerConfigOptionsReader(AnalyzerConfigOptions options) - { - Options = options; - } + public readonly AnalyzerConfigOptions Options = options; public bool TryGetOption(OptionKey2 optionKey, out T value) => Options.TryGetEditorConfigOption(optionKey.Option, out value); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/InternalOptionStorageMapping.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/InternalOptionStorageMapping.cs index 7435c45e6929c..801e96425ac41 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/InternalOptionStorageMapping.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/InternalOptionStorageMapping.cs @@ -8,15 +8,12 @@ namespace Microsoft.CodeAnalysis.Options; /// Some options store their values in a type that's not accessible publicly. /// The mapping provides translation between the two representations. /// -internal abstract class OptionStorageMapping +internal abstract class OptionStorageMapping(IOption2 internalOption) { /// /// The option that stores the value internally. /// - public IOption2 InternalOption { get; } - - public OptionStorageMapping(IOption2 internalOption) - => InternalOption = internalOption; + public IOption2 InternalOption { get; } = internalOption; /// /// Converts inernal option value representation to public. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionDefinition.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionDefinition.cs index ffd43e4502011..24c76a80ea24d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionDefinition.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionDefinition.cs @@ -97,23 +97,16 @@ public static bool IsSupportedOptionType(Type type) type == typeof(ImmutableArray); } - internal sealed class OptionDefinition : OptionDefinition + internal sealed class OptionDefinition( + T defaultValue, + EditorConfigValueSerializer? serializer, + OptionGroup? group, + string configName, + OptionStorageMapping? storageMapping, + bool isEditorConfigOption) : OptionDefinition(group, configName, defaultValue, storageMapping, isEditorConfigOption) { - public new T DefaultValue { get; } - public new EditorConfigValueSerializer Serializer { get; } - - public OptionDefinition( - T defaultValue, - EditorConfigValueSerializer? serializer, - OptionGroup? group, - string configName, - OptionStorageMapping? storageMapping, - bool isEditorConfigOption) - : base(group, configName, defaultValue, storageMapping, isEditorConfigOption) - { - DefaultValue = defaultValue; - Serializer = serializer ?? EditorConfigValueSerializer.Default(); - } + public new T DefaultValue { get; } = defaultValue; + public new EditorConfigValueSerializer Serializer { get; } = serializer ?? EditorConfigValueSerializer.Default(); public override Type Type => typeof(T); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionGroup.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionGroup.cs index b32932097274c..ddb4628f7fd84 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionGroup.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionGroup.cs @@ -9,36 +9,28 @@ namespace Microsoft.CodeAnalysis.Options /// /// Group/sub-feature associated with an option. /// - internal sealed class OptionGroup + internal sealed class OptionGroup(string name, string description, int priority = int.MaxValue, OptionGroup? parent = null) { public static readonly OptionGroup Default = new(string.Empty, string.Empty, int.MaxValue); - public OptionGroup(string name, string description, int priority = int.MaxValue, OptionGroup? parent = null) - { - Description = description; - Priority = priority; - Parent = parent; - Name = name; - } - /// /// Optional parent group. /// - public OptionGroup? Parent { get; } + public OptionGroup? Parent { get; } = parent; /// /// A localizable resource description string for the option group. /// - public string Description { get; } + public string Description { get; } = description; /// /// Name of the option group /// - public string Name { get; } + public string Name { get; } = name; /// /// Relative priority of the option group with respect to other option groups within the same feature. /// - public int Priority { get; } + public int Priority { get; } = priority; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PublicOptionFactory.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PublicOptionFactory.cs index 170fdd0d2d5df..920bc71a34801 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PublicOptionFactory.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PublicOptionFactory.cs @@ -37,23 +37,13 @@ public static PerLanguageOption2> WithPublicOption(this P #pragma warning restore #else #pragma warning disable RS0030 // Do not used banned APIs: Option, PerLanguageOption - private sealed class StorageMapping : OptionStorageMapping + private sealed class StorageMapping(IOption2 internalOption, Func toPublicValue, Func toInternalValue) : OptionStorageMapping(internalOption) { - private readonly Func _toPublicValue; - private readonly Func _toInternalValue; - - public StorageMapping(IOption2 internalOption, Func toPublicValue, Func toInternalValue) - : base(internalOption) - { - _toPublicValue = toPublicValue; - _toInternalValue = toInternalValue; - } - public override object? ToPublicOptionValue(object? internalValue) - => _toPublicValue(internalValue); + => toPublicValue(internalValue); public override object? UpdateInternalOptionValue(object? currentInternalValue, object? newPublicValue) - => _toInternalValue(newPublicValue); + => toInternalValue(newPublicValue); } private static OptionDefinition ToPublicOptionDefinition(this OptionDefinition definition, IOption2 internalOption, Func toPublicValue, Func toInternalValue) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ExternalSourceInfo.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ExternalSourceInfo.cs index ed9952eed6a42..2901b52459e8a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ExternalSourceInfo.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ExternalSourceInfo.cs @@ -6,15 +6,9 @@ namespace Microsoft.CodeAnalysis.LanguageService { - internal readonly struct ExternalSourceInfo + internal readonly struct ExternalSourceInfo(int? startLine, bool ends) { - public readonly int? StartLine; - public readonly bool Ends; - - public ExternalSourceInfo(int? startLine, bool ends) - { - this.StartLine = startLine; - this.Ends = ends; - } + public readonly int? StartLine = startLine; + public readonly bool Ends = ends; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.ComparisonOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.ComparisonOptions.cs index df85fe3fd88dd..30a02677953cf 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.ComparisonOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.ComparisonOptions.cs @@ -8,7 +8,7 @@ namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { - private readonly struct ComparisonOptions + private readonly struct ComparisonOptions(bool ignoreCase, bool ignoreAssemblyKeys) { [Flags] private enum Option : byte @@ -18,14 +18,9 @@ private enum Option : byte IgnoreAssemblyKeys = 0x2, } - private readonly Option _flags; - - public ComparisonOptions(bool ignoreCase, bool ignoreAssemblyKeys) - { - _flags = + private readonly Option _flags = BoolToOption(ignoreCase, Option.IgnoreCase) | BoolToOption(ignoreAssemblyKeys, Option.IgnoreAssemblyKeys); - } public bool IgnoreCase => (_flags & Option.IgnoreCase) == Option.IgnoreCase; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.SymbolKeyReader.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.SymbolKeyReader.cs index 1826bd1cfed1f..e8de3a3151e00 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.SymbolKeyReader.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.SymbolKeyReader.cs @@ -438,34 +438,16 @@ private void PopContextualSymbol(ISymbol? contextualSymbol) public ISymbol? CurrentContextualSymbol => _contextualSymbolStack.Count == 0 ? null : _contextualSymbolStack.Peek(); - public readonly ref struct MethodPopper + public readonly ref struct MethodPopper(SymbolKeyReader reader, IMethodSymbol? method) { - private readonly SymbolKeyReader _reader; - private readonly IMethodSymbol? _method; - - public MethodPopper(SymbolKeyReader reader, IMethodSymbol? method) - { - _reader = reader; - _method = method; - } - public void Dispose() - => _reader.PopMethod(_method); + => reader.PopMethod(method); } - public readonly ref struct ContextualSymbolPopper + public readonly ref struct ContextualSymbolPopper(SymbolKeyReader reader, ISymbol? contextualSymbol) { - private readonly SymbolKeyReader _reader; - private readonly ISymbol? _contextualSymbol; - - public ContextualSymbolPopper(SymbolKeyReader reader, ISymbol? contextualSymbol) - { - _reader = reader; - _contextualSymbol = contextualSymbol; - } - public void Dispose() - => _reader.PopContextualSymbol(_contextualSymbol); + => reader.PopContextualSymbol(contextualSymbol); } internal SyntaxTree? GetSyntaxTree(string filePath) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.cs index 2590702ff28c1..8c9156344405c 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/SymbolKey/SymbolKey.cs @@ -107,7 +107,7 @@ namespace Microsoft.CodeAnalysis /// /// [DataContract] - internal partial struct SymbolKey : IEquatable + internal partial struct SymbolKey(string data) : IEquatable { /// /// Current format version. Any time we change anything about our format, we should @@ -118,15 +118,7 @@ internal partial struct SymbolKey : IEquatable internal const int FormatVersion = 5; [DataMember(Order = 0)] - private readonly string _symbolKeyData; - - /// - /// Constructs a new using the result of a previous call to - /// from this same session. Instantiating with a string - /// from any other source is not supported. - /// - public SymbolKey(string data) - => _symbolKeyData = data ?? throw new ArgumentNullException(nameof(data)); + private readonly string _symbolKeyData = data ?? throw new ArgumentNullException(nameof(data)); /// /// Constructs a new representing the provided . diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AbstractSpeculationAnalyzer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AbstractSpeculationAnalyzer.cs index 7408d65fdfc4e..cc2dce4714fd0 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AbstractSpeculationAnalyzer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AbstractSpeculationAnalyzer.cs @@ -24,6 +24,21 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities /// It uses the original tree's semantic model to create a speculative semantic model and verifies that /// the syntax replacement doesn't break the semantics of any parenting nodes of the original expression. /// + /// + /// Creates a semantic analyzer for speculative syntax replacement. + /// + /// Original expression to be replaced. + /// New expression to replace the original expression. + /// Semantic model of node's syntax tree. + /// Cancellation token. + /// + /// True if semantic analysis should be skipped for the replaced node and performed starting from parent of the original and replaced nodes. + /// This could be the case when custom verifications are required to be done by the caller or + /// semantics of the replaced expression are different from the original expression. + /// + /// + /// True if semantic analysis should fail when any of the invocation expression ancestors of in original code has overload resolution failures. + /// internal abstract class AbstractSpeculationAnalyzer< TExpressionSyntax, TTypeSyntax, @@ -32,7 +47,13 @@ internal abstract class AbstractSpeculationAnalyzer< TForEachStatementSyntax, TThrowStatementSyntax, TInvocationExpressionSyntax, - TConversion> : ISpeculationAnalyzer + TConversion>( + TExpressionSyntax expression, + TExpressionSyntax newExpression, + SemanticModel semanticModel, + CancellationToken cancellationToken, + bool skipVerificationForReplacedNode = false, + bool failOnOverloadResolutionFailuresInOriginalCode = false) : ISpeculationAnalyzer where TExpressionSyntax : SyntaxNode where TTypeSyntax : TExpressionSyntax where TAttributeSyntax : SyntaxNode @@ -42,54 +63,12 @@ internal abstract class AbstractSpeculationAnalyzer< where TInvocationExpressionSyntax : TExpressionSyntax where TConversion : struct { - private readonly TExpressionSyntax _expression; - private readonly TExpressionSyntax _newExpressionForReplace; - private readonly SemanticModel _semanticModel; - private readonly CancellationToken _cancellationToken; - private readonly bool _skipVerificationForReplacedNode; - private readonly bool _failOnOverloadResolutionFailuresInOriginalCode; - private readonly bool _isNewSemanticModelSpeculativeModel; - - private SyntaxNode? _lazySemanticRootOfOriginalExpression; - private TExpressionSyntax? _lazyReplacedExpression; - private SyntaxNode? _lazySemanticRootOfReplacedExpression; - private SemanticModel? _lazySpeculativeSemanticModel; + private readonly bool _isNewSemanticModelSpeculativeModel = true; - /// - /// Creates a semantic analyzer for speculative syntax replacement. - /// - /// Original expression to be replaced. - /// New expression to replace the original expression. - /// Semantic model of node's syntax tree. - /// Cancellation token. - /// - /// True if semantic analysis should be skipped for the replaced node and performed starting from parent of the original and replaced nodes. - /// This could be the case when custom verifications are required to be done by the caller or - /// semantics of the replaced expression are different from the original expression. - /// - /// - /// True if semantic analysis should fail when any of the invocation expression ancestors of in original code has overload resolution failures. - /// - public AbstractSpeculationAnalyzer( - TExpressionSyntax expression, - TExpressionSyntax newExpression, - SemanticModel semanticModel, - CancellationToken cancellationToken, - bool skipVerificationForReplacedNode = false, - bool failOnOverloadResolutionFailuresInOriginalCode = false) - { - _expression = expression; - _newExpressionForReplace = newExpression; - _semanticModel = semanticModel; - _cancellationToken = cancellationToken; - _skipVerificationForReplacedNode = skipVerificationForReplacedNode; - _failOnOverloadResolutionFailuresInOriginalCode = failOnOverloadResolutionFailuresInOriginalCode; - _isNewSemanticModelSpeculativeModel = true; - _lazyReplacedExpression = null; - _lazySemanticRootOfOriginalExpression = null; - _lazySemanticRootOfReplacedExpression = null; - _lazySpeculativeSemanticModel = null; - } + private SyntaxNode? _lazySemanticRootOfOriginalExpression = null; + private TExpressionSyntax? _lazyReplacedExpression = null; + private SyntaxNode? _lazySemanticRootOfReplacedExpression = null; + private SemanticModel? _lazySpeculativeSemanticModel = null; protected abstract ISyntaxFacts SyntaxFactsService { get; } protected abstract bool CanAccessInstanceMemberThrough(TExpressionSyntax? expression); @@ -97,7 +76,7 @@ public AbstractSpeculationAnalyzer( /// /// Original expression to be replaced. /// - public TExpressionSyntax OriginalExpression => _expression; + public TExpressionSyntax OriginalExpression => expression; SyntaxNode ISpeculationAnalyzer.OriginalExpression => OriginalExpression; @@ -123,7 +102,7 @@ public SyntaxNode SemanticRootOfOriginalExpression /// /// Semantic model for the syntax tree corresponding to /// - public SemanticModel OriginalSemanticModel => _semanticModel; + public SemanticModel OriginalSemanticModel => semanticModel; /// /// Node which replaces the . @@ -167,7 +146,7 @@ public SemanticModel SpeculativeSemanticModel } } - public CancellationToken CancellationToken => _cancellationToken; + public CancellationToken CancellationToken => cancellationToken; protected abstract SyntaxNode GetSemanticRootForSpeculation(TExpressionSyntax expression); @@ -183,7 +162,7 @@ private void EnsureReplacedExpressionAndSemanticRoot() // expression in its parent, we annotate it here to allow us to get back to // it after replace. var annotation = new SyntaxAnnotation(); - var annotatedExpression = _newExpressionForReplace.WithAdditionalAnnotations(annotation); + var annotatedExpression = newExpression.WithAdditionalAnnotations(annotation); _lazySemanticRootOfReplacedExpression = GetSemanticRootOfReplacedExpression(this.SemanticRootOfOriginalExpression, annotatedExpression); _lazyReplacedExpression = (TExpressionSyntax)_lazySemanticRootOfReplacedExpression.GetAnnotatedNodesAndTokens(annotation).Single().AsNode()!; } @@ -202,7 +181,7 @@ private void EnsureSpeculativeSemanticModel() if (_lazySpeculativeSemanticModel == null) { var nodeToSpeculate = this.SemanticRootOfReplacedExpression; - _lazySpeculativeSemanticModel = CreateSpeculativeSemanticModel(this.SemanticRootOfOriginalExpression, nodeToSpeculate, _semanticModel); + _lazySpeculativeSemanticModel = CreateSpeculativeSemanticModel(this.SemanticRootOfOriginalExpression, nodeToSpeculate, semanticModel); ValidateSpeculativeSemanticModel(_lazySpeculativeSemanticModel, nodeToSpeculate); } } @@ -468,7 +447,7 @@ public bool ReplacementChangesSemantics() currentOriginalNode: this.OriginalExpression, currentReplacedNode: this.ReplacedExpression, originalRoot: this.SemanticRootOfOriginalExpression, - skipVerificationForCurrentNode: _skipVerificationForReplacedNode); + skipVerificationForCurrentNode: skipVerificationForReplacedNode); } protected abstract bool IsParenthesizedExpression([NotNullWhen(true)] SyntaxNode? node); @@ -623,7 +602,7 @@ private bool MemberAccessesAreCompatible(TExpressionSyntax? originalExpression, // semantics. We could potentially support this, but we'd have to do the analysis the instance invoked // on and the instance passed as the first parameter are identical. - var originalIsStaticAccess = IsStaticAccess(_semanticModel.GetSymbolInfo(originalExpression, CancellationToken).Symbol); + var originalIsStaticAccess = IsStaticAccess(semanticModel.GetSymbolInfo(originalExpression, CancellationToken).Symbol); var replacedIsStaticAccess = IsStaticAccess(this.SpeculativeSemanticModel.GetSymbolInfo(newExpression, CancellationToken).Symbol); if (originalIsStaticAccess != replacedIsStaticAccess) return false; @@ -724,16 +703,16 @@ private bool ReplacementBreaksForEachStatement(TForEachStatementSyntax forEachSt { var forEachExpression = GetForEachStatementExpression(forEachStatement); if (forEachExpression.IsMissing || - !forEachExpression.Span.Contains(_expression.SpanStart)) + !forEachExpression.Span.Contains(expression.SpanStart)) { return false; } // inferred variable type compatible - if (IsForEachTypeInferred(forEachStatement, _semanticModel)) + if (IsForEachTypeInferred(forEachStatement, semanticModel)) { - var local = (ILocalSymbol)_semanticModel.GetRequiredDeclaredSymbol(forEachStatement, _cancellationToken); - var newLocal = (ILocalSymbol)this.SpeculativeSemanticModel.GetRequiredDeclaredSymbol(newForEachStatement, _cancellationToken); + var local = (ILocalSymbol)semanticModel.GetRequiredDeclaredSymbol(forEachStatement, cancellationToken); + var newLocal = (ILocalSymbol)this.SpeculativeSemanticModel.GetRequiredDeclaredSymbol(newForEachStatement, cancellationToken); if (!SymbolsAreCompatible(local.Type, newLocal.Type)) { return true; @@ -777,7 +756,7 @@ private bool ReplacementBreaksForEachGetEnumerator(IMethodSymbol getEnumerator, // GetEnumerator method on a specific type. if (getEnumerator.IsImplementableMember()) { - var expressionType = this.SpeculativeSemanticModel.GetTypeInfo(newForEachStatementExpression, _cancellationToken).ConvertedType; + var expressionType = this.SpeculativeSemanticModel.GetTypeInfo(newForEachStatementExpression, cancellationToken).ConvertedType; if (expressionType != null) { var implementationMember = expressionType.FindImplementationForInterfaceMember(getEnumerator); @@ -820,7 +799,7 @@ private bool ReplacementBreaksTypeResolution(TTypeSyntax type, TTypeSyntax newTy ISymbol? newSymbol; if (useSpeculativeModel) { - newSymbol = this.SpeculativeSemanticModel.GetSymbolInfo(newType, _cancellationToken).Symbol; + newSymbol = this.SpeculativeSemanticModel.GetSymbolInfo(newType, cancellationToken).Symbol; } else { @@ -848,8 +827,8 @@ private static bool IsAnonymousDelegateInvoke(ISymbol symbol) private bool ReplacementBreaksExpression(TExpressionSyntax expression, TExpressionSyntax newExpression) { - var originalSymbolInfo = _semanticModel.GetSymbolInfo(expression); - if (_failOnOverloadResolutionFailuresInOriginalCode && originalSymbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure) + var originalSymbolInfo = semanticModel.GetSymbolInfo(expression); + if (failOnOverloadResolutionFailuresInOriginalCode && originalSymbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure) { return true; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AnnotationTable.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AnnotationTable.cs index c1fe7b3f74a61..b162a803b5414 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AnnotationTable.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AnnotationTable.cs @@ -24,18 +24,13 @@ namespace Roslyn.Utilities /// /// also, note that this table is not thread safe. /// - internal class AnnotationTable where TAnnotation : class + internal class AnnotationTable(string annotationKind) where TAnnotation : class { private int _globalId; private readonly Dictionary _realAnnotationMap = new(); private readonly Dictionary _annotationMap = new(); - private readonly string _annotationKind; - - public AnnotationTable(string annotationKind) - => _annotationKind = annotationKind; - private IEnumerable GetOrCreateRealAnnotations(TAnnotation[] annotations) { foreach (var annotation in annotations) @@ -51,7 +46,7 @@ private SyntaxAnnotation GetOrCreateRealAnnotation(TAnnotation annotation) var id = Interlocked.Increment(ref _globalId); var idString = id.ToString(); - realAnnotation = new SyntaxAnnotation(_annotationKind, idString); + realAnnotation = new SyntaxAnnotation(annotationKind, idString); _annotationMap.Add(idString, annotation); _realAnnotationMap.Add(annotation, realAnnotation); } @@ -114,16 +109,16 @@ private IEnumerable GetAnnotations(IEnumerable re } public IEnumerable GetAnnotations(SyntaxNode node) - => GetAnnotations(node.GetAnnotations(_annotationKind)); + => GetAnnotations(node.GetAnnotations(annotationKind)); public IEnumerable GetAnnotations(SyntaxToken token) - => GetAnnotations(token.GetAnnotations(_annotationKind)); + => GetAnnotations(token.GetAnnotations(annotationKind)); public IEnumerable GetAnnotations(SyntaxTrivia trivia) - => GetAnnotations(trivia.GetAnnotations(_annotationKind)); + => GetAnnotations(trivia.GetAnnotations(annotationKind)); public IEnumerable GetAnnotations(SyntaxNodeOrToken nodeOrToken) - => GetAnnotations(nodeOrToken.GetAnnotations(_annotationKind)); + => GetAnnotations(nodeOrToken.GetAnnotations(annotationKind)); public IEnumerable GetAnnotations(SyntaxNode node) where TSpecificAnnotation : TAnnotation => this.GetAnnotations(node).OfType(); @@ -138,16 +133,16 @@ public IEnumerable GetAnnotations(Synt => this.GetAnnotations(nodeOrToken).OfType(); public bool HasAnnotations(SyntaxNode node) - => node.HasAnnotations(_annotationKind); + => node.HasAnnotations(annotationKind); public bool HasAnnotations(SyntaxToken token) - => token.HasAnnotations(_annotationKind); + => token.HasAnnotations(annotationKind); public bool HasAnnotations(SyntaxTrivia trivia) - => trivia.HasAnnotations(_annotationKind); + => trivia.HasAnnotations(annotationKind); public bool HasAnnotations(SyntaxNodeOrToken nodeOrToken) - => nodeOrToken.HasAnnotations(_annotationKind); + => nodeOrToken.HasAnnotations(annotationKind); public bool HasAnnotations(SyntaxNode node) where TSpecificAnnotation : TAnnotation => this.GetAnnotations(node).OfType().Any(); @@ -174,27 +169,27 @@ public bool HasAnnotation(SyntaxNodeOrToken nodeOrToken, TAnnotation annotation) => nodeOrToken.HasAnnotation(this.GetRealAnnotation(annotation)); public IEnumerable GetAnnotatedNodesAndTokens(SyntaxNode node) - => node.GetAnnotatedNodesAndTokens(_annotationKind); + => node.GetAnnotatedNodesAndTokens(annotationKind); public IEnumerable GetAnnotatedNodes(SyntaxNode node) - => node.GetAnnotatedNodesAndTokens(_annotationKind).Where(nt => nt.IsNode).Select(nt => nt.AsNode()!); + => node.GetAnnotatedNodesAndTokens(annotationKind).Where(nt => nt.IsNode).Select(nt => nt.AsNode()!); public IEnumerable GetAnnotatedTokens(SyntaxNode node) - => node.GetAnnotatedNodesAndTokens(_annotationKind).Where(nt => nt.IsToken).Select(nt => nt.AsToken()); + => node.GetAnnotatedNodesAndTokens(annotationKind).Where(nt => nt.IsToken).Select(nt => nt.AsToken()); public IEnumerable GetAnnotatedTrivia(SyntaxNode node) - => node.GetAnnotatedTrivia(_annotationKind); + => node.GetAnnotatedTrivia(annotationKind); public IEnumerable GetAnnotatedNodesAndTokens(SyntaxNode node) where TSpecificAnnotation : TAnnotation - => node.GetAnnotatedNodesAndTokens(_annotationKind).Where(this.HasAnnotations); + => node.GetAnnotatedNodesAndTokens(annotationKind).Where(this.HasAnnotations); public IEnumerable GetAnnotatedNodes(SyntaxNode node) where TSpecificAnnotation : TAnnotation - => node.GetAnnotatedNodesAndTokens(_annotationKind).Where(nt => nt.IsNode && this.HasAnnotations(nt)).Select(nt => nt.AsNode()!); + => node.GetAnnotatedNodesAndTokens(annotationKind).Where(nt => nt.IsNode && this.HasAnnotations(nt)).Select(nt => nt.AsNode()!); public IEnumerable GetAnnotatedTokens(SyntaxNode node) where TSpecificAnnotation : TAnnotation - => node.GetAnnotatedNodesAndTokens(_annotationKind).Where(nt => nt.IsToken && this.HasAnnotations(nt)).Select(nt => nt.AsToken()); + => node.GetAnnotatedNodesAndTokens(annotationKind).Where(nt => nt.IsToken && this.HasAnnotations(nt)).Select(nt => nt.AsToken()); public IEnumerable GetAnnotatedTrivia(SyntaxNode node) where TSpecificAnnotation : TAnnotation - => node.GetAnnotatedTrivia(_annotationKind).Where(this.HasAnnotations); + => node.GetAnnotatedTrivia(annotationKind).Where(this.HasAnnotations); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy`1.cs index 73371861e1f11..d3815d5adbb04 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy`1.cs @@ -130,16 +130,11 @@ private WaitThatValidatesInvariants TakeLock(CancellationToken cancellationToken return new WaitThatValidatesInvariants(this); } - private readonly struct WaitThatValidatesInvariants : IDisposable + private readonly struct WaitThatValidatesInvariants(AsyncLazy asyncLazy) : IDisposable { - private readonly AsyncLazy _asyncLazy; - - public WaitThatValidatesInvariants(AsyncLazy asyncLazy) - => _asyncLazy = asyncLazy; - public void Dispose() { - _asyncLazy.AssertInvariants_NoLock(); + asyncLazy.AssertInvariants_NoLock(); s_gate.Release(); } } @@ -367,16 +362,10 @@ private AsynchronousComputationToStart RegisterAsynchronousComputation_NoLock() return new AsynchronousComputationToStart(_asynchronousComputeFunction, _asynchronousComputationCancellationSource); } - private readonly struct AsynchronousComputationToStart + private readonly struct AsynchronousComputationToStart(Func> asynchronousComputeFunction, CancellationTokenSource cancellationTokenSource) { - public readonly Func> AsynchronousComputeFunction; - public readonly CancellationTokenSource CancellationTokenSource; - - public AsynchronousComputationToStart(Func> asynchronousComputeFunction, CancellationTokenSource cancellationTokenSource) - { - AsynchronousComputeFunction = asynchronousComputeFunction; - CancellationTokenSource = cancellationTokenSource; - } + public readonly Func> AsynchronousComputeFunction = asynchronousComputeFunction; + public readonly CancellationTokenSource CancellationTokenSource = cancellationTokenSource; } private void StartAsynchronousComputation(AsynchronousComputationToStart computationToStart, Request? requestToCompleteSynchronously, CancellationToken callerCancellationToken) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Builder.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Builder.cs index 63c7053500e93..5fdbfb7aa2b35 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Builder.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Builder.cs @@ -283,14 +283,11 @@ private bool TryGetChildIndex(BuilderNode currentNode, int currentNodeIndex, int return false; } - private struct BuilderNode + private struct BuilderNode(TextSpan characterSpan) { - public readonly TextSpan CharacterSpan; + public readonly TextSpan CharacterSpan = characterSpan; public int EdgeCount; public Dictionary? SpilloverEdges; - - public BuilderNode(TextSpan characterSpan) - => this.CharacterSpan = characterSpan; } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Edge.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Edge.cs index c385a3d85fccc..07692d5432316 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Edge.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Edge.cs @@ -6,20 +6,14 @@ namespace Roslyn.Utilities { internal readonly partial struct BKTree { - private readonly struct Edge + private readonly struct Edge(int editDistance, int childNodeIndex) { // The edit distance between the child and parent connected by this edge. // The child can be found in _nodes at ChildNodeIndex. - public readonly int EditDistance; + public readonly int EditDistance = editDistance; /// Where the child node can be found in . - public readonly int ChildNodeIndex; - - public Edge(int editDistance, int childNodeIndex) - { - EditDistance = editDistance; - ChildNodeIndex = childNodeIndex; - } + public readonly int ChildNodeIndex = childNodeIndex; internal void WriteTo(ObjectWriter writer) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Node.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Node.cs index 26cbd119eb5fc..d74f9ee0326db 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Node.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Node.cs @@ -8,28 +8,21 @@ namespace Roslyn.Utilities { internal readonly partial struct BKTree { - private readonly struct Node + private readonly struct Node(TextSpan wordSpan, int edgeCount, int firstEdgeIndex) { /// /// The string this node corresponds to. Specifically, this span is the range of /// for that string. /// - public readonly TextSpan WordSpan; + public readonly TextSpan WordSpan = wordSpan; ///How many child edges this node has. - public readonly int EdgeCount; + public readonly int EdgeCount = edgeCount; ///Where the first edge can be found in . The edges ///are in the range _edges[FirstEdgeIndex, FirstEdgeIndex + EdgeCount) /// - public readonly int FirstEdgeIndex; - - public Node(TextSpan wordSpan, int edgeCount, int firstEdgeIndex) - { - WordSpan = wordSpan; - EdgeCount = edgeCount; - FirstEdgeIndex = firstEdgeIndex; - } + public readonly int FirstEdgeIndex = firstEdgeIndex; internal void WriteTo(ObjectWriter writer) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ConcatImmutableArray`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ConcatImmutableArray`1.cs index 75f845cda7d7f..57b0f338f1291 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ConcatImmutableArray`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ConcatImmutableArray`1.cs @@ -11,27 +11,18 @@ namespace Roslyn.Utilities { - internal readonly struct ConcatImmutableArray : IEnumerable + internal readonly struct ConcatImmutableArray(ImmutableArray first, ImmutableArray second) : IEnumerable { - private readonly ImmutableArray _first; - private readonly ImmutableArray _second; - - public ConcatImmutableArray(ImmutableArray first, ImmutableArray second) - { - _first = first; - _second = second; - } - - public int Length => _first.Length + _second.Length; + public int Length => first.Length + second.Length; public bool Any(Func predicate) - => _first.Any(predicate) || _second.Any(predicate); + => first.Any(predicate) || second.Any(predicate); public Enumerator GetEnumerator() - => new(_first, _second); + => new(first, second); public ImmutableArray ToImmutableArray() - => _first.NullToEmpty().AddRange(_second.NullToEmpty()); + => first.NullToEmpty().AddRange(second.NullToEmpty()); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); @@ -39,16 +30,10 @@ IEnumerator IEnumerable.GetEnumerator() IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public struct Enumerator : IEnumerator + public struct Enumerator(ImmutableArray first, ImmutableArray second) : IEnumerator { - private ImmutableArray.Enumerator _current; - private ImmutableArray _next; - - public Enumerator(ImmutableArray first, ImmutableArray second) - { - _current = first.NullToEmpty().GetEnumerator(); - _next = second.NullToEmpty(); - } + private ImmutableArray.Enumerator _current = first.NullToEmpty().GetEnumerator(); + private ImmutableArray _next = second.NullToEmpty(); public T Current => _current.Current; object? IEnumerator.Current => Current; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EditDistance.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EditDistance.cs index bf76ac5bd6d95..f62f215e9f7ce 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EditDistance.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EditDistance.cs @@ -28,7 +28,7 @@ namespace Roslyn.Utilities /// Specifically, this implementation satisfies the following inequality: D(x, y) + D(y, z) >= D(x, z) /// (where D is the edit distance). /// - internal readonly struct EditDistance : IDisposable + internal readonly struct EditDistance(string text) : IDisposable { // Our edit distance algorithm makes use of an 'infinite' value. A value so high that it // could never participate in an edit distance (and effectively means the path through it @@ -45,14 +45,8 @@ namespace Roslyn.Utilities public const int BeyondThreshold = int.MaxValue; - private readonly string _source; - private readonly char[] _sourceLowerCaseCharacters; - - public EditDistance(string text) - { - _source = text ?? throw new ArgumentNullException(nameof(text)); - _sourceLowerCaseCharacters = ConvertToLowercaseArray(text); - } + private readonly string _source = text ?? throw new ArgumentNullException(nameof(text)); + private readonly char[] _sourceLowerCaseCharacters = ConvertToLowercaseArray(text); private static char[] ConvertToLowercaseArray(string text) { @@ -607,14 +601,10 @@ private static void SetValue(int[,] matrix, int i, int j, int val) } } - internal class SimplePool where T : class + internal class SimplePool(Func allocate) where T : class { private readonly object _gate = new(); private readonly Stack _values = new(); - private readonly Func _allocate; - - public SimplePool(Func allocate) - => _allocate = allocate; public T Allocate() { @@ -625,7 +615,7 @@ public T Allocate() return _values.Pop(); } - return _allocate(); + return allocate(); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EventMap.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EventMap.cs index 78f87cd91db26..6d13ecabff2c9 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EventMap.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EventMap.cs @@ -94,13 +94,10 @@ private void SetRegistries_NoLock(string eventName, ImmutableArra _eventNameToRegistries[eventName] = registries; } - internal class Registry : IEquatable?> + internal class Registry(TEventHandler handler) : IEquatable?> where TEventHandler : class { - private TEventHandler? _handler; - - public Registry(TEventHandler handler) - => _handler = handler; + private TEventHandler? _handler = handler; public void Unregister() => _handler = null; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/IReadOnlyListExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/IReadOnlyListExtensions.cs index e4cdba9b8f338..44e81cbfc1094 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/IReadOnlyListExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/IReadOnlyListExtensions.cs @@ -35,17 +35,12 @@ public static int IndexOf(this IReadOnlyList list, T value, int startIndex return -1; } - private class ReadOnlyList : IReadOnlyList + private class ReadOnlyList(IList list) : IReadOnlyList { - private readonly IList _list; - - public ReadOnlyList(IList list) - => _list = list; - - public T this[int index] => _list[index]; - public int Count => _list.Count; - public IEnumerator GetEnumerator() => _list.GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator(); + public T this[int index] => list[index]; + public int Count => list.Count; + public IEnumerator GetEnumerator() => list.GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => list.GetEnumerator(); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.ChoiceMatcher.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.ChoiceMatcher.cs index 94aa3026b1f68..eacbbbc1d94c6 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.ChoiceMatcher.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.ChoiceMatcher.cs @@ -8,17 +8,12 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class Matcher { - private class ChoiceMatcher : Matcher + private class ChoiceMatcher(params Matcher[] matchers) : Matcher { - private readonly IEnumerable> _matchers; - - public ChoiceMatcher(params Matcher[] matchers) - => _matchers = matchers; - public override bool TryMatch(IList sequence, ref int index) { // we can't use .Any() here because ref parameters can't be used in lambdas - foreach (var matcher in _matchers) + foreach (var matcher in matchers) { if (matcher.TryMatch(sequence, ref index)) { @@ -30,7 +25,7 @@ public override bool TryMatch(IList sequence, ref int index) } public override string ToString() - => $"({string.Join("|", _matchers)})"; + => $"({string.Join("|", matchers)})"; } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.RepeatMatcher.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.RepeatMatcher.cs index 40ee33ae80857..d8078f49a60b7 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.RepeatMatcher.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.RepeatMatcher.cs @@ -8,16 +8,11 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class Matcher { - private class RepeatMatcher : Matcher + private class RepeatMatcher(Matcher matcher) : Matcher { - private readonly Matcher _matcher; - - public RepeatMatcher(Matcher matcher) - => _matcher = matcher; - public override bool TryMatch(IList sequence, ref int index) { - while (_matcher.TryMatch(sequence, ref index)) + while (matcher.TryMatch(sequence, ref index)) { } @@ -25,7 +20,7 @@ public override bool TryMatch(IList sequence, ref int index) } public override string ToString() - => string.Format("({0}*)", _matcher); + => string.Format("({0}*)", matcher); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.SequenceMatcher.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.SequenceMatcher.cs index 2019979daf83b..7574ecc562bdd 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.SequenceMatcher.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.SequenceMatcher.cs @@ -8,17 +8,12 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class Matcher { - private class SequenceMatcher : Matcher + private class SequenceMatcher(params Matcher[] matchers) : Matcher { - private readonly Matcher[] _matchers; - - public SequenceMatcher(params Matcher[] matchers) - => _matchers = matchers; - public override bool TryMatch(IList sequence, ref int index) { var currentIndex = index; - foreach (var matcher in _matchers) + foreach (var matcher in matchers) { if (!matcher.TryMatch(sequence, ref currentIndex)) { @@ -31,7 +26,7 @@ public override bool TryMatch(IList sequence, ref int index) } public override string ToString() - => string.Format("({0})", string.Join(",", (object[])_matchers)); + => string.Format("({0})", string.Join(",", (object[])matchers)); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.SingleMatcher.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.SingleMatcher.cs index 5706b1ab296b4..4d98a1540839a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.SingleMatcher.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.SingleMatcher.cs @@ -9,20 +9,11 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class Matcher { - private class SingleMatcher : Matcher + private class SingleMatcher(Func predicate, string description) : Matcher { - private readonly Func _predicate; - private readonly string _description; - - public SingleMatcher(Func predicate, string description) - { - _predicate = predicate; - _description = description; - } - public override bool TryMatch(IList sequence, ref int index) { - if (index < sequence.Count && _predicate(sequence[index])) + if (index < sequence.Count && predicate(sequence[index])) { index++; return true; @@ -32,7 +23,7 @@ public override bool TryMatch(IList sequence, ref int index) } public override string ToString() - => _description; + => description; } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/NonReentrantLock.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/NonReentrantLock.cs index e7a97bdf33724..95d8ecf2f733d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/NonReentrantLock.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/NonReentrantLock.cs @@ -240,15 +240,10 @@ public SemaphoreDisposer DisposableWait(CancellationToken cancellationToken = de /// /// Since we want to avoid boxing the return from , this type must be public. /// - public readonly struct SemaphoreDisposer : IDisposable + public readonly struct SemaphoreDisposer(NonReentrantLock semaphore) : IDisposable { - private readonly NonReentrantLock _semaphore; - - public SemaphoreDisposer(NonReentrantLock semaphore) - => _semaphore = semaphore; - public void Dispose() - => _semaphore.Release(); + => semaphore.Release(); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs index 7ddb2f5fdb583..72b47d877d620 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposable.cs @@ -306,7 +306,7 @@ public WeakReference(ReferenceCountedDisposable reference) /// /// Holds the reference count associated with a disposable object. /// - private sealed class BoxedReferenceCount + private sealed class BoxedReferenceCount(int referenceCount) { /// /// Holds the weak reference used by instances of to obtain a reference-counted @@ -319,12 +319,7 @@ private sealed class BoxedReferenceCount [DisallowNull] public WeakReference? _weakInstance; - public int _referenceCount; - - public BoxedReferenceCount(int referenceCount) - { - _referenceCount = referenceCount; - } + public int _referenceCount = referenceCount; } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposableCache.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposableCache.cs index cd86b1d66a3e5..64ebb559837dc 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposableCache.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ReferenceCountedDisposableCache.cs @@ -57,25 +57,17 @@ public void Evict(TKey key) } } - private sealed class Entry : IDisposable, ICacheEntry + private sealed class Entry(ReferenceCountedDisposableCache cache, TKey key, TValue value) : IDisposable, ICacheEntry { - private readonly ReferenceCountedDisposableCache _cache; - public TKey Key { get; } - public TValue Value { get; } - - public Entry(ReferenceCountedDisposableCache cache, TKey key, TValue value) - { - _cache = cache; - Key = key; - Value = value; - } + public TKey Key { get; } = key; + public TValue Value { get; } = value; public void Dispose() { // Evict us out of the cache. We already know that cache entry is going to be expired: any further calls on the WeakReference would give nothing, // but we don't want to be holding onto the key either. - _cache.Evict(Key); + cache.Evict(Key); // Dispose the underlying value Value.Dispose(); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/RestrictedInternalsVisibleToAttribute.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/RestrictedInternalsVisibleToAttribute.cs index 4ac623c3e3e68..dd04d5c364120 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/RestrictedInternalsVisibleToAttribute.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/RestrictedInternalsVisibleToAttribute.cs @@ -7,15 +7,9 @@ namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - internal sealed class RestrictedInternalsVisibleToAttribute : Attribute + internal sealed class RestrictedInternalsVisibleToAttribute(string assemblyName, params string[] allowedNamespaces) : Attribute { - public RestrictedInternalsVisibleToAttribute(string assemblyName, params string[] allowedNamespaces) - { - AssemblyName = assemblyName; - AllowedNamespaces = allowedNamespaces.ToImmutableArray(); - } - - public string AssemblyName { get; } - public ImmutableArray AllowedNamespaces { get; } + public string AssemblyName { get; } = assemblyName; + public ImmutableArray AllowedNamespaces { get; } = allowedNamespaces.ToImmutableArray(); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SerializableBytes.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SerializableBytes.cs index ea9c2543f13f6..c2b3f4e937a53 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SerializableBytes.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SerializableBytes.cs @@ -291,13 +291,8 @@ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); } - private class ReadStream : PooledStream + private class ReadStream(long length, byte[][] chunks) : PooledStream(length, new List(chunks)) { - public ReadStream(long length, byte[][] chunks) - : base(length, new List(chunks)) - { - - } } private class ReadWriteStream : PooledStream diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.EquivalenceVisitor.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.EquivalenceVisitor.cs index a97aabca44428..5fa1f53a92e95 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.EquivalenceVisitor.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.EquivalenceVisitor.cs @@ -15,21 +15,11 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class SymbolEquivalenceComparer { - private class EquivalenceVisitor + private class EquivalenceVisitor( + SymbolEquivalenceComparer symbolEquivalenceComparer, + bool compareMethodTypeParametersByIndex, + bool objectAndDynamicCompareEqually) { - private readonly bool _compareMethodTypeParametersByIndex; - private readonly bool _objectAndDynamicCompareEqually; - private readonly SymbolEquivalenceComparer _symbolEquivalenceComparer; - - public EquivalenceVisitor( - SymbolEquivalenceComparer symbolEquivalenceComparer, - bool compareMethodTypeParametersByIndex, - bool objectAndDynamicCompareEqually) - { - _symbolEquivalenceComparer = symbolEquivalenceComparer; - _compareMethodTypeParametersByIndex = compareMethodTypeParametersByIndex; - _objectAndDynamicCompareEqually = objectAndDynamicCompareEqually; - } #if TRACKDEPTH private int depth = 0; @@ -65,7 +55,7 @@ public bool AreEquivalent(ISymbol? x, ISymbol? y, Dictionary x, ImmutableArray _symbolEquivalenceComparer._ignoreNullableAnnotations || x.NullableAnnotation == y.NullableAnnotation; + => symbolEquivalenceComparer._ignoreNullableAnnotations || x.NullableAnnotation == y.NullableAnnotation; private bool AreEquivalentWorker(ISymbol x, ISymbol y, SymbolKind k, Dictionary? equivalentTypesWithDifferingAssemblies) { @@ -148,7 +138,7 @@ private bool ArrayTypesAreEquivalent(IArrayTypeSymbol x, IArrayTypeSymbol y, Dic } private bool AssembliesAreEquivalent(IAssemblySymbol x, IAssemblySymbol y) - => _symbolEquivalenceComparer._assemblyComparerOpt?.Equals(x, y) ?? true; + => symbolEquivalenceComparer._assemblyComparerOpt?.Equals(x, y) ?? true; private bool FieldsAreEquivalent(IFieldSymbol x, IFieldSymbol y, Dictionary? equivalentTypesWithDifferingAssemblies) { @@ -413,7 +403,7 @@ private bool HandleTupleTypes(INamedTypeSymbol x, INamedTypeSymbol y, Dictionary return false; // Check names first if necessary. - if (_symbolEquivalenceComparer._tupleNamesMustMatch) + if (symbolEquivalenceComparer._tupleNamesMustMatch) { for (var i = 0; i < xElements.Length; i++) { @@ -461,7 +451,7 @@ private bool ParametersAreEquivalent( for (var i = 0; i < count; i++) { - if (!_symbolEquivalenceComparer.ParameterEquivalenceComparer.Equals(xParameters[i], yParameters[i], equivalentTypesWithDifferingAssemblies, compareParameterName, isParameterNameCaseSensitive)) + if (!symbolEquivalenceComparer.ParameterEquivalenceComparer.Equals(xParameters[i], yParameters[i], equivalentTypesWithDifferingAssemblies, compareParameterName, isParameterNameCaseSensitive)) { return false; } @@ -472,7 +462,7 @@ private bool ParametersAreEquivalent( internal bool ReturnTypesAreEquivalent(IMethodSymbol x, IMethodSymbol y, Dictionary? equivalentTypesWithDifferingAssemblies = null) { - return _symbolEquivalenceComparer.SignatureTypeEquivalenceComparer.Equals(x.ReturnType, y.ReturnType, equivalentTypesWithDifferingAssemblies) && + return symbolEquivalenceComparer.SignatureTypeEquivalenceComparer.Equals(x.ReturnType, y.ReturnType, equivalentTypesWithDifferingAssemblies) && AreEquivalent(x.ReturnTypeCustomModifiers, y.ReturnTypeCustomModifiers, equivalentTypesWithDifferingAssemblies); } @@ -539,7 +529,7 @@ private bool NamespacesAreEquivalent(INamespaceSymbol x, INamespaceSymbol y, Dic return false; } - if (x.IsGlobalNamespace && _symbolEquivalenceComparer._assemblyComparerOpt == null) + if (x.IsGlobalNamespace && symbolEquivalenceComparer._assemblyComparerOpt == null) { // No need to compare the containers of global namespace when assembly identities are ignored. return true; @@ -617,7 +607,7 @@ private bool TypeParametersAreEquivalent(ITypeParameterSymbol x, ITypeParameterS // If this is a method type parameter, and we are in 'non-recurse' mode (because // we're comparing method parameters), then we're done at this point. The types are // equal. - if (x.TypeParameterKind == TypeParameterKind.Method && _compareMethodTypeParametersByIndex) + if (x.TypeParameterKind == TypeParameterKind.Method && compareMethodTypeParametersByIndex) { return true; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.ParameterSymbolEqualityComparer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.ParameterSymbolEqualityComparer.cs index 709cd723dec3c..6028cd1dd9666 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.ParameterSymbolEqualityComparer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.ParameterSymbolEqualityComparer.cs @@ -11,19 +11,10 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class SymbolEquivalenceComparer { - internal class ParameterSymbolEqualityComparer : IEqualityComparer + internal class ParameterSymbolEqualityComparer( + SymbolEquivalenceComparer symbolEqualityComparer, + bool distinguishRefFromOut) : IEqualityComparer { - private readonly SymbolEquivalenceComparer _symbolEqualityComparer; - private readonly bool _distinguishRefFromOut; - - public ParameterSymbolEqualityComparer( - SymbolEquivalenceComparer symbolEqualityComparer, - bool distinguishRefFromOut) - { - _symbolEqualityComparer = symbolEqualityComparer; - _distinguishRefFromOut = distinguishRefFromOut; - } - public bool Equals( IParameterSymbol? x, IParameterSymbol? y, @@ -53,10 +44,10 @@ public bool Equals( // equality, then we want to consider method type parameters by index only. return - AreRefKindsEquivalent(x.RefKind, y.RefKind, _distinguishRefFromOut) && + AreRefKindsEquivalent(x.RefKind, y.RefKind, distinguishRefFromOut) && nameComparisonCheck && - _symbolEqualityComparer.GetEquivalenceVisitor().AreEquivalent(x.CustomModifiers, y.CustomModifiers, equivalentTypesWithDifferingAssemblies) && - _symbolEqualityComparer.SignatureTypeEquivalenceComparer.Equals(x.Type, y.Type, equivalentTypesWithDifferingAssemblies); + symbolEqualityComparer.GetEquivalenceVisitor().AreEquivalent(x.CustomModifiers, y.CustomModifiers, equivalentTypesWithDifferingAssemblies) && + symbolEqualityComparer.SignatureTypeEquivalenceComparer.Equals(x.Type, y.Type, equivalentTypesWithDifferingAssemblies); } public bool Equals(IParameterSymbol? x, IParameterSymbol? y) @@ -74,7 +65,7 @@ public int GetHashCode(IParameterSymbol? x) return Hash.Combine(x.IsRefOrOut(), - _symbolEqualityComparer.SignatureTypeEquivalenceComparer.GetHashCode(x.Type)); + symbolEqualityComparer.SignatureTypeEquivalenceComparer.GetHashCode(x.Type)); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.SignatureTypeSymbolEquivalenceComparer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.SignatureTypeSymbolEquivalenceComparer.cs index c3fbf019e7f42..cfab690699e04 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.SignatureTypeSymbolEquivalenceComparer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.SignatureTypeSymbolEquivalenceComparer.cs @@ -8,21 +8,16 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class SymbolEquivalenceComparer { - internal class SignatureTypeSymbolEquivalenceComparer : IEqualityComparer + internal class SignatureTypeSymbolEquivalenceComparer(SymbolEquivalenceComparer symbolEquivalenceComparer) : IEqualityComparer { - private readonly SymbolEquivalenceComparer _symbolEquivalenceComparer; - - public SignatureTypeSymbolEquivalenceComparer(SymbolEquivalenceComparer symbolEquivalenceComparer) - => _symbolEquivalenceComparer = symbolEquivalenceComparer; - public bool Equals(ITypeSymbol? x, ITypeSymbol? y) => this.Equals(x, y, null); public bool Equals(ITypeSymbol? x, ITypeSymbol? y, Dictionary? equivalentTypesWithDifferingAssemblies) - => _symbolEquivalenceComparer.GetEquivalenceVisitor(compareMethodTypeParametersByIndex: true, objectAndDynamicCompareEqually: true).AreEquivalent(x, y, equivalentTypesWithDifferingAssemblies); + => symbolEquivalenceComparer.GetEquivalenceVisitor(compareMethodTypeParametersByIndex: true, objectAndDynamicCompareEqually: true).AreEquivalent(x, y, equivalentTypesWithDifferingAssemblies); public int GetHashCode(ITypeSymbol? x) - => _symbolEquivalenceComparer.GetGetHashCodeVisitor(compareMethodTypeParametersByIndex: true, objectAndDynamicCompareEqually: true).GetHashCode(x, currentHash: 0); + => symbolEquivalenceComparer.GetGetHashCodeVisitor(compareMethodTypeParametersByIndex: true, objectAndDynamicCompareEqually: true).GetHashCode(x, currentHash: 0); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/WordSimilarityChecker.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/WordSimilarityChecker.cs index 3f2edd035f2d9..9a75f7906af0e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/WordSimilarityChecker.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/WordSimilarityChecker.cs @@ -9,18 +9,11 @@ namespace Roslyn.Utilities { internal struct WordSimilarityChecker : IDisposable { - private readonly struct CacheResult + private readonly struct CacheResult(string candidate, bool areSimilar, double similarityWeight) { - public readonly string CandidateText; - public readonly bool AreSimilar; - public readonly double SimilarityWeight; - - public CacheResult(string candidate, bool areSimilar, double similarityWeight) - { - CandidateText = candidate; - AreSimilar = areSimilar; - SimilarityWeight = similarityWeight; - } + public readonly string CandidateText = candidate; + public readonly bool AreSimilar = areSimilar; + public readonly double SimilarityWeight = similarityWeight; } // Cache the result of the last call to AreSimilar. We'll often be called with the same diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeActions/CodeFixOptionsProvider.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeActions/CodeFixOptionsProvider.cs index 1f572ec2cd76c..e5d0ed1d514c0 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeActions/CodeFixOptionsProvider.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeActions/CodeFixOptionsProvider.cs @@ -20,66 +20,54 @@ namespace Microsoft.CodeAnalysis.CodeActions; -internal readonly struct CodeFixOptionsProvider +/// +/// Document editorconfig options. +/// +/// +/// Fallback options provider - default options provider in Code Style layer. +/// +/// +/// C# language services. +/// +internal readonly struct CodeFixOptionsProvider(IOptionsReader options, CodeActionOptionsProvider fallbackOptions, HostLanguageServices languageServices) { - /// - /// Document editorconfig options. - /// - private readonly IOptionsReader _options; - - /// - /// C# language services. - /// - private readonly HostLanguageServices _languageServices; - - /// - /// Fallback options provider - default options provider in Code Style layer. - /// - private readonly CodeActionOptionsProvider _fallbackOptions; - - public CodeFixOptionsProvider(IOptionsReader options, CodeActionOptionsProvider fallbackOptions, HostLanguageServices languageServices) - { - _options = options; - _fallbackOptions = fallbackOptions; - _languageServices = languageServices; - } // LineFormattingOptions public string NewLine => GetOption(FormattingOptions2.NewLine, FallbackLineFormattingOptions.NewLine); public LineFormattingOptions GetLineFormattingOptions() - => _options.GetLineFormattingOptions(_languageServices.Language, FallbackLineFormattingOptions); + => options.GetLineFormattingOptions(languageServices.Language, FallbackLineFormattingOptions); // SyntaxFormattingOptions public SyntaxFormattingOptions GetFormattingOptions(ISyntaxFormatting formatting) - => formatting.GetFormattingOptions(_options, FallbackSyntaxFormattingOptions); + => formatting.GetFormattingOptions(options, FallbackSyntaxFormattingOptions); - public AccessibilityModifiersRequired AccessibilityModifiersRequired => _options.GetOptionValue(CodeStyleOptions2.AccessibilityModifiersRequired, _languageServices.Language, FallbackCommonSyntaxFormattingOptions.AccessibilityModifiersRequired); + public AccessibilityModifiersRequired AccessibilityModifiersRequired => options.GetOptionValue(CodeStyleOptions2.AccessibilityModifiersRequired, languageServices.Language, FallbackCommonSyntaxFormattingOptions.AccessibilityModifiersRequired); private TValue GetOption(PerLanguageOption2 option, TValue defaultValue) - => _options.GetOption(option, _languageServices.Language, defaultValue); + => options.GetOption(option, languageServices.Language, defaultValue); private LineFormattingOptions FallbackLineFormattingOptions #if CODE_STYLE => LineFormattingOptions.Default; #else - => _fallbackOptions.GetOptions(_languageServices.LanguageServices).CleanupOptions.FormattingOptions.LineFormatting; + => fallbackOptions.GetOptions(languageServices.LanguageServices).CleanupOptions.FormattingOptions.LineFormatting; #endif private SyntaxFormattingOptions? FallbackSyntaxFormattingOptions #if CODE_STYLE => null; #else - => _fallbackOptions.GetOptions(_languageServices.LanguageServices).CleanupOptions.FormattingOptions; + => fallbackOptions.GetOptions(languageServices.LanguageServices).CleanupOptions.FormattingOptions; #endif private SyntaxFormattingOptions FallbackCommonSyntaxFormattingOptions #if CODE_STYLE => SyntaxFormattingOptions.CommonDefaults; #else - => _fallbackOptions.GetOptions(_languageServices.LanguageServices).CleanupOptions.FormattingOptions; + => fallbackOptions.GetOptions(languageServices.LanguageServices).CleanupOptions.FormattingOptions; #endif } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/CodeActionOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/CodeActionOptions.cs index 7e23c66c9eefe..9aaf4a2eefee0 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/CodeActionOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/CodeActionOptions.cs @@ -145,15 +145,10 @@ ValueTask OptionsProvider @delegate) : AbstractCodeActionOptionsProvider { - private readonly Func _delegate; - - public DelegatingCodeActionOptionsProvider(Func @delegate) - => _delegate = @delegate; - public override CodeActionOptions GetOptions(LanguageServices languageService) - => _delegate(languageService); + => delegate(languageService); } internal static class CodeActionOptionsProviders diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/CustomCodeActions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/CustomCodeActions.cs index 97b0dcbd89f06..55a74bf5f773b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/CustomCodeActions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/CustomCodeActions.cs @@ -24,60 +24,39 @@ internal enum CodeActionPriority internal static class CustomCodeActions { - internal abstract class SimpleCodeAction : CodeAction + internal abstract class SimpleCodeAction( + string title, + string? equivalenceKey) : CodeAction { - public SimpleCodeAction( - string title, - string? equivalenceKey) - { - Title = title; - EquivalenceKey = equivalenceKey; - } - - public sealed override string Title { get; } - public sealed override string? EquivalenceKey { get; } + public sealed override string Title { get; } = title; + public sealed override string? EquivalenceKey { get; } = equivalenceKey; } - internal class DocumentChangeAction : SimpleCodeAction + internal class DocumentChangeAction( + string title, + Func> createChangedDocument, + string? equivalenceKey, + CodeActionPriority priority) : SimpleCodeAction(title, equivalenceKey) { - private readonly Func> _createChangedDocument; #if CODE_STYLE internal CodeActionPriority Priority { get; } #else - internal override CodeActionPriority Priority { get; } -#endif + internal override CodeActionPriority Priority { get; } = priority; - public DocumentChangeAction( - string title, - Func> createChangedDocument, - string? equivalenceKey, - CodeActionPriority priority) - : base(title, equivalenceKey) - { - _createChangedDocument = createChangedDocument; - Priority = priority; - } +#endif protected sealed override Task GetChangedDocumentAsync(CancellationToken cancellationToken) - => _createChangedDocument(cancellationToken); + => createChangedDocument(cancellationToken); } - internal class SolutionChangeAction : SimpleCodeAction + internal class SolutionChangeAction( + string title, + Func> createChangedSolution, + string? equivalenceKey) : SimpleCodeAction(title, equivalenceKey) { - private readonly Func> _createChangedSolution; - - public SolutionChangeAction( - string title, - Func> createChangedSolution, - string? equivalenceKey) - : base(title, equivalenceKey) - { - _createChangedSolution = createChangedSolution; - } - protected sealed override Task GetChangedSolutionAsync(CancellationToken cancellationToken) - => _createChangedSolution(cancellationToken).AsNullable(); + => createChangedSolution(cancellationToken).AsNullable(); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationArrayTypeSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationArrayTypeSymbol.cs index 5b9c8126e0b60..dca2d8c337b8c 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationArrayTypeSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationArrayTypeSymbol.cs @@ -7,18 +7,11 @@ namespace Microsoft.CodeAnalysis.CodeGeneration { - internal class CodeGenerationArrayTypeSymbol : CodeGenerationTypeSymbol, IArrayTypeSymbol + internal class CodeGenerationArrayTypeSymbol(ITypeSymbol elementType, int rank, NullableAnnotation nullableAnnotation) : CodeGenerationTypeSymbol(null, null, default, Accessibility.NotApplicable, default, string.Empty, SpecialType.None, nullableAnnotation), IArrayTypeSymbol { - public CodeGenerationArrayTypeSymbol(ITypeSymbol elementType, int rank, NullableAnnotation nullableAnnotation) - : base(null, null, default, Accessibility.NotApplicable, default, string.Empty, SpecialType.None, nullableAnnotation) - { - this.ElementType = elementType; - this.Rank = rank; - } - - public ITypeSymbol ElementType { get; } + public ITypeSymbol ElementType { get; } = elementType; - public int Rank { get; } + public int Rank { get; } = rank; public bool IsSZArray { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationAttributeData.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationAttributeData.cs index fb36ae94478ce..52cfb981322c8 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationAttributeData.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationAttributeData.cs @@ -9,26 +9,18 @@ namespace Microsoft.CodeAnalysis.CodeGeneration { - internal class CodeGenerationAttributeData : AttributeData + internal class CodeGenerationAttributeData( + INamedTypeSymbol attributeClass, + ImmutableArray constructorArguments, + ImmutableArray> namedArguments) : AttributeData { - private readonly INamedTypeSymbol _attributeClass; - private readonly ImmutableArray _constructorArguments; - private readonly ImmutableArray> _namedArguments; + private readonly ImmutableArray _constructorArguments = constructorArguments.NullToEmpty(); + private readonly ImmutableArray> _namedArguments = namedArguments.NullToEmpty(); - protected override INamedTypeSymbol CommonAttributeClass => _attributeClass; + protected override INamedTypeSymbol CommonAttributeClass => attributeClass; protected override IMethodSymbol CommonAttributeConstructor => null; protected override ImmutableArray CommonConstructorArguments => _constructorArguments; protected override ImmutableArray> CommonNamedArguments => _namedArguments; protected override SyntaxReference CommonApplicationSyntaxReference => null; - - public CodeGenerationAttributeData( - INamedTypeSymbol attributeClass, - ImmutableArray constructorArguments, - ImmutableArray> namedArguments) - { - _attributeClass = attributeClass; - _constructorArguments = constructorArguments.NullToEmpty(); - _namedArguments = namedArguments.NullToEmpty(); - } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConstructorSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConstructorSymbol.cs index be6376ceae81d..c1c9be8a76ef9 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConstructorSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConstructorSymbol.cs @@ -14,28 +14,23 @@ namespace Microsoft.CodeAnalysis.CodeGeneration { - internal class CodeGenerationConstructorSymbol : CodeGenerationMethodSymbol + internal class CodeGenerationConstructorSymbol( + INamedTypeSymbol containingType, + ImmutableArray attributes, + Accessibility accessibility, + DeclarationModifiers modifiers, + ImmutableArray parameters) : CodeGenerationMethodSymbol(containingType, + attributes, + accessibility, + modifiers, + returnType: null, + refKind: RefKind.None, + explicitInterfaceImplementations: default, + name: string.Empty, + typeParameters: ImmutableArray.Empty, + parameters: parameters, + returnTypeAttributes: ImmutableArray.Empty) { - public CodeGenerationConstructorSymbol( - INamedTypeSymbol containingType, - ImmutableArray attributes, - Accessibility accessibility, - DeclarationModifiers modifiers, - ImmutableArray parameters) - : base(containingType, - attributes, - accessibility, - modifiers, - returnType: null, - refKind: RefKind.None, - explicitInterfaceImplementations: default, - name: string.Empty, - typeParameters: ImmutableArray.Empty, - parameters: parameters, - returnTypeAttributes: ImmutableArray.Empty) - { - } - public override MethodKind MethodKind => MethodKind.Constructor; protected override CodeGenerationSymbol Clone() diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConversionSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConversionSymbol.cs index 2239363eb1c04..409de23fe5d25 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConversionSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationConversionSymbol.cs @@ -14,35 +14,30 @@ namespace Microsoft.CodeAnalysis.CodeGeneration { - internal class CodeGenerationConversionSymbol : CodeGenerationMethodSymbol - { - public CodeGenerationConversionSymbol( - INamedTypeSymbol containingType, - ImmutableArray attributes, - Accessibility declaredAccessibility, - DeclarationModifiers modifiers, - ITypeSymbol toType, - IParameterSymbol fromType, - bool isImplicit, - ImmutableArray toTypeAttributes, - string documentationCommentXml) - : base(containingType, - attributes, - declaredAccessibility, - modifiers, - returnType: toType, - refKind: RefKind.None, - explicitInterfaceImplementations: default, - name: isImplicit + internal class CodeGenerationConversionSymbol( + INamedTypeSymbol containingType, + ImmutableArray attributes, + Accessibility declaredAccessibility, + DeclarationModifiers modifiers, + ITypeSymbol toType, + IParameterSymbol fromType, + bool isImplicit, + ImmutableArray toTypeAttributes, + string documentationCommentXml) : CodeGenerationMethodSymbol(containingType, + attributes, + declaredAccessibility, + modifiers, + returnType: toType, + refKind: RefKind.None, + explicitInterfaceImplementations: default, + name: isImplicit ? WellKnownMemberNames.ImplicitConversionName : WellKnownMemberNames.ExplicitConversionName, - typeParameters: ImmutableArray.Empty, - parameters: ImmutableArray.Create(fromType), - returnTypeAttributes: toTypeAttributes, - documentationCommentXml) - { - } - + typeParameters: ImmutableArray.Empty, + parameters: ImmutableArray.Create(fromType), + returnTypeAttributes: toTypeAttributes, + documentationCommentXml) + { public override MethodKind MethodKind => MethodKind.Conversion; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationDestructorSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationDestructorSymbol.cs index 1c4f6403a89b8..1508534c952c6 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationDestructorSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationDestructorSymbol.cs @@ -8,25 +8,20 @@ namespace Microsoft.CodeAnalysis.CodeGeneration { - internal class CodeGenerationDestructorSymbol : CodeGenerationMethodSymbol + internal class CodeGenerationDestructorSymbol( + INamedTypeSymbol containingType, + ImmutableArray attributes) : CodeGenerationMethodSymbol(containingType, + attributes, + Accessibility.NotApplicable, + default, + returnType: null, + refKind: RefKind.None, + explicitInterfaceImplementations: default, + name: string.Empty, + typeParameters: ImmutableArray.Empty, + parameters: ImmutableArray.Empty, + returnTypeAttributes: ImmutableArray.Empty) { - public CodeGenerationDestructorSymbol( - INamedTypeSymbol containingType, - ImmutableArray attributes) - : base(containingType, - attributes, - Accessibility.NotApplicable, - default, - returnType: null, - refKind: RefKind.None, - explicitInterfaceImplementations: default, - name: string.Empty, - typeParameters: ImmutableArray.Empty, - parameters: ImmutableArray.Empty, - returnTypeAttributes: ImmutableArray.Empty) - { - } - public override MethodKind MethodKind => MethodKind.Destructor; protected override CodeGenerationSymbol Clone() diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationEventSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationEventSymbol.cs index 7a519574807ca..910219f0342bb 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationEventSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationEventSymbol.cs @@ -12,36 +12,26 @@ namespace Microsoft.CodeAnalysis.CodeGeneration { - internal class CodeGenerationEventSymbol : CodeGenerationSymbol, IEventSymbol + internal class CodeGenerationEventSymbol( + INamedTypeSymbol? containingType, + ImmutableArray attributes, + Accessibility declaredAccessibility, + DeclarationModifiers modifiers, + ITypeSymbol type, + ImmutableArray explicitInterfaceImplementations, + string name, + IMethodSymbol? addMethod, + IMethodSymbol? removeMethod, + IMethodSymbol? raiseMethod) : CodeGenerationSymbol(containingType?.ContainingAssembly, containingType, attributes, declaredAccessibility, modifiers, name), IEventSymbol { - public ITypeSymbol Type { get; } + public ITypeSymbol Type { get; } = type; public NullableAnnotation NullableAnnotation => Type.NullableAnnotation; - public ImmutableArray ExplicitInterfaceImplementations { get; } + public ImmutableArray ExplicitInterfaceImplementations { get; } = explicitInterfaceImplementations.NullToEmpty(); - public IMethodSymbol? AddMethod { get; } - public IMethodSymbol? RemoveMethod { get; } - public IMethodSymbol? RaiseMethod { get; } - - public CodeGenerationEventSymbol( - INamedTypeSymbol? containingType, - ImmutableArray attributes, - Accessibility declaredAccessibility, - DeclarationModifiers modifiers, - ITypeSymbol type, - ImmutableArray explicitInterfaceImplementations, - string name, - IMethodSymbol? addMethod, - IMethodSymbol? removeMethod, - IMethodSymbol? raiseMethod) - : base(containingType?.ContainingAssembly, containingType, attributes, declaredAccessibility, modifiers, name) - { - this.Type = type; - this.ExplicitInterfaceImplementations = explicitInterfaceImplementations.NullToEmpty(); - this.AddMethod = addMethod; - this.RemoveMethod = removeMethod; - this.RaiseMethod = raiseMethod; - } + public IMethodSymbol? AddMethod { get; } = addMethod; + public IMethodSymbol? RemoveMethod { get; } = removeMethod; + public IMethodSymbol? RaiseMethod { get; } = raiseMethod; protected override CodeGenerationSymbol Clone() { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationFieldSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationFieldSymbol.cs index 4ccdb599c4406..5a315659e20d8 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationFieldSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationFieldSymbol.cs @@ -14,28 +14,20 @@ namespace Microsoft.CodeAnalysis.CodeGeneration { - internal class CodeGenerationFieldSymbol : CodeGenerationSymbol, IFieldSymbol + internal class CodeGenerationFieldSymbol( + INamedTypeSymbol containingType, + ImmutableArray attributes, + Accessibility accessibility, + DeclarationModifiers modifiers, + ITypeSymbol type, + string name, + bool hasConstantValue, + object constantValue) : CodeGenerationSymbol(containingType?.ContainingAssembly, containingType, attributes, accessibility, modifiers, name), IFieldSymbol { - public ITypeSymbol Type { get; } + public ITypeSymbol Type { get; } = type; public NullableAnnotation NullableAnnotation => Type.NullableAnnotation; - public object ConstantValue { get; } - public bool HasConstantValue { get; } - - public CodeGenerationFieldSymbol( - INamedTypeSymbol containingType, - ImmutableArray attributes, - Accessibility accessibility, - DeclarationModifiers modifiers, - ITypeSymbol type, - string name, - bool hasConstantValue, - object constantValue) - : base(containingType?.ContainingAssembly, containingType, attributes, accessibility, modifiers, name) - { - this.Type = type; - this.HasConstantValue = hasConstantValue; - this.ConstantValue = constantValue; - } + public object ConstantValue { get; } = constantValue; + public bool HasConstantValue { get; } = hasConstantValue; protected override CodeGenerationSymbol Clone() { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceSymbol.cs index 3abdc3e60df66..6cfb14840c4dc 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationNamespaceSymbol.cs @@ -11,15 +11,9 @@ namespace Microsoft.CodeAnalysis.CodeGeneration { - internal class CodeGenerationNamespaceSymbol : CodeGenerationNamespaceOrTypeSymbol, INamespaceSymbol + internal class CodeGenerationNamespaceSymbol(string name, IList members) : CodeGenerationNamespaceOrTypeSymbol(null, null, default, Accessibility.NotApplicable, default, name), INamespaceSymbol { - private readonly IList _members; - - public CodeGenerationNamespaceSymbol(string name, IList members) - : base(null, null, default, Accessibility.NotApplicable, default, name) - { - _members = members ?? SpecializedCollections.EmptyList(); - } + private readonly IList _members = members ?? SpecializedCollections.EmptyList(); public override bool IsNamespace => true; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationOperatorSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationOperatorSymbol.cs index 20c17ee27a840..dd63d294240f3 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationOperatorSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationOperatorSymbol.cs @@ -15,33 +15,28 @@ namespace Microsoft.CodeAnalysis.CodeGeneration { - internal class CodeGenerationOperatorSymbol : CodeGenerationMethodSymbol + internal class CodeGenerationOperatorSymbol( + INamedTypeSymbol containingType, + ImmutableArray attributes, + Accessibility accessibility, + DeclarationModifiers modifiers, + ITypeSymbol returnType, + CodeGenerationOperatorKind operatorKind, + ImmutableArray parameters, + ImmutableArray returnTypeAttributes, + string documentationCommentXml) : CodeGenerationMethodSymbol(containingType, + attributes, + accessibility, + modifiers, + returnType, + refKind: RefKind.None, + explicitInterfaceImplementations: default, + GetMetadataName(operatorKind), + typeParameters: ImmutableArray.Empty, + parameters, + returnTypeAttributes, + documentationCommentXml) { - public CodeGenerationOperatorSymbol( - INamedTypeSymbol containingType, - ImmutableArray attributes, - Accessibility accessibility, - DeclarationModifiers modifiers, - ITypeSymbol returnType, - CodeGenerationOperatorKind operatorKind, - ImmutableArray parameters, - ImmutableArray returnTypeAttributes, - string documentationCommentXml) - : base(containingType, - attributes, - accessibility, - modifiers, - returnType, - refKind: RefKind.None, - explicitInterfaceImplementations: default, - GetMetadataName(operatorKind), - typeParameters: ImmutableArray.Empty, - parameters, - returnTypeAttributes, - documentationCommentXml) - { - } - public override MethodKind MethodKind => MethodKind.UserDefinedOperator; public static int GetParameterCount(CodeGenerationOperatorKind operatorKind) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationParameterSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationParameterSymbol.cs index 4a7d499181501..29e81ca85ca88 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationParameterSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationParameterSymbol.cs @@ -14,37 +14,26 @@ namespace Microsoft.CodeAnalysis.CodeGeneration { - internal class CodeGenerationParameterSymbol : CodeGenerationSymbol, IParameterSymbol + internal class CodeGenerationParameterSymbol( + INamedTypeSymbol containingType, + ImmutableArray attributes, + RefKind refKind, + bool isParams, + ITypeSymbol type, + string name, + bool isOptional, + bool hasDefaultValue, + object defaultValue) : CodeGenerationSymbol(containingType?.ContainingAssembly, containingType, attributes, Accessibility.NotApplicable, new DeclarationModifiers(), name), IParameterSymbol { - public RefKind RefKind { get; } - public bool IsParams { get; } - public ITypeSymbol Type { get; } + public RefKind RefKind { get; } = refKind; + public bool IsParams { get; } = isParams; + public ITypeSymbol Type { get; } = type; public NullableAnnotation NullableAnnotation => Type.NullableAnnotation; - public bool IsOptional { get; } + public bool IsOptional { get; } = isOptional; public int Ordinal { get; } - public bool HasExplicitDefaultValue { get; } - public object ExplicitDefaultValue { get; } - - public CodeGenerationParameterSymbol( - INamedTypeSymbol containingType, - ImmutableArray attributes, - RefKind refKind, - bool isParams, - ITypeSymbol type, - string name, - bool isOptional, - bool hasDefaultValue, - object defaultValue) - : base(containingType?.ContainingAssembly, containingType, attributes, Accessibility.NotApplicable, new DeclarationModifiers(), name) - { - this.RefKind = refKind; - this.IsParams = isParams; - this.Type = type; - this.IsOptional = isOptional; - this.HasExplicitDefaultValue = hasDefaultValue; - this.ExplicitDefaultValue = defaultValue; - } + public bool HasExplicitDefaultValue { get; } = hasDefaultValue; + public object ExplicitDefaultValue { get; } = defaultValue; protected override CodeGenerationSymbol Clone() { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationPointerTypeSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationPointerTypeSymbol.cs index c82e5d662af3f..2eb74d7b11fe7 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationPointerTypeSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationPointerTypeSymbol.cs @@ -6,15 +6,9 @@ namespace Microsoft.CodeAnalysis.CodeGeneration { - internal class CodeGenerationPointerTypeSymbol : CodeGenerationTypeSymbol, IPointerTypeSymbol + internal class CodeGenerationPointerTypeSymbol(ITypeSymbol pointedAtType) : CodeGenerationTypeSymbol(null, null, default, Accessibility.NotApplicable, default, string.Empty, SpecialType.None, NullableAnnotation.None), IPointerTypeSymbol { - public ITypeSymbol PointedAtType { get; } - - public CodeGenerationPointerTypeSymbol(ITypeSymbol pointedAtType) - : base(null, null, default, Accessibility.NotApplicable, default, string.Empty, SpecialType.None, NullableAnnotation.None) - { - this.PointedAtType = pointedAtType; - } + public ITypeSymbol PointedAtType { get; } = pointedAtType; protected override CodeGenerationTypeSymbol CloneWithNullableAnnotation(NullableAnnotation nullableAnnotation) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationPropertySymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationPropertySymbol.cs index 9478d48d01f27..4ba30d3f00673 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationPropertySymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationPropertySymbol.cs @@ -14,42 +14,29 @@ namespace Microsoft.CodeAnalysis.CodeGeneration { - internal class CodeGenerationPropertySymbol : CodeGenerationSymbol, IPropertySymbol + internal class CodeGenerationPropertySymbol( + INamedTypeSymbol containingType, + ImmutableArray attributes, + Accessibility declaredAccessibility, + DeclarationModifiers modifiers, + ITypeSymbol type, + RefKind refKind, + ImmutableArray explicitInterfaceImplementations, + string name, + bool isIndexer, + ImmutableArray parametersOpt, + IMethodSymbol getMethod, + IMethodSymbol setMethod) : CodeGenerationSymbol(containingType?.ContainingAssembly, containingType, attributes, declaredAccessibility, modifiers, name), IPropertySymbol { - private readonly RefKind _refKind; - public ITypeSymbol Type { get; } + public ITypeSymbol Type { get; } = type; public NullableAnnotation NullableAnnotation => Type.NullableAnnotation; - public bool IsIndexer { get; } - - public ImmutableArray Parameters { get; } - public ImmutableArray ExplicitInterfaceImplementations { get; } - - public IMethodSymbol GetMethod { get; } - public IMethodSymbol SetMethod { get; } - - public CodeGenerationPropertySymbol( - INamedTypeSymbol containingType, - ImmutableArray attributes, - Accessibility declaredAccessibility, - DeclarationModifiers modifiers, - ITypeSymbol type, - RefKind refKind, - ImmutableArray explicitInterfaceImplementations, - string name, - bool isIndexer, - ImmutableArray parametersOpt, - IMethodSymbol getMethod, - IMethodSymbol setMethod) - : base(containingType?.ContainingAssembly, containingType, attributes, declaredAccessibility, modifiers, name) - { - this.Type = type; - _refKind = refKind; - this.IsIndexer = isIndexer; - this.Parameters = parametersOpt.NullToEmpty(); - this.ExplicitInterfaceImplementations = explicitInterfaceImplementations.NullToEmpty(); - this.GetMethod = getMethod; - this.SetMethod = setMethod; - } + public bool IsIndexer { get; } = isIndexer; + + public ImmutableArray Parameters { get; } = parametersOpt.NullToEmpty(); + public ImmutableArray ExplicitInterfaceImplementations { get; } = explicitInterfaceImplementations.NullToEmpty(); + + public IMethodSymbol GetMethod { get; } = getMethod; + public IMethodSymbol SetMethod { get; } = setMethod; protected override CodeGenerationSymbol Clone() { @@ -85,11 +72,11 @@ public override TResult Accept(SymbolVisitor this; - public RefKind RefKind => _refKind; + public RefKind RefKind => refKind; - public bool ReturnsByRef => _refKind == RefKind.Ref; + public bool ReturnsByRef => refKind == RefKind.Ref; - public bool ReturnsByRefReadonly => _refKind == RefKind.RefReadOnly; + public bool ReturnsByRefReadonly => refKind == RefKind.RefReadOnly; public IPropertySymbol OverriddenProperty => null; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationTypeParameterSymbol.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationTypeParameterSymbol.cs index 852e315c0ddd2..8f115657a4d55 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationTypeParameterSymbol.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeGeneration/Symbols/CodeGenerationTypeParameterSymbol.cs @@ -8,41 +8,28 @@ namespace Microsoft.CodeAnalysis.CodeGeneration { - internal class CodeGenerationTypeParameterSymbol : CodeGenerationTypeSymbol, ITypeParameterSymbol + internal class CodeGenerationTypeParameterSymbol( + INamedTypeSymbol containingType, + ImmutableArray attributes, + VarianceKind varianceKind, + string name, + NullableAnnotation nullableAnnotation, + ImmutableArray constraintTypes, + bool hasConstructorConstraint, + bool hasReferenceConstraint, + bool hasValueConstraint, + bool hasUnmanagedConstraint, + bool hasNotNullConstraint, + int ordinal) : CodeGenerationTypeSymbol(containingType?.ContainingAssembly, containingType, attributes, Accessibility.NotApplicable, default, name, SpecialType.None, nullableAnnotation), ITypeParameterSymbol { - public VarianceKind Variance { get; } - public ImmutableArray ConstraintTypes { get; internal set; } - public bool HasConstructorConstraint { get; } - public bool HasReferenceTypeConstraint { get; } - public bool HasValueTypeConstraint { get; } - public bool HasUnmanagedTypeConstraint { get; } - public bool HasNotNullConstraint { get; } - public int Ordinal { get; } - - public CodeGenerationTypeParameterSymbol( - INamedTypeSymbol containingType, - ImmutableArray attributes, - VarianceKind varianceKind, - string name, - NullableAnnotation nullableAnnotation, - ImmutableArray constraintTypes, - bool hasConstructorConstraint, - bool hasReferenceConstraint, - bool hasValueConstraint, - bool hasUnmanagedConstraint, - bool hasNotNullConstraint, - int ordinal) - : base(containingType?.ContainingAssembly, containingType, attributes, Accessibility.NotApplicable, default, name, SpecialType.None, nullableAnnotation) - { - this.Variance = varianceKind; - this.ConstraintTypes = constraintTypes; - this.Ordinal = ordinal; - this.HasConstructorConstraint = hasConstructorConstraint; - this.HasReferenceTypeConstraint = hasReferenceConstraint; - this.HasValueTypeConstraint = hasValueConstraint; - this.HasUnmanagedTypeConstraint = hasUnmanagedConstraint; - this.HasNotNullConstraint = hasNotNullConstraint; - } + public VarianceKind Variance { get; } = varianceKind; + public ImmutableArray ConstraintTypes { get; internal set; } = constraintTypes; + public bool HasConstructorConstraint { get; } = hasConstructorConstraint; + public bool HasReferenceTypeConstraint { get; } = hasReferenceConstraint; + public bool HasValueTypeConstraint { get; } = hasValueConstraint; + public bool HasUnmanagedTypeConstraint { get; } = hasUnmanagedConstraint; + public bool HasNotNullConstraint { get; } = hasNotNullConstraint; + public int Ordinal { get; } = ordinal; protected override CodeGenerationTypeSymbol CloneWithNullableAnnotation(NullableAnnotation nullableAnnotation) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ITypeSymbolExtensions.CollectTypeParameterSymbolsVisitor.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ITypeSymbolExtensions.CollectTypeParameterSymbolsVisitor.cs index a24b2991a7b0c..c9cfc9388084d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ITypeSymbolExtensions.CollectTypeParameterSymbolsVisitor.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ITypeSymbolExtensions.CollectTypeParameterSymbolsVisitor.cs @@ -11,19 +11,11 @@ namespace Microsoft.CodeAnalysis.Shared.Extensions { internal partial class ITypeSymbolExtensions { - private class CollectTypeParameterSymbolsVisitor : SymbolVisitor + private class CollectTypeParameterSymbolsVisitor( + IList typeParameters, + bool onlyMethodTypeParameters) : SymbolVisitor { private readonly HashSet _visited = new(); - private readonly bool _onlyMethodTypeParameters; - private readonly IList _typeParameters; - - public CollectTypeParameterSymbolsVisitor( - IList typeParameters, - bool onlyMethodTypeParameters) - { - _onlyMethodTypeParameters = onlyMethodTypeParameters; - _typeParameters = typeParameters; - } public override void DefaultVisit(ISymbol node) => throw new NotImplementedException(); @@ -82,11 +74,11 @@ public override void VisitTypeParameter(ITypeParameterSymbol symbol) { if (_visited.Add(symbol)) { - if (symbol.TypeParameterKind == TypeParameterKind.Method || !_onlyMethodTypeParameters) + if (symbol.TypeParameterKind == TypeParameterKind.Method || !onlyMethodTypeParameters) { - if (!_typeParameters.Contains(symbol)) + if (!typeParameters.Contains(symbol)) { - _typeParameters.Add(symbol); + typeParameters.Add(symbol); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Rename/Annotations/RenameActionAnnotation.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Rename/Annotations/RenameActionAnnotation.cs index 823bb9b605b05..271cbbcf524dd 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Rename/Annotations/RenameActionAnnotation.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Rename/Annotations/RenameActionAnnotation.cs @@ -13,76 +13,63 @@ namespace Microsoft.CodeAnalysis.Rename.ConflictEngine /// check if the semantics have been changes (conflict detection). /// /// This annotation should be put on tokens only. - internal class RenameActionAnnotation : RenameAnnotation + internal class RenameActionAnnotation( + TextSpan originalSpan, + bool isRenameLocation, + string prefix, + string suffix, + bool isOriginalTextLocation, + RenameDeclarationLocationReference[] renameDeclarationLocations, + bool isNamespaceDeclarationReference, + bool isInvocationExpression, + bool isMemberGroupReference) : RenameAnnotation { /// /// The span this token occupied in the original syntax tree. Can be used to show e.g. conflicts in the UI. /// - public readonly TextSpan OriginalSpan; + public readonly TextSpan OriginalSpan = originalSpan; /// /// A flag indicating whether this is a location that needs to be renamed or just tracked for conflicts. /// - public readonly bool IsRenameLocation; + public readonly bool IsRenameLocation = isRenameLocation; /// /// A flag indicating whether the token at this location has the same ValueText then the original name /// of the symbol that gets renamed. /// - public readonly bool IsOriginalTextLocation; + public readonly bool IsOriginalTextLocation = isOriginalTextLocation; /// /// When replacing the annotated token this string will be prepended to the token's value. This is used when renaming compiler /// generated fields and methods backing properties (e.g. "get_X" or "_X" for property "X"). /// - public readonly string Prefix; + public readonly string Prefix = prefix; /// /// When replacing the annotated token this string will be appended to the token's value. This is used when renaming compiler /// generated types whose names are derived from user given names (e.g. "XEventHandler" for event "X"). /// - public readonly string Suffix; + public readonly string Suffix = suffix; /// /// A single dimensional array of annotations to verify after rename. /// - public readonly RenameDeclarationLocationReference[] RenameDeclarationLocationReferences; + public readonly RenameDeclarationLocationReference[] RenameDeclarationLocationReferences = renameDeclarationLocations; /// /// States if this token is a Namespace Declaration Reference /// - public readonly bool IsNamespaceDeclarationReference; + public readonly bool IsNamespaceDeclarationReference = isNamespaceDeclarationReference; /// /// States if this token is a member group reference, typically found in NameOf expressions /// - public readonly bool IsMemberGroupReference; + public readonly bool IsMemberGroupReference = isMemberGroupReference; /// /// States if this token is annotated as a part of the Invocation Expression that needs to be checked for the Conflicts /// - public readonly bool IsInvocationExpression; - - public RenameActionAnnotation( - TextSpan originalSpan, - bool isRenameLocation, - string prefix, - string suffix, - bool isOriginalTextLocation, - RenameDeclarationLocationReference[] renameDeclarationLocations, - bool isNamespaceDeclarationReference, - bool isInvocationExpression, - bool isMemberGroupReference) - { - this.OriginalSpan = originalSpan; - this.IsRenameLocation = isRenameLocation; - this.Prefix = prefix; - this.Suffix = suffix; - this.RenameDeclarationLocationReferences = renameDeclarationLocations; - this.IsOriginalTextLocation = isOriginalTextLocation; - this.IsNamespaceDeclarationReference = isNamespaceDeclarationReference; - this.IsInvocationExpression = isInvocationExpression; - this.IsMemberGroupReference = isMemberGroupReference; - } + public readonly bool IsInvocationExpression = isInvocationExpression; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/IProgressTracker.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/IProgressTracker.cs index 04d5b88d22cd3..1b8e8f210ea26 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/IProgressTracker.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/IProgressTracker.cs @@ -32,18 +32,11 @@ public static ItemCompletedDisposer ItemCompletedScope(this IProgressTracker tra return new ItemCompletedDisposer(tracker); } - public readonly struct ItemCompletedDisposer : IDisposable + public readonly struct ItemCompletedDisposer(IProgressTracker tracker) : IDisposable { - private readonly IProgressTracker _tracker; - - public ItemCompletedDisposer(IProgressTracker tracker) - { - _tracker = tracker; - } - public void Dispose() { - _tracker.ItemCompleted(); + tracker.ItemCompleted(); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/TextReaderWithLength.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/TextReaderWithLength.cs index 49d932868fb34..3bb34dabaff26 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/TextReaderWithLength.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/TextReaderWithLength.cs @@ -8,11 +8,8 @@ namespace Microsoft.CodeAnalysis.Shared.Utilities { - internal abstract class TextReaderWithLength : TextReader + internal abstract class TextReaderWithLength(int length) : TextReader { - public TextReaderWithLength(int length) - => Length = length; - - public int Length { get; } + public int Length { get; } = length; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/LanguageServiceMetadata.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/LanguageServiceMetadata.cs index ce463c5bf0cef..46aa7d78eb7c8 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/LanguageServiceMetadata.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/LanguageServiceMetadata.cs @@ -12,19 +12,11 @@ namespace Microsoft.CodeAnalysis.Host.Mef /// /// MEF metadata class used for finding and exports. /// - internal class LanguageServiceMetadata : LanguageMetadata + internal class LanguageServiceMetadata(IDictionary data) : LanguageMetadata(data) { - public string ServiceType { get; } - public string Layer { get; } + public string ServiceType { get; } = (string)data.GetValueOrDefault("ServiceType"); + public string Layer { get; } = (string)data.GetValueOrDefault("Layer"); - public IReadOnlyDictionary Data { get; } - - public LanguageServiceMetadata(IDictionary data) - : base(data) - { - this.ServiceType = (string)data.GetValueOrDefault("ServiceType"); - this.Layer = (string)data.GetValueOrDefault("Layer"); - this.Data = (IReadOnlyDictionary)data; - } + public IReadOnlyDictionary Data { get; } = (IReadOnlyDictionary)data; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefLanguageServices.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefLanguageServices.cs index 63d9a29e51e4b..23c4d12255fb9 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefLanguageServices.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefLanguageServices.cs @@ -127,15 +127,10 @@ private static bool TryGetServiceByLayer(string layer, IEnumerable> services) { - private readonly ImmutableArray> _services; - - public LazyServiceMetadataDebuggerProxy(ImmutableArray> services) - => _services = services; - public (string type, string layer)[] Metadata - => _services.Select(s => (s.Metadata.ServiceType, s.Metadata.Layer)).ToArray(); + => services.Select(s => (s.Metadata.ServiceType, s.Metadata.Layer)).ToArray(); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefWorkspaceServices.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefWorkspaceServices.cs index 4269c84ff1c19..d6b5e40891cc9 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefWorkspaceServices.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefWorkspaceServices.cs @@ -208,15 +208,10 @@ public override IEnumerable FindLanguageServices _languageServicesMap.TryGetValue(languageName, out languageServices); - internal sealed class LazyServiceMetadataDebuggerProxy + internal sealed class LazyServiceMetadataDebuggerProxy(ImmutableArray> services) { - private readonly ImmutableArray> _services; - - public LazyServiceMetadataDebuggerProxy(ImmutableArray> services) - => _services = services; - public (string type, string layer)[] Metadata - => _services.Select(s => (s.Metadata.ServiceType, s.Metadata.Layer)).ToArray(); + => services.Select(s => (s.Metadata.ServiceType, s.Metadata.Layer)).ToArray(); } } }