template-haskell- Support library for Template Haskell

Safe HaskellNone




The public face of Template Haskell

For other documentation, refer to: http://www.haskell.org/haskellwiki/Template_Haskell


The monad and its operations

data Q a Source

runQ :: Quasi m => Q a -> m a Source

Administration: errors, locations and IO

reportError :: String -> Q () Source

Report an error to the user, but allow the current splice's computation to carry on. To abort the computation, use fail.

reportWarning :: String -> Q () Source

Report a warning to the user, and carry on.

report :: Bool -> String -> Q () Source

Deprecated: Use reportError or reportWarning instead

Report an error (True) or warning (False), but carry on; use fail to stop.

recover Source


:: Q a

handler to invoke on failure

-> Q a

computation to run

-> Q a 

Recover from errors raised by reportError or fail.

location :: Q Loc Source

The location at which this computation is spliced.

runIO :: IO a -> Q a Source

The runIO function lets you run an I/O computation in the Q monad. Take care: you are guaranteed the ordering of calls to runIO within a single Q computation, but not about the order in which splices are run.

Note: for various murky reasons, stdout and stderr handles are not necesarily flushed when the compiler finishes running, so you should flush them yourself.

Querying the compiler


reify :: Name -> Q Info Source

reify looks up information about the Name.

It is sometimes useful to construct the argument name using lookupTypeName or lookupValueName to ensure that we are reifying from the right namespace. For instance, in this context:

data D = D

