简体   繁体   English

ANSI C YACC语法中的歧义

[英]Ambiguity in ANSI C YACC grammar

I'm watching ANSI C YACC grammar. 我正在看ANSI C YACC语法。 And there is something that I don't understand. 还有一些我不理解的东西。 http://www.lysator.liu.se/c/ANSI-C-grammar-y.html#expression 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? 我的问题是,他们怎么都可以使用conditional_expression来减少? 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 ? 如果有一个令牌减少到conditional_expression,则在令牌减少之后,YACC解析器如何知道接下来如何减少assignment_expressionconstant_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. 没有歧义,因为没有上下文可以同时出现assignment_expressionconstant_expression

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. 如果abc都出现在不同的上下文中。 If you have the following 如果您有以下内容

t: a | b | c;

then there's a problem. 那就有问题了 But there's nothing like that for conditional_expression . 但是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. EBNF语法可以同时具有多个有效的规则/状态,这意味着在这种情况下,如果找到条件,则可以同时匹配Assignment_expression和constant_expression。 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. 要获得唯一答案,使用这两个规则的规则必须足够具体,以仅将给定输入序列与单个规则序列进行匹配,或者可以使用优先级从多个可能的序列中选择单个规则序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM