flutter_corelibrary icon indicating copy to clipboard operation
flutter_corelibrary copied to clipboard

Feat: Add Quick Fix for `catch_parameter_names` rule

Open natty-pluz opened this issue 11 months ago • 0 comments

This PR introduces an automated Quick Fix for the existing catch_parameter_names lint rule.

Previously, the linter would warn if catch parameters (exception or stack trace) did not match the configured standard (default err, st), but users had to manually rename them. This update adds a DartFix that automatically renames the parameter and all its usages within the catch block.

Changes

  1. New Fix Class (RenameCatchParameter):

    • Analyzes the specific parameter causing the lint error.
    • Determines the correct replacement name based on the CatchParameterNamesConfig.
    • Implements a RecursiveAstVisitor (_UsageFinder) to safely find all usages of that parameter within the catch block scope.
    • Handles Shadowing: Correctly detects and skips nested scopes (nested catch clauses, function declarations, or function expressions) where the parameter name might be shadowed, ensuring safe refactoring.
  2. Updated CatchParameterNames Rule:

    • Registered RenameCatchParameter in getFixes().
  3. Documentation:

    • Updated README.md to indicate that catch_parameter_names now supports a Quick Fix.

Example

Configuration:

custom_lint:
  rules:
    - catch_parameter_names:
      exception: error
      stack_trace: stackTrace

Input (Before Fix):

try {
  // ...
} catch (e, s) { // LINT: Parameter name for exception/stacktrace is non-standard.
  print(e);
  log(s);
}

Output (After Fix):

try {
  // ...
} catch (error, stackTrace) {
  print(error);
  log(stackTrace);
}

Implementation Details

The fix logic is sturdy against scope shadowing. For example, in the following case, the inner e is not renamed when fixing the outer catch block:

try {
  // ...
} catch (e) { // Fix triggered here
  print(e); // Renamed

  try { ... } catch (e) { // Shadowed variable
     print(e); // Ignored/Not renamed
  }
}

Checklist

  • [x] The code compiles correctly.
  • [x] Lint rules passed.
  • [x] README.md updated.
  • [x] Tested with custom configuration options.

natty-pluz avatar Dec 31 '25 22:12 natty-pluz