which D does reify (mkName "D") return information about? (Answer: D-the-type, but don't rely on it.) To ensure we get information about D-the-value, use lookupValueName:

  Just nm <- lookupValueName "D"
  reify nm

and to get information about D-the-type, use lookupTypeName.

reifyModule :: Module -> Q ModuleInfo Source

reifyModule mod looks up information about module mod. To look up the current module, call this function with the return value of thisModule.

thisModule :: Q Module Source

Return the Module at the place of splicing. Can be used as an input for reifyModule.

data Info Source

Obtained from reify in the Q Monad.


ClassI Dec [InstanceDec]

A class, with a list of its visible instances

ClassOpI Name Type ParentName Fixity

A class method

TyConI Dec

A "plain" type constructor. "Fancier" type constructors are returned using PrimTyConI or FamilyI as appropriate

FamilyI Dec [InstanceDec]

A type or data family, with a list of its visible instances. A closed type family is returned with 0 instances.

PrimTyConI Name Arity Unlifted

A "primitive" type constructor, which can't be expressed with a Dec. Examples: (->), Int#.

DataConI Name Type ParentName Fixity

A data constructor

VarI Name Type (Maybe Dec) Fixity

A "value" variable (as opposed to a type variable, see TyVarI).

The Maybe Dec field contains Just the declaration which defined the variable -- including the RHS of the declaration -- or else Nothing, in the case where the RHS is unavailable to the compiler. At present, this value is _always_ Nothing: returning the RHS has not yet been implemented because of lack of interest.

TyVarI Name Type

A type variable.

The Type field contains the type which underlies the variable. At present, this is always VarT theName, but future changes may permit refinement of this.

data ModuleInfo Source

Obtained from reifyModule in the Q Monad.


ModuleInfo [Module]

Contains the import list of the module.

type InstanceDec = Dec Source

InstanceDec desribes a single instance of a class or type function. It is just a Dec, but guaranteed to be one of the following:

type ParentName = Name Source

In ClassOpI and DataConI, name of the parent class or type

type Arity = Int Source

In PrimTyConI, arity of the type constructor

type Unlifted = Bool Source

In PrimTyConI, is the type constructor unlifted?

Name lookup

lookupTypeName :: String -> Q (Maybe Name) Source

Look up the given name in the (type namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.

lookupValueName :: String -> Q (Maybe Name) Source

Look up the given name in the (value namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.

Instance lookup

reifyInstances :: Name -> [Type] -> Q [InstanceDec] Source

reifyInstances nm tys returns a list of visible instances of nm tys. That is, if nm is the name of a type class, then all instances of this class at the types tys are returned. Alternatively, if nm is the name of a data family or type family, all instances of this family at the types tys are returned.

isInstance :: Name -> [Type] -> Q Bool Source

Is the list of instances returned by reifyInstances nonempty?

Roles lookup

reifyRoles :: Name -> Q [Role] Source

reifyRoles nm returns the list of roles associated with the parameters of the tycon nm. Fails if nm cannot be found or is not a tycon. The returned list should never contain InferR.

Annotation lookup

reifyAnnotations :: Data a => AnnLookup -> Q [a] Source

reifyAnnotations target returns the list of annotations associated with target. Only the annotations that are appropriately typed is returned. So if you have Int and String annotations for the same target, you have to call this function twice.

data AnnLookup Source

Annotation target for reifyAnnotations

Typed expressions

data TExp a Source


data Name Source

An abstract type representing names in the syntax tree.

Names can be constructed in several ways, which come with different name-capture guarantees (see "Language.Haskell.TH.Syntax#namecapture" for an explanation of name capture):

  • the built-in syntax 'f and ''T can be used to construct names, The expression 'f gives a Name which refers to the value f currently in scope, and ''T gives a Name which refers to the type T currently in scope. These names can never be captured.
  • lookupValueName and lookupTypeName are similar to 'f and ''T respectively, but the Names are looked up at the point where the current splice is being run. These names can never be captured.
  • newName monadically generates a new name, which can never be captured.
  • mkName generates a capturable name.

Names constructed using newName and mkName may be used in bindings (such as let x = ... or x -> ...), but names constructed using lookupValueName, lookupTypeName, 'f, ''T may not.

Constructing names

mkName :: String -> Name Source

Generate a capturable name. Occurrences of such names will be resolved according to the Haskell scoping rules at the occurrence site.

For example:

f = [| pi + $(varE (mkName "pi")) |]
g = let pi = 3 in $f

In this case, g is desugared to

g = Prelude.pi + 3

Note that mkName may be used with qualified names:

mkName "Prelude.pi"

See also dyn for a useful combinator. The above example could be rewritten using dyn as

f = [| pi + $(dyn "pi") |]

newName :: String -> Q Name Source

Generate a fresh name, which cannot be captured.

For example, this:

f = $(do
  nm1 <- newName "x"
  let nm2 = mkName "x"
  return (LamE [VarP nm1] (LamE [VarP nm2] (VarE nm1)))

will produce the splice

f = \x0 -> \x -> x0

In particular, the occurrence VarE nm1 refers to the binding VarP nm1, and is not captured by the binding VarP nm2.

Although names generated by newName cannot be captured, they can capture other names. For example, this:

g = $(do
  nm1 <- newName "x"
  let nm2 = mkName "x"
  return (LamE [VarP nm2] (LamE [VarP nm1] (VarE nm2)))

will produce the splice

g = \x -> \x0 -> x0

since the occurrence VarE nm2 is captured by the innermost binding of x, namely VarP nm1.

Deconstructing names

nameBase :: Name -> String Source

The name without its module prefix

nameModule :: Name -> Maybe String Source

Module prefix of a name, if it exists

Built-in names

tupleTypeName :: Int -> Name Source

Tuple type constructor

tupleDataName :: Int -> Name Source

Tuple data constructor

unboxedTupleTypeName :: Int -> Name Source

Unboxed tuple type constructor

unboxedTupleDataName :: Int -> Name Source

Unboxed tuple data constructor

The algebraic data types

The lowercase versions (syntax operators) of these constructors are preferred to these constructors, since they compose better with quotations ([| |]) and splices ($( ... ))


data Dec Source


FunD Name [Clause]
{ f p1 p2 = b where decs }
ValD Pat Body [Dec]
{ p = b where decs }
DataD Cxt Name [TyVarBndr] [Con] [Name]
{ data Cxt x => T x = A x | B (T x)
       deriving (Z,W)}
NewtypeD Cxt Name [TyVarBndr] Con [Name]
{ newtype Cxt x => T x = A (B x)
       deriving (Z,W)}
TySynD Name [TyVarBndr] Type
{ type T x = (x,x) }
ClassD Cxt Name [TyVarBndr] [FunDep] [Dec]
{ class Eq a => Ord a where ds }
InstanceD Cxt Type [Dec]
{ instance Show w => Show [w]
       where ds }
SigD Name Type
{ length :: [a] -> Int }
ForeignD Foreign
{ foreign import ... }
{ foreign export ... }
InfixD Fixity Name
{ infix 3 foo }
PragmaD Pragma
{ {-# INLINE [1] foo #-} }
FamilyD FamFlavour Name [TyVarBndr] (Maybe Kind)
{ type family T a b c :: * }
DataInstD Cxt Name [Type] [Con] [Name]
{ data instance Cxt x => T [x] = A x
                                | B (T x)
       deriving (Z,W)}
NewtypeInstD Cxt Name [Type] Con [Name]
{ newtype instance Cxt x => T [x] = A (B x)
       deriving (Z,W)}
TySynInstD Name TySynEqn
{ type instance ... }
ClosedTypeFamilyD Name [TyVarBndr] (Maybe Kind) [TySynEqn]
{ type family F a b :: * where ... }
RoleAnnotD Name [Role]
{ type role T nominal representational }


data Con Source


NormalC Name [StrictType]
C Int a
RecC Name [VarStrictType]
C { v :: Int, w :: a }
InfixC StrictType Name StrictType
Int :+ a
ForallC [TyVarBndr] Cxt Con
forall a. Eq a => C [a]


data Clause Source


Clause [Pat] Body [Dec]
f { p1 p2 = body where decs }

data FunDep Source


FunDep [Name] [Name] 

data TySynEqn Source

One equation of a type family instance or closed type family. The arguments are the left-hand-side type patterns and the right-hand-side result.


TySynEqn [Type] Type 

defaultFixity :: Fixity Source

Default fixity: infixl 9

maxPrecedence :: Int Source

Highest allowed operator precedence for Fixity constructor (answer: 9)


data Exp Source


VarE Name
{ x }
ConE Name
data T1 = C1 t1 t2; p = {C1} e1 e2
LitE Lit
{ 5 or c}
AppE Exp Exp
{ f x }
InfixE (Maybe Exp) Exp (Maybe Exp)
{x + y} or {(x+)} or {(+ x)} or {(+)}
UInfixE Exp Exp Exp
{x + y}

See "Language.Haskell.TH.Syntax#infix"

ParensE Exp
{ (e) }

See "Language.Haskell.TH.Syntax#infix"

LamE [Pat] Exp
{  p1 p2 -> e }
LamCaseE [Match]
{ case m1; m2 }
TupE [Exp]
{ (e1,e2) }
UnboxedTupE [Exp]
{ (# e1,e2 #) }
CondE Exp Exp Exp
{ if e1 then e2 else e3 }
MultiIfE [(Guard, Exp)]
{ if | g1 -> e1 | g2 -> e2 }
LetE [Dec] Exp
{ let x=e1;   y=e2 in e3 }
CaseE Exp [Match]
{ case e of m1; m2 }
DoE [Stmt]
{ do { p <- e1; e2 }  }
CompE [Stmt]
{ [ (x,y) | x <- xs, y <- ys ] }

The result expression of the comprehension is the last of the Stmts, and should be a NoBindS.

E.g. translation:

[ f x | x <- xs ]
CompE [BindS (VarP x) (VarE xs), NoBindS (AppE (VarE f) (VarE x))]
ArithSeqE Range
{ [ 1 ,2 .. 10 ] }
ListE [Exp]
{ [1,2,3] }
SigE Exp Type
{ e :: t }
RecConE Name [FieldExp]
{ T { x = y, z = w } }
RecUpdE Exp [FieldExp]
{ (f x) { z = w } }


data Match Source


Match Pat Body [Dec]
case e of { pat -> body where decs }

data Body Source


GuardedB [(Guard, Exp)]
f p { | e1 = e2
      | e3 = e4 }
 where ds
NormalB Exp
f p { = e } where ds


data Guard Source


NormalG Exp
f x { | odd x } = x
PatG [Stmt]
f x { | Just y <- x, Just z <- y } = z

data Stmt Source


BindS Pat Exp 
LetS [Dec] 
NoBindS Exp 
ParS [[Stmt]] 

data Lit Source


CharL Char 
StringL String 
IntegerL Integer

Used for overloaded and non-overloaded literals. We don't have a good way to represent non-overloaded literals at the moment. Maybe that doesn't matter?

RationalL Rational 
IntPrimL Integer 
WordPrimL Integer 
FloatPrimL Rational 
DoublePrimL Rational 
StringPrimL [Word8]

A primitive C-style string, type Addr#



data Pat Source

Pattern in Haskell given in {}


LitP Lit
{ 5 or c }
VarP Name
{ x }
TupP [Pat]
{ (p1,p2) }
UnboxedTupP [Pat]
{ (# p1,p2 #) }
ConP Name [Pat]
data T1 = C1 t1 t2; {C1 p1 p1} = e
InfixP Pat Name Pat
foo ({x :+ y}) = e
UInfixP Pat Name Pat
foo ({x :+ y}) = e

See "Language.Haskell.TH.Syntax#infix"

ParensP Pat

See "Language.Haskell.TH.Syntax#infix"

TildeP Pat
{ ~p }
BangP Pat
{ !p }
AsP Name Pat
{ x @ p }
{ _ }
RecP Name [FieldPat]
f (Pt { pointx = x }) = g x
ListP [Pat]
{ [1,2,3] }
SigP Pat Type
{ p :: t }
ViewP Exp Pat
{ e -> p }



data Type Source


ForallT [TyVarBndr] Cxt Type
forall <vars>. <ctxt> -> <type>
AppT Type Type
T a b
SigT Type Kind
t :: k
VarT Name
ConT Name
PromotedT Name
TupleT Int
(,), (,,), etc.
UnboxedTupleT Int
(#,#), (#,,#), etc.
PromotedTupleT Int
'(), '(,), '(,,), etc.
LitT TyLit
0,1,2, etc.

type Kind = Type Source

To avoid duplication between kinds and types, they are defined to be the same. Naturally, you would never have a type be StarT and you would never have a kind be SigT, but many of the other constructors are shared. Note that the kind Bool is denoted with ConT, not PromotedT. Similarly, tuple kinds are made with TupleT, not PromotedTupleT.

type Cxt Source


 = [Pred]
(Eq a, Ord b)

data Pred Source


ClassP Name [Type]
Eq (Int, a)
EqualP Type Type
F a ~ Bool

data Role Source

Role annotations



Library functions


type ExpQ = Q Exp Source

type DecQ = Q Dec Source

type DecsQ = Q [Dec] Source

type ConQ = Q Con Source

type CxtQ = Q Cxt Source

type PatQ = Q Pat Source

Constructors lifted to Q



conP :: Name -> [PatQ] -> PatQ Source

Pattern Guards

patGE :: [StmtQ] -> ExpQ -> Q (Guard, Exp) Source

match :: PatQ -> BodyQ -> [DecQ] -> MatchQ Source

Use with caseE

clause :: [PatQ] -> BodyQ -> [DecQ] -> ClauseQ Source

Use with funD


dyn :: String -> ExpQ Source

Dynamically binding a variable (unhygenic)

global :: Name -> ExpQ Source

Deprecated: Use varE instead

lamE :: [PatQ] -> ExpQ -> ExpQ Source

lam1E :: PatQ -> ExpQ -> ExpQ Source

Single-arg lambda

letE :: [DecQ] -> ExpQ -> ExpQ Source

recConE :: Name -> [Q (Name, Exp)] -> ExpQ Source

recUpdE :: ExpQ -> [Q (Name, Exp)] -> ExpQ Source


Ranges with more indirection



Type literals


Class Contexts



Top Level Declarations


valD :: PatQ -> BodyQ -> [DecQ] -> DecQ Source

dataD :: CxtQ -> Name -> [TyVarBndr] -> [ConQ] -> [Name] -> DecQ Source

newtypeD :: CxtQ -> Name -> [TyVarBndr] -> ConQ -> [Name] -> DecQ Source


classD :: CxtQ -> Name -> [TyVarBndr] -> [FunDep] -> [DecQ] -> DecQ Source

Role annotations

Type Family / Data Family

dataInstD :: CxtQ -> Name -> [TypeQ] -> [ConQ] -> [Name] -> DecQ Source

newtypeInstD :: CxtQ -> Name -> [TypeQ] -> ConQ -> [Name] -> DecQ Source

Foreign Function Interface (FFI)



pprint :: Ppr a => a -> String Source