I want to write parser for JavaScript.
What I figured it out that I need to use some sort of scanning each character and as soon as I interact with any {
, I must track for the next }
(closing braces).
For effic开发者_运维问答ient usage I can use stack.
Can anyone suggest me some better idea or approach to build a parser for JavaScript with Java?
You may want to investigate using ANTLR - it is a tool which will allow you to generate parser classes in java or other languages, based on a grammar file which you write. You will likely be able to find a grammar (or at least a partial grammar) for javascript online.
Antlr home page with tutorials - http://www.antlr.org/
If you're not familiar with the concept of grammars you may need to read up on them and on compiling; a good first start would likely be wiki: http://en.wikipedia.org/wiki/Formal_grammar
There already is a complete JavaScript engine written in Java, names Rhino. Obviously it has to include a parser, and it's open source, so you could have a look how it's done there.
I suspect that you'll find that parsing a language such as JavaScript is much more complex than you expect.
ANTLR is the de-facto standard for building parser (not only in Java), and is also very easy to use (including Eclipse plugin). Seems like there are some readily available grammars for JavaScript.
There's also JavaCC
精彩评论