[antlr-interest] Rewriting Repeatable Prefix Operators To Nested AST Structure

Randall R Schulz rschulz at sonic.net
Thu Oct 2 12:24:32 PDT 2008


Hi,

I have a couple of productions that use a prefix operator that may be
repeated arbitrarily. One of them (negation) just has the operator
symbol. The other has a keyword (two different keywords, actually)
followed by an identifier.

For example, with the negation operator, this:

	---p

should produce this tree structure:

	(Not (Not (Not p)))

The other case ("forall" is the keyword, "Forall" the token name):

	forall A forall B forall C q
->
	(Forall A (Forall B (Forall C q)))


I have a similar situation with a repeatable suffix operator (the prime
symbol from calculus or analysis). That's handled properly by this
approach ("Prime" is the token name for the single apostrophe operator):

op300Term
    :   (primitiveTerm  -> primitiveTerm)
        (Prime          -> ^(Prime $op300Term)) *
    ;


However, using an analogous approach with the prefix operators doesn't
seem to work:

op350Formula
    :   (
            Not ->  ^(Not $op350Formula)
        ) *
        (primitiveFormula -> primitiveFormula)
    ;

The result of attempting to parse an instance of this:

Exception in thread "main" org.antlr.runtime.tree.RewriteEmptyStreamException: token retval
        at org.antlr.runtime.tree.RewriteRuleElementStream._next(RewriteRuleElementStream.java:158)
        at org.antlr.runtime.tree.RewriteRuleElementStream.nextTree(RewriteRuleElementStream.java:145)
        at tau.p9.P9Parser.op350Formula(P9Parser.java:2235)


The grammar itself parsed the test input successfully before I added the
AST building constructs shown above.


What's a good way to deal with this sort of prefix, repeatable, nested
construct?

Thanks.

Randall Schulz


More information about the antlr-interest mailing list