Chapter 6 |
Extending the syntax of OCaml |
|
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:
-
expr
for expressions, returning values of type
MLast.expr
.
-
patt
for patterns, returning values of type
MLast.patt
.
-
ctyp
for types, returning values of type
MLast.ctyp
.
-
module_type
for module types, returning values of type
MLast.module_type
.
-
module_expr
for module expressions, returning values of type
MLast.module_expr
.
-
sig_item
for signature items, returning values of type
MLast.sig_item
.
-
str_item
for structure items, returning values of type
MLast.str_item
.
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