我在看龙书。引用书中的文字(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 keywordif
or an undeclared function identifier. Sincefi
is a valid lexeme for the token id, the lexical analyzer must return the tokenid
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/