Skip to content

Commit 70797e1

Browse files
authored
[analysis] Upgrade package:analyzer to 14.3.0 and enable custom plugin compilation (#191590)
## Description Upgrades `package:analyzer` to `14.2.0` and `_fe_analyzer_shared` to `106.0.0` in the root `pubspec.yaml`, pulling in modern transitive dependencies (`analysis_server_plugin: 0.3.21`, `analyzer_plugin: 0.14.15`, `dart_style: 3.1.12`, and `analyzer_testing: 0.4.0`). ### Key Changes: - **Dependency Upgrades**: Bumped `package:analyzer` to `14.2.0` and updated lockfiles. - **Update Packages Command**: Added `dev/flutter_analyzer_plugin` to `_updatePubspec` in `packages/flutter_tools/lib/src/commands/update_packages.dart` and added hermetic test coverage in `update_packages_test.dart`. - **Plugin Migration & Base Class**: - Introduced `FlutterAnalysisRule` in `dev/flutter_analyzer_plugin/lib/src/flutter_analysis_rule.dart` which intercepts `registerNodeProcessors` and automatically skips rule and visitor registration for read-only Material and Cupertino implementations and tests. - Migrated all 17 `dev/flutter_analyzer_plugin` rules to extend `FlutterAnalysisRule` and implement `registerCustomNodeProcessors`. - Migrated rules and test fixtures to Analyzer 14 AST patterns and `package:analyzer_testing`. - Added unit test suite `dev/flutter_analyzer_plugin/test/flutter_analysis_rule_test.dart` verifying path filtering behavior. - **Rule Scopes & Improvements**: - `no_sync_async_star`: Restricted to `packages/` and `examples/`, excluding test files. - `no_test_imports`: Restricted to `packages/` to avoid flagging runner helpers. - `integration_test_timeouts`: Restricted to `dev/` directory. - `deprecation_syntax`: Excluded `analyze-test-input` fixtures. - `skip_test_comments`: Expanded ignore scan window across multi-line argument nodes. - **Snippets Migration**: Migrated `dev/snippets` AST visitors and mock filesystem resource provider to Analyzer 14. - **SDK Compatibility**: Added `dependency_overrides: analysis_server_plugin: ^0.3.21` to subpackage `analysis_options.yaml` files to allow isolated plugin runners to resolve on development/master Dart SDKs that specify unreleased protocol constraints. - **Linter Fixes**: - Replaced `scope.catchError` with `scope.then(..., onError: ...)` in `packages/flutter_tools/lib/src/desktop_device.dart`. - Added missing `@protected` annotations to non-material public `State` subtypes in `packages/flutter/lib` (`form.dart`, `raw_tooltip.dart`). - **CI Tuning**: - Added heartbeat progress output every 30s during analysis passes in `dev/bots/analyze.dart` and `dev/devicelab/lib/tasks/analysis.dart`. - Updated `Linux analyzer_benchmark` in `.ci.yaml` to set `device_type: none`, routing to 32 GB RAM VM drone bots. ## Tests - Added unit tests in `packages/flutter_tools/test/commands.shard/hermetic/update_packages_test.dart`. - Added unit tests in `dev/flutter_analyzer_plugin/test/flutter_analysis_rule_test.dart`. - Ran all 65 unit tests in `dev/flutter_analyzer_plugin` (all pass). - Ran all 18 unit tests in `dev/snippets` (all pass). - Ran `flutter analyze --flutter-repo` (0 issues found).
1 parent 540a271 commit 70797e1

68 files changed

Lines changed: 550 additions & 216 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎dev/analysis_options.yaml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ include: ../analysis_options.yaml
33
plugins:
44
flutter_analyzer_plugin:
55
path: flutter_analyzer_plugin
6+
dependency_overrides:
7+
analysis_server_plugin: ^0.3.22
68

79
linter:
810
rules:

‎dev/bots/analyze.dart‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
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 'dart:async';
56
import 'dart:convert';
67
import 'dart:core' hide print;
78
import 'dart:io' hide exit;
@@ -15,6 +16,8 @@ import 'allowlist.dart';
1516
import 'run_command.dart';
1617
import 'utils.dart';
1718

19+
const _kHeartbeatInterval = Duration(seconds: 30);
20+
1821
/// The path to the `dart` executable; set at the top of `main`
1922
late final String dart;
2023

@@ -1794,12 +1797,20 @@ Future<CommandResult> _runFlutterAnalyze(
17941797
List<String> options = const <String>[],
17951798
String? failureMessage,
17961799
}) async {
1797-
return runCommand(
1798-
flutter,
1799-
<String>['analyze', ...options],
1800-
workingDirectory: workingDirectory,
1801-
failureMessage: failureMessage,
1802-
);
1800+
final stopwatch = Stopwatch()..start();
1801+
final heartbeatTimer = Timer.periodic(_kHeartbeatInterval, (Timer _) {
1802+
print('Analysis in progress (${stopwatch.elapsed.inSeconds}s)...');
1803+
});
1804+
try {
1805+
return await runCommand(
1806+
flutter,
1807+
<String>['analyze', ...options],
1808+
workingDirectory: workingDirectory,
1809+
failureMessage: failureMessage,
1810+
);
1811+
} finally {
1812+
heartbeatTimer.cancel();
1813+
}
18031814
}
18041815

