Overview
Camlp5 is a preprocessor and pretty-printer for ocaml programs.
As a preprocessor, it allows to:
- add syntax extensions,
- redefine the whole syntax of the language.
As a pretty printer, it allows to:
- display programs in a elegant way,
- convert from a syntax to another,
- check the results of syntax extensions.
It works as a shell command and can also be used in the ocaml toplevel.
Camlp5 also provides some parsing and pretty printing tools.
Usage
The main shell commands are:
- camlp5o : to treat files written in normal ocaml syntax,
- camlp5r : to treat files written in an original syntax named the revised syntax.
These commands can be given as parameters of the option -pp of the ocaml compiler. Examples:
ocamlc -pp camlp5o foo.ml ocamlc -pp camlp5r bar.ml
This way, the parsing is done by camlp5. In case of syntax errors, the parsing fails with an error message and the compilation is aborted. Otherwise, the ocaml compiler continues with the syntax tree provided by camlp5.
In the toplevel, it is possible to preprocess the input phrases by loading one of the files "camlp5o.cma" or "camlp5r.cma". The common usage is:
ocaml -I +camlp5 camlp5o.cma ocaml -I +camlp5 camlp5r.cma
Extending syntax
A syntax extension is an ocaml object file, i.e. a file with the extension ".cmo". It is a result of the compilation of an ocaml source file containing what is necessary to do the syntax extensions. These object files are named parsing kits.
There are two ways to use a syntax extension:
- Either by giving this object file as parameter to the camlp5
command. For example:
ocamlc -pp "camlp5o ./myext.cmo" foo.ml
- Or by adding the directive "#load" in the source file:
#load "./myext.cmo";;
and compile it simply like this:
ocamlc -pp camlp5o foo.ml
Several syntax extensions can be used for a single file. The way to create one's own syntax extensions is explained further.
Pretty printing
Like for syntax extensions, pretty printing kits are ocaml object files. The main pretty printing kits provided by camlp5 are:
- pr_o.cmo: to pretty print in normal syntax,
- pr_r.cmo: to pretty print in revised syntax.
Examples: if we have a file, foo.ml, written in normal syntax and and another one, bar.ml, written in revised syntax, here are the commands to pretty print them in their own syntax:
camlp5o pr_o.cmo foo.ml camlp5r pr_r.cmo bar.ml
And how to convert them into the other syntax:
camlp5o pr_r.cmo foo.ml camlp5r pr_o.cmo foo.ml
The way to create one's own pretty printing extensions is explained further.