Search code examples
cgrammaryacc

Ambiguity in ANSI C YACC grammar


I'm watching ANSI C YACC grammar. And there is something that I don't understand. http://www.lysator.liu.se/c/ANSI-C-grammar-y.html#expression

assignment_expression
    : conditional_expression
    | unary_expression assignment_operator assignment_expression
    ;

constant_expression
    : conditional_expression
    ;

Here are the rules for assignment expression and constant expression. My question is that how can they both use conditional_expression to reduce? If there is a token reduced to a conditional_expression, after the token reduced how does YACC parser know how to reduce the token next between assignment_expression and constant_expression? I think I'm missing something huge but I can't find that by myself. Thank you


Solution

  • There is no ambiguity because there is no context in which both assignment_expression and constant_expression may appear.

    There is absolutely nothing wrong with having rules of the form

    a: z;
    b: z;
    c: z;
    

    if a, b, and c all appear in different contexts. If you have the following

    t: a | b | c;
    

    then there's a problem. But there's nothing like that for conditional_expression.