Skip to content

Commit ae9963e

Browse files
authored
[analysis] Reland "Added initial implementation of the flutter_analyzer_plugin (flutter#175679)" (flutter#191022)
Relands flutter#175679 (reverted in flutter#179766). Fixes flutter#175276. ### Context & Fixes The original PR was reverted because the `Linux linux_unopt` engine builder timed out during postsubmit. Root cause & changes in this reland: 1. **Scoped Plugin Configuration**: Plugin activation is now configured directly in target package `analysis_options.yaml` files (`packages/flutter/lib`, `packages/flutter/test`, `packages/flutter_tools`) rather than at the monorepo root `analysis_options.yaml`. This avoids leaking plugin configuration into subtrees such as `engine/src/flutter` where standard pub resolution and framework plugin rules do not apply. 2. **Analyzer AST Modernization**: Updated `ClassDeclaration` pattern matching in `render_box_intrinsics.dart` from `name` to `namePart` for compatibility with `package:analyzer` 10.1+. 3. **State Element Caching**: Updated `isPublicStateSubtype` in `protect_public_state_subtypes.dart` to cache `InterfaceElement` rather than instantiated `DartType`, ensuring all `State<T>` subclasses are properly analyzed regardless of generic type arguments. 4. **Defensive Guard**: Added null check on `ConstructorElement` in `no_stopwatches.dart`. 5. **Path & Test Fixes**: Corrected relative plugin path in `packages/flutter/test/analysis_options.yaml` and test method naming in `no_stopwatches_test.dart`. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] All existing and new tests are passing.
1 parent 277ba13 commit ae9963e

27 files changed

Lines changed: 1377 additions & 14 deletions

‎analysis_options.yaml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
include: analysis_options_common.yaml
22

3+
# Note: Analyzer plugins (such as flutter_analyzer_plugin) are intentionally
4+
# configured directly in subpackages (e.g. packages/flutter/lib,
5+
# packages/flutter/test, packages/flutter_tools) rather than here at the root.
6+
# This prevents plugins from leaking into excluded or standalone subtrees (like
7+
# engine/src/flutter) that do not use the framework plugin.
8+
39
analyzer:
10+
errors:
11+
plugins_in_inner_options: ignore
412
exclude:
513
- "bin/cache/**"
614
# Ignore protoc generated files

‎dev/bots/suite_runners/run_framework_tests.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,7 @@ Future<void> frameworkTestsRunner() async {
301301
path.join(flutterRoot, 'dev', 'integration_tests', 'android_semantics_testing'),
302302
fatalWarnings: false,
303303
);
304+
await runDartTest(path.join(flutterRoot, 'dev', 'flutter_analyzer_plugin'));
304305
await runFlutterTest(path.join(flutterRoot, 'dev', 'integration_tests', 'ui'));
305306
await runFlutterTest(path.join(flutterRoot, 'dev', 'manual_tests'));
306307
await runFlutterTest(path.join(flutterRoot, 'dev', 'tools'));

‎dev/bots/test/analyze-test-input/root/packages/flutter/lib/renderbox_intrinsics.dart‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,15 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5-
import '../../foo/fake_render_box.dart';
5+
abstract class RenderBox {
6+
void computeDryBaseline() {}
7+
void computeDryLayout() {}
8+
void computeDistanceToActualBaseline() {}
9+
void computeMaxIntrinsicHeight() {}
10+
void computeMinIntrinsicHeight() {}
11+
void computeMaxIntrinsicWidth() {}
12+
void computeMinIntrinsicWidth() {}
13+
}
614

715
mixin ARenderBoxMixin on RenderBox {
816
@override

‎dev/bots/test/analyze-test-input/root/packages/foo/fake_render_box.dart‎

Lines changed: 0 additions & 13 deletions
This file was deleted.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# https://dart.dev/guides/libraries/private-files
2+
# Created by `dart pub`
3+
.dart_tool/
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Flutter Analyzer Plugin
2+
3+
This plugin provides custom lint rules specific to development within flutter/flutter.
4+
5+
This plugin is a WIP as cases covered by `dev/bots/analyze.dart` are ported to this plugin,
6+
with the eventual goal of implementing as many of the checks as possible to reduce the number
7+
of analysis failures only discovered by CI checks.
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
analyzer:
2+
exclude:
3+
- build/**
4+
- android/**
5+
- ios/**
6+
- web/**
7+
- windows/**
8+
- macos/**
9+
- linux/**
10+
include: ../analysis_options.yaml
11+
12+
linter:
13+
rules:
14+
unawaited_futures: true
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'package:analysis_server_plugin/plugin.dart';
6+
import 'package:analysis_server_plugin/registry.dart';
7+
import 'src/rules/avoid_future_catch_error.dart';
8+
import 'src/rules/no_double_clamp.dart';
9+
import 'src/rules/no_stopwatches.dart';
10+
import 'src/rules/protect_public_state_subtypes.dart';
11+
import 'src/rules/render_box_intrinsics.dart';
12+
13+
final FlutterAnalyzerPlugin plugin = FlutterAnalyzerPlugin();
14+
15+
class FlutterAnalyzerPlugin extends Plugin {
16+
@override
17+
void register(PluginRegistry registry) {
18+
registry
19+
..registerWarningRule(AvoidFutureCatchError())
20+
..registerWarningRule(NoDoubleClamp())
21+
..registerWarningRule(NoStopwatches())
22+
..registerWarningRule(ProtectPublicStateSubtypes())
23+
..registerWarningRule(RenderBoxIntrinsicCalculationRule());
24+
}
25+
26+
@override
27+
String get name => 'flutter/flutter analyzer plugin';
28+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'package:analyzer/analysis_rule/analysis_rule.dart';
6+
import 'package:analyzer/analysis_rule/rule_context.dart';
7+
import 'package:analyzer/analysis_rule/rule_visitor_registry.dart';
8+
import 'package:analyzer/dart/ast/ast.dart';
9+
import 'package:analyzer/dart/ast/visitor.dart';
10+
import 'package:analyzer/dart/element/type.dart';
11+
import 'package:analyzer/error/error.dart';
12+
13+
class AvoidFutureCatchError extends AnalysisRule {
14+
AvoidFutureCatchError()
15+
: super(
16+
name: code.name,
17+
description: 'Future.catchError and Future.onError are not type safe.',
18+
);
19+
20+
static const LintCode code = LintCode(
21+
'avoid_future_catch_error',
22+
'Avoid using Future.catchError',
23+
correctionMessage: 'Use Future.then instead (https://github.com/dart-lang/sdk/issues/51248).',
24+
severity: DiagnosticSeverity.ERROR,
25+
);
26+
27+
@override
28+
LintCode get diagnosticCode => code;
29+
30+
@override
31+
void registerNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
32+
final visitor = _Visitor(this, context);
33+
registry.addMethodInvocation(this, visitor);
34+
}
35+
}
36+
37+
class _Visitor extends SimpleAstVisitor<void> {
38+
_Visitor(this.rule, this.context);
39+
40+
final AnalysisRule rule;
41+
final RuleContext context;
42+
43+
@override
44+
void visitMethodInvocation(MethodInvocation node) {
45+
if (node case MethodInvocation(
46+
methodName: SimpleIdentifier(name: 'onError' || 'catchError'),
47+
realTarget: Expression(staticType: DartType(isDartAsyncFuture: true)),
48+
)) {
49+
rule.reportAtNode(node);
50+
}
51+
}
52+
}
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'package:analyzer/analysis_rule/analysis_rule.dart';
6+
import 'package:analyzer/analysis_rule/rule_context.dart';
7+
import 'package:analyzer/analysis_rule/rule_visitor_registry.dart';
8+
import 'package:analyzer/dart/ast/ast.dart';
9+
import 'package:analyzer/dart/ast/visitor.dart';
10+
import 'package:analyzer/dart/element/element.dart';
11+
import 'package:analyzer/dart/element/type.dart';
12+
import 'package:analyzer/error/error.dart';
13+
14+
/// Verify that we use clampDouble instead of double.clamp for performance
15+
/// reasons.
16+
///
17+
/// See also:
18+
/// * https://github.com/flutter/flutter/pull/103559
19+
/// * https://github.com/flutter/flutter/issues/103917
20+
class NoDoubleClamp extends AnalysisRule {
21+
NoDoubleClamp()
22+
: super(
23+
name: code.name,
24+
description:
25+
'Verify that we use clampDouble instead of double.clamp for performance reasons.',
26+
);
27+
28+
static const LintCode code = LintCode(
29+
'no_double_clamp',
30+
'Avoid double.clamp for performance reasons.',
31+
correctionMessage: 'Use clampDouble instead.',
32+
severity: DiagnosticSeverity.ERROR,
33+
);
34+
35+
@override
36+
DiagnosticCode get diagnosticCode => code;
37+
38+
@override
39+
void registerNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
40+
final visitor = _Visitor(this, context);
41+
registry.addSimpleIdentifier(this, visitor);
42+
}
43+
}
44+
45+
class _Visitor extends SimpleAstVisitor<void> {
46+
_Visitor(this.rule, this.context);
47+
48+
final AnalysisRule rule;
49+
final RuleContext context;
50+
51+
@override
52+
void visitSimpleIdentifier(SimpleIdentifier node) {
53+
if (node.name != 'clamp' || node.element is! MethodElement) {
54+
return;
55+
}
56+
final bool isAllowed = switch (node.parent) {
57+
// PropertyAccess and PrefixedIdentifier match num.clamp in tear-off form.
58+
// Always prefer doubleClamp over tear-offs: even when all 3 operands are
59+
// int literals, the return type doesn't get promoted to int:
60+
// final x = 1.clamp(0, 2); // The inferred return type is int, where as:
61+
// final f = 1.clamp;
62+
// final y = f(0, 2) // The inferred return type is num.
63+
PropertyAccess(
64+
target: Expression(
65+
staticType: DartType(isDartCoreDouble: true) ||
66+
DartType(isDartCoreNum: true) ||
67+
DartType(isDartCoreInt: true),
68+
),
69+
) ||
70+
PrefixedIdentifier(
71+
prefix: Expression(
72+
staticType: DartType(isDartCoreDouble: true) ||
73+
DartType(isDartCoreNum: true) ||
74+
DartType(isDartCoreInt: true),
75+
),
76+
) => false,
77+
78+
// Expressions like `final int x = 1.clamp(0, 2);` should be allowed.
79+
MethodInvocation(
80+
target: Expression(staticType: DartType(isDartCoreInt: true)),
81+
argumentList: ArgumentList(
82+
arguments: [
83+
Expression(staticType: DartType(isDartCoreInt: true)),
84+
Expression(staticType: DartType(isDartCoreInt: true)),
85+
],
86+
),
87+
) =>
88+
true,
89+
90+
// Otherwise, disallow num.clamp() invocations.
91+
MethodInvocation(
92+
target: Expression(
93+
staticType: DartType(isDartCoreDouble: true) ||
94+
DartType(isDartCoreNum: true) ||
95+
DartType(isDartCoreInt: true),
96+
),
97+
) =>
98+
false,
99+
100+
_ => true,
101+
};
102+
if (!isAllowed) {
103+
rule.reportAtNode(node);
104+
}
105+
}
106+
}

0 commit comments

Comments
 (0)