Skip to content

Commit

Permalink
delint (pedantic 1.9.0) (dart-lang#1871)
Browse files Browse the repository at this point in the history
* delint (pedantic 1.9.0)

* de-dup pedantic-defined lints
  • Loading branch information
pq authored Dec 5, 2019
1 parent ef7f19d commit 7ddeafe
Show file tree
Hide file tree
Showing 122 changed files with 579 additions and 625 deletions.
18 changes: 0 additions & 18 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,9 @@ analyzer:
- test/rules/**
linter:
rules:
# - always_declare_return_types
# - always_put_control_body_on_new_line
- always_put_required_named_parameters_first
- always_require_non_null_named_parameters
# - always_specify_types
- annotate_overrides
- avoid_annotating_with_dynamic
# - avoid_as
# - avoid_bool_literals_in_conditional_expressions # under review (see #1068)
Expand All @@ -28,7 +25,6 @@ linter:
# - avoid_function_literals_in_foreach_calls
# - avoid_implementing_value_types
# - avoid_js_rounded_ints # under review (see #1068)
- avoid_null_checks_in_equality_operators
- avoid_positional_boolean_parameters
# - avoid_private_typedef_functions # under review (see #1068)
# - avoid_renaming_method_parameters # under review (see #1068)
Expand All @@ -38,7 +34,6 @@ linter:
- avoid_setters_without_getters
# - avoid_single_cascade_in_expression_statements # under review (see #1068)
- avoid_slow_async_io
# - avoid_types_as_parameter_names (included in pedantic)
# - avoid_types_on_closure_parameters
# - avoid_unused_constructor_parameters # under review (see #1068)
# - avoid_void_async # under review (see #1068)
Expand Down Expand Up @@ -71,11 +66,8 @@ linter:
- package_names
- package_prefixed_library_names
- parameter_assignments
- prefer_adjacent_string_concatenation
- prefer_asserts_in_initializer_lists
# - prefer_bool_in_asserts # Deprecated
- prefer_collection_literals
- prefer_conditional_assignment
# - prefer_const_constructors
- prefer_const_constructors_in_immutables
# - prefer_const_declarations # under review (see #1068)
Expand All @@ -84,20 +76,14 @@ linter:
- prefer_expression_function_bodies
- prefer_final_fields
# - prefer_final_locals
- prefer_for_elements_to_map_fromIterable
- prefer_foreach
# - prefer_function_declarations_over_variables
- prefer_generic_function_type_aliases
- prefer_if_null_operators
- prefer_initializing_formals
- prefer_inlined_adds
- prefer_interpolation_to_compose_strings
# - prefer_iterable_whereType (included in pedantic)
# - prefer_mixin
- prefer_null_aware_operators
- prefer_relative_imports
- prefer_single_quotes
- prefer_spread_collections
# - prefer_typing_uninitialized_variables # under review (see #1068)
- prefer_void_to_null
- provide_deprecation_message
Expand All @@ -109,16 +95,12 @@ linter:
- throw_in_finally
# - type_annotate_public_apis
- unnecessary_brace_in_string_interps
# - unnecessary_const (included in pedantic)
- unnecessary_getters_setters
- unnecessary_lambdas
# - unnecessary_new (included in pedantic)
- unnecessary_null_aware_assignments
- unnecessary_overrides
- unnecessary_parenthesis
- unnecessary_statements
- unnecessary_this
- use_function_type_syntax_for_parameters
- use_setters_to_change_properties
- use_string_buffers
- use_to_and_as_if_applicable
Expand Down
6 changes: 3 additions & 3 deletions lib/src/analyzer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Future<Iterable<AnalysisErrorInfo>> lintFiles(
DartLinter linter, List<File> filesToLint) async {
// Setup an error watcher to track whether an error was logged to stderr so
// we can set the exit code accordingly.
ErrorWatchingSink errorWatcher = ErrorWatchingSink(errorSink);
final errorWatcher = ErrorWatchingSink(errorSink);
errorSink = errorWatcher;

final errors = await linter.lintFiles(filesToLint);
Expand All @@ -73,8 +73,8 @@ Iterable<AnalysisError> _filtered(
: errors.where((AnalysisError e) => !filter.filter(e));

int _maxSeverity(List<AnalysisErrorInfo> errors, LintFilter filter) {
int max = 0;
for (AnalysisErrorInfo info in errors) {
var max = 0;
for (final info in errors) {
_filtered(info.errors, filter).forEach((AnalysisError e) {
max = math.max(max, e.errorCode.errorSeverity.ordinal);
});
Expand Down
22 changes: 11 additions & 11 deletions lib/src/ast.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import 'utils.dart';

/// Returns direct children of [parent].
List<Element> getChildren(Element parent, [String name]) {
List<Element> children = <Element>[];
final children = <Element>[];
visitChildren(parent, (Element element) {
if (name == null || element.displayName == name) {
children.add(element);
Expand All @@ -47,7 +47,7 @@ SimpleIdentifier getFieldIdentifier(FieldDeclaration decl, String name) {

/// Returns the most specific AST node appropriate for associating errors.
AstNode getNodeToAnnotate(Declaration node) {
AstNode mostSpecific = _getNodeToAnnotate(node);
final mostSpecific = _getNodeToAnnotate(node);
return mostSpecific ?? node;
}

Expand Down Expand Up @@ -96,7 +96,7 @@ bool hasOverrideAnnotation(Element element) {
/// Returns `true` if this [node] is the child of a private compilation unit
/// member.
bool inPrivateMember(AstNode node) {
AstNode parent = node.parent;
final parent = node.parent;
if (parent is NamedCompilationUnitMember) {
return isPrivate(parent.name);
}
Expand Down Expand Up @@ -170,7 +170,7 @@ bool isSimpleGetter(MethodDeclaration declaration) {
if (body is ExpressionFunctionBody) {
return _checkForSimpleGetter(declaration, body.expression);
} else if (body is BlockFunctionBody) {
Block block = body.block;
final block = body.block;
if (block.statements.length == 1) {
var statement = block.statements[0];
if (statement is ReturnStatement) {
Expand Down Expand Up @@ -200,7 +200,7 @@ bool isSimpleSetter(MethodDeclaration setter) {
if (body is ExpressionFunctionBody) {
return _checkForSimpleSetter(setter, body.expression);
} else if (body is BlockFunctionBody) {
Block block = body.block;
final block = body.block;
if (block.statements.length == 1) {
var statement = block.statements[0];
if (statement is ExpressionStatement) {
Expand All @@ -220,7 +220,7 @@ bool isVar(Token token) => isKeyword(token, Keyword.VAR);

/// Return the nearest enclosing pubspec file.
File locatePubspecFile(CompilationUnit compilationUnit) {
String fullName = compilationUnit?.declaredElement?.source?.fullName;
final fullName = compilationUnit?.declaredElement?.source?.fullName;
if (fullName == null) {
return null;
}
Expand All @@ -231,12 +231,12 @@ File locatePubspecFile(CompilationUnit compilationUnit) {
return null;
}

File file = resourceProvider.getFile(fullName);
Folder folder = file.parent;
final file = resourceProvider.getFile(fullName);
var folder = file.parent;

// Look for a pubspec.yaml file.
while (folder != null) {
File pubspecFile = folder.getChildAssumingFile('pubspec.yaml');
final pubspecFile = folder.getChildAssumingFile('pubspec.yaml');
if (pubspecFile.exists) {
return pubspecFile;
}
Expand Down Expand Up @@ -272,7 +272,7 @@ bool _checkForSimpleSetter(MethodDeclaration setter, Expression expression) {
if (expression is! AssignmentExpression) {
return false;
}
AssignmentExpression assignment = expression as AssignmentExpression;
final assignment = expression as AssignmentExpression;

var leftHandSide = assignment.leftHandSide;
var rightHandSide = assignment.rightHandSide;
Expand Down Expand Up @@ -383,7 +383,7 @@ class _ElementVisitorAdapter extends GeneralizingElementVisitor {

@override
void visitElement(Element element) {
bool visitChildren = processor(element);
final visitChildren = processor(element);
if (visitChildren == true) {
element.visitChildren(this);
}
Expand Down
4 changes: 2 additions & 2 deletions lib/src/cli.dart
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ Future runLinter(List<String> args, LinterOptions initialLintOptions) async {
..packageConfigPath = packageConfigFile
..resourceProvider = PhysicalResourceProvider.INSTANCE;

List<File> filesToLint = [];
final filesToLint = <File>[];
for (var path in options.rest) {
filesToLint.addAll(collectFiles(path));
}
Expand All @@ -166,7 +166,7 @@ Future runLinter(List<String> args, LinterOptions initialLintOptions) async {

try {
final timer = Stopwatch()..start();
Iterable<AnalysisErrorInfo> errors = await lintFiles(linter, filesToLint);
final errors = await lintFiles(linter, filesToLint);
timer.stop();

var commonRoot = getRoot(options.rest);
Expand Down
37 changes: 19 additions & 18 deletions lib/src/formatter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ final int _pipeCodeUnit = '|'.codeUnitAt(0);
final int _slashCodeUnit = '\\'.codeUnitAt(0);

String getLineContents(int lineNumber, AnalysisError error) {
String path = error.source.fullName;
File file = File(path);
final path = error.source.fullName;
final file = File(path);
String failureDetails;
if (!file.existsSync()) {
failureDetails = 'file at $path does not exist';
Expand All @@ -45,12 +45,12 @@ String shorten(String fileRoot, String fullName) {

Future writeBenchmarks(
IOSink out, List<File> filesToLint, LinterOptions lintOptions) async {
Map<String, int> timings = <String, int>{};
for (int i = 0; i < benchmarkRuns; ++i) {
final timings = <String, int>{};
for (var i = 0; i < benchmarkRuns; ++i) {
await lintFiles(DartLinter(lintOptions), filesToLint);
lintRegistry.timers.forEach((n, t) {
int timing = t.elapsedMilliseconds;
int previous = timings[n];
final timing = t.elapsedMilliseconds;
final previous = timings[n];
if (previous == null) {
timings[n] = timing;
} else {
Expand Down Expand Up @@ -79,23 +79,24 @@ String _escapePipe(String input) {
}

void _writeTimings(IOSink out, List<_Stat> timings, int summaryLength) {
List<String> names = timings.map((s) => s.name).toList();
final names = timings.map((s) => s.name).toList();

int longestName = names.fold(0, (prev, element) => max(prev, element.length));
int longestTime = 8;
int tableWidth = max(summaryLength, longestName + longestTime);
int pad = tableWidth - longestName;
String line = ''.padLeft(tableWidth, '-');
var longestName =
names.fold<int>(0, (prev, element) => max(prev, element.length));
final longestTime = 8;
final tableWidth = max(summaryLength, longestName + longestTime);
final pad = tableWidth - longestName;
final line = ''.padLeft(tableWidth, '-');

out
..writeln()
..writeln(line)
..writeln('${'Timings'.padRight(longestName)}${'ms'.padLeft(pad)}')
..writeln(line);
int totalTime = 0;
var totalTime = 0;

timings.sort();
for (_Stat stat in timings) {
for (var stat in timings) {
totalTime += stat.elapsed;
// TODO: Shame timings slower than 100ms?
// TODO: Present both total times and time per count?
Expand Down Expand Up @@ -127,7 +128,7 @@ class DetailedReporter extends SimpleFormatter {
quiet: quiet);

@override
writeLint(AnalysisError error, {int offset, int line, int column}) {
void writeLint(AnalysisError error, {int offset, int line, int column}) {
super.writeLint(error, offset: offset, column: column, line: line);

if (!machineOutput) {
Expand Down Expand Up @@ -160,7 +161,7 @@ abstract class ReportFormatter {
machineOutput: machineOutput,
quiet: quiet);

write();
void write();
}

/// Simple formatter suitable for subclassing.
Expand Down Expand Up @@ -195,7 +196,7 @@ class SimpleFormatter implements ReportFormatter {
/// Override to influence error sorting
int compare(AnalysisError error1, AnalysisError error2) {
// Severity
int compare = error2.errorCode.errorSeverity
var compare = error2.errorCode.errorSeverity
.compareTo(error1.errorCode.errorSeverity);
if (compare != 0) {
return compare;
Expand All @@ -211,7 +212,7 @@ class SimpleFormatter implements ReportFormatter {
}

@override
write() {
void write() {
writeLints();
writeSummary();
if (showStatistics) {
Expand Down
4 changes: 2 additions & 2 deletions lib/src/rules/always_put_required_named_parameters_first.dart
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ class _Visitor extends SimpleAstVisitor<void> {

@override
void visitFormalParameterList(FormalParameterList node) {
bool nonRequiredSeen = false;
for (FormalParameter param in node.parameters.where((p) => p.isNamed)) {
var nonRequiredSeen = false;
for (var param in node.parameters.where((p) => p.isNamed)) {
if (param.declaredElement.hasRequired) {
if (nonRequiredSeen) {
rule.reportLintForToken(param.identifier.token);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ class _Visitor extends SimpleAstVisitor<void> {
for (final p in node.parameters) {
// Only named parameters
if (p.isNamed) {
DefaultFormalParameter parameter = p as DefaultFormalParameter;
final parameter = p as DefaultFormalParameter;
// Without a default value or marked @required
if (parameter.defaultValue == null &&
!parameter.declaredElement.hasRequired) {
Expand Down
6 changes: 3 additions & 3 deletions lib/src/rules/always_specify_types.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ String _META_LIB_NAME = 'meta';
String _OPTIONAL_TYPE_ARGS_VAR_NAME = 'optionalTypeArgs';

bool _isOptionallyParameterized(InterfaceType type) {
List<ElementAnnotation> metadata = type.element?.metadata;
final metadata = type.element?.metadata;
if (metadata != null) {
return metadata
.any((ElementAnnotation a) => _isOptionalTypeArgs(a.element));
Expand Down Expand Up @@ -124,8 +124,8 @@ class _Visitor extends SimpleAstVisitor<void> {
checkLiteral(literal);
}

visitNamedType(NamedType namedType) {
DartType type = namedType.type;
void visitNamedType(NamedType namedType) {
final type = namedType.type;
if (type is InterfaceType) {
if (type.element.typeParameters.isNotEmpty &&
namedType.typeArguments == null &&
Expand Down
12 changes: 6 additions & 6 deletions lib/src/rules/annotate_overrides.dart
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,13 @@ class _Visitor extends SimpleAstVisitor<void> {
return null;
}

ClassElement classElement =
member.getAncestor((element) => element is ClassElement);
final classElement = member
.getAncestor((element) => element is ClassElement) as ClassElement;
if (classElement == null) {
return null;
}

Uri libraryUri = classElement.library.source.uri;
final libraryUri = classElement.library.source.uri;
return context.inheritanceManager.getInherited(
classElement.thisType,
Name(libraryUri, member.name),
Expand All @@ -89,10 +89,10 @@ class _Visitor extends SimpleAstVisitor<void> {

@override
void visitFieldDeclaration(FieldDeclaration node) {
for (VariableDeclaration field in node.fields.variables) {
for (var field in node.fields.variables) {
var element = field.declaredElement;
if (element != null && !element.hasOverride) {
Element member = getOverriddenMember(element);
final member = getOverriddenMember(element);
if (member != null) {
rule.reportLint(field);
}
Expand All @@ -104,7 +104,7 @@ class _Visitor extends SimpleAstVisitor<void> {
void visitMethodDeclaration(MethodDeclaration node) {
var element = node.declaredElement;
if (element != null && !element.hasOverride) {
Element member = getOverriddenMember(element);
final member = getOverriddenMember(element);
if (member != null) {
rule.reportLint(node.name);
}
Expand Down
2 changes: 1 addition & 1 deletion lib/src/rules/avoid_empty_else.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class _Visitor extends SimpleAstVisitor<void> {

@override
void visitIfStatement(IfStatement node) {
Statement elseStatement = node.elseStatement;
final elseStatement = node.elseStatement;
if (elseStatement is EmptyStatement &&
!elseStatement.semicolon.isSynthetic) {
rule.reportLint(elseStatement);
Expand Down
Loading

0 comments on commit 7ddeafe

Please sign in to comment.