Question on lexical analysis
我正在读龙书。 引用书中的文字(3.1.4词汇错误,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 stringfi is encountered for the
first time in a C program in the
context:
1 fi ( a == f(x) ) ...a lexical analyzer cannot tell whether
fi is a misspelling of the keyword
if 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.
看完这篇文章我有点困惑。 我的理解是词法分析器开始从左到右处理文本,并在模式匹配时返回标记。 那么对于
有什么想法吗?
它与
1 | fi ( a == f(x) ); |
您必须在语法分析和词法分析之间进行区分。
-
词法分析的任务是将字符序列转换为标记字符串。可以有各种类型的标记,例如标识符,附加运算符,语句结尾运算符等。如果词法分析遇到与任何标记都不对应的文本字符串,则词法分析只会因错误而失败。在您的情况下,
fi ( a == f(x) ) ... 将转换为 ..... -
生成令牌字符串后,便会执行语法分析。这通常涉及根据令牌构造某种语法树。解析器知道该语言允许的所有有效语句形式。如果解析器找不到允许上述标记序列的语法规则,它将失败。
对于词法分析错误的解释,这是一个糟糕的示例选择。这段文字试图告诉您的是,编译器无法识别您拼写错误的" if"关键字(将其倒写)。它仅看到" fi",例如是一个有效的变量名,因此将ID(例如)" VARIABLE"返回给解析器。解析器随后会发现语法错误。
与从左到右或从右到左无关。编译器当然会从左到右读取源代码。正如我所说的-这种解释的关键字选择不多。
您如何确定
1 2 3 |
与
1 2 3 |
1 2 3 |
其中