Module: RuboCop::Cop::AutocorrectUnlessChangingAST

Included in:
Style::AndOr, Style::Blocks, Style::Not
Defined in:
lib/rubocop/cop/mixin/autocorrect_unless_changing_ast.rb

Overview

This module does auto-correction of nodes that could become grammatically different after the correction. If the code change would alter the abstract syntax tree, it is not done.

Instance Method Summary collapse

Instance Method Details

#autocorrect(node) ⇒ Object


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rubocop/cop/mixin/autocorrect_unless_changing_ast.rb', line 9

def autocorrect(node)
  new_source = rewrite_node(node)

  # Make the correction only if it doesn't change the AST. Regenerate the
  # AST for `node` so we get it without context. Otherwise the comparison
  # could be misleading.
  if ast_for(node.loc.expression.source) != ast_for(new_source)
    fail CorrectionNotPossible
  end

  if syntax_error?(node.loc.expression, new_source)
    fail CorrectionNotPossible
  end

  @corrections << correction(node)
end