[antlr-interest] and, finally, ternary operator works

Terence Parr parrt at cs.usfca.edu
Fri Feb 25 17:41:08 PST 2011


Wow. I'm having fun.  I guess i'll bring into main line now.  The beauty is that I'm generating another grammar with very little target code needed.  I will add the following to each target:

// used for left-recursive rules
recRuleDefArg() ::= "int <recRuleArg()>"
recRuleArg() ::= "_p"
recRuleAltPredicate(ruleName,opPrec) ::= "<recRuleArg()> \<= <opPrec>"
recRuleSetResultAction() ::= "root_0=$<ruleName>_primary.tree;"

That will be correct for most targets.  here's output for the below test:

e_[int _p]
    :   e_primary {root_0=$e_primary.tree;}
        (
          ( {_p <= 6}?=> '*'^ e_[7]{}
        | {_p <= 5}?=> '+'^ e_[6]{}
        | {_p <= 3}?=> '='<assoc=right>^ e_[3]{}
        | {_p <= 4}?=> '?'<assoc=right>^ e ':'! e_[4]{}
          )
        )*
    ;

here's another test. 

	@Test public void testTernaryExpr() throws Exception {
		String grammar =
			"grammar T;\n" +
			"options {output=AST;}\n" +
			"e : e '*'^ e" +
			"  | e '+'^ e" +
			"  | e '?'<assoc=right>^ e ':'! e" +
			"  | e '='<assoc=right>^ e" +
			"  | ID" +
			"  ;\n" +
			"ID : 'a'..'z'+ ;\n" +
			"WS : (' '|'\\n') {skip();} ;\n";
		String[] tests = {
			"a",			"a",
			"a+b",			"(+ a b)",
			"a*b",			"(* a b)",
			"a?b:c",		"(? a b c)",
			"a=b=c",		"(= a (= b c))",
			"a?b+c:d",		"(? a (+ b c) d)",
			"a?b=c:d",		"(? a (= b c) d)",
			"a? b?c:d : e",	"(? a (? b c d) e)",
			"a?b: c?d:e",	"(? a b (? c d e))",
		};
		runTests(grammar, tests, "e");
	}

 ternary is pretty weird.  C and Java grammars show

ConditionalExpression:
	ConditionalOrExpression
	ConditionalOrExpression ? Expression : ConditionalExpression

So it's right associative but middle expr acts like (expr).

Ter


More information about the antlr-interest mailing list