18051816
// These files legitimately require executable permissions

‎dev/devicelab/lib/tasks/analysis.dart‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,16 @@
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 'dart:async';
56
import 'dart:io';
67

78
import 'package:path/path.dart' as path;
89

910
import '../framework/task_result.dart';
1011
import '../framework/utils.dart';
1112

13+
const _kHeartbeatInterval = Duration(seconds: 30);
14+
1215
/// Run each benchmark this many times and compute average, min, max.
1316
///
1417
/// This must be small enough that we can do all the work in 15 minutes, the
@@ -70,11 +73,18 @@ abstract class _Benchmark {
7073
Future<double> execute(int iteration, int targetIterations) async {
7174
section('Analyze $title ${watch ? 'with watcher' : ''} - ${iteration + 1} / $targetIterations');
7275
final stopwatch = Stopwatch();
73-
await inDirectory<void>(directory, () async {
74-
stopwatch.start();
75-
await flutter('analyze', options: options);
76-
stopwatch.stop();
76+
final heartbeatTimer = Timer.periodic(_kHeartbeatInterval, (Timer _) {
77+
print('Analysis in progress (${stopwatch.elapsed.inSeconds}s)...');
7778
});
79+
try {
80+
await inDirectory<void>(directory, () async {
81+
stopwatch.start();
82+
await flutter('analyze', options: options);
83+
stopwatch.stop();
84+
});
85+
} finally {
86+
heartbeatTimer.cancel();
87+
}
7888
return stopwatch.elapsedMicroseconds / (1000.0 * 1000.0);
7989
}
8090
}

‎dev/flutter_analyzer_plugin/lib/main.dart‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,23 +29,25 @@ class FlutterAnalyzerPlugin extends Plugin {
2929
@override
3030
void register(PluginRegistry registry) {
3131
registry
32-
..registerWarningRule(AvoidFutureCatchError())
32+
// Repo-wide warning rules (migrated from dev/bots/analyze.dart validations).
3333
..registerWarningRule(DeprecationSyntax())
3434
..registerWarningRule(GoldenTestTags())
3535
..registerWarningRule(IntegrationTestTimeouts())
3636
..registerWarningRule(IssueLinkSyntax())
3737
..registerWarningRule(NoBadImportsInFlutter())
38-
..registerWarningRule(NoDoubleClamp())
39-
..registerWarningRule(NoRuntimeTypeInToString())
40-
..registerWarningRule(NoStopwatches())
4138
..registerWarningRule(NoSyncAsyncStar())
4239
..registerWarningRule(NoTestImports())
43-
..registerWarningRule(NullInitializedDebugExpensiveFields())
44-
..registerWarningRule(ProtectPublicStateSubtypes())
45-
..registerWarningRule(RenderBoxIntrinsicCalculationRule())
4640
..registerWarningRule(RepositoryLinkSyntax())
4741
..registerWarningRule(SkipTestComments())
48-
..registerWarningRule(TabooDocumentation());
42+
..registerWarningRule(TabooDocumentation())
43+
// Package-specific lint rules (opt-in via diagnostics: in analysis_options.yaml).
44+
..registerLintRule(AvoidFutureCatchError())
45+
..registerLintRule(NoDoubleClamp())
46+
..registerLintRule(NoRuntimeTypeInToString())
47+
..registerLintRule(NoStopwatches())
48+
..registerLintRule(NullInitializedDebugExpensiveFields())
49+
..registerLintRule(ProtectPublicStateSubtypes())
50+
..registerLintRule(RenderBoxIntrinsicCalculationRule());
4951
}
5052

5153
@override
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
9+
/// Base class for all custom analysis rules in the Flutter repository.
10+
///
11+
/// Automatically excludes read-only areas of the repository, including
12+
/// Material and Cupertino implementations and tests.
13+
abstract class FlutterAnalysisRule extends AnalysisRule {
14+
FlutterAnalysisRule({required super.name, required super.description});
15+
16+
@override
17+
void registerNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
18+
final String filePath = context.definingUnit.file.path.replaceAll(r'\', '/');
19+
if (isReadOnly(filePath)) {
20+
return;
21+
}
22+
registerCustomNodeProcessors(registry, context);
23+
}
24+
25+
/// Registers AST node processors for this rule when the target file is not exempt.
26+
void registerCustomNodeProcessors(RuleVisitorRegistry registry, RuleContext context);
27+
28+
/// Whether [normalizedPath] belongs to a read-only area of the repository
29+
/// (e.g. Material and Cupertino implementations and tests).
30+
static bool isReadOnly(String normalizedPath) {
31+
// In-memory test files in package:analyzer_testing start with /home/test
32+
if (normalizedPath.contains('/home/test')) {
33+
return false;
34+
}
35+
return normalizedPath.contains('/material/') ||
36+
normalizedPath.contains('/cupertino/') ||
37+
normalizedPath.endsWith('/material.dart') ||
38+
normalizedPath.endsWith('/cupertino.dart') ||
39+
normalizedPath.contains('src/material') ||
40+
normalizedPath.contains('src/cupertino') ||
41+
normalizedPath.contains('test/material') ||
42+
normalizedPath.contains('test/cupertino');
43+
}
44+
}

‎dev/flutter_analyzer_plugin/lib/src/rules/avoid_future_catch_error.dart‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@ import 'package:analyzer/dart/ast/visitor.dart';
1010
import 'package:analyzer/dart/element/type.dart';
1111
import 'package:analyzer/error/error.dart';
1212

13-
class AvoidFutureCatchError extends AnalysisRule {
13+
import '../flutter_analysis_rule.dart';
14+
15+
class AvoidFutureCatchError extends FlutterAnalysisRule {
1416
AvoidFutureCatchError()
1517
: super(
1618
name: code.name,
@@ -28,7 +30,7 @@ class AvoidFutureCatchError extends AnalysisRule {
2830
LintCode get diagnosticCode => code;
2931

3032
@override
31-
void registerNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
33+
void registerCustomNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
3234
final visitor = _Visitor(this, context);
3335
registry.addMethodInvocation(this, visitor);
3436
}

‎dev/flutter_analyzer_plugin/lib/src/rules/deprecation_syntax.dart‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,10 @@ import 'package:analyzer/dart/ast/visitor.dart';
1010
import 'package:analyzer/error/error.dart';
1111
import 'package:analyzer/source/line_info.dart';
1212

13+
import '../flutter_analysis_rule.dart';
14+
1315
/// A rule that enforces standard Flutter deprecation notice syntax.
14-
class DeprecationSyntax extends AnalysisRule {
16+
class DeprecationSyntax extends FlutterAnalysisRule {
1517
/// Creates a new [DeprecationSyntax] rule.
1618
DeprecationSyntax() : super(name: code.name, description: 'Verify deprecation syntax');
1719

@@ -28,7 +30,11 @@ class DeprecationSyntax extends AnalysisRule {
2830
DiagnosticCode get diagnosticCode => code;
2931

3032
@override
31-
void registerNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
33+
void registerCustomNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
34+
final String filePath = context.definingUnit.file.path.replaceAll(r'\', '/');
35+
if (filePath.contains('analyze-test-input')) {
36+
return;
37+
}
3238
registry.addAnnotation(this, _Visitor(this, context));
3339
}
3440
}

‎dev/flutter_analyzer_plugin/lib/src/rules/golden_test_tags.dart‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,14 @@ import 'package:analyzer/dart/ast/ast.dart';
99
import 'package:analyzer/dart/ast/visitor.dart';
1010
import 'package:analyzer/error/error.dart';
1111

12+
import '../flutter_analysis_rule.dart';
13+
1214
const String _matchesGoldenFile = 'matchesGoldenFile';
1315
const String _reducedTestSetTag = 'reduced-test-set';
1416
const String _tagsAnnotation = 'Tags';
1517

1618
/// Files containing golden tests must be tagged using `@Tags(<String>['reduced-test-set'])`.
17-
class GoldenTestTags extends AnalysisRule {
19+
class GoldenTestTags extends FlutterAnalysisRule {
1820
GoldenTestTags() : super(name: code.name, description: ruleDescription);
1921

2022
static const String ruleDescription =
@@ -33,7 +35,12 @@ class GoldenTestTags extends AnalysisRule {
3335
LintCode get diagnosticCode => code;
3436

3537
@override
36-
void registerNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
38+
void registerCustomNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
39+
final String filePath = context.definingUnit.file.path.replaceAll(r'\', '/');
40+
// Only golden tests in packages/flutter (or test runner) are subject to reduced testing tags.
41+
if (!filePath.contains('packages/flutter/test') && !filePath.contains('/home/test')) {
42+
return;
43+
}
3744
final visitor = _Visitor(this, context);
3845
registry.addMethodInvocation(this, visitor);
3946
}
@@ -48,10 +55,9 @@ class _Visitor extends SimpleAstVisitor<void> {
4855
bool? _hasReducedTestSetTagCache;
4956

5057
bool _isReducedTestSetTag(Annotation annotation) {
51-
final String? name = switch (annotation.name) {
58+
final String name = switch (annotation.name) {
5259
SimpleIdentifier(:final String name) => name,
5360
PrefixedIdentifier(:final SimpleIdentifier identifier) => identifier.name,
54-
_ => null,
5561
};
5662
if (name != _tagsAnnotation) {
5763
return false;
@@ -60,11 +66,15 @@ class _Visitor extends SimpleAstVisitor<void> {
6066
if (argumentList == null) {
6167
return false;
6268
}
63-
for (final Expression argument in argumentList.arguments) {
64-
final Expression expr = switch (argument) {
65-
NamedExpression(:final Expression expression) => expression,
66-
_ => argument,
69+
for (final Argument argument in argumentList.arguments) {
70+
final Expression? expr = switch (argument) {
71+
NamedArgument(:final Expression argumentExpression) => argumentExpression,
72+
final Expression expression => expression,
73+
_ => null,
6774
};
75+
if (expr == null) {
76+
continue;
77+
}
6878
if (expr case StringLiteral(
6979
:final String? stringValue,
7080
) when stringValue == _reducedTestSetTag) {

‎dev/flutter_analyzer_plugin/lib/src/rules/integration_test_timeouts.dart‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,14 @@ import 'package:analyzer/analysis_rule/analysis_rule.dart';
66
import 'package:analyzer/analysis_rule/rule_context.dart';
77
import 'package:analyzer/analysis_rule/rule_visitor_registry.dart';
88
import 'package:analyzer/dart/ast/ast.dart';
9+
import 'package:analyzer/dart/ast/token.dart';
910
import 'package:analyzer/dart/ast/visitor.dart';
1011
import 'package:analyzer/error/error.dart';
1112

12-
/// Integration tests in flutter test_driver must have `timeout: Timeout.none`.
13-
class IntegrationTestTimeouts extends AnalysisRule {
13+
import '../flutter_analysis_rule.dart';
14+
15+
/// Integration tests must specify `timeout: Timeout.none` to prevent them from getting stuck.
16+
class IntegrationTestTimeouts extends FlutterAnalysisRule {
1417
IntegrationTestTimeouts() : super(name: code.name, description: ruleDescription);
1518

1619
static const String ruleDescription =
@@ -27,9 +30,15 @@ class IntegrationTestTimeouts extends AnalysisRule {
2730
DiagnosticCode get diagnosticCode => code;
2831

2932
@override
30-
void registerNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
31-
final String filePath = context.definingUnit.file.path;
32-
if (!filePath.contains('test_driver') && !filePath.contains('test.dart')) {
33+
void registerCustomNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
34+
final String filePath = context.definingUnit.file.path.replaceAll(r'\', '/');
35+
if (!filePath.contains('/home/test') && !filePath.contains('/dev/')) {
36+
return;
37+
}
38+
if (!filePath.contains('test_driver') ||
39+
(!filePath.endsWith('_test.dart') &&
40+
!filePath.endsWith('util.dart') &&
41+
!filePath.endsWith('test.dart'))) {
3342
return;
3443
}
3544
final visitor = _Visitor(this);
@@ -48,10 +57,10 @@ class _Visitor extends SimpleAstVisitor<void> {
4857
methodName: SimpleIdentifier(name: 'test'),
4958
:final ArgumentList argumentList,
5059
)) {
51-
final bool hasTimeoutNone = argumentList.arguments.any((Expression argument) {
52-
if (argument case NamedExpression(
53-
name: Label(label: SimpleIdentifier(name: 'timeout')),
54-
expression: PrefixedIdentifier(
60+
final bool hasTimeoutNone = argumentList.arguments.any((Argument argument) {
61+
if (argument case NamedArgument(
62+
name: Token(lexeme: 'timeout'),
63+
argumentExpression: PrefixedIdentifier(
5564
prefix: SimpleIdentifier(name: 'Timeout'),
5665
identifier: SimpleIdentifier(name: 'none'),
5766
),

‎dev/flutter_analyzer_plugin/lib/src/rules/issue_link_syntax.dart‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import 'package:analyzer/dart/ast/token.dart';
1010
import 'package:analyzer/dart/ast/visitor.dart';
1111
import 'package:analyzer/error/error.dart';
1212

13+
import '../flutter_analysis_rule.dart';
14+
1315
// Pattern matching GitHub issue URLs starting with the Flutter issue creation prefix.
1416
// Delimiters (whitespace, quotes, backslashes, parentheses, brackets) define the URL boundary.
1517
final RegExp _issueUrlPattern = RegExp(
@@ -33,7 +35,7 @@ const Set<String> _validTemplates = <String>{
3335
};
3436

3537
/// Links to create GitHub issues must specify a valid template or use "/choose".
36-
class IssueLinkSyntax extends AnalysisRule {
38+
class IssueLinkSyntax extends FlutterAnalysisRule {
3739
IssueLinkSyntax() : super(name: code.name, description: ruleDescription);
3840

3941
static const String ruleDescription =
@@ -52,8 +54,8 @@ class IssueLinkSyntax extends AnalysisRule {
5254
LintCode get diagnosticCode => code;
5355

5456
@override
55-
void registerNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
56-
final String filePath = context.definingUnit.file.path;
57+
void registerCustomNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
58+
final String filePath = context.definingUnit.file.path.replaceAll(r'\', '/');
5759
if (filePath.endsWith('_test.dart') || filePath.endsWith('issue_link_syntax.dart')) {
5860
return;
5961
}
@@ -110,7 +112,6 @@ class _Visitor extends SimpleAstVisitor<void> {
110112

111113
@override
112114
void visitCompilationUnit(CompilationUnit node) {
113-
114115
// In the Dart analyzer AST, non-doc comments (`// ...`) are not represented
115116
// as Comment AST nodes; they are attached to lexical tokens as precedingComments.
116117
// We walk the token stream from beginToken to ensure all comments are inspected.
@@ -132,7 +133,6 @@ class _Visitor extends SimpleAstVisitor<void> {
132133

133134
@override
134135
void visitSimpleStringLiteral(SimpleStringLiteral node) {
135-
136136
// Ignore children of AdjacentStrings to avoid double-reporting;
137137
// visitAdjacentStrings inspects the full concatenated literal.
138138
if (node.parent is AdjacentStrings) {

0 commit comments

Comments
 (0)