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.addBlock((Block node) {
    final List<Statement> statements = node.statements;
    if (statements.length < 2) return;

    // Check for pattern: variable declaration followed by return of that variable
    for (int i = 0; i < statements.length - 1; i++) {
      final Statement current = statements[i];
      final Statement next = statements[i + 1];

      if (current is! VariableDeclarationStatement) continue;
      if (next is! ReturnStatement) continue;

      final VariableDeclarationList varList = current.variables;
      if (varList.variables.length != 1) continue;

      final VariableDeclaration varDecl = varList.variables.first;
      if (varDecl.initializer == null) continue;

      final Expression? returnExpr = next.expression;
      if (returnExpr is! SimpleIdentifier) continue;

      // Check if return uses the same variable
      if (returnExpr.name == varDecl.name.lexeme) {
        reporter.atNode(current);
      }
    }
  });
}