Skip to content

Commit

Permalink
Merge pull request dotnet#43987 from CyrusNajmabadi/arrayBuilder
Browse files Browse the repository at this point in the history
Use ArrayBuilders instead of Lists in more places.
  • Loading branch information
msftbot[bot] authored Jun 18, 2020
2 parents e18704c + f1cd5f8 commit 697e630
Show file tree
Hide file tree
Showing 62 changed files with 267 additions and 290 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ protected void Clear()
return null;
}

var matches = ArrayBuilder<TMatch>.GetInstance();
using var _ = ArrayBuilder<TMatch>.GetInstance(out var matches);
AddMatches(matches);
return matches.ToImmutableAndFree();
return matches.ToImmutable();
}

private bool TryInitializeVariableDeclarationCase()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,18 +94,18 @@ public async Task<FirstDiagnosticResult> GetMostSevereFixableDiagnosticAsync(
return default;
}

using var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject();
using var _ = ArrayBuilder<DiagnosticData>.GetInstance(out var diagnostics);
using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

var linkedToken = linkedTokenSource.Token;

// This flag is used by SuggestedActionsSource to track what solution is was
// last able to get "full results" for.
var isFullResult = await _diagnosticService.TryAppendDiagnosticsForSpanAsync(
document, range, diagnostics.Object, cancellationToken: linkedToken).ConfigureAwait(false);
document, range, diagnostics, cancellationToken: linkedToken).ConfigureAwait(false);

var errorDiagnostics = diagnostics.Object.Where(d => d.Severity == DiagnosticSeverity.Error);
var otherDiagnostics = diagnostics.Object.Where(d => d.Severity != DiagnosticSeverity.Error);
var errorDiagnostics = diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error);
var otherDiagnostics = diagnostics.Where(d => d.Severity != DiagnosticSeverity.Error);

// Kick off a task that will determine there's an Error Diagnostic with a fixer
var errorDiagnosticsTask = Task.Run(
Expand Down
12 changes: 6 additions & 6 deletions src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests
End Sub

<WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub TestRulesetBasedDiagnosticFiltering()
Public Async Function TestRulesetBasedDiagnosticFiltering() As Task
Dim test = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
Expand Down Expand Up @@ -274,10 +274,10 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests
Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, descriptors(0).Id)

Dim document = project.Documents.Single()
Dim span = document.GetSyntaxRootAsync().WaitAndGetResult(CancellationToken.None).FullSpan
Dim span = (Await document.GetSyntaxRootAsync()).FullSpan

Dim analyzer = diagnosticService.CreateIncrementalAnalyzer(workspace)
Dim diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, span).WaitAndGetResult(CancellationToken.None).ToImmutableArray()
Dim diagnostics = Await diagnosticService.GetDiagnosticsForSpanAsync(document, span)
Assert.Equal(1, diagnostics.Length)
Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, diagnostics(0).Id)
Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.DefaultSeverity, diagnostics(0).Severity)
Expand All @@ -288,21 +288,21 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests
Dim newCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(suppressDiagOptions)
project = project.WithCompilationOptions(newCompilationOptions)
document = project.Documents.Single()
diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, span).WaitAndGetResult(CancellationToken.None).ToImmutableArray()
diagnostics = Await diagnosticService.GetDiagnosticsForSpanAsync(document, span)
Assert.Equal(0, diagnostics.Length)

Dim changeSeverityDiagOptions = New Dictionary(Of String, ReportDiagnostic)
changeSeverityDiagOptions.Add(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, ReportDiagnostic.Error)
newCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(changeSeverityDiagOptions)
project = project.WithCompilationOptions(newCompilationOptions)
document = project.Documents.Single()
diagnostics = diagnosticService.GetDiagnosticsForSpanAsync(document, span).WaitAndGetResult(CancellationToken.None).ToImmutableArray()
diagnostics = Await diagnosticService.GetDiagnosticsForSpanAsync(document, span)
Assert.Equal(1, diagnostics.Length)
Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.Id, diagnostics(0).Id)
Assert.Equal(workspaceDiagnosticAnalyzer.DiagDescriptor.DefaultSeverity, diagnostics(0).DefaultSeverity)
Assert.Equal(DiagnosticSeverity.Error, diagnostics(0).Severity)
End Using
End Sub
End Function

