class Fast::Rewriter

Rewriter encapsulates {Rewriter#match_index} to allow {ExperimentFile.partial_replace} in a {Fast::ExperimentFile}. @see www.rubydoc.info/github/whitequark/parser/Parser/TreeRewriter @note the standalone class needs to combines {Rewriter#replace_on} to properly generate the `on_<node-type>` methods depending on the expression being used. @example Simple Rewriter

rewriter = Rewriter.new buffer
rewriter.ast = Fast.ast("a = 1")
rewriter.search ='(lvasgn _ ...)'
rewriter.replacement =  -> (node) { replace(node.location.name, 'variable_renamed') }
rewriter.rewrite! # => "variable_renamed = 1"

Attributes

ast[RW]
match_index[R]

@return [Integer] with occurrence index

replacement[RW]
source[RW]

Public Class Methods

new(*_args) click to toggle source
Calls superclass method
# File lib/fast/rewriter.rb, line 61
def initialize(*_args)
  super()
  @match_index = 0
end

Public Instance Methods

buffer() click to toggle source
# File lib/fast/rewriter.rb, line 71
def buffer
  buffer = Parser::Source::Buffer.new('replacement')
  buffer.source = source || ast.loc.expression.source
  buffer
end
execute_replacement(node, captures) click to toggle source

Execute {#replacement} block @param [Astrolabe::Node] node that will be yield in the replacement block @param [Array<Object>, nil] captures are yield if {#replacement} take second argument.

# File lib/fast/rewriter.rb, line 103
def execute_replacement(node, captures)
  if replacement.parameters.length == 1
    instance_exec node, &replacement
  else
    instance_exec node, captures, &replacement
  end
end
match?(node) click to toggle source
# File lib/fast/rewriter.rb, line 82
def match?(node)
  Fast.match?(search, node)
end
replace_on(*types) click to toggle source

Generate methods for all affected types. @see Fast.replace

Calls superclass method
# File lib/fast/rewriter.rb, line 88
def replace_on(*types)
  types.map do |type|
    self.class.send :define_method, "on_#{type}" do |node|
      if captures = match?(node) # rubocop:disable Lint/AssignmentInCondition
        @match_index += 1
        execute_replacement(node, captures)
      end
      super(node)
    end
  end
end
rewrite!() click to toggle source
# File lib/fast/rewriter.rb, line 66
def rewrite!
  replace_on(*types)
  rewrite(buffer, ast)
end
types() click to toggle source

@return [Array<Symbol>] with all types that matches

# File lib/fast/rewriter.rb, line 78
def types
  Fast.search(search, ast).grep(Parser::AST::Node).map(&:type).uniq
end