Skip to content

Instantly share code, notes, and snippets.

@eljojo
Last active August 29, 2015 14:04
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 eljojo/a67ce77379f5e22da760 to your computer and use it in GitHub Desktop.
Save eljojo/a67ce77379f5e22da760 to your computer and use it in GitHub Desktop.
Using the information extracted from an AST Tree, so we can do something meaningful with it.
# Using the information extracted from an AST Tree, so we can do something meaningful with it.
# this needs https://github.com/whitequark/parser
require 'parser/current'
op = "(a > 3) or (a == b) or ((b > 3.months) and (c =~ 'd')) or jojo?"
parsed = Parser::CurrentRuby.parse(op)
def clean_begin(node)
return node unless node.type == :begin
raise "begin has more than one children!" if node.children.length > 1
node.children.first
end
def process_node(node)
raise "object is not a AST::Node" unless node.is_a?(Parser::AST::Node)
node = clean_begin(node)
children = node.children
case node.type
when :int
children.first
when :str
"'%s'" % children.first
when :send
case children.length
when 2
if children.first.nil? then # method or local variable
children.last
else # method on (method or local variable)
left = process_node(children.first)
right = children.last
"#{left}.#{right}"
end
when 3 # ==, <, >, <=, >=, =~, etc operations
left, op, right = process_node(children[0]), children[1], process_node(children[2])
"(#{left} #{op} #{right})"
else
raise "send has weird children. #{children.length}"
end
when :or, :and
left, right = children.map{|child| clean_begin(child)}
return "(#{process_node(left)} #{node.type} #{process_node(right)})"
else
raise "Found another type of node! #{node.type}"
end
end
puts op # => (a > 3) or (a == b) or ((b > 3.months) and (c =~ 'd')) or jojo?
puts debug(parsed) # => ((((a > 3) or (a == b)) or ((b > 3.months) and (c =~ 'd'))) or jojo?)
# p parsed
@eljojo
Copy link
Author

eljojo commented Aug 4, 2014

this is the first version.
i'm keeping an "updated" version in https://gist.github.com/eljojo/53f145473c1d30244efa

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment