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


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

def autocorrect(node)
  current_buffer_src = processed_source.buffer.source
  replaced_range = node.loc.expression
  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 = ProcessedSource.new(new_buffer_src)

  # 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