Skip to content

Instantly share code, notes, and snippets.

@noonat
Created November 14, 2009 18:30
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 noonat/234683 to your computer and use it in GitHub Desktop.
Save noonat/234683 to your computer and use it in GitHub Desktop.
Parse a JS file using JRuby and Rhino and print the AST
require 'js-1_7r3.jar'
import Java::OrgMozillaJavascript::Context
import Java::OrgMozillaJavascript::CompilerEnvirons
import Java::OrgMozillaJavascript::Parser
import Java::OrgMozillaJavascript::Token
class Visitor
include Java::OrgMozillaJavascriptAst::NodeVisitor
def visit(node)
indent = " " * node.depth
type_name = Token.type_to_name(node.type)
name = case node.type
when Token::NAME
node.identifier
when Token::COMMENT, Token::NUMBER, Token::REGEXP, Token::STRING
node.to_source
end
puts [node.lineno, indent, type_name, name].join(' ')
true
end
end
context = Context.enter()
context.init_standard_objects()
compiler_environs = CompilerEnvirons.new
compiler_environs.init_from_context(context)
parser = Parser.new(compiler_environs, nil)
script = "
/// This is a test.
function foo() {
alert('Hello, world!');
}
"
ast = parser.parse(script, '<code>', 1)
ast.visit(Visitor.new);
=begin
$ jruby rhino_ast.rb
1 SCRIPT
2 COMMENT /// This is a test.
3 FUNCTION
3 NAME foo
3 BLOCK
4 EXPR_VOID
4 CALL
4 NAME alert
4 STRING 'Hello, world!'
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment