runWithReporter method

  1. @override
void runWithReporter(
  1. SaropaDiagnosticReporter reporter,
  2. SaropaContext context
)
override

Override this method to implement your lint rule.

Use context to register callbacks for AST node types:

context.addMethodInvocation((node) {
  if (condition) {
    reporter.atNode(node);
  }
});

Implementation

@override
void runWithReporter(
  SaropaDiagnosticReporter reporter,
  SaropaContext context,
) {
  context.addInstanceCreationExpression((InstanceCreationExpression node) {
    final String typeName = node.constructorName.type.name.lexeme;
    if (typeName != 'Paint') return;

    // Check if inside a paint() method
    bool insidePaintMethod = false;
    bool inCustomPainter = false;
    AstNode? current = node.parent;

    while (current != null) {
      if (current is MethodDeclaration && current.name.lexeme == 'paint') {
        insidePaintMethod = true;
      }
      if (current is ClassDeclaration) {
        final ExtendsClause? extendsClause = current.extendsClause;
        if (extendsClause != null) {
          final String? superName = extendsClause.superclass.element?.name;
          if (superName == 'CustomPainter') {
            inCustomPainter = true;
          }
        }
        break;
      }
      current = current.parent;
    }

    if (insidePaintMethod && inCustomPainter) {
      reporter.atNode(node.constructorName, code);
    }
  });
}