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: [email protected] [mailto:[email protected]] 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 List: http://www.antlr.org/mailman/listinfo/antlr-interest Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-email-address -- You received this message because you are subscribed to the Google Groups "il-antlr-interest" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/il-antlr-interest?hl=en.
