Auto-format Framework (#160545)

This auto-formats all *.dart files in the repository outside of the
`engine` subdirectory and enforces that these files stay formatted with
a presubmit check.

**Reviewers:** Please carefully review all the commits except for the
one titled "formatted". The "formatted" commit was auto-generated by
running `dev/tools/format.sh -a -f`. The other commits were hand-crafted
to prepare the repo for the formatting change. I recommend reviewing the
commits one-by-one via the "Commits" tab and avoiding Github's "Files
changed" tab as it will likely slow down your browser because of the
size of this PR.

---------

Co-authored-by: Kate Lovett <katelovett@google.com>
Co-authored-by: LongCatIsLooong <31859944+LongCatIsLooong@users.noreply.github.com>
This commit is contained in:
Michael Goderbauer
2024-12-19 12:06:21 -08:00
committed by GitHub
parent 8e0993eda8
commit 5491c8c146
4411 changed files with 455108 additions and 415991 deletions

View File

@@ -25,18 +25,26 @@ import '../utils.dart';
///
/// If a compilation unit can not be resolved, this function ignores the
/// corresponding dart source file and logs an error using [foundError].
Future<void> analyzeWithRules(String flutterRootDirectory, List<AnalyzeRule> rules, {
Future<void> analyzeWithRules(
String flutterRootDirectory,
List<AnalyzeRule> rules, {
Iterable<String>? includePaths,
Iterable<String>? excludePaths,
}) async {
if (!Directory(flutterRootDirectory).existsSync()) {
foundError(<String>['Analyzer error: the specified $flutterRootDirectory does not exist.']);
}
final Iterable<String> includes = includePaths?.map((String relativePath) => path.canonicalize('$flutterRootDirectory/$relativePath'))
?? <String>[path.canonicalize(flutterRootDirectory)];
final Iterable<String> includes =
includePaths?.map(
(String relativePath) => path.canonicalize('$flutterRootDirectory/$relativePath'),
) ??
<String>[path.canonicalize(flutterRootDirectory)];
final AnalysisContextCollection collection = AnalysisContextCollection(
includedPaths: includes.toList(),
excludedPaths: excludePaths?.map((String relativePath) => path.canonicalize('$flutterRootDirectory/$relativePath')).toList(),
excludedPaths:
excludePaths
?.map((String relativePath) => path.canonicalize('$flutterRootDirectory/$relativePath'))
.toList(),
);
final List<String> analyzerErrors = <String>[];
@@ -51,7 +59,9 @@ Future<void> analyzeWithRules(String flutterRootDirectory, List<AnalyzeRule> rul
rule.applyTo(unit);
}
} else {
analyzerErrors.add('Analyzer error: file $unit could not be resolved. Expected "ResolvedUnitResult", got ${unit.runtimeType}.');
analyzerErrors.add(
'Analyzer error: file $unit could not be resolved. Expected "ResolvedUnitResult", got ${unit.runtimeType}.',
);
}
}
}

View File

@@ -55,13 +55,13 @@ class _DoubleClampVisitor extends RecursiveAstVisitor<void> {
// We don't care about directives or comments.
@override
void visitImportDirective(ImportDirective node) { }
void visitImportDirective(ImportDirective node) {}
@override
void visitExportDirective(ExportDirective node) { }
void visitExportDirective(ExportDirective node) {}
@override
void visitComment(Comment node) { }
void visitComment(Comment node) {}
@override
void visitSimpleIdentifier(SimpleIdentifier node) {
@@ -76,19 +76,35 @@ class _DoubleClampVisitor extends RecursiveAstVisitor<void> {
// final f = 1.clamp;
// final y = f(0, 2) // The inferred return type is num.
PropertyAccess(
target: Expression(staticType: DartType(isDartCoreDouble: true) || DartType(isDartCoreNum: true) || DartType(isDartCoreInt: true)),
) => false,
target: Expression(
staticType: DartType(isDartCoreDouble: true) ||
DartType(isDartCoreNum: true) ||
DartType(isDartCoreInt: true),
),
) =>
false,
// Expressions like `final int x = 1.clamp(0, 2);` should be allowed.
MethodInvocation(
target: Expression(staticType: DartType(isDartCoreInt: true)),
argumentList: ArgumentList(arguments: [Expression(staticType: DartType(isDartCoreInt: true)), Expression(staticType: DartType(isDartCoreInt: true))]),
) => true,
argumentList: ArgumentList(
arguments: [
Expression(staticType: DartType(isDartCoreInt: true)),
Expression(staticType: DartType(isDartCoreInt: true)),
],
),
) =>
true,
// Otherwise, disallow num.clamp() invocations.
MethodInvocation(
target: Expression(staticType: DartType(isDartCoreDouble: true) || DartType(isDartCoreNum: true) || DartType(isDartCoreInt: true)),
) => false,
target: Expression(
staticType: DartType(isDartCoreDouble: true) ||
DartType(isDartCoreNum: true) ||
DartType(isDartCoreInt: true),
),
) =>
false,
_ => true,
};

