Previous Contents Next
Chapter 5 OCaml syntax trees
This chapter explains how to create OCaml syntax trees using quotations.

The OCaml syntax tree is defined in the module MLast (file ``mLast.mli''): it is of course always possible to create your syntax tree nodes by combining values of these types. But, for that, you need a precise documentation of all the constructors, how they have to be used, and which syntactic construct they correspond to.

Chapter 3 explained us that quotations are helpful to represent abstract values with concrete syntax. This is very adapted for abstract syntax trees, since they have corresponding concrete syntaxes. In this case, you have nothing to learn: if you know the concrete syntax, you know the abstract syntax. Actually, you need to know the revised syntax (chapter 4) because it is the syntax used in these quotations.

The provided quotation extension is the file q_MLast.cmo. Once this file loaded, you can write any complicated piece of program in concrete syntax, e.g.:
         <:expr< match f $x$ with [ $uid:p$ -> $x$ | C z -> 7 ] >>
This example corresponds exactly to this code (written in normal syntax):
         MLast.ExMat
          (loc, MLast.ExApp (loc, MLast.ExLid (loc, "f"), x),
           [MLast.PaUid (loc, p), None, x;
            MLast.PaApp
             (loc, MLast.PaUid (loc, "C"), MLast.PaLid (loc, "z")), None,
            MLast.ExInt (loc, "7")]);;
These two forms are absolutely equivalent, but the first one is much simpler and more readable. Notice the expressions between dollar signs $: they are antiquotations (see chapter 3). We are going to see how to use them.

For the moment, here is the list of the quotations defined in the file q_MLast.cmo:

Each of these quotations use the revised syntax (chapter 4). You have to know that their expression form (i.e. not pattern) all contain the variable named "loc". It allows you to specify a source location to the syntax tree. There must then exist a variable "loc" visible in the environment where the quotation is used.

Notice that in the Camlp4 grammar system (chapter 2), the variable "loc" in defined in all semantic actions of the rules: Camlp4 grammar system and Camlp4 quotations of abstract syntax trees are made to work together.