check method

  1. @override
void check(
  1. DcqRegistry registry
)

Implementation

@override
void check(DcqRegistry registry) {
  final allowed = _parseAllowed(ruleConfig) ?? const [-1, 0, 1];
  final ignoreInstances = configBool(ruleConfig, 'ignore-instances') ?? false;
  final allowOnlyOnce = configBool(ruleConfig, 'allow-only-once') ?? false;
  final pending = <_MagicLiteral>[];

  void checkLiteral(AstNode node, num value) {
    if (allowed.contains(value)) return;
    if (_isInConstContext(node)) return;
    if (_isInDateTimeConstructor(node)) return;
    if (_isInAnnotation(node)) return;
    if (_isInDefaultParameterValue(node)) return;
    if (_isInEnumConstant(node)) return;
    if (ignoreInstances && _isInInstanceCreation(node)) return;

    final parent = node.parent;
    if (parent is PrefixExpression &&
        parent.operator.lexeme == '-' &&
        allowed.contains(-value)) {
      return;
    }

    if (allowOnlyOnce) {
      pending.add(_MagicLiteral(node, value));
    } else {
      reportAtNode(node);
    }
  }

  registry.addIntegerLiteral((node) {
    checkLiteral(node, node.value ?? 0);
  });

  registry.addDoubleLiteral((node) {
    checkLiteral(node, node.value);
  });

  if (allowOnlyOnce) {
    registry.afterLibrary(() {
      final groups = <num, List<AstNode>>{};
      for (final entry in pending) {
        (groups[entry.value] ??= []).add(entry.node);
      }
      for (final nodes in groups.values) {
        if (nodes.length > 1) {
          for (final n in nodes) {
            reportAtNode(n);
          }
        }
      }
    });
  }
}