Skip to content

Instantly share code, notes, and snippets.

@kddnewton
Created November 8, 2022 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kddnewton/f809f07ce814b2cb926c543175567441 to your computer and use it in GitHub Desktop.
Save kddnewton/f809f07ce814b2cb926c543175567441 to your computer and use it in GitHub Desktop.
Mutation visitor
require "syntax_tree"
# Create a new visitor that is going to visit the parsed tree.
visitor = SyntaxTree::Visitor::MutationVisitor.new
# Define a mutation on the visitor that is going to search for the given pattern
# to find nodes that match it and then call the given block to mutate the node
# in place in the tree.
visitor.mutate("If[predicate: Assign | OpAssign]") do |node|
# Get the existing If's predicate node.
predicate = node.predicate
# Create a new predicate node that wraps the existing predicate node
# in parentheses.
predicate =
SyntaxTree::Paren.new(
lparen: SyntaxTree::LParen.default,
contents: predicate,
location: predicate.location
)
# Return a copy of this node with the new predicate.
node.copy(predicate: predicate)
end
# Parse the source code into a tree.
source = "if a = 1; end"
program = SyntaxTree.parse(source)
# Visit the tree with the mutation visitor and obtain the new tree.
mutated = program.accept(visitor)
# Format the mutated tree back into source code.
SyntaxTree::Formatter.format(source, mutated)
# => "if (a = 1)\nend\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment