Syntax extensions in OCaml can be done by extending the
grammars entries of the OCaml syntax. All grammars entries are defined
in the module named Pcaml. They all return values of types
defined in the module MLast: nodes of these types can be
created using the predefined quotation expansion q_MLast.cmo.

Most of these entries are generally defined (``extended'') with
several ``levels'' (see chapter 3). Some of them
are labelled, in order to be able to extend them or to insert other
levels.

The levels and their possible labels are not predefined. It depend on
how the syntax define them. To see which labels are defined and which
rule they contain, enter the toplevel and type for the normal syntax:

#load "camlp4o.cma";;
Grammar.Entry.print Pcaml.expr;; (* for the expressions *)
Grammar.Entry.print Pcaml.patt;; (* for the patterns *)
(* ... and so on *)

For the revised syntax, load "camlp4r.cma" instead. If you
defined another syntax of the whole language or want to see the other
syntaxes provided, load it before, and call Grammar.Entry.print
of the desired grammar entry. Look at the manual page
(man camlp4 in the shell) to see all available syntaxes and
extensions.

Once you have the list of the grammar entry you want to extend and the
possible level label, you can do your extension.

Here is an example of an syntax extension allowing to write a ``for''
loop like in C. A construction is added with the loop variable and 3
parameters, simple expressions: the first one is the initial value,
the second the test, the third the way to change the loop variable.

Note that we use here the directives #load inside the source of
the syntax extension, allowing to parse it with camlp4o without
having to specify these files in the command line.

We are going to define a syntax extension, so that for all types
definitions, the definition of printers of the values of this types
is automatically added. In this example, we limit to sum types (types
with constructors), but it can be easily extensible for record types,
abstract types, types renaming.

The syntax extension will be defined in the following file
``pa_type.ml''. As a beginning, let us just see how we insert
the grammar rule. The function ``gen_print_funs'' generating
the printer functions just generates a phony statement:

Remark the ``declare'' statement in the ``str_item''
syntax tree at the end of this file, destinated to group two structure
items together: 1/ the type definition 2/ the printer.

This file can be compiled like this:

$ ocamlc -pp camlp4o -I +camlp4 -c pa_type.ml

We can test the example file, ``col.ml'', but not yet with the
compiler, since it would generate semantic error because of the ``not
yet implemented'' statement. Let us test it therefore with a pretty
printer:

See the extra generated statement ``not yet implemented''. You remark,
also, that there is a warning in the beginning: it means that the
syntax rule we added in str_item was already present in the
grammar we used.

To avoid such a warning message, the solution is to add, before the
EXTEND statement, a DELETE_RULE statement:

Let us attack now the function gen_print_funcs. It receives a
list (since the ``type'' declaration can define several types,
possibly mutually recursive) of types definitions. We know that we
have to generate a definition, recursive, with as many printing
functions as types. The following function,
gen_one_type_print_fun, will generate the printer for one type
definition. For the moment, the body is a ``not yet implemented''
statement:

Recompile the syntax expander file with these functions and test with
``col.ml'': you can see a function named ``print_colour''.

Let use improve now ``gen_one_print_fun''. It has to generate a
let binding definition, composed of the couple of a pattern (the name
of the function) and an expression. Our function receives as parameter
a type definition which is a t-uple of 4 values: 1/ the type name
(with his location), 2/ the list of its possible parameters, 3/ the
type kind (a type, actually) and 4/ a list of possible constraints.

In a first version, we are going to ignore the type parameters
``tpl'': we see later how they intervene in the generated
function and our code will work, for the moment, only for monomorphic
types.

We limit also to the ``sum'' types (i.e. types with constructors); for
other types kinds, we shall generate a function which fails.

We added the function ``gen_print_sum'' which treats a sum type
by generating a match association for each constructor (function
``gen_print_cons'') and building the function with the
resulting list.

That function ``gen_print_cons'' gets a constructor definition,
i.e. a tuple with: 1/ a location, 2/ a string (the constructor name)
and 3/ a list of types parameters (ctyp list). We ignore for the
moments the constructors parameters. The function
``gen_print_cons_patt'' generates the pattern part of the case,
and ``gen_print_cons_expr'' the expression part of the
function, the print statement:

Here is a first (but complete) version of our syntax extension (file
``pa_type.ml''):

Like in the above desired result, we decide to name the parameters
with ``x'' followed by the number of the parameter, defined by
the following function ``param_name'':

let param_name cnt = "x" ^ string_of_int cnt

We need a function ``list_mapi'', which is like
``List.map'' but the function applied receives the number of
the list element as first parameter. This allows us to generate the
name of the constructor parameter while exploring the type list:

With these changes, the pattern part of the generated function
``print_term'' is correct. Test it.

For the expression part, we have to generate the call to the printers
for all the constructors parameters. We add a function
``gen_print_type'' to generate a printer associated with a
type. For the moment, it just generates it for a simple type name. For
other types, it generates a printer displaying an ellipsis:

This time, we are going to generate the good code for polymorphic
types, i.e. types defined with types variables. Our example will be
the definition of the type ``mlist'' like this. File
``mlist.ml'':

type 'a mlist = Nil | Cons of 'a * 'a mlist

The printer of such a type will receive as parameter the print
functions of the instantiated type. As many as the type has type
variables. We can then call ``print_mlistprint_int'' for an ``int mlist'', ``print_mlistprint_string'' for a ``string mlist'' and so on.

The name of the printer function for a type variable will be
``pr_'' followed by the type variable name:

let fun_param_name n = "pr_" ^ n

To add the function parameters to the printer definition (``letprint_mlistpr_a= ...'' in our example), we
change our function ``gen_one_print_func'' by inserting them in
the body of the function, just before its result, like this:

For the printing of a type variable (``pr_ax1'' in our
example), we add the case of type variables in our function
``gen_print_type'':

| <:ctyp< '$s$ >> -> <:expr< $lid:fun_param_name s$ >>

And to generate the printing of types with parameters (we have a
recursive case in our example: ``print_mlistpr_ax2'' for the constructor parameter of type ``'amlist''), we add, in the same function, the case of types
applications. But since it needs a recursive call, the function
``gen_print_type'' is rewritten with a internal recursive
definition.

It is possible to add, the same way, the other kind of types: record
types, abstract types, and so on.

Another interesting improvement is to generate, instead of
``print_string'' statements, functions of the
``Format'' library, with pretty printing boxes.

Further, that version can be still improved, by generating only one
``Format.fprintf'' by printing case (instead of a sequence of
printing statements), using the very useful abbreviations provided by
that library by the prefixes ``@'' inside the format strings.