Skip to content

Instantly share code, notes, and snippets.

@tuchida
Created July 22, 2013 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tuchida/6052611 to your computer and use it in GitHub Desktop.
Save tuchida/6052611 to your computer and use it in GitHub Desktop.
Nashorn Parser
function parse(str) {
var ir = Packages.jdk.nashorn.internal.ir;
var runtime = Packages.jdk.nashorn.internal.runtime;
var parser = Packages.jdk.nashorn.internal.parser;
var context = runtime.Context.getContext();
var source = new runtime.Source('test', str);
var node = new parser.Parser(context.getEnv(), source, new runtime.Context.ThrowErrorManager(), true).parse();
var lexContext = new ir.LexicalContext();
node.accept(lexContext, new ir.visitor.NodeVisitor(lexContext) {
enterDefault: function(node) {
// print(node.tokenType() + ': ' + node);
print(node.tokenType().toString() + ': ' + node);
return true;
}
});
}
parse(function() {
if (1) {
print('hoge');
} else {
print(1 + 2);
}
}.toString());
// function: [<unknown>] function runScript()
// function: var _L1 = [<unknown>] function _L1();
// function: var _L1 = [<unknown>] function _L1()
// function: _L1
// {: [<unknown>] function _L1()
// {: if (1);
// if: if (1)
// null: 1
// {: print("hoge");
// null: print("hoge")
// null: print("hoge")
// null: print
// null: "hoge"
// {: print(1 + 2);
// null: print(1 + 2)
// null: print(1 + 2)
// null: print
// +: 1 + 2
// null: 1
// null: 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment