数字的识别属于扫描器还是解析器?

发布于 2024-11-30 01:44:59 字数 302 浏览 0 评论 0原文

当你查看一种语言的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

入画浅相思 2024-12-07 01:44:59

许多常见的解析器生成器工具(例如 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),

The only difference between [lexers and parsers] is that the parser recognizes grammatical structure in a stream of tokens while the lexer recognizes structure in a stream of characters.

夜雨飘雪 2024-12-07 01:44:59

语法语法需要完整才能精确,因此它当然包括标识符的精确格式和运算符的拼写等细节。

是的,编译器工程师决定,但通常这是非常明显的。您希望词法分析器能够有效地处理所有字符级细节。

有一个更长的答案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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文