registerNodeProcessors method

  1. @override
void registerNodeProcessors(
  1. RuleVisitorRegistry registry,
  2. RuleContext context
)

Registers node processors in the given registry.

The node processors may use the provided context to access information that is not available from the AST nodes or their associated elements.

Implementation

@override
void registerNodeProcessors(
  RuleVisitorRegistry registry,
  RuleContext context,
) {
  // The plugin framework has no API for rule specific configuration yet,
  // so the `string_literal_finder:` section of `analysis_options.yaml` is
  // parsed by hand in `findAnalysisOptions` below.
  // See https://github.com/dart-lang/sdk/issues/63098
  final visitor = StringLiteralVisitor.context(
    // The rule framework walks the unit itself and dispatches every
    // registered node type, so the visitor must not descend as well.
    descendIntoInterpolations: false,
    context: () => StringLiteralContext(
      filePath: context.currentUnit?.file.path ?? '',
      unit: context.currentUnit?.unit,
      lineInfo: context.currentUnit?.unit.lineInfo,
    ),
    foundStringLiteral: (foundStringLiteral) {
      final file = context.currentUnit?.file;
      final options = findAnalysisOptions(file);
      if (file != null) {
        if (options != null && options.isExcluded(file.path)) {
          return;
        }
      }
      final content = context.currentUnit?.content ?? '';
      String stringValue() {
        if (content.length < foundStringLiteral.charEnd) {
          return '';
        }
        return content
            .substring(
              foundStringLiteral.charOffset,
              foundStringLiteral.charEnd,
            )
            .trim();
      }

      final stringCode = foundStringLiteral.stringValue ?? stringValue();
      reportAtNode(foundStringLiteral.stringLiteral, arguments: [stringCode]);
    },
  );
  // All three concrete `StringLiteral` subtypes have to be registered
  // individually. Omitting `StringInterpolation` used to make the plugin
  // blind to exactly the literals that matter most, e.g. `'$distance km'`.
  registry.addSimpleStringLiteral(this, visitor);
  registry.addAdjacentStrings(this, visitor);
  registry.addStringInterpolation(this, visitor);
}