编程语言的解析器应该做什么?
我已经编写了一个返回标记的词法分析器,现在我正在开发一个解析器。我有一个问题。
想象一下这个代码示例:
print("Hello, world!")
词法分析器返回四个标记(print
、(
、"Hello, world!"
和 )
)。最终程序应打印字符串“Hello, world!”。
但是解析器应该做什么呢?如果解析器已经执行了代码,它是否应该返回由另一个对象处理的东西(以及什么)?
I have already written a lexer which returns tokens, and now I'm working on a parser. I have one problem.
Imagine this code example:
print("Hello, world!")
The lexer returns four tokens (print
, (
, "Hello, world!"
and )
). The final program should print the string "Hello, world!".
But what should the parser do? Should the parser already execute the code, should it return something (and what) that is handled by another object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
解析器应该生成一个抽象语法树,它是程序在内存中的表示。解析后可以遍历这棵树来进行代码生成。我建议阅读一些关于这个主题的好书,也许是一本涉及龙。
The parser should generate an abstract syntax tree, which is an in memory representation of the program. This tree can be traversed after parsing to do the code generation. I'd recommend to read some good book about the subject, maybe one involving dragons.
解析器的典型作用是读取标记流,并从中构建一个解析树 或抽象语法树。
?否。这不是解析。
The typical role of a parser is to read the stream of tokens and, from that, build a parse tree or abstract syntax tree.
No. That's not parsing.
通常,解析器不执行任何操作。解析器通常接受输入(文本或二进制)并生成内存中的表示,仅此而已......但这已经很多了!
如果您已经有词法分析器,那么第二步通常是执行语义分析,以生成抽象语法树< /a>.
这意味着,产生以下形式的东西:
Typically, a parser does not execute anything. Parsers usually take an input (text or binary) and produce an in-memory representation, nothing more... but that's already much!
If you already have a Lexer, then the second step is normally to perform Semantic Analysis, to produce an Abstract Syntax Tree.
This means, producing something of the form:
它应该返回一个抽象语法树。
It should return an abstract syntax tree.
解析器基本上应该做两件事:
The parser should basically do two things: