Quotations are expressions or patterns enclosed by special
parentheses: <:id<
and >>
(id
is a quotation
identifier). They exist also enclosed by <<
and
>>
.
Examples of quotations:
<:expr< let a = b in c >>
<< [x](x y) >>
<:myquot< quotations can be any text >>
The contents of quotations are not lexed: quotations themselves are
tokens, exactly like strings. Therefore like the contents of strings,
their contents do not have to respect any special lexing rule.
3.1 |
OCaml syntax extensions |
|
In the previous chapter, we saw the grammar system of Camlp4. This was
a first step in the way to be able to write syntax extensions in
OCaml.
The second step is: how to make OCaml syntax trees nodes? The
immediate answer is: use the module defining them. Indeed, this
module exist: its name is MLast
. You can then try do
understand it or... you can use quotations.
Let us suppose we want to generate the syntax tree of the OCaml
expression: "let a = b in c"
. The version using the module
MLast
directly is:
MLast.ExLet
(loc, false, [MLast.PaLid (loc, "a"), MLast.ExLid (loc, "b")],
MLast.ExLid (loc, "c"))
Not so complicated, perhaps. But you need directions for use detailing
all tree nodes, their parameters, their usages. If you are courageous,
you may try to look inside the code of Camlp4 to see how they are
used.
But the quotation system of Camlp4 provides a handy way to represent
these trees. In this system, if the right file is loaded, you are able
to write the above example as:
<:expr< let a = b in c >>
Simpler, isn't it? Everything inside is treated at compile time by
Camlp4 which generates exactly the same code than the above ``long''
version.
Let us look in details at the Camlp4 quotation system, then. It can be
used for these tree notes of OCaml syntax, but actually for any other
type. You can define your own quotations, using any syntax you choose.
3.2 |
Camlp4 quotation system |
|
The quotations contents are not lexed, as said above, but they are
even so treated at parse time. Actually they are not lexed by the
OCaml lexer (of Camlp4), but they are analyzed by other functions,
which are called ``quotation expanders''. These expanders just take
a string as parameter (the contents of the quotation) and return
a piece of OCaml program.
There are two kinds of quotations expanders, which do the same things:
but