4

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?

pbp
  • 1,461
  • 17
  • 28
  • For your next project you should consider [menhir](http://gallium.inria.fr/~fpottier/menhir/), a superior alternative to ocamlyacc. – gasche Jan 21 '12 at 16:41

1 Answers1

5

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 ... -> ...
Thomas
  • 5,047
  • 19
  • 30