<Fact>
Public Sub TestProjectAnalyzerMessages()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Assert.NotNull(document)

Dim symbol = Await SymbolFinder.FindSymbolAtPositionAsync(document, cursorPosition)
Dim result = SpecializedCollections.EmptyEnumerable(Of ReferencedSymbol)()
Dim result = ImmutableArray(Of ReferencedSymbol).Empty
If symbol IsNot Nothing Then

Dim scope = If(searchSingleFileOnly, ImmutableHashSet.Create(Of Document)(document), Nothing)
Expand Down Expand Up @@ -388,7 +388,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
End Using
End Function

Private Shared Function GetActualReferences(result As IEnumerable(Of ReferencedSymbol),
Private Shared Function GetActualReferences(result As ImmutableArray(Of ReferencedSymbol),
uiVisibleOnly As Boolean,
options As FindReferencesSearchOptions,
document As Document,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ private static async Task<ImmutableArray<ConstructorCandidate>> GetConstructorCa
ImmutableArray<IParameterSymbol> parametersForSelectedMembers,
CancellationToken cancellationToken)
{
var applicableConstructors = ArrayBuilder<ConstructorCandidate>.GetInstance();
using var _ = ArrayBuilder<ConstructorCandidate>.GetInstance(out var applicableConstructors);

foreach (var constructor in containingType.InstanceConstructors)
{
Expand All @@ -86,7 +86,7 @@ private static async Task<ImmutableArray<ConstructorCandidate>> GetConstructorCa
}
}

return applicableConstructors.ToImmutableAndFree();
return applicableConstructors.ToImmutable();
}

