2.4. Type Signatures
Prev | Chapter 2. Using Happy | Next

## 2.4. Type Signatures

Happy allows you to include type signatures in the grammar file itself, to indicate the type of each production. This has several benefits:

- Documentation: including types in the grammar helps to document the grammar for someone else (and indeed yourself) reading the code.

- Fixing type errors in the generated module can become slightly easier if Happy has inserted type signatures for you. This is a slightly dubious benefit, since type errors in the generated module are still somewhat difficult to find.

- Type signatures generally help the Haskell compiler to compile the parser faster. This is important when really large grammar files are being used.

The syntax for type signatures in the grammar file is as follows:

    stmts   :: { [ Stmt ] }
    stmts   : stmts stmt                { $2 : $1 }
    	| stmt                      { [$1] }

In fact, you can leave out the superfluous occurrence of `stmts`:

    stmts   :: { [ Stmt ] }
    	: stmts stmt                { $2 : $1 }
    	| stmt                      { [$1] }

Note that currently, you have to include type signatures for all the productions in the grammar to benefit from the second and third points above. This is due to boring technical reasons, but it is hoped that this restriction can be removed in the future.

It is possible to have productions with polymorphic or overloaded types. However, because the type of each production becomes the argument type of a constructor in an algebraic datatype in the generated source file, compiling the generated file requires a compiler that supports local universal quantification. GHC (with the `-fglasgow-exts` option) and Hugs are known to support this.

Prev | Up | Next
2.3. Using Precedences | Home | 2.5. Monadic Parsers