run method

  1. @override
void run(
  1. CustomLintResolver resolver,
  2. ChangeReporter reporter,
  3. CustomLintContext context,
  4. SourceRange target,
)

Emits lints for a given file.

run will only be invoked with files respecting filesToAnalyze

Implementation

@override
void run(
  CustomLintResolver resolver,
  ChangeReporter reporter,
  CustomLintContext context,
  SourceRange target,
) {
  context.registry.addFormalParameterList((node) {
    // parameter list has positional optional parameters, named params cannot be added
    if (node.leftDelimiter?.kind == TokenType.OPEN_SQUARE_BRACKET.kind) {
      return;
    }

    final parameters =
        node.parameters.where((parameter) => parameter.isRequiredPositional);

    final nextItem = parameters
        .skip(1)
        .cast<SyntacticEntity>()
        .followedBy([node.leftDelimiter ?? node.rightParenthesis]);

    final found = parameters
        .zip(nextItem)
        .map(
          (e) => (e.$1, SourceRange(e.$1.offset, e.$2.offset - e.$1.offset)),
        )
        .firstWhereOrNull((e) => target.intersects(e.$2));

    if (found == null) {
      return;
    }

    final (parameter, sourceRange) = found;

    reporter
        .createChangeBuilder(
      message: 'Convert to named formal parameter',
      priority: 1,
    )
        .addDartFileEdit((builder) {
      // delete positional parameter
      builder.addDeletion(sourceRange);

      final namedParam =
          '${Keyword.REQUIRED.lexeme} ${Keyword.THIS.lexeme}.${parameter.name},';

      if (node.leftDelimiter case final brace?) {
        // has named parameters, add to list
        builder.addSimpleInsertion(brace.offset + 1, namedParam);
      } else {
        // no named parameters, create
        builder.addSimpleInsertion(
          node.rightParenthesis.offset,
          '{$namedParam}',
        );
      }

      builder.format(node.sourceRange);
    });
  });
}