c - 关于词法分析的问题

标签 c algorithm lexical-analysis compiler-construction

我在看龙书。引用书中的文字(3.1.4 Lexical errors, Pno 114)

It is hard for a lexical analyzer to tell, without the aid of other components, that there is a source-code error. For instance, if the string fi is encountered for the first time in a C program in the context:

fi ( a == f(x) ) ...

a lexical analyzer cannot tell whether fi is a misspelling of the keyword if or an undeclared function identifier. Since fi is a valid lexeme for the token id, the lexical analyzer must return the token id to the parser and let some other phase of the compiler - probably the parser in this case - handle an error due to transposition of the letters.

读完后我有点困惑。我的理解是词法分析器从左到右开始处理文本,并在模式匹配时返回标记。那么对于以if为关键字匹配的语言,fi如何匹配呢?

有什么想法吗?

最佳答案

它不匹配 if 标记,而是匹配 id 标记,代表“标识符”。如果没有关键字匹配,它就是万能的。词法分析器不知道在某些位置“期望”什么。它只是返回标记,解析器会知道它期望什么。例如,C 解析器必须接受以下语句,这是一个函数调用

fi ( a  == f(x) );

关于c - 关于词法分析的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3220320/

相关文章:

C 中的纸牌游戏。数据类型四舍五入会给出不正确的结果

c - "main"地址的功能保持不变。为什么局部变量地址每次运行都会改变?

arrays - 查找字符串中字符之间的长度

java - 使用java创建解释器的工具

c - 如何用 C 语言读取文本文件中的字母?

c++ - 在源代码中查找函数/变量定义以供引用

C++ 修复 OpenCV squares.cpp 示例以合并封闭的正方形

c++ - 将值均匀分布到数组中

c++ - C/C++ 编译器如何区分 * 运算符(指针、解引用运算符、乘法运算符)的使用?

c++ - 检查一个序列是否由两个相同的序列组成