Skip to content

Create linter that flags Double.clamp usage #103917

@gaaclarke

Description

@gaaclarke

clampDouble is 12x faster than Double.clamp and we should make sure that new usage of Double.clamp don't show up.

Context: #103559

I tried to implement it in dev/bots/analyze.dart but I got blocked with my AST's were not "resolved" so I didn't have the type information to know if we are calling clamp on doubles.

Here's how far I got:

class _DoubleClampVisitor extends RecursiveAstVisitor<CompilationUnit> {
  List<int> doubleClamps = <int>[];
  final ParseStringResult parseResult;
  _DoubleClampVisitor(this.parseResult);

  @override
  CompilationUnit? visitMethodInvocation(MethodInvocation node) {
    if (node.methodName.name == 'clamp') {
      print(node.argumentList.arguments.first);
    }

    node.visitChildren(this);
    return null;
  }
}

/// Verify that we use clampDouble instead of Double.clamp for performance reasons.
Future<void> verifyNoDoubleClamp(String workingDirectory) async {
  final String flutterLibPath = '$workingDirectory/packages/flutter/lib';
  final Stream<File> testFiles =
      _allFiles(flutterLibPath, 'dart', minimumMatches: 100);
  await for (final File file in testFiles) {
    try {
      final ParseStringResult parseResult = parseFile(
        featureSet: FeatureSet.fromEnableFlags2(
            sdkLanguageVersion: Version.parse('2.17.0-0'),
            flags: <String>['super-parameters']),
        path: file.absolute.path,
      );
      final _DoubleClampVisitor visitor = _DoubleClampVisitor(parseResult);
      visitor.visitCompilationUnit(parseResult.unit);
      for (final int doubleClamp in visitor.doubleClamps) {
        final int lineNumber =
            parseResult.lineInfo.getLocation(doubleClamp).lineNumber;
        print('${file.path} $lineNumber');
      }
    } catch (ex) {
      /// TODO(gaaclarke): There appears to be a bug with super parameter
      /// parsing on mac so we skip certain files until that is fixed.
      print('skipping ${file.path}: $ex');
    }
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Important issues not at the top of the work listframeworkflutter/packages/flutter repository. See also f: labels.team-frameworkOwned by Framework teamtriaged-frameworkTriaged by Framework team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions