关于C#:关于词法分析的问题

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 string fi 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. 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令牌(表示" identifier")不匹配。如果没有关键字匹配,这就是万能的。词法分析器不知道在某些位置"期望"什么。它只返回令牌,解析器将知道它的期望。例如,C解析器必须接受以下语句,这是一个函数调用

1
fi ( a  == f(x) );


您必须在语法分析和词法分析之间进行区分。

  • 词法分析的任务是将字符序列转换为标记字符串。可以有各种类型的标记,例如标识符,附加运算符,语句结尾运算符等。如果词法分析遇到与任何标记都不对应的文本字符串,则词法分析只会因错误而失败。在您的情况下,fi ( a == f(x) ) ...将转换为 .....

  • 生成令牌字符串后,便会执行语法分析。这通常涉及根据令牌构造某种语法树。解析器知道该语言允许的所有有效语句形式。如果解析器找不到允许上述标记序列的语法规则,它将失败。


对于词法分析错误的解释,这是一个糟糕的示例选择。这段文字试图告诉您的是,编译器无法识别您拼写错误的" if"关键字(将其倒写)。它仅看到" fi",例如是一个有效的变量名,因此将ID(例如)" VARIABLE"返回给解析器。解析器随后会发现语法错误。

与从左到右或从右到左无关。编译器当然会从左到右读取源代码。正如我所说的-这种解释的关键字选择不多。


您如何确定if是否是给定点上唯一的预期输入?

1
2
3
int a = 42;
if (a == 42)
    puts("ok");

1
2
3
int a = 42;
fi (a == 42)
    puts("ok");

fi可以是函数调用。例如,上面的代码可能会误拼:

1
2
3
int a = 42;
fi(a == 42);
puts("ok");

其中fi是采用int并返回void的函数。