Previous Contents Next
Chapter 3 Grammars
Camlp4 grammar system is a way to parse streams with more power and more convenience than simple stream parsers. A grammar deals with operator precedences and associativity, and left factorization, and its entries are extensible.

3.1 Grammars and entries

The Camlp4 library provides a module ``Grammar'' and a syntax extension file ``pa_extend.cmo'' to program grammars. All details on modules, types and functions are described chapter 7.

A grammar can be created using the function ``Grammar.create''. It takes a lexer as parameter. A good candidate it the function ``Plexer.make'' but the user can creates its own lexer, providing that it is of type ``Token.lexer''.

A grammar holds entries. An entry can be created using the function ``Grammar.Entry.create''. The first parameter is the grammar, the second one is a string used to name the entry in error messages and in entries dump. Entries are created empty, i.e. raising ``Stream.Error'' when called. An entry is composed of entry precedence levels, the first one being the least precedent and the last one the most.

Lastly, a stream can be parsed by en entry using the function ``Grammar.Entry.parse''. In case of syntax error, the exception ``Stream.Error'' is raised, encapsulated by the exception ``Stdpp.Exc_located'', giving the location of the error.

3.2 Extension

An entry can be extended using the function ``Grammar.extend''. But its interface being quite complicated and, as it must be used with appropriate type constraints, the Camlp4 library provides a file, named ``pa_extend.cmo'', compatible with ``pa_o.cmo'' and ``pa_r.cmo'' which creates a new instruction doing this work.

This instruction is ``EXTEND'' which has the following format:

EXTEND
{ GLOBAL : global-list ; }
entry : { position } extension ;
...
entry : { position } extension ;
END

EXTEND, GLOBAL and END are keywords. There are some other keywords in this instruction, all in uppercase.

The entry is a name of an entry va