Last active
August 29, 2015 14:04
-
-
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.
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
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is the first version.
i'm keeping an "updated" version in https://gist.github.com/eljojo/53f145473c1d30244efa