gpt4 book ai didi

c++ - 编译器 : limitation of lexical analysis

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:29:36 25 4
gpt4 key购买 nike

在经典的编译器理论中,前两个阶段是词法分析和语法分析。他们正在筹备中。词法分析将标记识别为解析的输入。

但是我遇到了一些在词法分析中很难被正确识别的情况。例如下面关于C++模板的代码:


map<int, vector<int>>

>>在“常规”词法分析中会被认为是按位右移,但这是不正确的。我的感觉是很难将这种语法的处理分为两个阶段,词法分析工作必须在解析阶段完成,因为要正确解析 >>。依赖于语法,而不仅仅是简单的词汇规则。

我想知道关于这个问题的理论和实践。另外,我想知道 C++ 编译器如何处理这种情况?

最佳答案

C++ 标准要求实现在解析阶段之前执行词法分析以生成标记流。根据词法分析规则,连续两个>字符(后面没有 = )将始终被解释为一个 >> token 。 C++ 标准提供的语法是根据这些标记定义的。

要求在某些上下文中(例如在模板 ID 中期望 > 时)实现应解释 >>作为两个 >未在语法中指定。相反,该规则被指定为一种特殊情况:

14.2 Names of template specializations [temp.names] ###

After name lookup (3.4) finds that a name is a template-name or that an operator-function-id or a literal-operator-id refers to a set of overloaded functions any member of which is a function template if this is followed by a <, the < is always taken as the delimiter of a template-argument-list and never as the less-than operator. When parsing a template-argument-list, the first non-nested > is taken as the ending delimiter rather than a greater-than operator. Similarly, the first non-nested >> is treated as two consecutive but distinct > tokens, the first of which is taken as the end of the template-argument-list and completes the template-id. [ Note: The second > token produced by this replacement rule may terminate an enclosing template-id construct or it may be part of a different construct (e.g. a cast).—end note ]

注意前面的规则,在某些情况下 <应解释为 <模板参数列表中。这是另一个需要上下文来消除解析歧义的构造示例。

C++ 语法包含许多这样的歧义,在没有上下文信息的情况下无法在解析过程中解决这些歧义。其中最著名的是Most Vexing Parse。 ,其中标识符可能会根据上下文解释为类型名称

在 C++ 中跟踪上述上下文需要一个实现来与解析阶段并行执行一些语义分析。这通常以语义 Action 的形式实现,当在给定的上下文中识别出特定的语法结构时,这些语义 Action 就会被调用。然后,这些语义操作构建了一个表示上下文并允许高效查询的数据结构。这通常称为 symbol table , 但 C++ 所需的结构几乎是整个 AST .

这些上下文相关的语义 Action 也可以用来解决歧义。例如,在 namespace-body 上下文中识别identifier 时,语义操作将检查该名称是否先前被定义为模板。然后将结果反馈给解析器。这可以通过用结果标记 identifier 标记,或用匹配不同语法规则的特殊标记替换它来完成。

可以使用相同的技术来标记 <作为 template-argument-list 的开头,或者 >作为结束。 >> 的上下文相关替换规则有两个>提出本质上相同的问题,可以使用相同的方法解决。

关于c++ - 编译器 : limitation of lexical analysis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19106622/

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