2.7. Generating Multiple Parsers From a Single Grammar
Prev | Chapter 2. Using Happy | Next

## 2.7. Generating Multiple Parsers From a Single Grammar

It is often useful to use a single grammar to describe multiple parsers, where each parser has a different top-level non-terminal, but parts of the grammar are shared between parsers. A classic example of this is an interpreter, which needs to be able to parse both entire files and single expressions: the expression grammar is likely to be identical for the two parsers, so we would like to use a single grammar but have two entry points.

Happy lets you do this by allowing multiple `%name` directives in the grammar file. The `%name` directive takes an optional second parameter specifying the top-level non-terminal for this parser, so we may specify multiple parsers like so:

    %name parse1 non-terminal1
    %name parse2 non-terminal2

Happy will generate from this a module which defines two functions `parse1` and `parse2`, which parse the grammars given by `non-terminal1` and `non-terminal2` respectively. Each parsing function will of course have a different type, depending on the type of the appropriate non-terminal.

Prev | Up | Next
2.6. The Error Token | Home | Chapter 3. Generalized LR Parsing