View File

@@ -50,7 +50,7 @@ class _NoStopwatches implements AnalyzeRule {
for (final AstNode node in entry.value)
'${locationInFile(entry.key, node)}: ${node.parent}',
'\n${bold}Stopwatches introduce flakes by falling out of sync with the FakeAsync used in testing.$reset',
'A Stopwatch that stays in sync with FakeAsync is available through the Gesture or Test bindings, through samplingClock.'
'A Stopwatch that stays in sync with FakeAsync is available through the Gesture or Test bindings, through samplingClock.',
]);
}
@@ -83,8 +83,11 @@ class _StopwatchVisitor extends RecursiveAstVisitor<void> {
// The cached version, call this method instead of _checkIfImplementsStopwatchRecursively.
bool _implementsStopwatch(ClassElement classElement) {
return classElement.library.isDartCore
? classElement.name == 'Stopwatch'
:_isStopwatchClassElementCache.putIfAbsent(classElement, () => _checkIfImplementsStopwatchRecursively(classElement));
? classElement.name == 'Stopwatch'
: _isStopwatchClassElementCache.putIfAbsent(
classElement,
() => _checkIfImplementsStopwatchRecursively(classElement),
);
}
bool _isInternal(LibraryElement libraryElement) {
@@ -96,19 +99,22 @@ class _StopwatchVisitor extends RecursiveAstVisitor<void> {
bool _hasTrailingFlutterIgnore(AstNode node) {
return compilationUnit.content
.substring(node.offset + node.length, compilationUnit.lineInfo.getOffsetOfLineAfter(node.offset + node.length))
.contains(_ignoreStopwatch);
.substring(
node.offset + node.length,
compilationUnit.lineInfo.getOffsetOfLineAfter(node.offset + node.length),
)
.contains(_ignoreStopwatch);
}
// We don't care about directives or comments, skip them.
@override
void visitImportDirective(ImportDirective node) { }
void visitImportDirective(ImportDirective node) {}
@override
void visitExportDirective(ExportDirective node) { }
void visitExportDirective(ExportDirective node) {}
@override
void visitComment(Comment node) { }
void visitComment(Comment node) {}
@override
void visitConstructorName(ConstructorName node) {
@@ -118,7 +124,8 @@ class _StopwatchVisitor extends RecursiveAstVisitor<void> {
return;
}
final bool isAllowed = switch (element.returnType) {
InterfaceType(element: final ClassElement classElement) => !_implementsStopwatch(classElement),
InterfaceType(element: final ClassElement classElement) =>
!_implementsStopwatch(classElement),
InterfaceType(element: InterfaceElement()) => true,
};
if (isAllowed || _hasTrailingFlutterIgnore(node)) {
@@ -132,8 +139,9 @@ class _StopwatchVisitor extends RecursiveAstVisitor<void> {
final bool isAllowed = switch (node.staticElement) {
ExecutableElement(
returnType: DartType(element: final ClassElement classElement),
library: final LibraryElement libraryElement
) => _isInternal(libraryElement) || !_implementsStopwatch(classElement),
library: final LibraryElement libraryElement,
) =>
_isInternal(libraryElement) || !_implementsStopwatch(classElement),
Element() || null => true,
};
if (isAllowed || _hasTrailingFlutterIgnore(node)) {

View File

@@ -17,7 +17,8 @@ import 'analyze.dart';
final AnalyzeRule protectPublicStateSubtypes = _ProtectPublicStateSubtypes();
class _ProtectPublicStateSubtypes implements AnalyzeRule {
final Map<ResolvedUnitResult, List<MethodDeclaration>> _errors = <ResolvedUnitResult, List<MethodDeclaration>>{};
final Map<ResolvedUnitResult, List<MethodDeclaration>> _errors =
<ResolvedUnitResult, List<MethodDeclaration>>{};
@override
void applyTo(ResolvedUnitResult unit) {
@@ -35,15 +36,13 @@ class _ProtectPublicStateSubtypes implements AnalyzeRule {
return;
}
foundError(
<String>[
for (final MapEntry<ResolvedUnitResult, List<MethodDeclaration>> entry in _errors.entries)
for (final MethodDeclaration method in entry.value)
'${locationInFile(entry.key, method, workingDirectory)}: $method - missing "@protected" annotation.',
'\nPublic State subtypes should add @protected when overriding methods,',
'to avoid exposing internal logic to developers.',
],
);
foundError(<String>[
for (final MapEntry<ResolvedUnitResult, List<MethodDeclaration>> entry in _errors.entries)
for (final MethodDeclaration method in entry.value)
'${locationInFile(entry.key, method, workingDirectory)}: $method - missing "@protected" annotation.',
'\nPublic State subtypes should add @protected when overriding methods,',
'to avoid exposing internal logic to developers.',
]);
}
@override

View File

@@ -12,22 +12,23 @@ import '../utils.dart';
import 'analyze.dart';
/// Verify that no RenderBox subclasses call compute* instead of get* for
/// computing the intrinsic dimensions. The full list of RenderBox intrinsic
/// methods checked by this rule is listed in [candidates].
/// computing the intrinsic dimensions. The [candidates] variable contains the
/// full list of RenderBox intrinsic method invocations checked by this rule.
final AnalyzeRule renderBoxIntrinsicCalculation = _RenderBoxIntrinsicCalculationRule();
const Map<String, String> candidates = <String, String> {
const Map<String, String> candidates = <String, String>{
'computeDryBaseline': 'getDryBaseline',
'computeDryLayout': 'getDryLayout',
'computeDistanceToActualBaseline': 'getDistanceToBaseline, or getDistanceToActualBaseline',
'computeMaxIntrinsicHeight': 'getMaxIntrinsicHeight',
'computeMinIntrinsicHeight': 'getMinIntrinsicHeight',
'computeMaxIntrinsicWidth': 'getMaxIntrinsicWidth',
'computeMinIntrinsicWidth': 'getMinIntrinsicWidth'
'computeMinIntrinsicWidth': 'getMinIntrinsicWidth',
};
class _RenderBoxIntrinsicCalculationRule implements AnalyzeRule {
final Map<ResolvedUnitResult, List<(AstNode, String)>> _errors = <ResolvedUnitResult, List<(AstNode, String)>>{};
final Map<ResolvedUnitResult, List<(AstNode, String)>> _errors =
<ResolvedUnitResult, List<(AstNode, String)>>{};
@override
void applyTo(ResolvedUnitResult unit) {
@@ -60,30 +61,36 @@ class _RenderBoxIntrinsicCalculationRule implements AnalyzeRule {
class _RenderBoxSubclassVisitor extends RecursiveAstVisitor<void> {
final List<(AstNode, String)> violationNodes = <(AstNode, String)>[];
static final Map<InterfaceElement, bool> _isRenderBoxClassElementCache = <InterfaceElement, bool>{};
static final Map<InterfaceElement, bool> _isRenderBoxClassElementCache =
<InterfaceElement, bool>{};
// The cached version, call this method instead of _checkIfImplementsRenderBox.
static bool _implementsRenderBox(InterfaceElement interfaceElement) {
// Framework naming convention: a RenderObject subclass names have "Render" in its name.
if (!interfaceElement.name.contains('Render')) {
return false;
}
return interfaceElement.name == 'RenderBox'
|| _isRenderBoxClassElementCache.putIfAbsent(interfaceElement, () => _checkIfImplementsRenderBox(interfaceElement));
return interfaceElement.name == 'RenderBox' ||
_isRenderBoxClassElementCache.putIfAbsent(
interfaceElement,
() => _checkIfImplementsRenderBox(interfaceElement),
);
}
static bool _checkIfImplementsRenderBox(InterfaceElement element) {
return element.allSupertypes.any((InterfaceType interface) => _implementsRenderBox(interface.element));
return element.allSupertypes.any(
(InterfaceType interface) => _implementsRenderBox(interface.element),
);
}
// We don't care about directives, comments, or asserts.
@override
void visitImportDirective(ImportDirective node) { }
void visitImportDirective(ImportDirective node) {}
@override
void visitExportDirective(ExportDirective node) { }
void visitExportDirective(ExportDirective node) {}
@override
void visitComment(Comment node) { }
void visitComment(Comment node) {}
@override
void visitAssertStatement(AssertStatement node) { }
void visitAssertStatement(AssertStatement node) {}
@override
void visitClassDeclaration(ClassDeclaration node) {
@@ -101,15 +108,16 @@ class _RenderBoxSubclassVisitor extends RecursiveAstVisitor<void> {
return;
}
final bool isCallingSuperImplementation = switch (node.parent) {
PropertyAccess(target: SuperExpression()) ||
MethodInvocation(target: SuperExpression()) => true,
PropertyAccess(target: SuperExpression()) || MethodInvocation(target: SuperExpression()) =>
true,
_ => false,
};
if (isCallingSuperImplementation) {
return;
}
final Element? declaredInClassElement = node.staticElement?.declaration?.enclosingElement;
if (declaredInClassElement is InterfaceElement && _implementsRenderBox(declaredInClassElement)) {
if (declaredInClassElement is InterfaceElement &&
_implementsRenderBox(declaredInClassElement)) {
violationNodes.add((node, correctMethodName));
}
}