[wg-camlp4] My uses of syntax extension

Fabrice Le Fessant Fabrice.Le_fessant at inria.fr
Mon Jan 28 15:44:51 GMT 2013


> From: Alain Frisch <alain at frisch.fr>
>> Also it'd be nice to have:
>>  -ppt Typedtree -> Typedtree for type-level transformations
>
> I don't believe this is a viable option.  Producing Typedtree without breaking invariants of the type system (and the type soundness) is extremely challenging.  I'd be more comfortable with supporting a "Typedtree -> Parsetree" pass, where you'd only need to be able to use information from the typedtree so as to produce fragments of code which are then type-checked again.  You don't need to fully understand everything in the Typedtree to do that, and the type-checker acts as a safety net.
>
> OCamlPro worked on a project called "OCaml Templates" doing exactly that, but I don't know the status of this project.  (Someone from OCamlPro to comment?)

What I did was to add a new quotation <:PARSER_NAME<STRING>> to the
syntax for expressions (and <#PARSER_NAME<STRING>> for toplevel
statements). Then, a new node would be produced in the parsetree,
containing both the PARSER_NAME and the STRING.

During typing, when the typer would find this node, it would try to
find a parser called PARSER_NAME in a database of parsers (loaded by
dynamic linking), use it to parse STRING and generate a parsetree from
it (sometimes, it would return a parsetree containing other quoted
nodes), that would be given to the typer immediatly.

One interesting thing is that the typer calls the parser with an Env.t
argument, i.e. the typing environment at the quotation, that can be
used to find the types of identifiers.

For example:

<@string_of<t>>

would be parsed by a parser "string_of", that would locate "t" among
types in the current environment, and generate a function to print it
in a string. The difference with "type_conv" is that the definition of
the type is exact, i.e. not a syntactic approximation.

Also, <:type_of<x>> can be used to return a type representation of the
type of variable "x" in the current env.

--Fabrice


More information about the wg-camlp4 mailing list