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
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
.
A EBNF grammar can have multiple valid rules/states at the same time.That means in this case if it finds a conditional it can match an assignment_expression and a constant_expression at the same time. To get an unique answer the rules using these two rules must be specific enough to match a given input sequence only to a single sequence of rules or you can use priorities to select a single sequence of rules from multiple possible sequences.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.