How to write LALR parser for some grammar in Java?

2019-04-14 10:17发布

I want to write Java code to build a LALR parser for my grammar. Can someone please suggest some books or some links where I can learn how to write Java code for a LALR parser?

4条回答
【Aperson】
2楼-- · 2019-04-14 10:46

As previously stated, you would always use a parser-generator to produce an LALAR parser. A few such tools for Java are:

查看更多
We Are One
3楼-- · 2019-04-14 10:56

Writing a LALR parser by hand is difficult, but it can he done. If you want to learn the theory behind constructing parsers for them by hand, consider looking into "Parsing Techniques: A Practical Guide" by Grune and Jacobs. It's an excellent book on general parsing techniques, and the chapter on LR parsing is particularly good.

If you're more interested in just getting a LALR parser that is written in Java, consider looking into Java CUP, which is a general purpose parser generator for Java.

Hope this helps!

查看更多
做自己的国王
4楼-- · 2019-04-14 11:03

You can split the LALR functionality in two parts: preparation of the tables and parsing the input.

The first part is complex and errorprone, so even if you like knowing how it works I suggest to use a proven working table generator for the LALR states (and for the tokenizer DFA as well).

The second part consists of consuming those tables using some quite simple algorithms to tokenize and process the input into a parse tree/concrete syntax tree. This is easier to implement yourself if you like to do so, and you still have full control over how it works and what it does.

When doing parsing tasks, I personally use the free GOLD Parsing System, which has a nice UI for creating and debugging the grammar and it does also generate table files which can then be loaded and processed by an existing engine or your own implementation (the file format for these CGT files is well documented).

查看更多
做自己的国王
5楼-- · 2019-04-14 11:03

Just want to mention that my project CookCC ( http://coconut2015.github.io/cookcc/ ) is a LALR(1) parser + Lexer (much like flex).

The unique feature of CookCC is that you can write your lexer and parser in Java using Java annotations. See the calculator example here: https://github.com/coconut2015/cookcc/blob/master/tests/javaap/calc/Calculator.java

查看更多
登录 后发表回答