Skip to content

Use toList(growable: false) more #3151

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions lib/src/comment_references/model_comment_reference.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ abstract class ModelCommentReference {
/// and [ResourceProvider] after construction.
class _ModelCommentReferenceImpl implements ModelCommentReference {
void _initAllowCache() {
var referencePieces = parsed.whereType<IdentifierNode>().toList();
final referencePieces =
parsed.whereType<IdentifierNode>().toList(growable: false);
_allowUnnamedConstructor = false;
_allowUnnamedConstructorParameter = false;
if (referencePieces.length >= 2) {
Expand All @@ -51,7 +52,7 @@ class _ModelCommentReferenceImpl implements ModelCommentReference {
}
}
}
// e.g. [C.new], which may be the unnamed constructor
// e.g. [C.new], which may be the unnamed constructor.
if (referencePieces.isNotEmpty && referencePieces.last.text == 'new') {
_allowUnnamedConstructor = true;
}
Expand Down
7 changes: 4 additions & 3 deletions lib/src/dartdoc_options.dart
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,9 @@ class ToolConfiguration {
if (compileArgs is String) {
args = [toolMap[compileArgsTagName].toString()];
} else if (compileArgs is YamlList) {
args =
compileArgs.map<String>((node) => node.toString()).toList();
args = compileArgs
.map<String>((node) => node.toString())
.toList(growable: false);
} else {
throw DartdocOptionError(
'Tool compile arguments must be a list of strings. The tool '
Expand Down Expand Up @@ -307,7 +308,7 @@ class _OptionValueWithContext<T> {
return (value as List<String>)
.map((v) => pathContext.canonicalizeWithTilde(v))
.cast<String>()
.toList() as T;
.toList(growable: false) as T;
} else if (value is String) {
return pathContext.canonicalizeWithTilde(value as String) as T;
} else if (value is Map<String, String>) {
Expand Down
2 changes: 1 addition & 1 deletion lib/src/generator/generator_frontend.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class GeneratorFrontEnd implements Generator {
var categories = indexElements
.whereType<Categorization>()
.where((e) => e.hasCategorization)
.toList();
.toList(growable: false);
_generatorBackend.generateCategoryJson(categories);
_generatorBackend.generateSearchIndex(indexElements);
}
Expand Down
4 changes: 2 additions & 2 deletions lib/src/generator/generator_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ String generateCategoryJson(Iterable<Categorization> categories, bool pretty) {
final encoder =
pretty ? const JsonEncoder.withIndent(' ') : const JsonEncoder();

return encoder.convert(indexItems.toList());
return encoder.convert(indexItems.toList(growable: false));
}

String removeHtmlTags(String? input) {
Expand Down Expand Up @@ -69,7 +69,7 @@ String generateSearchIndexJson(
final encoder =
pretty ? const JsonEncoder.withIndent(' ') : const JsonEncoder();

return encoder.convert(indexItems.toList());
return encoder.convert(indexItems);
}

// Compares two elements, first by fully qualified name, then by kind.
Expand Down
2 changes: 1 addition & 1 deletion lib/src/markdown_processor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ class MarkdownDocument extends md.Document {
/// if [processFullText] is `true`.
List<md.Node> parseMarkdownText(String text,
{required bool processFullText}) {
var lines = LineSplitter.split(text).toList();
var lines = LineSplitter.split(text).toList(growable: false);
md.Node? firstNode;
var nodes = <md.Node>[];
// TODO(srawlins): Refactor this. I think with null safety, it is more clear
Expand Down
3 changes: 2 additions & 1 deletion lib/src/model/canonicalization.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ abstract class Canonicalization implements Locatable, Documentable {
Set<String> get locationPieces;

List<ScoredCandidate> scoreCanonicalCandidates(Iterable<Library> libraries) {
return libraries.map(_scoreElementWithLibrary).toList()..sort();
return libraries.map(_scoreElementWithLibrary).toList(growable: false)
..sort();
}

ScoredCandidate _scoreElementWithLibrary(Library lib) {
Expand Down
4 changes: 2 additions & 2 deletions lib/src/model/categorization.dart
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ abstract class Categorization implements ModelElement {
return '';
});

_categoryNames = categorySet.toList()..sort();
_subCategoryNames = subCategorySet.toList()..sort();
_categoryNames = categorySet.toList(growable: false)..sort();
_subCategoryNames = subCategorySet.toList(growable: false)..sort();
_image ??= '';
_samples ??= '';
return rawDocs;
Expand Down
24 changes: 14 additions & 10 deletions lib/src/model/container.dart
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ abstract class Container extends ModelElement
];

late final List<ModelElement> allCanonicalModelElements =
allModelElements.where((e) => e.isCanonical).toList();
allModelElements.where((e) => e.isCanonical).toList(growable: false);

/// All methods, including operators and statics, declared as part of this
/// [Container].
Expand Down Expand Up @@ -108,7 +108,7 @@ abstract class Container extends ModelElement
model_utils.filterNonPublic(instanceMethods);

late final List<Method> publicInstanceMethodsSorted =
publicInstanceMethods.toList()..sort();
publicInstanceMethods.toList(growable: false)..sort();

@nonVirtual
late final Iterable<Operator> declaredOperators =
Expand All @@ -128,7 +128,7 @@ abstract class Container extends ModelElement
model_utils.filterNonPublic(instanceOperators);

late final List<Operator> publicInstanceOperatorsSorted =
publicInstanceOperators.toList()..sort();
publicInstanceOperators.toList(growable: false)..sort();

/// Fields fully declared in this [Container].
Iterable<Field> get declaredFields;
Expand All @@ -147,7 +147,7 @@ abstract class Container extends ModelElement
bool get hasPublicInstanceFields => publicInstanceFields.isNotEmpty;

late final List<Field> publicInstanceFieldsSorted =
publicInstanceFields.toList()..sort(byName);
publicInstanceFields.toList(growable: false)..sort(byName);

Iterable<Field> get constantFields => declaredFields.where((f) => f.isConst);

Expand All @@ -157,7 +157,7 @@ abstract class Container extends ModelElement
bool get hasPublicConstantFields => publicConstantFields.isNotEmpty;

late final List<Field> publicConstantFieldsSorted =
publicConstantFields.toList()..sort(byName);
publicConstantFields.toList(growable: false)..sort(byName);

Iterable<Field> get publicEnumValues => [];

Expand Down Expand Up @@ -208,7 +208,7 @@ abstract class Container extends ModelElement
bool get hasPublicStaticFields => publicStaticFieldsSorted.isNotEmpty;

late final List<Field> publicStaticFieldsSorted =
model_utils.filterNonPublic(staticFields).toList()..sort();
model_utils.filterNonPublic(staticFields).toList(growable: false)..sort();

Iterable<Field> get staticFields => declaredFields.where((f) => f.isStatic);

Expand All @@ -218,17 +218,21 @@ abstract class Container extends ModelElement
bool get hasPublicVariableStaticFields =>
publicVariableStaticFieldsSorted.isNotEmpty;

late final List<Field> publicVariableStaticFieldsSorted =
model_utils.filterNonPublic(variableStaticFields).toList()..sort();
late final List<Field> publicVariableStaticFieldsSorted = model_utils
.filterNonPublic(variableStaticFields)
.toList(growable: false)
..sort();

Iterable<Method> get staticMethods =>
declaredMethods.where((m) => m.isStatic);

bool get hasPublicStaticMethods =>
model_utils.filterNonPublic(publicStaticMethodsSorted).isNotEmpty;

late final List<Method> publicStaticMethodsSorted =
model_utils.filterNonPublic(staticMethods).toList()..sort();
late final List<Method> publicStaticMethodsSorted = model_utils
.filterNonPublic(staticMethods)
.toList(growable: false)
..sort();

/// For subclasses to add items after the main pass but before the
/// parameter-global.
Expand Down
6 changes: 3 additions & 3 deletions lib/src/model/documentation_comment.dart
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ mixin DocumentationComment
var invocationIndex = 0;
return await _replaceAllMappedAsync(rawDocs, _basicToolPattern,
(basicMatch) async {
var args = _splitUpQuotedArgs(basicMatch[1]!).toList();
final args = _splitUpQuotedArgs(basicMatch[1]!);
// Tool name must come first.
if (args.isEmpty) {
warn(PackageWarning.toolError,
Expand All @@ -268,8 +268,8 @@ mixin DocumentationComment
// Count the number of invocations of tools in this dartdoc block,
// so that tools can differentiate different blocks from each other.
invocationIndex++;
return await config.tools.runner.run(args, content: basicMatch[2]!,
toolErrorCallback: (String message) async {
return await config.tools.runner.run(args.toList(),
content: basicMatch[2]!, toolErrorCallback: (String message) async {
warn(PackageWarning.toolError, message: message);
}, environment: _toolsEnvironment(invocationIndex: invocationIndex));
});
Expand Down
13 changes: 7 additions & 6 deletions lib/src/model/inheriting_container.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ mixin Constructable on InheritingContainer {

@override
late final List<Constructor> publicConstructorsSorted =
model_utils.filterNonPublic(constructors).toList()..sort();
model_utils.filterNonPublic(constructors).toList(growable: false)..sort();

static Iterable<MapEntry<String, CommentReferable>> _constructorGenerator(
Iterable<Constructor> source) sync* {
Expand Down Expand Up @@ -171,7 +171,8 @@ mixin TypeImplementing on InheritingContainer {
List<InheritingContainer>? _publicImplementorsSorted;

Iterable<InheritingContainer> get publicImplementorsSorted =>
_publicImplementorsSorted ??= publicImplementors.toList()..sort(byName);
_publicImplementorsSorted ??= publicImplementors.toList(growable: false)
..sort(byName);
}

/// A [Container] that participates in inheritance in Dart.
Expand Down Expand Up @@ -354,7 +355,7 @@ abstract class InheritingContainer extends Container
// Elements in the inheritance chain starting from [this.element]
// down to, but not including, [Object].
inheritanceChainElements ??=
inheritanceChain.map((c) => c!.element).toList();
inheritanceChain.map((c) => c!.element).toList(growable: false);
// [packageGraph.specialClasses] is not available yet.
bool isDartCoreObject(ClassElement e) =>
e.name == 'Object' && e.library.name == 'dart.core';
Expand All @@ -379,7 +380,7 @@ abstract class InheritingContainer extends Container
}
}

__inheritedElements = combinedMap.values.toList();
__inheritedElements = combinedMap.values.toList(growable: false);
}
return __inheritedElements;
}
Expand Down Expand Up @@ -419,7 +420,7 @@ abstract class InheritingContainer extends Container
// Now we only have inherited accessors who aren't associated with
// anything in cls._fields.
for (var fieldName in accessorMap.keys) {
var elements = accessorMap[fieldName]!.toList();
var elements = accessorMap[fieldName]!.toList(growable: false);
var getterElement = elements.firstWhereOrNull((e) => e.isGetter);
var setterElement = elements.firstWhereOrNull((e) => e.isSetter);
fields.add(_createSingleField(
Expand Down Expand Up @@ -519,7 +520,7 @@ abstract class InheritingContainer extends Container
_typeParameters ??= element.typeParameters.map((f) {
var lib = modelBuilder.fromElement(f.enclosingElement3!.library!);
return modelBuilder.from(f, lib as Library) as TypeParameter;
}).toList();
}).toList(growable: false);
return _typeParameters!;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/src/model/method.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class Method extends ModelElement
void _calcTypeParameters() {
typeParameters = element.typeParameters.map((f) {
return modelBuilder.from(f, library) as TypeParameter;
}).toList();
}).toList(growable: false);
}

@override
Expand Down
17 changes: 9 additions & 8 deletions lib/src/model/model_element.dart
Original file line number Diff line number Diff line change
Expand Up @@ -570,7 +570,7 @@ abstract class ModelElement extends Canonicalization
topLevelElement = topLevelElement.enclosingElement3!;
}

var candidateLibraries = thisAndExported
final candidateLibraries = thisAndExported
.where((l) =>
l.isPublic && l.package.documentedWhere != DocumentLocation.missing)
.where((l) {
Expand All @@ -580,7 +580,7 @@ abstract class ModelElement extends Canonicalization
lookup = lookup.variable;
}
return topLevelElement == lookup;
}).toList();
}).toList(growable: true);

// Avoid claiming canonicalization for elements outside of this element's
// defining package.
Expand Down Expand Up @@ -609,21 +609,22 @@ abstract class ModelElement extends Canonicalization
// canonical. Still warn if the heuristic isn't that confident.
var scoredCandidates =
warnable.scoreCanonicalCandidates(candidateLibraries);
candidateLibraries = scoredCandidates.map((s) => s.library).toList();
final librariesByScore = scoredCandidates.map((s) => s.library).toList();
var secondHighestScore =
scoredCandidates[scoredCandidates.length - 2].score;
var highestScore = scoredCandidates.last.score;
var confidence = highestScore - secondHighestScore;
final canonicalLibrary = librariesByScore.last;

if (confidence < config.ambiguousReexportScorerMinConfidence) {
var libraryNames = candidateLibraries.map((l) => l.name);
var message = '$libraryNames -> ${candidateLibraries.last.name} '
var libraryNames = librariesByScore.map((l) => l.name);
var message = '$libraryNames -> ${canonicalLibrary.name} '
'(confidence ${confidence.toStringAsPrecision(4)})';
warnable.warn(PackageWarning.ambiguousReexport,
message: message, extendedDebug: scoredCandidates.map((s) => '$s'));
}

return candidateLibraries.last;
return canonicalLibrary;
}

@override
Expand Down Expand Up @@ -737,7 +738,7 @@ abstract class ModelElement extends Canonicalization
var setterDeprecated = pie.setter?.metadata.any((a) => a.isDeprecated);

var deprecatedValues =
[getterDeprecated, setterDeprecated].whereNotNull().toList();
[getterDeprecated, setterDeprecated].whereNotNull();

// At least one of these should be non-null. Otherwise things are weird
assert(deprecatedValues.isNotEmpty);
Expand Down Expand Up @@ -854,7 +855,7 @@ abstract class ModelElement extends Canonicalization
}
}
}
return recursedParameters.toList();
return recursedParameters.toList(growable: false);
}();

@override
Expand Down
5 changes: 3 additions & 2 deletions lib/src/model/package.dart
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ class Package extends LibraryContainer
late final List<Category> categories = [
defaultCategory,
...nameToCategory.values,
].where((c) => c.name.isNotEmpty).toList()
].where((c) => c.name.isNotEmpty).toList(growable: false)
..sort();

Iterable<Category> get categoriesWithPublicLibraries =>
Expand All @@ -346,7 +346,8 @@ class Package extends LibraryContainer
/// ordered by name.
Iterable<Category> get documentedCategoriesSorted {
if (config.categoryOrder.isNotEmpty) {
final documentedCategories = this.documentedCategories.toList();
final documentedCategories =
this.documentedCategories.toList(growable: false);
return documentedCategories
..sort((a, b) {
var aIndex = config.categoryOrder.indexOf(a.name);
Expand Down
Loading