4

I am using antlr to generate a java parser, but the generated code has references to the antlr library.

// Generated from Sentences.g by ANTLR. Needs the JAR... How to avoid this?
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.*;
...

@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class SentencesParser extends Parser {
    static { RuntimeMetaData.checkVersion("4.5.1", RuntimeMetaData.VERSION); }
...

Is there an alternative that generates standalone java code? (or is there a way to make the generated code standalone)

  • 1
    I think [JavaCC](https://javacc.java.net/) does, but it is not nearly as powerful as ANTLR. – Sergey Kalinichenko Jul 18 '15 at 12:29
  • @dasblinkenlight: that would not be a problem, my grammer is kindof simple. I will give it a try –  Jul 18 '15 at 12:36
  • If your grammar is simple enough, you can hand-code a recursive descent parser, which has only the code you choose to put into it. See http://stackoverflow.com/questions/2245962/is-there-an-alternative-for-flex-bison-that-is-usable-on-8-bit-embedded-systems/2336769#2336769 – Ira Baxter Jul 18 '15 at 13:13
  • I agree with @dasblinkenlight - JavaCC is a good choice if you don't need something super sophisticated. – AlexJ136 Aug 18 '15 at 08:51
  • CookCC is what you are looking for. Unlike ANTLR though, it is LALR(1) + lexer (flex-like syntax). The code generated is standalone without any library dependencies. http://coconut2015.github.io/cookcc/ – user1456982 Aug 28 '18 at 20:31

2 Answers2

0

You can avoid introducing any other dependences by hand-coding a recursive descent parser (you may end up introducing some of your own, but that's completely up to you).

See my SO answer on how to build a recursive descent parser: https://stackoverflow.com/a/2336769/120163

Community
  • 1
  • 1
Ira Baxter
  • 93,541
  • 22
  • 172
  • 341
0

As already mentioned, the easiest way is to write a recursive descent parser by hand if your grammar doesn't have left recursion and is unambiguous. By the way, many grammars can be converted to LL(k) or even LL(1) grammars by left recursion elimination and left factoring. Bottom-up parsers are hard to construct by hand because of their shift/reduce behaviour.

If you are looking for tools that can generate standalone java parsers, take a look at this top-down non-recursive parser generation tool i've recently been working on. A popular tool in the Java world is javacc - but it generates recursive descent parsers.

ZeroBone
  • 11
  • 2