Alex Rivera | Logout

ANTLR (or alternative): decoupling parsing from evaluation

Asked 2010-10-11T21:04:00.660
12

I have a relatively simple DSL that I would like to handle more robustly than a bunch of manually-coded java.util.regex.Pattern statements + parsing logic.

The most-quoted tool seems to be ANTLR. I'm not familiar with it and am willing to give it a try. However I get a little leery when I look at the examples (e.g. the ANTLR expression evaluator example, or Martin Fowler's HelloAntlr, or this other Q on stackoverflow). The reason for this is that the grammar files seem like they are a hodgepodge of grammar definitions interspersed with fragments of the implementation language (e.g. Java) that are imperative in nature.

What I would really prefer is to separate out the imperative / evaluation part of the parser. Is there a way to use ANTLR (or some other tool) to define a grammar & produce a set of Java source files so that it compiles into classes that I can use to parse input into a structure w/o acting upon that structure?

for example, if I wanted to use expression evaluation with just the + and * and () operators, and I had the input

3 * (4 + 7 * 6) * (3 + 7 * (4 + 2))

then what I would like to do is write a grammar to convert that to a hierarchical structure like

Product
  Term(3)
  Sum
     Term(4)
     Product
        Term(7)
        Term(6)
  Sum
     Term(3)
     Product
        Term(7)
        Sum
            Term(4)
            Term(2)

where I can use classes like

interface Expression<T> {
    public T evaluate();
}

class Term implements Expression<Double> {
    final private doubl
Edit
Report

1 Answer

3

What about using ANTLR AST (Abstract Syntax Tree) and constructing a mirrored tree with your classes by visiting each tree node.


@Giuseppe Cardone added some great links that I post here:

http://www.antlr.org/article/1100569809276/use.tree.grammars.tml

http://www.antlr.org/article/1170602723163/treewalkers.html

An example can be found at:

http://sagarsunkle.spaces.live.com/blog/cns!E07F3B561597E4EE!664.entry?sa=97619042

answered 2010-10-11T21:35:54.367

Your Answer