|
| 1 | +// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +import 'package:analyzer/dart/ast/ast.dart'; |
| 6 | +import 'package:analyzer/dart/ast/visitor.dart'; |
| 7 | + |
| 8 | +import '../analyzer.dart'; |
| 9 | +import '../util/obvious_types.dart'; |
| 10 | + |
| 11 | +const _desc = |
| 12 | + r'Omit obvious type annotations for top-level and static variables.'; |
| 13 | + |
| 14 | +class OmitObviousPropertyTypes extends LintRule { |
| 15 | + OmitObviousPropertyTypes() |
| 16 | + : super( |
| 17 | + name: 'omit_obvious_property_types', |
| 18 | + description: _desc, |
| 19 | + state: State.experimental(), |
| 20 | + ); |
| 21 | + |
| 22 | + @override |
| 23 | + List<String> get incompatibleRules => const ['always_specify_types']; |
| 24 | + |
| 25 | + @override |
| 26 | + LintCode get lintCode => LinterLintCode.omit_obvious_property_types; |
| 27 | + |
| 28 | + @override |
| 29 | + void registerNodeProcessors( |
| 30 | + NodeLintRegistry registry, LinterContext context) { |
| 31 | + var visitor = _Visitor(this); |
| 32 | + registry.addFieldDeclaration(this, visitor); |
| 33 | + registry.addTopLevelVariableDeclaration(this, visitor); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +class _Visitor extends SimpleAstVisitor<void> { |
| 38 | + final LintRule rule; |
| 39 | + |
| 40 | + _Visitor(this.rule); |
| 41 | + |
| 42 | + @override |
| 43 | + void visitFieldDeclaration(FieldDeclaration node) => |
| 44 | + _visitVariableDeclarationList(node.fields); |
| 45 | + |
| 46 | + @override |
| 47 | + void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) => |
| 48 | + _visitVariableDeclarationList(node.variables); |
| 49 | + |
| 50 | + void _visitVariableDeclarationList(VariableDeclarationList node) { |
| 51 | + var staticType = node.type?.type; |
| 52 | + if (staticType == null || staticType.isDartCoreNull) { |
| 53 | + return; |
| 54 | + } |
| 55 | + for (var child in node.variables) { |
| 56 | + var initializer = child.initializer; |
| 57 | + if (initializer != null && !initializer.hasObviousType) { |
| 58 | + return; |
| 59 | + } |
| 60 | + if (initializer?.staticType != staticType) { |
| 61 | + return; |
| 62 | + } |
| 63 | + } |
| 64 | + rule.reportLint(node.type); |
| 65 | + } |
| 66 | +} |
0 commit comments