Tracking source position of AST nodes in a compiler (ocaml)

▼魔方 西西 提交于 2019-12-10 15:57:03

问题


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

but that seems redundant. Later, when I'm done with verifying the AST, I'll have to write

match n with 
| NodeX(..., _) -> ...

in every match which is a waste of space.

What's the best way to solve this?


回答1:


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 }

and then:

match n.exp with
  | NodeX ... -> ...


来源:https://stackoverflow.com/questions/8931064/tracking-source-position-of-ast-nodes-in-a-compiler-ocaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!