Class: Parser::Rewriter

Inherits:
AST::Processor show all
Defined in:
lib/parser/rewriter.rb

Overview

Rewriter offers a basic API that makes it easy to rewrite existing ASTs. It’s built on top of AST::Processor and Source::Rewriter.

For example, assume you want to remove do tokens from a while statement. You can do this as following:

require 'parser/current'

class RemoveDo < Parser::Rewriter
  def on_while(node)
    # Check if the statement starts with "do"
    if node.location.begin.is?('do')
      remove(node.location.begin)
    end
  end
end

code = <<-EOF
while true do
  puts 'hello'
end
EOF

buffer        = Parser::Source::Buffer.new('(example)')
buffer.source = code
parser        = Parser::CurrentRuby.new
ast           = parser.parse(buffer)
rewriter      = RemoveDo.new

# Rewrite the AST, returns a String with the new form.
puts rewriter.rewrite(buffer, ast)

This would result in the following Ruby code:

while true
  puts 'hello'
end

Keep in mind that Rewriter does not take care of indentation when inserting/replacing code so you’ll have to do this yourself.

See also a blog entry describing rewriters in greater detail.

Instance Method Summary (collapse)

Methods inherited from AST::Processor

#on_argument, #on_casgn, #on_const, #on_def, #on_defs, #on_op_asgn, #on_send, #on_var, #on_vasgn, #process_argument_node, #process_regular_node, #process_var_asgn_node, #process_variable_node

Instance Method Details

- (Boolean) assignment?(node)

Returns true if the specified node is an assignment node, returns false otherwise.

Parameters:

Returns:

  • (Boolean)


75
76
77
# File 'lib/parser/rewriter.rb', line 75

def assignment?(node)
  [:lvasgn, :ivasgn, :gvasgn, :cvasgn, :casgn].include?(node.type)
end

- (Object) insert_after(range, content)

Inserts new code after the given source range.

Parameters:



104
105
106
# File 'lib/parser/rewriter.rb', line 104

def insert_after(range, content)
  @source_rewriter.insert_after(range, content)
end

- (Object) insert_before(range, content)

Inserts new code before the given source range.

Parameters:



94
95
96
# File 'lib/parser/rewriter.rb', line 94

def insert_before(range, content)
  @source_rewriter.insert_before(range, content)
end

- (Object) remove(range)

Removes the source range.

Parameters:



84
85
86
# File 'lib/parser/rewriter.rb', line 84

def remove(range)
  @source_rewriter.remove(range)
end

- (Object) replace(range, content)

Replaces the code of the source range range with content.

Parameters:



114
115
116
# File 'lib/parser/rewriter.rb', line 114

def replace(range, content)
  @source_rewriter.replace(range, content)
end

- (String) rewrite(source_buffer, ast)

Rewrites the AST/source buffer and returns a String containing the new version.

Parameters:

Returns:



60
61
62
63
64
65
66
# File 'lib/parser/rewriter.rb', line 60

def rewrite(source_buffer, ast)
  @source_rewriter = Source::Rewriter.new(source_buffer)

  process(ast)

  @source_rewriter.process
end