I am using ECMAScript grammar provided by ANLR for the purpose of identifying the JavaScript global variable. AST is produced and now I am wondering what is the way to filter global variable announcements.
I am interested in looking at all the outermost "variable radiation" tokens in my AST; Real-how-what-is it eluding me though. Here's my set up code:
string input = "var a, b; var c;"; Charstream CS = new ANTLRStringStream (input); Javascript Liker Laser = New JavaScript Letter (CS); GeneralTokenStream Token = New CommonTokenStream (); Tokens.setTokenSource (lexer); Javascript parser parser = new javascript parser (token); Program_return programReturn = parser.program ();
Can anyone give any signal to be new to the ANLR?
I think you are using.
Although that grammar suggests that proper AST has been made, this is not the case. It uses some inline operators to exclude some tokens from pars-trees, but it never creates any root for the tree, resulting in a completely flat parsed tree. From this, you can not get all the universal Vars properly.
You will need to adjust some grammar:
option {...}
at the top of the grammar file:
< Code> token {VARIABLE; Ceremony; }
Now change the following rules: functionDeclaration
, functionExpression
and variableDeclaration
with these:
Function Declaration: 'Function' LT * Identifier LT * Formal Permiter List LT * FunctionBody - & gt; ^ (FUNCTION identifier formal parameterList functionBody); Performance: 'function' lt * identifier? LT * Formal Permiter List LT * FunctionBody - & gt; ^ (FUNCTION identifier? Formal ParameterList functionBody); Variable decryption: Identifier LT * initiator? - & gt; ^ (Phase Identifier initial?);
Now another suitable tree is produced. If you now parse the source:
var a = 1; Function foo () {var b = 2; } Var c = 3;
The following tree is produced:
Now what you have to do, you have to walk again on the root children of your tree and when you stumble on variables
token, then you know that this" Global "will be all other variables under the FUNCTION
nodes.
How to do this:
import org.antlr.runtime. *; Import org.antlr.runtime.tree *; Public class main {public static zero main (string [] args) exception {string source = "var one = 1; function fu () {var b = 2;} var c = 3;"; ANTLRStringStream = new ANTLRStringStream (source); JavaScriptLexer lexer = new JavaScript letter (in); Common Token Stream Token = New Common Token Stream (Lexer); Javascript parser parser = new javascript parser (token); JavaScriptParser.program_ Return Return Value = parser.program (); Common Tree Tree = (CommonTree) Return Value.getTree (); (Object o: tree .get childland ()) {COMMUNITY CHILD = (Commontree) o; If (child.getType () == JavaScriptParser.VARIABLE) {System.out.println ("found a global form:" + child.getChild (0)); }}}}
which produces the following output:
found a global variable: a global variable found: c
< / Pre>
Comments
Post a Comment