Skip to content

Instantly share code, notes, and snippets.

@komax
Last active December 19, 2015 02:58
Show Gist options
  • Save komax/5886547 to your computer and use it in GitHub Desktop.
Save komax/5886547 to your computer and use it in GitHub Desktop.
Pretty Printer for current Intermediate Representation (IR)
#!/usr/bin/env jruby
require 'jruby'
def get_ast(code)
JRuby.parse(code)
end
def get_ir(ast_node)
ir_manager = JRuby::runtime.ir_manager
ir_manager.dry_run = true
JRuby::IR.compiler_debug = true
builder =
if JRuby::runtime.is1_9?
org.jruby.ir.IRBuilder19
else
org.jruby.ir.IRBuilder
end
builder = builder.new(ir_manager)
scope = builder.build_root(ast_node)
ir_instrs(scope)
end
def ir_instrs(scope, indent="")
instrs = scope.instrs.map do |instr|
indent + instr.to_s
end
scope.lexical_scopes.each do |lex_scope|
instrs += ir_instrs(lex_scope, indent + "\s" * 4)
end
instrs
end
def print_ir(code)
root_node = get_ast(code)
ir_instrs = get_ir(root_node)
ir_instrs.each do |instr|
puts instr
end
end
example_code =
if ARGV.length == 1
ARGV[0]
else
"def foo(x); return 41 + x; end"
end
print_ir(example_code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment