Skip to content

Instantly share code, notes, and snippets.

@miura1729
Created August 11, 2023 09:44
Show Gist options
  • Save miura1729/84d038c04e25e252b0c48e93fdeab986 to your computer and use it in GitHub Desktop.
Save miura1729/84d038c04e25e252b0c48e93fdeab986 to your computer and use it in GitHub Desktop.
def ast2str(node)
case node.type
when :SCOPE
tbl, args, body = node.children
"(#{tbl.map {|e| e.to_s}.join(" ,")}) \n #{ast2str(body)}"
when :ARGS
p node.children[1]
p node.children
"()"
when :LIT
node.children[0].to_s
when :LVAR
node.children[0].to_s
when :OPCALL
left, op, right = node.children
"#{ast2str(left)}.#{op}(#{ast2str(right)})"
when :ARRAY
node.children.compact.map{|nele| ast2str(nele)}.join(" ,")
when :LIST
node.children.compact.map {|nele| ast2str(nele)}.join(", ")
when :RETURN
"return #{ast2str(node.children[0])}\n"
when :BLOCK
node.children.map {|nele| ast2str(nele)}.join("\n")
else
p node.type
end
end
$mtab = {}
class <<self.class
def method_added(name)
if $mtab[name] == nil then
$mtab[name] = true
begin
p name
ins = self.new
ast = RubyVM::AbstractSyntaxTree.of(proc: ins.method(name), keep_tokens: true)
#p "def #{name} #{ast2str(ast)}\n nil\n end"
self.class_eval "def #{name} #{ast2str(ast)}\n nil\n end"
# rescue
end
end
end
end
def foo
1 + 1
end
def bar
return 1 + 2
end
p foo
p bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment