gpt4 book ai didi

c - 如何在解析表达式语法(如 PEG.js)中处理语法上的歧义(如在 C 中)

转载 作者:行者123 更新时间:2023-12-01 04:24:25 25 4
gpt4 key购买 nike

所以从我有限的理解,C has syntax ambiguity如表达式所示:

T(*b)[4];

Here据说这样的事情:

The well-known "typedef problem" with parsing C is that the standard C grammar is ambiguous unless the lexer distinguishes identifiers bound by typedef and other identifiers as two separate lexical classes. This means that the parser needs to feed scope information to the lexer during parsing. One upshot is that lexing must be done concurrently with parsing.



问题是它可以根据上下文解释为乘法或指针(我不是 100% 理解这个细节,因为我不是 C 专家,但我明白了它的要点以及为什么这是一个问题)。
typedef a;
b * a; // multiplication
a * b; // b is pointer to type a

我想知道您是否要使用解析表达式语法 (PEG) 解析 C,例如 this C grammar ,它如何处理这种歧义?由于这个问题,我认为这个语法不是 100% 正确的,所以我想知道你将如何解决它。它需要跟踪什么或采取不同的方式来解决这个问题?

最佳答案

在 PEG 语法中处理这种情况的通常方法是在规则上使用语义谓词,这样规则仅在谓词为真时才匹配,并让谓词检查所讨论的名称是否是当前上下文中的类型.在您提供的链接中,有一条规则

typedefName : Identifier

这是(唯一)需要语义谓词来解决这种歧义的。谓词只是根据当前范围内的定义检查有问题的标识符。如果它未定义为类型,则它拒绝此规则,因此下一个优先级较低的将(尝试)匹配。

关于c - 如何在解析表达式语法(如 PEG.js)中处理语法上的歧义(如在 C 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59482460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com