Previous Up Next
Chapter 5 Syntax extensions
This chapter introduces the way to extend the syntax of OCaml, and how to redefine the whole syntax of the language.

5.1 The abstract syntax tree

A syntax extension or redefinition holds grammar rules which must return abstract syntax tree nodes. The provided file ``q_MLast.cmo'' holds quotations expanders allowing to create such nodes using a concrete syntax: the description of the abstract syntax tree is not necessary. The complete description of these quotations is given in appendix A.

5.2 Extending the language

The language predefined syntaxes, ``pa_o.cmo'' and ``pa_r.cmo'' use the Camlp4 grammar system: so they are extensible.

The module ``Pcaml'' holds grammars and entries variables used by the language predefined syntaxes files. Syntax extensions can be done by extensions of the appropriate entries.

In some entries, ``pa_o.cmo'' and ``pa_r.cmo'' define labels allowing to locate some levels and to add new rules relative to these levels. The entries and their labels are:
5.3 Examples of language extensions

All examples must be compiled using ``camlp4''. As they use the ``EXTEND'' instruction, Camlp4 must load ``pa_extend.cmo''. As they use the quotations to create abstract syntax tree nodes, Camlp4 must load ``q_MLast.cmo''. The compilation command is therefore:
    ocamlc -pp "camlp4o pa_extend.cmo q_MLast.cmo" -I camlp4-lib-dir -c file.ml
After this, the syntax extension takes place in Camlp4 when ``file.cmo'' is loaded.

5.3.1 Infix

This is an example to add the infix operator ``o'', composition of two functions. For the meaning of the quotation expr used here, see appendix A.
       open Pcaml;;
       EXTEND
         expr: AFTER "apply"
           [[ f = expr; "o"; g = expr -> <:expr< fun x -> $f$ ($g$ x) >> ]];
       END;;
5.3.2 Repeat until à la Pascal

The ``repeat...until'' loop of Pascal is closed to the ``while'' loop except that it is executed at least once. We can implement it like this:
       open Pcaml;;
       EXTEND
         expr: LEVEL "let"
           [[ "repeat"; e1 = expr; "until"; e2 = expr ->
                 <:expr< do { $e1$; while not $e2$ do { $e1$ } >> ]];
       END;;
5.4 Redefining the whole syntax

To redefine the whole syntax, one must start with an empty grammar and empty entries and extend them. The library module ``Grammar.Unsafe'' hold functions to clean up the grammars and the entries.

Examples can be found in the distribution: the files ``meta/pa_r.ml'' and ``etc/pa_o.ml'' which are the sources of ``pa_r.cmo'' and ``pa_o.cmo''.



Previous Up Next