Viral Shah
Viral Shah

Reputation: 2938

When is better to use a parser such as ANTLR vs. writing your own parsing code?

I need to parse a simple DSL which looks like this:

funcA Type1 a (funcB Type1 b) ReturnType c

As I have no experience with grammar parsing tools, I thought it would be quicker to write a basic parser myself (in Java).

Would it be better, even for a simple DSL, for me to use something like ANTLR and construct a proper grammar definition?

Upvotes: 6

Views: 2415

Answers (3)

questzen
questzen

Reputation: 3287

Grammars tend to evolve, (as do requirements). Home brew parsers are difficult to maintain and lead to re-inventing the wheel example. If you think you can write a quick parser in java, you should know that it would be quicker to use any of the lex/yacc/compiler-compiler solutions. Lexers are easier to write, then you would want your own rule precedence semantics which are not easy to test or maintain. ANTLR also provides an ide for visualising AST, can you beat that mate. Added advantage is the ability to generate intermediate code using string templates, which is a different aspect altogether.

Upvotes: 5

High Performance Mark
High Performance Mark

Reputation: 78364

It's better to use an off-the-shelf parser (generator) such as ANTLR when you want to develop and use a custom language. It's better to write your own parser when your objective is to write a parser.

UNLESS you have a lot of experience writing parsers and can get a working parser that way more quickly than using ANTLR. But I surmise from your asking the question that this get-out clause does not apply.

Upvotes: 4

danben
danben

Reputation: 83310

Simple answer: when it is easier to write the rules describing your grammar than to write code that accepts the language described by your grammar.

If the only thing you need to parse looks exactly like what you've written above, then I would say you could just write it by hand.

More generally speaking, I would say that most regular languages could be parsed more quickly by hand (using a regular expression).

If you are parsing a context-free language with lots of rules and productions, ANTLR (or other parser generators) can make life much easier.

Also, if you have a simple language that you expect to grow more complicated in the future, it will be easier to add rule descriptions to an ANTLR grammar than to build them into a hand-coded parser.

Upvotes: 5

Related Questions