[antlr-interest] and, finally, ternary operator works
    Sam Harwell 
    sharwell at pixelminegames.com
       
    Fri Feb 25 19:14:37 PST 2011
    
    
  
Ternary for C++ is even stranger, though I'm not sure it's necessary to
support it at this point.
x ? a : b = c
should parse as this in C++:
(? x a (= b c))
But as this is C (which is found to be invalid at a later time since the
ternary operator cannot return an lvalue in C):
(= (? x a b) c)
However, in both C and C++ the following:
x = c ? a : b
Should parse as:
(= x (? c a b))
I've been watching for those check-ins, and I see one now! :)
Sam
-----Original Message-----
From: antlr-interest-bounces at antlr.org
[mailto:antlr-interest-bounces at antlr.org] On Behalf Of Terence Parr
Sent: Friday, February 25, 2011 7:41 PM
To: antlr-interest Interest
Subject: [antlr-interest] and, finally, ternary operator works
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
List: http://www.antlr.org/mailman/listinfo/antlr-interest
Unsubscribe:
http://www.antlr.org/mailman/options/antlr-interest/your-email-address
    
    
More information about the antlr-interest
mailing list