Module: RuboCop::Cop::AutocorrectUnlessChangingAST

Included in:
Style::AndOr, Style::BlockDelimiters, Style::BracesAroundHashParameters, Style::Lambda, 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.

However, if the code change merely introduces extraneous “begin” nodes which do not change the meaning of the code, it is still accepted.

Defined Under Namespace

Classes: InlineBeginNodes

Instance Method Summary collapse

Instance Method Details

#autocorrect(node) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/rubocop/cop/mixin/autocorrect_unless_changing_ast.rb', line 14

def autocorrect(node)
  current_buffer_src = processed_source.buffer.source
  replaced_range = node.source_range
  pre = current_buffer_src[0...replaced_range.begin_pos]
  post = current_buffer_src[replaced_range.end_pos..-1]
  new_buffer_src = pre + rewrite_node(node) + post
  new_processed_src = parse(new_buffer_src, processed_source.buffer.name)

  # Make the correction only if it doesn't change the AST for the buffer.
  return if !new_processed_src.ast ||
            (INLINE_BEGIN.process(processed_source.ast) !=
             INLINE_BEGIN.process(new_processed_src.ast))

  correction(node)
end