数字的识别属于扫描器还是解析器?
当你查看一种语言的 EBNF 描述时,你经常会看到整数和实数的定义:(
integer ::= digit digit* // Accepts numbers with a 0 prefix
real ::= integer "." integer (('e'|'E') integer)?
定义是即时制定的,我可能在其中犯了一个错误)。
尽管它们出现在上下文无关语法中,但数字通常在词法分析阶段被识别。它们是否包含在语言定义中以使其更加完整,并且由实现者意识到它们实际上应该包含在扫描器中?
When you look at the EBNF description of a language, you often see a definition for integers and real numbers:
integer ::= digit digit* // Accepts numbers with a 0 prefix
real ::= integer "." integer (('e'|'E') integer)?
(Definitions were made on the fly, I have probably made a mistake in them).
Although they appear in the context-free grammar, numbers are often recognized in the lexical analysis phase. Are they included in the language definition to make it more complete and it is up to the implementer to realize that they should actually be in the scanner?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
许多常见的解析器生成器工具(例如 ANTLR、Lex/YACC)将解析分为两个阶段:首先,对输入字符串进行标记化。其次,将标记组合成产生式以创建具体的语法树。
然而,还有一些不需要标记化的替代技术:查看回溯递归下降解析器。对于这样的解析器,令牌的定义方式与非令牌类似。 pyparsing 是此类解析器的解析器生成器。
两步技术的优点是它通常会产生更高效的解析器——使用标记,字符串操作、字符串搜索和回溯会少得多。
根据《The Definitive ANTLR Reference》(Terence Parr),
Many common parser generator tools -- such as ANTLR, Lex/YACC -- separate parsing into two phases: first, the input string is tokenized. Second, the tokens are combined into productions to create a concrete syntax tree.
However, there are alternative techniques that do not require tokenization: check out backtracking recursive-descent parsers. For such a parser, tokens are defined in a similar way to non-tokens. pyparsing is a parser generator for such parsers.
The advantage of the two-step technique is that it usually produces more efficient parsers -- with tokens, there's a lot less string manipulation, string searching, and backtracking.
According to "The Definitive ANTLR Reference" (Terence Parr),
语法语法需要完整才能精确,因此它当然包括标识符的精确格式和运算符的拼写等细节。
是的,编译器工程师决定,但通常这是非常明显的。您希望词法分析器能够有效地处理所有字符级细节。
有一个更长的答案Lexer 的工作是解析数字和字符串?
The grammar syntax needs to be complete to be precise, so of course it includes details as to the precise format of identifiers and the spelling of operators.
Yes, the compiler engineer decides but generally it is pretty obvious. You want the lexer to handle all the character-level detail efficiently.
There's a longer answer at Is it a Lexer's Job to Parse Numbers and Strings?