词法分析器可以在编译期间检查语法规则吗?
很抱歉问了这么愚蠢的问题,但我和我的朋友们关于词法分析发生了争论,我们决定询问社区。
问题是: 是否声明“int some_variable = ;”在 C 语法的词法分析阶段或语法分析阶段会被解释为无效。 谢谢
sorry for such silly question, but I had argument with my pals about lexical analyze and we've decided to ask community.
The question is:
Whether the statement "int some_variable = ;" would be interpreted as invalid during the lexical analyze stage or during the syntax analyze stage in C grammar.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C 语言中,首先进行词法分析。 然后预处理器对生成的标记流应用宏及其所有神奇的转换。只有在预处理器起作用之后才会进行语法分析。
因此,要知道问题的答案,只需在预处理器中运行代码即可。对于
gcc
,这是使用-E
命令行标志的问题。如果预处理器满意,那么根据定义,词法分析就可以正常进行(您的示例就是这种情况)。In C, lexical analysis occurs first. Then the preprocessor applies macros and all its magical transforms on the resulting stream of tokens. Only after the preprocessor has acted does syntax analysis take place.
Thus, to know the answer to your question, just run the code in the preprocessor. With
gcc
this is a matter of using the-E
command-line flag. If the preprocessor is happy then the lexical analysis, by definition, went fine (which is the case for your example).词法分析检查所有标记是否有效(它们确实有效)。解析(或语法分析)检查标记序列是否在语法中形成有效的产生式(事实并非如此)。所以这将通过词法分析阶段并失败解析阶段。
Lexical analysis checks that all of your tokens are valid (they are). Parsing (or syntax analysis) checks whether the sequence of tokens forms a valid production in your grammar (it doesn't). So this would pass the lexical analysis phase and fail the parse phase.
在句法分析阶段,又名解析
During the syntactic analysis phase, aka parsing