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.addConstructorDeclaration((ConstructorDeclaration node) {
    final FunctionBody body = node.body;

    // Skip empty or expression bodies
    if (body is EmptyFunctionBody) return;
    if (body is ExpressionFunctionBody) {
      // Expression body in constructor is usually a redirect
      return;
    }

    if (body is BlockFunctionBody) {
      final Block block = body.block;
      // Allow empty blocks
      if (block.statements.isEmpty) return;

      // Check if it's just assert statements (allowed)
      bool hasOnlyAsserts = true;
      for (final Statement stmt in block.statements) {
        if (stmt is! AssertStatement) {
          hasOnlyAsserts = false;
          break;
        }
      }
      if (hasOnlyAsserts) return;

      // typeName is null for unnamed factory constructors
      final Token? nameToken = node.name ?? node.typeName?.beginToken;
      if (nameToken != null) {
        reporter.atToken(nameToken);
      }
    }
  });
}