Here's what I've done (and members of the group may add more insights/
better ways if they know of them).
First, here's a method I use to parse a JavaScript file into a
ScriptOrFn node (which represents the root of the file contents):
private ScriptOrFnNode parseJavascript(File file) throws
IOException {
// Try to open a reader to the file supplied...
Reader reader = new FileReader(file);
// Setup the compiler environment, error reporter...
CompilerEnvirons compilerEnv = new CompilerEnvirons();
ErrorReporter errorReporter = compilerEnv.getErrorReporter();
// Create an instance of the parser...
Parser parser = new Parser(compilerEnv, errorReporter);
String sourceURI;
try {
sourceURI = file.getCanonicalPath();
} catch (IOException e) {
sourceURI = file.toString();
}
// Try to parse the reader...
ScriptOrFnNode scriptOrFnNode = parser.parse(reader,
sourceURI, 1);
return scriptOrFnNode;
}
This top-level object represents the root "node" in this file. It
extends the org.mozilla.javascript.Node class.
>From there, you have a rough syntax tree that you can use for your
analysis of the JavaScript.
To get a textual representation of this syntax tree, you would call
the toStringTree method (and pass in the scriptOrFnNode as its
parameter).
Note that in the standard distribution, this returns null. To change
that, I had to change a constant in Token.java:
public static final boolean printTrees = true; // was false
Not sure if there are easier ways to do what I have done.
Regards,
Glenn
On Mar 14, 2:40 pm, [EMAIL PROTECTED] wrote:
> On Mar 13, 2:17 pm, Glenn Boysko <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hello:
>
> > I've been using Rhino for some time as a parser for JavaScript. The
> > lack of a complete grammar for ANTLR makes Rhino a good option for me.
> > I'm using it for things like specialized documentation tools (JavaDoc-
> > style docs for JavaScript classes) or other code analysis.
>
> > I'm sure that you get a lot of these types of questions. What do you
> > recommend?
>
> > For example, I've been using 1.5 and 1.6 in the past and found no node
> > visitor class. Does one exist in 1.7? There doesn't seem to be a way
> > to search for a node (by type) in 1.6 either.
>
> > If you have any suggestions for writing JavaScript parsers based on
> > Rhino, I'd really appreciate it.
>
> > Thanks,
> > Glenn
>
> Hello Glenn,
>
> Just yesterday I realized I need to parse JS in a project -- to
> generate GraphViz files for example. Since you are doing it already,
> could you point to any howto or documentation that the compiler-
> challenged among us can use? Anything to avoid? Any of you experience
> would be really useful.
>
> Thanks!
> Jaime
_______________________________________________
dev-tech-js-engine-rhino mailing list
[email protected]
https://lists.mozilla.org/listinfo/dev-tech-js-engine-rhino