Camlp4 is a preprocessor for OCaml. As a preprocessor, you can do
syntax extensions to your OCaml programs. But Camlp4 also provides
some other features:
A system of grammars
A kind of macros called quotations
A revised syntax for OCaml
A pretty printing system of OCaml programs
and other: extensible functions, functional streams, ...
Camlp4 is syntax, syntax, syntax. It uses its own syntax systems to do
its own syntax extensions: it is highly bootstrapped. Camlp4 stops at
syntax level: it does not know anything about semantic, typing nor
code generation (for it, a type definition is just a syntactic thing
which starts with ``type'').
The ``p4'' in the name ``camlp4'' stands for the 4 ``p'' of
``Pre-Processor-Pretty-Printer''.
1.1
Extending the syntax of OCaml
To start with the beginning, we could try to learn how to make simple
syntax extensions to OCaml. If you know the C language, you probably
experimented the define construction, very easy to use:
#define FOO xyzzy
and all occurrences of FOO in the rest of the program are
replaced by xyzzy.
In Camlp4, is it not so simple. A syntax extension is not just text
replacing: it is an extension of an entry of the grammar of the
language, and you need to create syntax trees.
It is therefore necessary 1/ to know what is the grammar system
provided by Camlp4 2/ to know how to create syntax trees. It is what
we are going to do in this tutorial. Once these points described, we
have got the tools to do the syntax extensions of the language.
If you are impatient, and you want to create your syntax extension in
the next quarter of an hour, and you don't want to learn all that
stuff, you may consider taking the text of an already existing syntax
extension and change it for you own needs. A syntax extension is not
necessarily a long program (for example, adding the
repeat..until construction of Pascal takes 6 lines) and you can
guess ``how it works'' and ask the wizards...
However, if you read this manual, you may be interested on learning
the original system of grammars that Camlp4 provides. It can be used
for other goals than extending the OCaml language: for your own
grammars. This system of grammars is an alternative of yacc: a
different approach, but you can describe your language in some
identical way.
Just the practical things before (what do I type to experiment?)
1.2
Using Camlp4 as a command and in the toplevel
You must first know that camlp4 is a command. This chapt