Skip to content

Commit

Permalink
Merge pull request #72895 from CyrusNajmabadi/emptyEnumerable
Browse files Browse the repository at this point in the history
  • Loading branch information
CyrusNajmabadi authored Apr 5, 2024
2 parents 7f05bbb + 2dc3493 commit 8213da0
Show file tree
Hide file tree
Showing 84 changed files with 202 additions and 354 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public UpdateExpressionState(

public IEnumerable<TStatementSyntax> GetSubsequentStatements()
=> ContainingStatement is null
? SpecializedCollections.EmptyEnumerable<TStatementSyntax>()
? []
: UseCollectionInitializerHelpers.GetSubsequentStatements(SyntaxFacts, ContainingStatement);

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ private static IEnumerable<SyntaxNode> GetOwningNodes(SyntaxNode root, int posit
var token = root.FindTokenFromEnd(position);
if (token.Kind() == SyntaxKind.None)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
return [];
}

return token.GetAncestors<SyntaxNode>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public IEnumerable<ITagSpan<TTag>> GetTags(NormalizedSnapshotSpanCollection span
return intersection.Select(s => new TagSpan<TTag>(s, _tagInstance));
}

return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>();
return [];
}

public event EventHandler<SnapshotSpanEventArgs> TagsChanged = (s, e) => { };
Expand Down
5 changes: 1 addition & 4 deletions src/EditorFeatures/Core/Copilot/CopilotTaggerProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,7 @@ protected override IEnumerable<SnapshotSpan> GetSpansToTag(ITextView? textView,
Contract.ThrowIfNull(textView);

// We only care about the cases where we have caret.
if (textView.GetCaretPoint(subjectBuffer) is { } caret)
return SpecializedCollections.SingletonEnumerable(new SnapshotSpan(caret, 0));

return SpecializedCollections.EmptyEnumerable<SnapshotSpan>();
return textView.GetCaretPoint(subjectBuffer) is { } caret ? [new SnapshotSpan(caret, 0)] : [];
}

