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.addBinaryExpression((BinaryExpression node) {
    final String op = node.operator.lexeme;
    if (op != '==' && op != '!=') return;

    final Expression left = node.leftOperand;
    final Expression right = node.rightOperand;

    // One side must be null literal
    final Expression? nonNullSide;
    if (right is NullLiteral) {
      nonNullSide = left;
    } else if (left is NullLiteral) {
      nonNullSide = right;
    } else {
      return;
    }

    final DartType? type = nonNullSide.staticType;
    if (type == null) return;

    // Skip dynamic, Object, and type parameters
    if (type is DynamicType) return;
    if (type.isDartCoreObject) return;
    if (type is TypeParameterType) return;

    // Flag if the type is non-nullable
    if (type.nullabilitySuffix == NullabilitySuffix.none) {
      reporter.atNode(node);
    }
  });
}