Created
November 8, 2022 20:22
-
-
Save kddnewton/f809f07ce814b2cb926c543175567441 to your computer and use it in GitHub Desktop.
Mutation visitor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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