跟踪AST节点在编译器(ocaml)中的源位置 [英] Tracking source position of AST nodes in a compiler (ocaml)
问题描述
我正在使用ocamllex/yacc用ocaml编写编译器.一切进展顺利,但我遇到了设计问题.对于我创建的每个AST节点,最好在源代码中包含有关该节点的行/字符位置的信息.这对于以后向用户提供错误消息很有用.
I'm writing a compiler in ocaml, using ocamllex/yacc. Things are going well, but I've a design problem. For each AST node I create, it'd be good to have information about line/character position of that node in the source code. That would be useful for providing error messages to the user later.
现在,我可以向节点添加某种元类型:
Now, I can add some kind of meta type to my nodes:
type node = Node1 of ... * meta | Node2 of ... * meta
但这似乎是多余的.稍后,当我完成对AST的验证后,我将不得不写
but that seems redundant. Later, when I'm done with verifying the AST, I'll have to write
match n with
| NodeX(..., _) -> ...
每个match
中的
都是浪费空间.
in every match
which is a waste of space.
解决此问题的最佳方法是什么?
What's the best way to solve this?
推荐答案
解决此问题的常用方法是使用记录保存元信息和节点表达式:
The usual way to solve this is to use a record to hold the meta-information and the node expression:
type node_exp = Node1 of ... | Node2 of ...
and node = { exp: node_exp; meta: meta }
然后:
match n.exp with
| NodeX ... -> ...
这篇关于跟踪AST节点在编译器(ocaml)中的源位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!