-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathprefer_last_rule.dart
More file actions
67 lines (60 loc) · 1.74 KB
/
prefer_last_rule.dart
File metadata and controls
67 lines (60 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import 'package:analyzer/error/listener.dart';
import 'package:custom_lint_builder/custom_lint_builder.dart';
import 'package:solid_lints/src/lints/prefer_last/fixes/prefer_last_fix.dart';
import 'package:solid_lints/src/lints/prefer_last/visitors/prefer_last_visitor.dart';
import 'package:solid_lints/src/models/rule_config.dart';
import 'package:solid_lints/src/models/solid_lint_rule.dart';
/// Warns about usage of `iterable[length - 1]` or
/// `iterable.elementAt(length - 1)` instead of `iterable.last`.
///
/// ### Example
///
/// #### BAD:
///
/// ```dart
/// final a = [1, 2, 3];
///
/// a[a.length - 1]; // LINT
/// a.elementAt(a.length - 1); // LINT
/// ```
///
/// #### GOOD:
///
/// ```dart
/// final a = [1, 2, 3];
///
/// a.last; // OK
/// ```
class PreferLastRule extends SolidLintRule {
/// This lint rule represents the error if iterable
/// access can be simplified.
static const lintName = 'prefer_last';
PreferLastRule._(super.config);
/// Creates a new instance of [PreferLastRule]
/// based on the lint configuration.
factory PreferLastRule.createRule(CustomLintConfigs configs) {
final config = RuleConfig(
configs: configs,
name: lintName,
problemMessage: (value) =>
'Use last instead of accessing the last element by index.',
);
return PreferLastRule._(config);
}
@override
void runRule(
CustomLintResolver resolver,
ErrorReporter reporter,
CustomLintContext context,
) {
context.registry.addCompilationUnit((node) {
final visitor = PreferLastVisitor();
node.accept(visitor);
for (final element in visitor.expressions) {
reporter.atNode(element, code);
}
});
}
@override
List<Fix> getFixes() => [PreferLastFix()];
}