Previous Contents Next
Chapter 6 Extending the syntax of OCaml
6.1 Introduction

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.

The entries in Pcaml are:

Most of these entries are generally defined (``extended'') with several ``levels'' (see chapter 2). 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.

6.2 Example: ``repeat until'' like in Pascal

If you read all this tutorial, you are able to understand this complete example. If you did not, just create the files and type the indicated commands.

Write first a file named foo.ml containing:
       open Pcaml;;
       EXTEND