protected override async Task ProduceTagsAsync(TaggerContext<ITextMarkerTag> context, DocumentSnapshotSpan spanToTag, int? caretPosition, CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ internal void ApplyConflictResolutionEdits(IInlineRenameReplacementInfo conflict
// Show merge conflicts comments as unresolvable conflicts, and do not
// show any other rename-related spans that overlap a merge conflict comment.
mergeResult.MergeConflictCommentSpans.TryGetValue(document.Id, out var mergeConflictComments);
mergeConflictComments ??= SpecializedCollections.EmptyEnumerable<TextSpan>();
mergeConflictComments ??= [];

foreach (var conflict in mergeConflictComments)
{
Expand Down Expand Up @@ -545,7 +545,7 @@ private static async Task<IEnumerable<TextChange>> GetTextChangesFromTextDiffere
if (oldDocument == newDocument)
{
// no changes
return SpecializedCollections.EmptyEnumerable<TextChange>();
return [];
}

if (newDocument.Id != oldDocument.Id)
Expand All @@ -558,7 +558,7 @@ private static async Task<IEnumerable<TextChange>> GetTextChangesFromTextDiffere

if (oldText == newText)
{
return SpecializedCollections.EmptyEnumerable<TextChange>();
return [];
}

var textChanges = newText.GetTextChanges(oldText).ToList();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ private void SetReferenceLocations(ImmutableArray<InlineRenameLocation> location

if (!documents.Any(static (d, locationsByDocument) => locationsByDocument.Contains(d.Id), locationsByDocument))
{
_openTextBuffers[textBuffer].SetReferenceSpans(SpecializedCollections.EmptyEnumerable<TextSpan>());
_openTextBuffers[textBuffer].SetReferenceSpans([]);
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ private sealed class JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinab
public override int MaximumConcurrencyLevel => 1;

protected override IEnumerable<Task> GetScheduledTasks()
=> SpecializedCollections.EmptyEnumerable<Task>();
=> [];

protected override void QueueTask(Task task)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ protected override IEnumerable<SnapshotSpan> GetSpansToTag(ITextView? textView,
// above/below tagger should tag nothing.
return _viewPortToTag == ViewPortToTag.InView
? base.GetSpansToTag(textView, subjectBuffer)
: SpecializedCollections.EmptyEnumerable<SnapshotSpan>();
: [];
}

var visibleSpan = visibleSpanOpt.Value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ private static IEnumerable<IEnumerable<int>> GetPermutations(IEnumerable<int> li
{
if (!list.Any())
{
yield return SpecializedCollections.EmptyEnumerable<int>();
yield return [];
yield break;
}

Expand Down Expand Up @@ -286,9 +286,7 @@ private static IEnumerable<int> GetListWithoutElementAtIndex(IEnumerable<int> li
private static IEnumerable<IEnumerable<int>> GetSubsets(IEnumerable<int> list)
{
if (!list.Any())
{
return SpecializedCollections.SingletonEnumerable(SpecializedCollections.EmptyEnumerable<int>());
}
return [[]];

var firstElement = list.Take(1);

Expand Down
8 changes: 4 additions & 4 deletions src/EditorFeatures/Test/CodeFixes/CodeFixServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public async Task TestGetFirstDiagnosticWithFixAsync()

var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => workspace.Services.GetRequiredService<IErrorLoggerService>()));
var fixService = new CodeFixService(
diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable<Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>>());
diagnosticService, logger, fixers, configurationProviders: []);

var reference = new MockAnalyzerReference();
var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference);
Expand Down Expand Up @@ -366,7 +366,7 @@ private static (EditorTestWorkspace workspace, DiagnosticAnalyzerService analyze

var configurationFixProviders = includeConfigurationFixProviders
? workspace.ExportProvider.GetExports<IConfigurationFixProvider, CodeChangeProviderMetadata>()
: SpecializedCollections.EmptyEnumerable<Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>>();
: [];

var fixService = new CodeFixService(
diagnosticService,
Expand Down Expand Up @@ -768,15 +768,15 @@ private static async Task<ImmutableArray<CodeFixCollection>> GetNuGetAndVsixCode

var vsixFixers = vsixFixer != null
? SpecializedCollections.SingletonEnumerable(new Lazy<CodeFixProvider, CodeChangeProviderMetadata>(() => vsixFixer, new CodeChangeProviderMetadata(name: nameof(VsixCodeFixProvider), languages: LanguageNames.CSharp)))
: SpecializedCollections.EmptyEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>();
: [];

using var workspace = TestWorkspace.CreateCSharp(code, composition: s_compositionWithMockDiagnosticUpdateSourceRegistrationService, openDocuments: true);

var diagnosticService = Assert.IsType<DiagnosticAnalyzerService>(workspace.GetService<IDiagnosticAnalyzerService>());

var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => workspace.Services.GetRequiredService<IErrorLoggerService>()));
var fixService = new CodeFixService(
diagnosticService, logger, vsixFixers, SpecializedCollections.EmptyEnumerable<Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>>());
diagnosticService, logger, vsixFixers, configurationProviders: []);

diagnosticAnalyzer ??= new MockAnalyzerReference.MockDiagnosticAnalyzer();
var analyzers = ImmutableArray.Create<DiagnosticAnalyzer>(diagnosticAnalyzer);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public static TestContext Create(
string? metadataCommonReferences = null)
{
projectLanguage ??= LanguageNames.CSharp;
metadataSources ??= SpecializedCollections.EmptyEnumerable<string>();
metadataSources ??= [];
metadataSources = !metadataSources.Any()
? new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource }
: metadataSources;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public MockPreviewPaneService()

public object GetPreviewPane(DiagnosticData diagnostic, IReadOnlyList<object> previewContents)
{
var contents = previewContents ?? SpecializedCollections.EmptyEnumerable<object>();
var contents = previewContents ?? [];

foreach (var content in contents.OfType<IDisposable>())
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ private static IEnumerable<ImmutableArray<IParameterSymbol>> GetParameterLists(
.Select(c => c.Parameters);
}

return SpecializedCollections.EmptyEnumerable<ImmutableArray<IParameterSymbol>>();
return [];
}

private static IEnumerable<ISymbol> GetAttributeNamedParameters(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ public override bool IsInsertionTrigger(SourceText text, int characterPosition,
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken, ErrorSeverity.General))
{
return SpecializedCollections.EmptyEnumerable<CompletionItem>();
return [];
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -851,9 +851,7 @@ internal static TextSpan CreateSpanForVariableDeclarator(
internal static IEnumerable<SyntaxToken> GetActiveTokensForVariableDeclarator(VariableDeclaratorSyntax variableDeclarator, SyntaxTokenList modifiers, SyntaxToken semicolon)
{
if (variableDeclarator.Initializer == null || modifiers.Any(SyntaxKind.ConstKeyword))
{
return SpecializedCollections.EmptyEnumerable<SyntaxToken>();
}
return [];

// [|int F = 1;|]
var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent!;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1003,7 +1003,7 @@ private static void GetNestedFunctionsParts(
}
else
{
parameters = SpecializedCollections.EmptyEnumerable<SyntaxToken>();
parameters = [];
}

asyncKeyword = anonymous.AsyncKeyword;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ private IEnumerable<SyntaxTrivia> TriviaResolver(
{
return (location == TriviaLocation.AfterBeginningOfSpan)
? SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticMarker)
: SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
: [];
}
}
else
Expand All @@ -114,15 +114,15 @@ private IEnumerable<SyntaxTrivia> TriviaResolver(
{
return (location == TriviaLocation.AfterBeginningOfSpan)
? SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticMarker)
: SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
: [];
}
}

triviaMap.TryGetValue(tokenPair.PreviousToken, out var previousTriviaPair);
var trailingTrivia = previousTriviaPair.TrailingTrivia ?? SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
var trailingTrivia = previousTriviaPair.TrailingTrivia ?? [];

triviaMap.TryGetValue(tokenPair.NextToken, out var nextTriviaPair);
var leadingTrivia = nextTriviaPair.LeadingTrivia ?? SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
var leadingTrivia = nextTriviaPair.LeadingTrivia ?? [];

var list = trailingTrivia.Concat(leadingTrivia);

Expand Down Expand Up @@ -166,7 +166,7 @@ private static IEnumerable<SyntaxTrivia> AppendLeadingTrivia(PreviousNextTokenPa
return tokenPair.NextToken.LeadingTrivia;
}

return SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
return [];
}

private static IEnumerable<SyntaxTrivia> AppendTrailingTrivia(PreviousNextTokenPair tokenPair)
Expand All @@ -177,7 +177,7 @@ private static IEnumerable<SyntaxTrivia> AppendTrailingTrivia(PreviousNextTokenP
return tokenPair.PreviousToken.TrailingTrivia;
}

return SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
return [];
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -453,9 +453,7 @@ public override IEnumerable<SyntaxNode> GetOuterReturnStatements(SyntaxNode comm

var container = commonRoot.GetAncestorsOrThis<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault();
if (container == null)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
return [];

var returnableConstructPairs = returnStatements.Select(r => (r, r.GetAncestors<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault()))
.Where(p => p.Item2 != null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,7 @@ private static IEnumerable<INamedTypeSymbol> GetTypesInFile(SemanticModel semant
while (!nodesToVisit.IsEmpty())
{
if (cancellationToken.IsCancellationRequested)
{
return SpecializedCollections.EmptyEnumerable<INamedTypeSymbol>();
}
return [];

var node = nodesToVisit.Pop();
var type = GetType(semanticModel, node, cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static SyntaxTokenList Organize(SyntaxTokenList modifiers)
{
var initialList = new List<SyntaxToken>(modifiers);
var leadingTrivia = initialList.First().LeadingTrivia;
initialList[0] = initialList[0].WithLeadingTrivia(SpecializedCollections.EmptyEnumerable<SyntaxTrivia>());
initialList[0] = initialList[0].WithLeadingTrivia();

var finalList = initialList.OrderBy(new Comparer()).ToList();
if (!initialList.SequenceEqual(finalList))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,6 @@ protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperation
}
}

return SpecializedCollections.EmptyEnumerable<CodeActionOperation>();
return [];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,7 @@ private static void AddDiagnosticForSymbolIfNeeded(ISymbol targetSymbol, Diagnos
private static IEnumerable<KeyValuePair<ISymbol, ImmutableArray<Diagnostic>>> CreateDiagnosticsBySymbol(ImmutableDictionary<ISymbol, List<Diagnostic>>.Builder diagnosticsMapBuilder)
{
if (diagnosticsMapBuilder.Count == 0)
{
return SpecializedCollections.EmptyEnumerable<KeyValuePair<ISymbol, ImmutableArray<Diagnostic>>>();
}
return [];

var builder = new List<KeyValuePair<ISymbol, ImmutableArray<Diagnostic>>>();
foreach (var (symbol, diagnostics) in diagnosticsMapBuilder)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ protected IEnumerable<CompletionItem> GetAttributeValueItems(ISymbol? symbol, st
return s_listTypeValues.Select(CreateCompletionItem);
}

return SpecializedCollections.EmptyEnumerable<CompletionItem>();
return [];
}

protected ImmutableArray<CompletionItem> GetTopLevelItems(ISymbol? symbol, TSyntax syntax)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,7 @@ private CompletionItem CreateCompletionItem(INamedTypeSymbol symbol, TSyntaxCont
var semanticModel = context.SemanticModel;

if (declaredSymbol.ContainingSymbol is not INamespaceOrTypeSymbol containingSymbol)
{
return SpecializedCollections.EmptyEnumerable<INamedTypeSymbol>();
}
return [];

return semanticModel.LookupNamespacesAndTypes(context.Position, containingSymbol)
.OfType<INamedTypeSymbol>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,5 @@ internal ImmutableArray<CompletionItem> GetItems(string directoryPath, Cancellat
}

private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName)
{
return IOUtilities.PerformIO(() => GlobalAssemblyCache.Instance.GetAssemblyIdentities(partialName),
SpecializedCollections.EmptyEnumerable<AssemblyIdentity>());
}
=> IOUtilities.PerformIO(() => GlobalAssemblyCache.Instance.GetAssemblyIdentities(partialName), []);
}
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public async ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(
}
else
{
initialDocumentStates = SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>();
initialDocumentStates = [];
}

var sessionId = new DebuggingSessionId(Interlocked.Increment(ref s_debuggingSessionId));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -524,8 +524,8 @@ public UnitTestingReanalyzeScope(SolutionId solutionId)

public UnitTestingReanalyzeScope(IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null)
{
projectIds ??= SpecializedCollections.EmptyEnumerable<ProjectId>();
documentIds ??= SpecializedCollections.EmptyEnumerable<DocumentId>();
projectIds ??= [];
documentIds ??= [];

_solutionId = null;
_projectOrDocumentIds = new HashSet<object>(projectIds);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,9 @@ protected sealed override CodeActionPriority ComputePriority()
protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(
object options, IProgress<CodeAnalysisProgress> progressTracker, CancellationToken cancellationToken)
{
// If user click cancel button, options will be null and hit this branch
if (options is not ExtractClassOptions extractClassOptions)
{
// If user click cancel button, options will be null and hit this branch
return SpecializedCollections.EmptyEnumerable<CodeActionOperation>();
}
return [];

// Map the symbols we're removing to annotations
// so we can find them easily
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,7 @@ private LeadingTrailingTriviaPair CreateTriviaPairs(
{
// beginning of the tree
if (tokenPair.PreviousToken.RawKind == 0)
{
return new LeadingTrailingTriviaPair { TrailingTrivia = SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(), LeadingTrivia = trivia };
}
return new LeadingTrailingTriviaPair { TrailingTrivia = [], LeadingTrivia = trivia };

return GetTrailingAndLeadingTrivia(trivia);
}
Expand Down Expand Up @@ -275,10 +273,10 @@ private static IEnumerable<SyntaxTrivia> ResolveTrivia(
Dictionary<SyntaxToken, LeadingTrailingTriviaPair> triviaMap)
{
triviaMap.TryGetValue(tokenPair.PreviousToken, out var previousTriviaPair);
var trailingTrivia = previousTriviaPair.TrailingTrivia ?? SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
var trailingTrivia = previousTriviaPair.TrailingTrivia ?? [];

triviaMap.TryGetValue(tokenPair.NextToken, out var nextTriviaPair);
var leadingTrivia = nextTriviaPair.LeadingTrivia ?? SpecializedCollections.EmptyEnumerable<SyntaxTrivia>();
var leadingTrivia = nextTriviaPair.LeadingTrivia ?? [];

return tokenPair.PreviousToken.TrailingTrivia.Concat(trailingTrivia).Concat(leadingTrivia).Concat(tokenPair.NextToken.LeadingTrivia);
}
Expand Down
Loading

0 comments on commit 8213da0

Please sign in to comment.