class Parser::TreeRewriter
@api public
describing rewriters in greater detail.
See also [a blog entry](whitequark.org/blog/2013/04/26/lets-play-with-ruby-code/)
inserting/replacing code so you’ll have to do this yourself.
Keep in mind that {Parser::TreeRewriter} does not take care of indentation when
end
puts ‘hello’
while true
This would result in the following Ruby code:
puts rewriter.rewrite(buffer, ast)
# Rewrite the AST, returns a String with the new form.
rewriter = RemoveDo.new
buffer = Parser::Source::Buffer.new(‘(example)’, source: code)
ast = Parser::CurrentRuby.parse code
EOF
end
puts ‘hello’
while true do
code = <<-EOF
end
end
end
remove(node.location.begin)
if node.location.begin.is?(‘do’)
# Check if the statement starts with “do”
def on_while(node)
class RemoveDo < Parser::TreeRewriter
require ‘parser/current’
You can do this as following:
For example, assume you want to remove ‘do` tokens from a while statement.
{Parser::Source::TreeRewriter}
existing ASTs. It’s built on top of {Parser::AST::Processor} and
{Parser::TreeRewriter} offers a basic API that makes it easy to rewrite
#
def assignment?(node)
-
(Boolean)
-
Parameters:
-
node
(Parser::AST::Node
) --
def assignment?(node) [:lvasgn, :ivasgn, :gvasgn, :cvasgn, :casgn].include?(node.type) end
def insert_after(range, content)
-
content
(String
) -- -
range
(Parser::Source::Range
) --
def insert_after(range, content) @source_rewriter.insert_after(range, content) end
def insert_before(range, content)
-
content
(String
) -- -
range
(Parser::Source::Range
) --
def insert_before(range, content) @source_rewriter.insert_before(range, content) end
def remove(range)
-
range
(Parser::Source::Range
) --
def remove(range) @source_rewriter.remove(range) end
def replace(range, content)
-
content
(String
) -- -
range
(Parser::Source::Range
) --
def replace(range, content) @source_rewriter.replace(range, content) end
def rewrite(source_buffer,
-
(String)
-
Parameters:
-
crossing_deletions:,
(Symbol
) -- different_replacements:, swallowed_insertions: -
ast
(Parser::AST::Node
) -- -
source_buffer
(Parser::Source::Buffer
) --
def rewrite(source_buffer, ast, **policy) @source_rewriter = Parser::Source::TreeRewriter.new(source_buffer, **policy) process(ast) @source_rewriter.process end
def wrap(range, before, after)
-
content
(String
) -- -
range
(Parser::Source::Range
) --
def wrap(range, before, after) @source_rewriter.wrap(range, before, after) end