Reputation: 1481
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?
Upvotes: 4
Views: 523
Reputation: 5048
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 ... -> ...
Upvotes: 5