Created
November 14, 2009 18:30
-
-
Save noonat/234683 to your computer and use it in GitHub Desktop.
Parse a JS file using JRuby and Rhino and print the AST
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
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