Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala parser combinators vs ANTLR/Java generated parser?

I am writing an expression parser for an app written mostly in Scala. I have built AST objects in Scala, and now need to write the parser. I have heard of Scala's built-in parser combinators, and also of ANTLR3, and am wondering: which would provide better performance and ease of writing code? So far:

ANTLR pros

  1. Well-known
  2. Fast
  3. External DSL
  4. ANTLRWorks (great IDE for parser grammer debugging/testing)

ANTLR cons

  1. Java-based (Scala interop may be challenging, any experience?)
  2. Requires a large dependency at runtime

Parser combinator pros

  1. Part of Scala
  2. One less build step
  3. No need for a runtime dependency; e.g. already included in Scala's runtime library

Parser combinator cons

  1. Internal DSL (may mean slower execution?)
  2. No ANTLRWorks (provides nice parser testing and visualization features)

Any thoughts?

EDIT: This expression parser parses algebraic/calculus expressions. It will be used in the app Magnificalc for Android when it is finalized.

like image 646
Nathan Moos Avatar asked May 15 '11 20:05

Nathan Moos


People also ask

What is Combinators in Scala?

In Scala, a combinator is a Higher-Order Function and also a pure function. As they are pure functions, we can easily compose them together very well as flexible, fine-grained building blocks for constructing larger, more complex programs. Some of the frequently used Scala combinators are as follows: map. flatMap.

Are parser combinators slow?

Parser combinators are generally slower than a hand-written or code-generated parser. That's somewhat innate due to the overhead of “threading” (for lack of a better word) your control flow through many function calls.


2 Answers

Scala's parser combinators aren't very efficient. They weren't designed to be. They're good for doing small tasks with relatively small inputs.

So it really depends on your requirements. There shouldn't be any interop problems with ANTLR. Calling Scala from Java can get hairy, but calling Java from Scala almost always just works.

like image 116
Erik Engbrecht Avatar answered Sep 23 '22 02:09

Erik Engbrecht


I wouldn't worry about the performance limitations of parser combinators unless you were planning on parsing algebraic expressions that are a few pages long. The Programming Scala book does mention that a more efficient implementation of parser combinators is feasible. Maybe somebody will find the time and energy to write one.

I think with ANTLR you are talking about two extra build steps: ANTLR compiles to Java, and you need to compile both Scala and Java to bytecode, instead of just Scala.

like image 23
sullivan- Avatar answered Sep 20 '22 02:09

sullivan-