private static async Task<bool> IsApplicableConstructorAsync(IMethodSymbol constructor, Document document, ImmutableArray<string> parameterNamesForSelectedMembers, CancellationToken cancellationToken)
Expand Down Expand Up @@ -115,8 +115,9 @@ private static bool SelectedMembersAlreadyExistAsParameters(ImmutableArray<strin

private static ConstructorCandidate CreateConstructorCandidate(ImmutableArray<IParameterSymbol> parametersForSelectedMembers, ImmutableArray<ISymbol> selectedMembers, IMethodSymbol constructor)
{
var missingParametersBuilder = ArrayBuilder<IParameterSymbol>.GetInstance();
var missingMembersBuilder = ArrayBuilder<ISymbol>.GetInstance();
using var _0 = ArrayBuilder<IParameterSymbol>.GetInstance(out var missingParametersBuilder);
using var _1 = ArrayBuilder<ISymbol>.GetInstance(out var missingMembersBuilder);

var constructorParamNames = constructor.Parameters.SelectAsArray(p => p.Name);
var zippedParametersAndSelectedMembers =
parametersForSelectedMembers.Zip(selectedMembers, (parameter, selectedMember) => (parameter, selectedMember));
Expand All @@ -131,7 +132,7 @@ private static ConstructorCandidate CreateConstructorCandidate(ImmutableArray<IP
}

return new ConstructorCandidate(
constructor, missingMembersBuilder.ToImmutableAndFree(), missingParametersBuilder.ToImmutableAndFree());
constructor, missingMembersBuilder.ToImmutable(), missingParametersBuilder.ToImmutable());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public static async Task<ImmutableArray<CodeAction>> AddConstructorParametersFro

private static ImmutableArray<CodeAction> CreateCodeActions(Document document, State state)
{
var result = ArrayBuilder<CodeAction>.GetInstance();
using var _0 = ArrayBuilder<CodeAction>.GetInstance(out var result);
var containingType = state.ContainingType;
if (state.ConstructorCandidates.Length == 1)
{
Expand All @@ -91,8 +91,8 @@ private static ImmutableArray<CodeAction> CreateCodeActions(Document document, S
else
{
// Create sub menus for suggested actions, one for required parameters and one for optional parameters
var requiredParameterCodeActions = ArrayBuilder<CodeAction>.GetInstance();
var optionalParameterCodeActions = ArrayBuilder<CodeAction>.GetInstance();
using var _1 = ArrayBuilder<CodeAction>.GetInstance(out var requiredParameterCodeActions);
using var _2 = ArrayBuilder<CodeAction>.GetInstance(out var optionalParameterCodeActions);
foreach (var constructorCandidate in state.ConstructorCandidates)
{
if (CanHaveRequiredParameters(constructorCandidate.Constructor.Parameters))
Expand All @@ -115,17 +115,17 @@ private static ImmutableArray<CodeAction> CreateCodeActions(Document document, S
{
result.Add(new CodeAction.CodeActionWithNestedActions(
FeaturesResources.Add_parameter_to_constructor,
requiredParameterCodeActions.ToImmutableAndFree(),
requiredParameterCodeActions.ToImmutable(),
isInlinable: false));
}

result.Add(new CodeAction.CodeActionWithNestedActions(
FeaturesResources.Add_optional_parameter_to_constructor,
optionalParameterCodeActions.ToImmutableAndFree(),
optionalParameterCodeActions.ToImmutable(),
isInlinable: false));
}

return result.ToImmutableAndFree();
return result.ToImmutable();

// local functions
static bool CanHaveRequiredParameters(ImmutableArray<IParameterSymbol> parameters)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,14 +114,14 @@ private ImmutableArray<SyntaxTrivia> UpdateEmbeddedFileNames(
return banner;
}

var result = ArrayBuilder<SyntaxTrivia>.GetInstance();
using var _ = ArrayBuilder<SyntaxTrivia>.GetInstance(out var result);
foreach (var trivia in banner)
{
var updated = CreateTrivia(trivia, trivia.ToFullString().Replace(sourceName, destinationName));
result.Add(updated);
}

return result.ToImmutableAndFree();
return result.ToImmutable();
}

private async Task<ImmutableArray<SyntaxTrivia>> TryGetBannerAsync(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ private async Task<ImmutableArray<AddImportFixData>> GetFixesInCurrentProcessAsy
var node = root.FindToken(span.Start, findInsideTrivia: true)
.GetAncestor(n => n.Span.Contains(span) && n != root);

var result = ArrayBuilder<AddImportFixData>.GetInstance();
using var _ = ArrayBuilder<AddImportFixData>.GetInstance(out var result);
if (node != null)
{

Expand Down Expand Up @@ -122,7 +122,7 @@ private async Task<ImmutableArray<AddImportFixData>> GetFixesInCurrentProcessAsy
}
}

return result.ToImmutableAndFree();
return result.ToImmutable();
}

private async Task<ImmutableArray<Reference>> FindResultsAsync(
Expand Down Expand Up @@ -172,7 +172,7 @@ private async Task<ImmutableArray<Reference>> FindResultsAsync(
ConcurrentDictionary<PortableExecutableReference, Compilation> referenceToCompilation,
Project project, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken)
{
var allReferences = ArrayBuilder<Reference>.GetInstance();
using var _ = ArrayBuilder<Reference>.GetInstance(out var allReferences);

// First search the current project to see if any symbols (source or metadata) match the
// search string.
Expand All @@ -199,7 +199,7 @@ await FindResultsInAllSymbolsInStartingProjectAsync(
}
}

return allReferences.ToImmutableAndFree();
return allReferences.ToImmutable();
}

private static async Task FindResultsInAllSymbolsInStartingProjectAsync(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,12 @@ protected override async Task<IEnumerable<CodeActionOperation>> ComputePreviewOp
{
// Make a SolutionChangeAction. This way we can let it generate the diff
// preview appropriately.
var solutionChangeAction = new SolutionChangeAction(
"", c => GetUpdatedSolutionAsync(c));
var solutionChangeAction = new SolutionChangeAction("", c => GetUpdatedSolutionAsync(c));

var result = ArrayBuilder<CodeActionOperation>.GetInstance();
using var _ = ArrayBuilder<CodeActionOperation>.GetInstance(out var result);
result.AddRange(await solutionChangeAction.GetPreviewOperationsAsync(cancellationToken).ConfigureAwait(false));
result.Add(_installOperation);
return result.ToImmutableAndFree();
return result.ToImmutable();
}

private async Task<Solution> GetUpdatedSolutionAsync(CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ private static ImmutableArray<CodeAction> CreateNestedActions(
// in this solution. We'll offer to add those specific versions to this project,
// followed by an option to "Find and install latest version."
var installedVersions = installerService.GetInstalledVersions(fixData.PackageName).NullToEmpty();
var codeActions = ArrayBuilder<CodeAction>.GetInstance();
using var _ = ArrayBuilder<CodeAction>.GetInstance(out var codeActions);

// First add the actions to install a specific version.
codeActions.AddRange(installedVersions.Select(
Expand All @@ -70,7 +70,7 @@ private static ImmutableArray<CodeAction> CreateNestedActions(

// And finally the action to show the package manager dialog.
codeActions.Add(new InstallWithPackageManagerCodeAction(installerService, fixData.PackageName));
return codeActions.ToImmutableAndFree();
return codeActions.ToImmutable();
}

private static CodeAction CreateCodeAction(
Expand Down
22 changes: 9 additions & 13 deletions src/Features/Core/Portable/AddImport/SymbolReferenceFinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,11 @@ private async Task<ImmutableArray<SymbolReference>> DoAsync(SearchScope searchSc
searchScope.CancellationToken.ThrowIfCancellationRequested();

// Spin off tasks to do all our searching in parallel
var tasks = new List<Task<ImmutableArray<SymbolReference>>>
{
GetReferencesForMatchingTypesAsync(searchScope),
GetReferencesForMatchingNamespacesAsync(searchScope),
GetReferencesForMatchingFieldsAndPropertiesAsync(searchScope),
GetReferencesForMatchingExtensionMethodsAsync(searchScope),
};
using var _1 = ArrayBuilder<Task<ImmutableArray<SymbolReference>>>.GetInstance(out var tasks);
tasks.Add(GetReferencesForMatchingTypesAsync(searchScope));
tasks.Add(GetReferencesForMatchingNamespacesAsync(searchScope));
tasks.Add(GetReferencesForMatchingFieldsAndPropertiesAsync(searchScope));
tasks.Add(GetReferencesForMatchingExtensionMethodsAsync(searchScope));

// Searching for things like "Add" (for collection initializers) and "Select"
// (for extension methods) should only be done when doing an 'exact' search.
Expand All @@ -144,14 +142,14 @@ private async Task<ImmutableArray<SymbolReference>> DoAsync(SearchScope searchSc
await Task.WhenAll(tasks).ConfigureAwait(false);
searchScope.CancellationToken.ThrowIfCancellationRequested();

var allReferences = ArrayBuilder<SymbolReference>.GetInstance();
using var _2 = ArrayBuilder<SymbolReference>.GetInstance(out var allReferences);
foreach (var task in tasks)
{
var taskResult = await task.ConfigureAwait(false);
allReferences.AddRange(taskResult);
}

return DeDupeAndSortReferences(allReferences.ToImmutableAndFree());
return DeDupeAndSortReferences(allReferences.ToImmutable());
}

private ImmutableArray<SymbolReference> DeDupeAndSortReferences(ImmutableArray<SymbolReference> allReferences)
Expand Down Expand Up @@ -552,20 +550,18 @@ protected bool ExpressionBinds(
private ImmutableArray<SymbolReference> GetNamespaceSymbolReferences(
SearchScope scope, ImmutableArray<SymbolResult<INamespaceSymbol>> namespaces)
{
var references = ArrayBuilder<SymbolReference>.GetInstance();
using var _ = ArrayBuilder<SymbolReference>.GetInstance(out var references);

foreach (var namespaceResult in namespaces)
{
var symbol = namespaceResult.Symbol;
var mappedResult = namespaceResult.WithSymbol(MapToCompilationNamespaceIfPossible(namespaceResult.Symbol));
var namespaceIsInScope = _namespacesInScope.Contains(mappedResult.Symbol);
if (!symbol.IsGlobalNamespace && !namespaceIsInScope)
{
references.Add(scope.CreateReference(mappedResult));
}
}

return references.ToImmutableAndFree();
return references.ToImmutable();
}

private static ImmutableArray<SymbolResult<T>> OfType<T>(ImmutableArray<SymbolResult<ISymbol>> symbols) where T : ISymbol
Expand Down
Loading

0 comments on commit 697e630

Please sign in to comment.