Template Haskell: support for kind annotations
[ghc-hetmet.git] / compiler / typecheck / TcHsSyn.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1996-1998
4 %
5
6 TcHsSyn: Specialisations of the @HsSyn@ syntax for the typechecker
7
8 This module is an extension of @HsSyn@ syntax, for use in the type
9 checker.
10
11 \begin{code}
12 module TcHsSyn (
13         mkHsConApp, mkHsDictLet, mkHsApp,
14         hsLitType, hsLPatType, hsPatType, 
15         mkHsAppTy, mkSimpleHsAlt,
16         nlHsIntLit, mkVanillaTuplePat, 
17         shortCutLit, hsOverLitName,
18         
19         mkArbitraryType,        -- Put this elsewhere?
20
21         -- re-exported from TcMonad
22         TcId, TcIdSet, TcDictBinds,
23
24         zonkTopDecls, zonkTopExpr, zonkTopLExpr,
25         zonkId, zonkTopBndrs
26   ) where
27
28 #include "HsVersions.h"
29
30 -- friends:
31 import HsSyn    -- oodles of it
32
33 -- others:
34 import Id
35
36 import TcRnMonad
37 import PrelNames
38 import TcType
39 import TcMType
40 import TysPrim
41 import TysWiredIn
42 import TyCon
43 import DataCon
44 import Name
45 import Var
46 import VarSet
47 import VarEnv
48 import Literal
49 import BasicTypes
50 import Maybes
51 import Unique
52 import SrcLoc
53 import Util
54 import Bag
55 import Outputable
56 import FastString
57 \end{code}
58
59 \begin{code}
60 -- XXX
61 thenM :: Monad a => a b -> (b -> a c) -> a c
62 thenM = (>>=)
63
64 thenM_ :: Monad a => a b -> a c -> a c
65 thenM_ = (>>)
66
67 returnM :: Monad m => a -> m a
68 returnM = return
69
70 mappM :: (Monad m) => (a -> m b) -> [a] -> m [b]
71 mappM = mapM
72 \end{code}
73
74
75 %************************************************************************
76 %*                                                                      *
77 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
78 %*                                                                      *
79 %************************************************************************
80
81 Note: If @hsLPatType@ doesn't bear a strong resemblance to @exprType@,
82 then something is wrong.
83 \begin{code}
84 mkVanillaTuplePat :: [OutPat Id] -> Boxity -> Pat Id
85 -- A vanilla tuple pattern simply gets its type from its sub-patterns
86 mkVanillaTuplePat pats box 
87   = TuplePat pats box (mkTupleTy box (length pats) (map hsLPatType pats))
88
89 hsLPatType :: OutPat Id -> Type
90 hsLPatType (L _ pat) = hsPatType pat
91
92 hsPatType :: Pat Id -> Type
93 hsPatType (ParPat pat)                = hsLPatType pat
94 hsPatType (WildPat ty)                = ty
95 hsPatType (VarPat var)                = idType var
96 hsPatType (VarPatOut var _)           = idType var
97 hsPatType (BangPat pat)               = hsLPatType pat
98 hsPatType (LazyPat pat)               = hsLPatType pat
99 hsPatType (LitPat lit)                = hsLitType lit
100 hsPatType (AsPat var _)               = idType (unLoc var)
101 hsPatType (ViewPat _ _ ty)            = ty
102 hsPatType (ListPat _ ty)              = mkListTy ty
103 hsPatType (PArrPat _ ty)              = mkPArrTy ty
104 hsPatType (TuplePat _ _ ty)           = ty
105 hsPatType (ConPatOut { pat_ty = ty }) = ty
106 hsPatType (SigPatOut _ ty)            = ty
107 hsPatType (NPat lit _ _)              = overLitType lit
108 hsPatType (NPlusKPat id _ _ _)        = idType (unLoc id)
109 hsPatType (CoPat _ _ ty)              = ty
110 hsPatType p                           = pprPanic "hsPatType" (ppr p)
111
112 hsLitType :: HsLit -> TcType
113 hsLitType (HsChar _)       = charTy
114 hsLitType (HsCharPrim _)   = charPrimTy
115 hsLitType (HsString _)     = stringTy
116 hsLitType (HsStringPrim _) = addrPrimTy
117 hsLitType (HsInt _)        = intTy
118 hsLitType (HsIntPrim _)    = intPrimTy
119 hsLitType (HsWordPrim _)   = wordPrimTy
120 hsLitType (HsInteger _ ty) = ty
121 hsLitType (HsRat _ ty)     = ty
122 hsLitType (HsFloatPrim _)  = floatPrimTy
123 hsLitType (HsDoublePrim _) = doublePrimTy
124 \end{code}
125
126 Overloaded literals. Here mainly becuase it uses isIntTy etc
127
128 \begin{code}
129 shortCutLit :: OverLitVal -> TcType -> Maybe (HsExpr TcId)
130 shortCutLit (HsIntegral i) ty
131   | isIntTy ty && inIntRange i   = Just (HsLit (HsInt i))
132   | isWordTy ty && inWordRange i = Just (mkLit wordDataCon (HsWordPrim i))
133   | isIntegerTy ty               = Just (HsLit (HsInteger i ty))
134   | otherwise                    = shortCutLit (HsFractional (fromInteger i)) ty
135         -- The 'otherwise' case is important
136         -- Consider (3 :: Float).  Syntactically it looks like an IntLit,
137         -- so we'll call shortCutIntLit, but of course it's a float
138         -- This can make a big difference for programs with a lot of
139         -- literals, compiled without -O
140
141 shortCutLit (HsFractional f) ty
142   | isFloatTy ty  = Just (mkLit floatDataCon  (HsFloatPrim f))
143   | isDoubleTy ty = Just (mkLit doubleDataCon (HsDoublePrim f))
144   | otherwise     = Nothing
145
146 shortCutLit (HsIsString s) ty
147   | isStringTy ty = Just (HsLit (HsString s))
148   | otherwise     = Nothing
149
150 mkLit :: DataCon -> HsLit -> HsExpr Id
151 mkLit con lit = HsApp (nlHsVar (dataConWrapId con)) (nlHsLit lit)
152
153 ------------------------------
154 hsOverLitName :: OverLitVal -> Name
155 -- Get the canonical 'fromX' name for a particular OverLitVal
156 hsOverLitName (HsIntegral {})   = fromIntegerName
157 hsOverLitName (HsFractional {}) = fromRationalName
158 hsOverLitName (HsIsString {})   = fromStringName
159 \end{code}
160
161 %************************************************************************
162 %*                                                                      *
163 \subsection[BackSubst-HsBinds]{Running a substitution over @HsBinds@}
164 %*                                                                      *
165 %************************************************************************
166
167 \begin{code}
168 -- zonkId is used *during* typechecking just to zonk the Id's type
169 zonkId :: TcId -> TcM TcId
170 zonkId id
171   = zonkTcType (idType id) `thenM` \ ty' ->
172     returnM (Id.setIdType id ty')
173 \end{code}
174
175 The rest of the zonking is done *after* typechecking.
176 The main zonking pass runs over the bindings
177
178  a) to convert TcTyVars to TyVars etc, dereferencing any bindings etc
179  b) convert unbound TcTyVar to Void
180  c) convert each TcId to an Id by zonking its type
181
182 The type variables are converted by binding mutable tyvars to immutable ones
183 and then zonking as normal.
184
185 The Ids are converted by binding them in the normal Tc envt; that
186 way we maintain sharing; eg an Id is zonked at its binding site and they
187 all occurrences of that Id point to the common zonked copy
188
189 It's all pretty boring stuff, because HsSyn is such a large type, and 
190 the environment manipulation is tiresome.
191
192 \begin{code}
193 data ZonkEnv = ZonkEnv  (TcType -> TcM Type)    -- How to zonk a type
194                         (IdEnv Id)              -- What variables are in scope
195         -- Maps an Id to its zonked version; both have the same Name
196         -- Is only consulted lazily; hence knot-tying
197
198 emptyZonkEnv :: ZonkEnv
199 emptyZonkEnv = ZonkEnv zonkTypeZapping emptyVarEnv
200
201 extendZonkEnv :: ZonkEnv -> [Id] -> ZonkEnv
202 extendZonkEnv (ZonkEnv zonk_ty env) ids 
203   = ZonkEnv zonk_ty (extendVarEnvList env [(id,id) | id <- ids])
204
205 extendZonkEnv1 :: ZonkEnv -> Id -> ZonkEnv
206 extendZonkEnv1 (ZonkEnv zonk_ty env) id 
207   = ZonkEnv zonk_ty (extendVarEnv env id id)
208
209 setZonkType :: ZonkEnv -> (TcType -> TcM Type) -> ZonkEnv
210 setZonkType (ZonkEnv _ env) zonk_ty = ZonkEnv zonk_ty env
211
212 zonkEnvIds :: ZonkEnv -> [Id]
213 zonkEnvIds (ZonkEnv _ env) = varEnvElts env
214
215 zonkIdOcc :: ZonkEnv -> TcId -> Id
216 -- Ids defined in this module should be in the envt; 
217 -- ignore others.  (Actually, data constructors are also
218 -- not LocalVars, even when locally defined, but that is fine.)
219 -- (Also foreign-imported things aren't currently in the ZonkEnv;
220 --  that's ok because they don't need zonking.)
221 --
222 -- Actually, Template Haskell works in 'chunks' of declarations, and
223 -- an earlier chunk won't be in the 'env' that the zonking phase 
224 -- carries around.  Instead it'll be in the tcg_gbl_env, already fully
225 -- zonked.  There's no point in looking it up there (except for error 
226 -- checking), and it's not conveniently to hand; hence the simple
227 -- 'orElse' case in the LocalVar branch.
228 --
229 -- Even without template splices, in module Main, the checking of
230 -- 'main' is done as a separate chunk.
231 zonkIdOcc (ZonkEnv _zonk_ty env) id 
232   | isLocalVar id = lookupVarEnv env id `orElse` id
233   | otherwise     = id
234
235 zonkIdOccs :: ZonkEnv -> [TcId] -> [Id]
236 zonkIdOccs env ids = map (zonkIdOcc env) ids
237
238 -- zonkIdBndr is used *after* typechecking to get the Id's type
239 -- to its final form.  The TyVarEnv give 
240 zonkIdBndr :: ZonkEnv -> TcId -> TcM Id
241 zonkIdBndr env id
242   = zonkTcTypeToType env (idType id)    `thenM` \ ty' ->
243     returnM (Id.setIdType id ty')
244
245 zonkIdBndrs :: ZonkEnv -> [TcId] -> TcM [Id]
246 zonkIdBndrs env ids = mappM (zonkIdBndr env) ids
247
248 zonkDictBndrs :: ZonkEnv -> [Var] -> TcM [Var]
249 -- "Dictionary" binders can be coercion variables or dictionary variables
250 zonkDictBndrs env ids = mappM (zonkDictBndr env) ids
251
252 zonkDictBndr :: ZonkEnv -> Var -> TcM Var
253 zonkDictBndr env var | isTyVar var = zonkTyVarBndr env var
254                      | otherwise   = zonkIdBndr env var
255
256 zonkTopBndrs :: [TcId] -> TcM [Id]
257 zonkTopBndrs ids = zonkIdBndrs emptyZonkEnv ids
258
259 -- Zonk the kind of a non-TC tyvar in case it is a coercion variable (their
260 -- kind contains types).
261 --
262 zonkTyVarBndr :: ZonkEnv -> TyVar -> TcM TyVar
263 zonkTyVarBndr env tv
264   | isCoVar tv
265   = do { kind <- zonkTcTypeToType env (tyVarKind tv)
266        ; return $ setTyVarKind tv kind
267        }
268   | otherwise = return tv
269 \end{code}
270
271
272 \begin{code}
273 zonkTopExpr :: HsExpr TcId -> TcM (HsExpr Id)
274 zonkTopExpr e = zonkExpr emptyZonkEnv e
275
276 zonkTopLExpr :: LHsExpr TcId -> TcM (LHsExpr Id)
277 zonkTopLExpr e = zonkLExpr emptyZonkEnv e
278
279 zonkTopDecls :: LHsBinds TcId -> [LRuleDecl TcId] -> [LForeignDecl TcId]
280              -> TcM ([Id], 
281                      Bag (LHsBind  Id),
282                      [LForeignDecl Id],
283                      [LRuleDecl    Id])
284 zonkTopDecls binds rules fords
285   = do  { (env, binds') <- zonkRecMonoBinds emptyZonkEnv binds
286                         -- Top level is implicitly recursive
287         ; rules' <- zonkRules env rules
288         ; fords' <- zonkForeignExports env fords
289         ; return (zonkEnvIds env, binds', fords', rules') }
290
291 ---------------------------------------------
292 zonkLocalBinds :: ZonkEnv -> HsLocalBinds TcId -> TcM (ZonkEnv, HsLocalBinds Id)
293 zonkLocalBinds env EmptyLocalBinds
294   = return (env, EmptyLocalBinds)
295
296 zonkLocalBinds env (HsValBinds binds)
297   = do  { (env1, new_binds) <- zonkValBinds env binds
298         ; return (env1, HsValBinds new_binds) }
299
300 zonkLocalBinds env (HsIPBinds (IPBinds binds dict_binds))
301   = mappM (wrapLocM zonk_ip_bind) binds `thenM` \ new_binds ->
302     let
303         env1 = extendZonkEnv env [ipNameName n | L _ (IPBind n _) <- new_binds]
304     in
305     zonkRecMonoBinds env1 dict_binds    `thenM` \ (env2, new_dict_binds) -> 
306     returnM (env2, HsIPBinds (IPBinds new_binds new_dict_binds))
307   where
308     zonk_ip_bind (IPBind n e)
309         = mapIPNameTc (zonkIdBndr env) n        `thenM` \ n' ->
310           zonkLExpr env e                       `thenM` \ e' ->
311           returnM (IPBind n' e')
312
313
314 ---------------------------------------------
315 zonkValBinds :: ZonkEnv -> HsValBinds TcId -> TcM (ZonkEnv, HsValBinds Id)
316 zonkValBinds _ (ValBindsIn _ _) 
317   = panic "zonkValBinds" -- Not in typechecker output
318 zonkValBinds env (ValBindsOut binds sigs) 
319   = do  { (env1, new_binds) <- go env binds
320         ; return (env1, ValBindsOut new_binds sigs) }
321   where
322     go env []         = return (env, [])
323     go env ((r,b):bs) = do { (env1, b')  <- zonkRecMonoBinds env b
324                            ; (env2, bs') <- go env1 bs
325                            ; return (env2, (r,b'):bs') }
326
327 ---------------------------------------------
328 zonkRecMonoBinds :: ZonkEnv -> LHsBinds TcId -> TcM (ZonkEnv, LHsBinds Id)
329 zonkRecMonoBinds env binds 
330  = fixM (\ ~(_, new_binds) -> do 
331         { let env1 = extendZonkEnv env (collectHsBindBinders new_binds)
332         ; binds' <- zonkMonoBinds env1 binds
333         ; return (env1, binds') })
334
335 ---------------------------------------------
336 zonkMonoBinds :: ZonkEnv -> LHsBinds TcId -> TcM (LHsBinds Id)
337 zonkMonoBinds env binds = mapBagM (wrapLocM (zonk_bind env)) binds
338
339 zonk_bind :: ZonkEnv -> HsBind TcId -> TcM (HsBind Id)
340 zonk_bind env bind@(PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty})
341   = do  { (_env, new_pat) <- zonkPat env pat            -- Env already extended
342         ; new_grhss <- zonkGRHSs env grhss
343         ; new_ty    <- zonkTcTypeToType env ty
344         ; return (bind { pat_lhs = new_pat, pat_rhs = new_grhss, pat_rhs_ty = new_ty }) }
345
346 zonk_bind env (VarBind { var_id = var, var_rhs = expr })
347   = zonkIdBndr env var                  `thenM` \ new_var ->
348     zonkLExpr env expr                  `thenM` \ new_expr ->
349     returnM (VarBind { var_id = new_var, var_rhs = new_expr })
350
351 zonk_bind env bind@(FunBind { fun_id = var, fun_matches = ms, fun_co_fn = co_fn })
352   = wrapLocM (zonkIdBndr env) var       `thenM` \ new_var ->
353     zonkCoFn env co_fn                  `thenM` \ (env1, new_co_fn) ->
354     zonkMatchGroup env1 ms              `thenM` \ new_ms ->
355     returnM (bind { fun_id = new_var, fun_matches = new_ms, fun_co_fn = new_co_fn })
356
357 zonk_bind env (AbsBinds { abs_tvs = tyvars, abs_dicts = dicts, 
358                           abs_exports = exports, abs_binds = val_binds })
359   = ASSERT( all isImmutableTyVar tyvars )
360     zonkDictBndrs env dicts                     `thenM` \ new_dicts ->
361     fixM (\ ~(new_val_binds, _) ->
362         let
363           env1 = extendZonkEnv env new_dicts
364           env2 = extendZonkEnv env1 (collectHsBindBinders new_val_binds)
365         in
366         zonkMonoBinds env2 val_binds            `thenM` \ new_val_binds ->
367         mappM (zonkExport env2) exports         `thenM` \ new_exports ->
368         returnM (new_val_binds, new_exports)
369     )                                           `thenM` \ (new_val_bind, new_exports) ->
370     returnM (AbsBinds { abs_tvs = tyvars, abs_dicts = new_dicts, 
371                         abs_exports = new_exports, abs_binds = new_val_bind })
372   where
373     zonkExport env (tyvars, global, local, prags)
374         -- The tyvars are already zonked
375         = zonkIdBndr env global                 `thenM` \ new_global ->
376           mapM zonk_prag prags                  `thenM` \ new_prags -> 
377           returnM (tyvars, new_global, zonkIdOcc env local, new_prags)
378     zonk_prag prag@(L _ (InlinePrag {}))  = return prag
379     zonk_prag (L loc (SpecPrag expr ty inl))
380         = do { expr' <- zonkExpr env expr 
381              ; ty'   <- zonkTcTypeToType env ty
382              ; return (L loc (SpecPrag expr' ty' inl)) }
383 \end{code}
384
385 %************************************************************************
386 %*                                                                      *
387 \subsection[BackSubst-Match-GRHSs]{Match and GRHSs}
388 %*                                                                      *
389 %************************************************************************
390
391 \begin{code}
392 zonkMatchGroup :: ZonkEnv -> MatchGroup TcId-> TcM (MatchGroup Id)
393 zonkMatchGroup env (MatchGroup ms ty) 
394   = do  { ms' <- mapM (zonkMatch env) ms
395         ; ty' <- zonkTcTypeToType env ty
396         ; return (MatchGroup ms' ty') }
397
398 zonkMatch :: ZonkEnv -> LMatch TcId-> TcM (LMatch Id)
399 zonkMatch env (L loc (Match pats _ grhss))
400   = do  { (env1, new_pats) <- zonkPats env pats
401         ; new_grhss <- zonkGRHSs env1 grhss
402         ; return (L loc (Match new_pats Nothing new_grhss)) }
403
404 -------------------------------------------------------------------------
405 zonkGRHSs :: ZonkEnv -> GRHSs TcId -> TcM (GRHSs Id)
406
407 zonkGRHSs env (GRHSs grhss binds)
408   = zonkLocalBinds env binds    `thenM` \ (new_env, new_binds) ->
409     let
410         zonk_grhs (GRHS guarded rhs)
411           = zonkStmts new_env guarded   `thenM` \ (env2, new_guarded) ->
412             zonkLExpr env2 rhs          `thenM` \ new_rhs ->
413             returnM (GRHS new_guarded new_rhs)
414     in
415     mappM (wrapLocM zonk_grhs) grhss    `thenM` \ new_grhss ->
416     returnM (GRHSs new_grhss new_binds)
417 \end{code}
418
419 %************************************************************************
420 %*                                                                      *
421 \subsection[BackSubst-HsExpr]{Running a zonkitution over a TypeCheckedExpr}
422 %*                                                                      *
423 %************************************************************************
424
425 \begin{code}
426 zonkLExprs :: ZonkEnv -> [LHsExpr TcId] -> TcM [LHsExpr Id]
427 zonkLExpr  :: ZonkEnv -> LHsExpr TcId   -> TcM (LHsExpr Id)
428 zonkExpr   :: ZonkEnv -> HsExpr TcId    -> TcM (HsExpr Id)
429
430 zonkLExprs env exprs = mappM (zonkLExpr env) exprs
431 zonkLExpr  env expr  = wrapLocM (zonkExpr env) expr
432
433 zonkExpr env (HsVar id)
434   = returnM (HsVar (zonkIdOcc env id))
435
436 zonkExpr env (HsIPVar id)
437   = returnM (HsIPVar (mapIPName (zonkIdOcc env) id))
438
439 zonkExpr env (HsLit (HsRat f ty))
440   = zonkTcTypeToType env ty        `thenM` \ new_ty  ->
441     returnM (HsLit (HsRat f new_ty))
442
443 zonkExpr _ (HsLit lit)
444   = returnM (HsLit lit)
445
446 zonkExpr env (HsOverLit lit)
447   = do  { lit' <- zonkOverLit env lit
448         ; return (HsOverLit lit') }
449
450 zonkExpr env (HsLam matches)
451   = zonkMatchGroup env matches  `thenM` \ new_matches ->
452     returnM (HsLam new_matches)
453
454 zonkExpr env (HsApp e1 e2)
455   = zonkLExpr env e1    `thenM` \ new_e1 ->
456     zonkLExpr env e2    `thenM` \ new_e2 ->
457     returnM (HsApp new_e1 new_e2)
458
459 zonkExpr env (HsBracketOut body bs) 
460   = mappM zonk_b bs     `thenM` \ bs' ->
461     returnM (HsBracketOut body bs')
462   where
463     zonk_b (n,e) = zonkLExpr env e      `thenM` \ e' ->
464                    returnM (n,e')
465
466 zonkExpr _ (HsSpliceE s) = WARN( True, ppr s ) -- Should not happen
467                              returnM (HsSpliceE s)
468
469 zonkExpr env (OpApp e1 op fixity e2)
470   = zonkLExpr env e1    `thenM` \ new_e1 ->
471     zonkLExpr env op    `thenM` \ new_op ->
472     zonkLExpr env e2    `thenM` \ new_e2 ->
473     returnM (OpApp new_e1 new_op fixity new_e2)
474
475 zonkExpr env (NegApp expr op)
476   = zonkLExpr env expr  `thenM` \ new_expr ->
477     zonkExpr env op     `thenM` \ new_op ->
478     returnM (NegApp new_expr new_op)
479
480 zonkExpr env (HsPar e)    
481   = zonkLExpr env e     `thenM` \new_e ->
482     returnM (HsPar new_e)
483
484 zonkExpr env (SectionL expr op)
485   = zonkLExpr env expr  `thenM` \ new_expr ->
486     zonkLExpr env op            `thenM` \ new_op ->
487     returnM (SectionL new_expr new_op)
488
489 zonkExpr env (SectionR op expr)
490   = zonkLExpr env op            `thenM` \ new_op ->
491     zonkLExpr env expr          `thenM` \ new_expr ->
492     returnM (SectionR new_op new_expr)
493
494 zonkExpr env (HsCase expr ms)
495   = zonkLExpr env expr          `thenM` \ new_expr ->
496     zonkMatchGroup env ms       `thenM` \ new_ms ->
497     returnM (HsCase new_expr new_ms)
498
499 zonkExpr env (HsIf e1 e2 e3)
500   = zonkLExpr env e1    `thenM` \ new_e1 ->
501     zonkLExpr env e2    `thenM` \ new_e2 ->
502     zonkLExpr env e3    `thenM` \ new_e3 ->
503     returnM (HsIf new_e1 new_e2 new_e3)
504
505 zonkExpr env (HsLet binds expr)
506   = zonkLocalBinds env binds    `thenM` \ (new_env, new_binds) ->
507     zonkLExpr new_env expr      `thenM` \ new_expr ->
508     returnM (HsLet new_binds new_expr)
509
510 zonkExpr env (HsDo do_or_lc stmts body ty)
511   = zonkStmts env stmts         `thenM` \ (new_env, new_stmts) ->
512     zonkLExpr new_env body      `thenM` \ new_body ->
513     zonkTcTypeToType env ty     `thenM` \ new_ty   ->
514     returnM (HsDo (zonkDo env do_or_lc) 
515                   new_stmts new_body new_ty)
516
517 zonkExpr env (ExplicitList ty exprs)
518   = zonkTcTypeToType env ty     `thenM` \ new_ty ->
519     zonkLExprs env exprs        `thenM` \ new_exprs ->
520     returnM (ExplicitList new_ty new_exprs)
521
522 zonkExpr env (ExplicitPArr ty exprs)
523   = zonkTcTypeToType env ty     `thenM` \ new_ty ->
524     zonkLExprs env exprs        `thenM` \ new_exprs ->
525     returnM (ExplicitPArr new_ty new_exprs)
526
527 zonkExpr env (ExplicitTuple exprs boxed)
528   = zonkLExprs env exprs        `thenM` \ new_exprs ->
529     returnM (ExplicitTuple new_exprs boxed)
530
531 zonkExpr env (RecordCon data_con con_expr rbinds)
532   = do  { new_con_expr <- zonkExpr env con_expr
533         ; new_rbinds   <- zonkRecFields env rbinds
534         ; return (RecordCon data_con new_con_expr new_rbinds) }
535
536 zonkExpr env (RecordUpd expr rbinds cons in_tys out_tys)
537   = do  { new_expr    <- zonkLExpr env expr
538         ; new_in_tys  <- mapM (zonkTcTypeToType env) in_tys
539         ; new_out_tys <- mapM (zonkTcTypeToType env) out_tys
540         ; new_rbinds  <- zonkRecFields env rbinds
541         ; return (RecordUpd new_expr new_rbinds cons new_in_tys new_out_tys) }
542
543 zonkExpr env (ExprWithTySigOut e ty) 
544   = do { e' <- zonkLExpr env e
545        ; return (ExprWithTySigOut e' ty) }
546
547 zonkExpr _ (ExprWithTySig _ _) = panic "zonkExpr env:ExprWithTySig"
548
549 zonkExpr env (ArithSeq expr info)
550   = zonkExpr env expr           `thenM` \ new_expr ->
551     zonkArithSeq env info       `thenM` \ new_info ->
552     returnM (ArithSeq new_expr new_info)
553
554 zonkExpr env (PArrSeq expr info)
555   = zonkExpr env expr           `thenM` \ new_expr ->
556     zonkArithSeq env info       `thenM` \ new_info ->
557     returnM (PArrSeq new_expr new_info)
558
559 zonkExpr env (HsSCC lbl expr)
560   = zonkLExpr env expr  `thenM` \ new_expr ->
561     returnM (HsSCC lbl new_expr)
562
563 zonkExpr env (HsTickPragma info expr)
564   = zonkLExpr env expr  `thenM` \ new_expr ->
565     returnM (HsTickPragma info new_expr)
566
567 -- hdaume: core annotations
568 zonkExpr env (HsCoreAnn lbl expr)
569   = zonkLExpr env expr   `thenM` \ new_expr ->
570     returnM (HsCoreAnn lbl new_expr)
571
572 -- arrow notation extensions
573 zonkExpr env (HsProc pat body)
574   = do  { (env1, new_pat) <- zonkPat env pat
575         ; new_body <- zonkCmdTop env1 body
576         ; return (HsProc new_pat new_body) }
577
578 zonkExpr env (HsArrApp e1 e2 ty ho rl)
579   = zonkLExpr env e1                    `thenM` \ new_e1 ->
580     zonkLExpr env e2                    `thenM` \ new_e2 ->
581     zonkTcTypeToType env ty             `thenM` \ new_ty ->
582     returnM (HsArrApp new_e1 new_e2 new_ty ho rl)
583
584 zonkExpr env (HsArrForm op fixity args)
585   = zonkLExpr env op                    `thenM` \ new_op ->
586     mappM (zonkCmdTop env) args         `thenM` \ new_args ->
587     returnM (HsArrForm new_op fixity new_args)
588
589 zonkExpr env (HsWrap co_fn expr)
590   = zonkCoFn env co_fn  `thenM` \ (env1, new_co_fn) ->
591     zonkExpr env1 expr  `thenM` \ new_expr ->
592     return (HsWrap new_co_fn new_expr)
593
594 zonkExpr _ expr = pprPanic "zonkExpr" (ppr expr)
595
596 zonkCmdTop :: ZonkEnv -> LHsCmdTop TcId -> TcM (LHsCmdTop Id)
597 zonkCmdTop env cmd = wrapLocM (zonk_cmd_top env) cmd
598
599 zonk_cmd_top :: ZonkEnv -> HsCmdTop TcId -> TcM (HsCmdTop Id)
600 zonk_cmd_top env (HsCmdTop cmd stack_tys ty ids)
601   = zonkLExpr env cmd                   `thenM` \ new_cmd ->
602     zonkTcTypeToTypes env stack_tys     `thenM` \ new_stack_tys ->
603     zonkTcTypeToType env ty             `thenM` \ new_ty ->
604     mapSndM (zonkExpr env) ids          `thenM` \ new_ids ->
605     returnM (HsCmdTop new_cmd new_stack_tys new_ty new_ids)
606
607 -------------------------------------------------------------------------
608 zonkCoFn :: ZonkEnv -> HsWrapper -> TcM (ZonkEnv, HsWrapper)
609 zonkCoFn env WpHole   = return (env, WpHole)
610 zonkCoFn env WpInline = return (env, WpInline)
611 zonkCoFn env (WpCompose c1 c2) = do { (env1, c1') <- zonkCoFn env c1
612                                     ; (env2, c2') <- zonkCoFn env1 c2
613                                     ; return (env2, WpCompose c1' c2') }
614 zonkCoFn env (WpCast co)    = do { co' <- zonkTcTypeToType env co
615                                  ; return (env, WpCast co') }
616 zonkCoFn env (WpLam id)     = do { id' <- zonkDictBndr env id
617                                  ; let env1 = extendZonkEnv1 env id'
618                                  ; return (env1, WpLam id') }
619 zonkCoFn env (WpTyLam tv)   = ASSERT( isImmutableTyVar tv )
620                               do { tv' <- zonkTyVarBndr env tv
621                                  ; return (env, WpTyLam tv') }
622 zonkCoFn env (WpApp v)
623         | isTcTyVar v       = do { co <- zonkTcTyVar v
624                                  ; return (env, WpTyApp co) }
625                 -- Yuk!  A mutable coercion variable is a TcTyVar 
626                 --       not a CoVar, so don't use isCoVar!
627                 -- Yuk!  A WpApp can't hold the zonked type,
628                 --       so we switch to WpTyApp
629         | otherwise         = return (env, WpApp (zonkIdOcc env v))
630 zonkCoFn env (WpTyApp ty)   = do { ty' <- zonkTcTypeToType env ty
631                                  ; return (env, WpTyApp ty') }
632 zonkCoFn env (WpLet bs)     = do { (env1, bs') <- zonkRecMonoBinds env bs
633                                  ; return (env1, WpLet bs') }
634
635
636 -------------------------------------------------------------------------
637 zonkDo :: ZonkEnv -> HsStmtContext Name -> HsStmtContext Name
638 -- Only used for 'do', so the only Ids are in a MDoExpr table
639 zonkDo env (MDoExpr tbl) = MDoExpr (mapSnd (zonkIdOcc env) tbl)
640 zonkDo _   do_or_lc      = do_or_lc
641
642 -------------------------------------------------------------------------
643 zonkOverLit :: ZonkEnv -> HsOverLit TcId -> TcM (HsOverLit Id)
644 zonkOverLit env lit@(OverLit { ol_witness = e, ol_type = ty })
645   = do  { ty' <- zonkTcTypeToType env ty
646         ; e' <- zonkExpr env e
647         ; return (lit { ol_witness = e', ol_type = ty' }) }
648
649 -------------------------------------------------------------------------
650 zonkArithSeq :: ZonkEnv -> ArithSeqInfo TcId -> TcM (ArithSeqInfo Id)
651
652 zonkArithSeq env (From e)
653   = zonkLExpr env e             `thenM` \ new_e ->
654     returnM (From new_e)
655
656 zonkArithSeq env (FromThen e1 e2)
657   = zonkLExpr env e1    `thenM` \ new_e1 ->
658     zonkLExpr env e2    `thenM` \ new_e2 ->
659     returnM (FromThen new_e1 new_e2)
660
661 zonkArithSeq env (FromTo e1 e2)
662   = zonkLExpr env e1    `thenM` \ new_e1 ->
663     zonkLExpr env e2    `thenM` \ new_e2 ->
664     returnM (FromTo new_e1 new_e2)
665
666 zonkArithSeq env (FromThenTo e1 e2 e3)
667   = zonkLExpr env e1    `thenM` \ new_e1 ->
668     zonkLExpr env e2    `thenM` \ new_e2 ->
669     zonkLExpr env e3    `thenM` \ new_e3 ->
670     returnM (FromThenTo new_e1 new_e2 new_e3)
671
672
673 -------------------------------------------------------------------------
674 zonkStmts :: ZonkEnv -> [LStmt TcId] -> TcM (ZonkEnv, [LStmt Id])
675 zonkStmts env []     = return (env, [])
676 zonkStmts env (s:ss) = do { (env1, s')  <- wrapLocSndM (zonkStmt env) s
677                           ; (env2, ss') <- zonkStmts env1 ss
678                           ; return (env2, s' : ss') }
679
680 zonkStmt :: ZonkEnv -> Stmt TcId -> TcM (ZonkEnv, Stmt Id)
681 zonkStmt env (ParStmt stmts_w_bndrs)
682   = mappM zonk_branch stmts_w_bndrs     `thenM` \ new_stmts_w_bndrs ->
683     let 
684         new_binders = concat (map snd new_stmts_w_bndrs)
685         env1 = extendZonkEnv env new_binders
686     in
687     return (env1, ParStmt new_stmts_w_bndrs)
688   where
689     zonk_branch (stmts, bndrs) = zonkStmts env stmts    `thenM` \ (env1, new_stmts) ->
690                                  returnM (new_stmts, zonkIdOccs env1 bndrs)
691
692 zonkStmt env (RecStmt segStmts lvs rvs rets binds)
693   = zonkIdBndrs env rvs         `thenM` \ new_rvs ->
694     let
695         env1 = extendZonkEnv env new_rvs
696     in
697     zonkStmts env1 segStmts     `thenM` \ (env2, new_segStmts) ->
698         -- Zonk the ret-expressions in an envt that 
699         -- has the polymorphic bindings in the envt
700     mapM (zonkExpr env2) rets   `thenM` \ new_rets ->
701     let
702         new_lvs = zonkIdOccs env2 lvs
703         env3 = extendZonkEnv env new_lvs        -- Only the lvs are needed
704     in
705     zonkRecMonoBinds env3 binds `thenM` \ (env4, new_binds) ->
706     returnM (env4, RecStmt new_segStmts new_lvs new_rvs new_rets new_binds)
707
708 zonkStmt env (ExprStmt expr then_op ty)
709   = zonkLExpr env expr          `thenM` \ new_expr ->
710     zonkExpr env then_op        `thenM` \ new_then ->
711     zonkTcTypeToType env ty     `thenM` \ new_ty ->
712     returnM (env, ExprStmt new_expr new_then new_ty)
713
714 zonkStmt env (TransformStmt (stmts, binders) usingExpr maybeByExpr)
715   = do { (env', stmts') <- zonkStmts env stmts 
716     ; let binders' = zonkIdOccs env' binders
717     ; usingExpr' <- zonkLExpr env' usingExpr
718     ; maybeByExpr' <- zonkMaybeLExpr env' maybeByExpr
719     ; return (env', TransformStmt (stmts', binders') usingExpr' maybeByExpr') }
720     
721 zonkStmt env (GroupStmt (stmts, binderMap) groupByClause)
722   = do { (env', stmts') <- zonkStmts env stmts 
723     ; binderMap' <- mappM (zonkBinderMapEntry env') binderMap
724     ; groupByClause' <- 
725         case groupByClause of
726             GroupByNothing usingExpr -> (zonkLExpr env' usingExpr) >>= (return . GroupByNothing)
727             GroupBySomething eitherUsingExpr byExpr -> do
728                 eitherUsingExpr' <- mapEitherM (zonkLExpr env') (zonkExpr env') eitherUsingExpr
729                 byExpr' <- zonkLExpr env' byExpr
730                 return $ GroupBySomething eitherUsingExpr' byExpr'
731                 
732     ; let env'' = extendZonkEnv env' (map snd binderMap')
733     ; return (env'', GroupStmt (stmts', binderMap') groupByClause') }
734   where
735     mapEitherM f g x = do
736       case x of
737         Left a -> f a >>= (return . Left)
738         Right b -> g b >>= (return . Right)
739   
740     zonkBinderMapEntry env (oldBinder, newBinder) = do 
741         let oldBinder' = zonkIdOcc env oldBinder
742         newBinder' <- zonkIdBndr env newBinder
743         return (oldBinder', newBinder') 
744
745 zonkStmt env (LetStmt binds)
746   = zonkLocalBinds env binds    `thenM` \ (env1, new_binds) ->
747     returnM (env1, LetStmt new_binds)
748
749 zonkStmt env (BindStmt pat expr bind_op fail_op)
750   = do  { new_expr <- zonkLExpr env expr
751         ; (env1, new_pat) <- zonkPat env pat
752         ; new_bind <- zonkExpr env bind_op
753         ; new_fail <- zonkExpr env fail_op
754         ; return (env1, BindStmt new_pat new_expr new_bind new_fail) }
755
756 zonkMaybeLExpr :: ZonkEnv -> Maybe (LHsExpr TcId) -> TcM (Maybe (LHsExpr Id))
757 zonkMaybeLExpr _   Nothing  = return Nothing
758 zonkMaybeLExpr env (Just e) = (zonkLExpr env e) >>= (return . Just)
759
760
761 -------------------------------------------------------------------------
762 zonkRecFields :: ZonkEnv -> HsRecordBinds TcId -> TcM (HsRecordBinds TcId)
763 zonkRecFields env (HsRecFields flds dd)
764   = do  { flds' <- mappM zonk_rbind flds
765         ; return (HsRecFields flds' dd) }
766   where
767     zonk_rbind fld
768       = do { new_id   <- wrapLocM (zonkIdBndr env) (hsRecFieldId fld)
769            ; new_expr <- zonkLExpr env (hsRecFieldArg fld)
770            ; return (fld { hsRecFieldId = new_id, hsRecFieldArg = new_expr }) }
771
772 -------------------------------------------------------------------------
773 mapIPNameTc :: (a -> TcM b) -> IPName a -> TcM (IPName b)
774 mapIPNameTc f (IPName n) = f n  `thenM` \ r -> returnM (IPName r)
775 \end{code}
776
777
778 %************************************************************************
779 %*                                                                      *
780 \subsection[BackSubst-Pats]{Patterns}
781 %*                                                                      *
782 %************************************************************************
783
784 \begin{code}
785 zonkPat :: ZonkEnv -> OutPat TcId -> TcM (ZonkEnv, OutPat Id)
786 -- Extend the environment as we go, because it's possible for one
787 -- pattern to bind something that is used in another (inside or
788 -- to the right)
789 zonkPat env pat = wrapLocSndM (zonk_pat env) pat
790
791 zonk_pat :: ZonkEnv -> Pat TcId -> TcM (ZonkEnv, Pat Id)
792 zonk_pat env (ParPat p)
793   = do  { (env', p') <- zonkPat env p
794         ; return (env', ParPat p') }
795
796 zonk_pat env (WildPat ty)
797   = do  { ty' <- zonkTcTypeToType env ty
798         ; return (env, WildPat ty') }
799
800 zonk_pat env (VarPat v)
801   = do  { v' <- zonkIdBndr env v
802         ; return (extendZonkEnv1 env v', VarPat v') }
803
804 zonk_pat env (VarPatOut v binds)
805   = do  { v' <- zonkIdBndr env v
806         ; (env', binds') <- zonkRecMonoBinds (extendZonkEnv1 env v') binds
807         ; returnM (env', VarPatOut v' binds') }
808
809 zonk_pat env (LazyPat pat)
810   = do  { (env', pat') <- zonkPat env pat
811         ; return (env',  LazyPat pat') }
812
813 zonk_pat env (BangPat pat)
814   = do  { (env', pat') <- zonkPat env pat
815         ; return (env',  BangPat pat') }
816
817 zonk_pat env (AsPat (L loc v) pat)
818   = do  { v' <- zonkIdBndr env v
819         ; (env', pat') <- zonkPat (extendZonkEnv1 env v') pat
820         ; return (env', AsPat (L loc v') pat') }
821
822 zonk_pat env (ViewPat expr pat ty)
823   = do  { expr' <- zonkLExpr env expr
824         ; (env', pat') <- zonkPat env pat
825         ; return (env', ViewPat expr' pat' ty) }
826
827 zonk_pat env (ListPat pats ty)
828   = do  { ty' <- zonkTcTypeToType env ty
829         ; (env', pats') <- zonkPats env pats
830         ; return (env', ListPat pats' ty') }
831
832 zonk_pat env (PArrPat pats ty)
833   = do  { ty' <- zonkTcTypeToType env ty
834         ; (env', pats') <- zonkPats env pats
835         ; return (env', PArrPat pats' ty') }
836
837 zonk_pat env (TuplePat pats boxed ty)
838   = do  { ty' <- zonkTcTypeToType env ty
839         ; (env', pats') <- zonkPats env pats
840         ; return (env', TuplePat pats' boxed ty') }
841
842 zonk_pat env p@(ConPatOut { pat_ty = ty, pat_dicts = dicts, pat_binds = binds, pat_args = args })
843   = ASSERT( all isImmutableTyVar (pat_tvs p) ) 
844     do  { new_ty <- zonkTcTypeToType env ty
845         ; new_dicts <- zonkDictBndrs env dicts
846         ; let env1 = extendZonkEnv env new_dicts
847         ; (env2, new_binds) <- zonkRecMonoBinds env1 binds
848         ; (env', new_args) <- zonkConStuff env2 args
849         ; returnM (env', p { pat_ty = new_ty, pat_dicts = new_dicts, 
850                              pat_binds = new_binds, pat_args = new_args }) }
851
852 zonk_pat env (LitPat lit) = return (env, LitPat lit)
853
854 zonk_pat env (SigPatOut pat ty)
855   = do  { ty' <- zonkTcTypeToType env ty
856         ; (env', pat') <- zonkPat env pat
857         ; return (env', SigPatOut pat' ty') }
858
859 zonk_pat env (NPat lit mb_neg eq_expr)
860   = do  { lit' <- zonkOverLit env lit
861         ; mb_neg' <- case mb_neg of
862                         Nothing  -> return Nothing
863                         Just neg -> do { neg' <- zonkExpr env neg
864                                        ; return (Just neg') }
865         ; eq_expr' <- zonkExpr env eq_expr
866         ; return (env, NPat lit' mb_neg' eq_expr') }
867
868 zonk_pat env (NPlusKPat (L loc n) lit e1 e2)
869   = do  { n' <- zonkIdBndr env n
870         ; lit' <- zonkOverLit env lit
871         ; e1' <- zonkExpr env e1
872         ; e2' <- zonkExpr env e2
873         ; return (extendZonkEnv1 env n', NPlusKPat (L loc n') lit' e1' e2') }
874
875 zonk_pat env (CoPat co_fn pat ty) 
876   = do { (env', co_fn') <- zonkCoFn env co_fn
877        ; (env'', pat') <- zonkPat env' (noLoc pat)
878        ; ty' <- zonkTcTypeToType env'' ty
879        ; return (env'', CoPat co_fn' (unLoc pat') ty') }
880
881 zonk_pat _ pat = pprPanic "zonk_pat" (ppr pat)
882
883 ---------------------------
884 zonkConStuff :: ZonkEnv
885              -> HsConDetails (OutPat TcId) (HsRecFields id (OutPat TcId))
886              -> TcM (ZonkEnv,
887                      HsConDetails (OutPat Id) (HsRecFields id (OutPat Id)))
888 zonkConStuff env (PrefixCon pats)
889   = do  { (env', pats') <- zonkPats env pats
890         ; return (env', PrefixCon pats') }
891
892 zonkConStuff env (InfixCon p1 p2)
893   = do  { (env1, p1') <- zonkPat env  p1
894         ; (env', p2') <- zonkPat env1 p2
895         ; return (env', InfixCon p1' p2') }
896
897 zonkConStuff env (RecCon (HsRecFields rpats dd))
898   = do  { (env', pats') <- zonkPats env (map hsRecFieldArg rpats)
899         ; let rpats' = zipWith (\rp p' -> rp { hsRecFieldArg = p' }) rpats pats'
900         ; returnM (env', RecCon (HsRecFields rpats' dd)) }
901         -- Field selectors have declared types; hence no zonking
902
903 ---------------------------
904 zonkPats :: ZonkEnv -> [OutPat TcId] -> TcM (ZonkEnv, [OutPat Id])
905 zonkPats env []         = return (env, [])
906 zonkPats env (pat:pats) = do { (env1, pat') <- zonkPat env pat
907                      ; (env', pats') <- zonkPats env1 pats
908                      ; return (env', pat':pats') }
909 \end{code}
910
911 %************************************************************************
912 %*                                                                      *
913 \subsection[BackSubst-Foreign]{Foreign exports}
914 %*                                                                      *
915 %************************************************************************
916
917
918 \begin{code}
919 zonkForeignExports :: ZonkEnv -> [LForeignDecl TcId] -> TcM [LForeignDecl Id]
920 zonkForeignExports env ls = mappM (wrapLocM (zonkForeignExport env)) ls
921
922 zonkForeignExport :: ZonkEnv -> ForeignDecl TcId -> TcM (ForeignDecl Id)
923 zonkForeignExport env (ForeignExport i _hs_ty spec) =
924    returnM (ForeignExport (fmap (zonkIdOcc env) i) undefined spec)
925 zonkForeignExport _ for_imp 
926   = returnM for_imp     -- Foreign imports don't need zonking
927 \end{code}
928
929 \begin{code}
930 zonkRules :: ZonkEnv -> [LRuleDecl TcId] -> TcM [LRuleDecl Id]
931 zonkRules env rs = mappM (wrapLocM (zonkRule env)) rs
932
933 zonkRule :: ZonkEnv -> RuleDecl TcId -> TcM (RuleDecl Id)
934 zonkRule env (HsRule name act (vars{-::[RuleBndr TcId]-}) lhs fv_lhs rhs fv_rhs)
935   = mappM zonk_bndr vars                `thenM` \ new_bndrs ->
936     newMutVar emptyVarSet               `thenM` \ unbound_tv_set ->
937     let
938         env_rhs = extendZonkEnv env [id | b <- new_bndrs, let id = unLoc b, isId id]
939         -- Type variables don't need an envt
940         -- They are bound through the mutable mechanism
941
942         env_lhs = setZonkType env_rhs (zonkTypeCollecting unbound_tv_set)
943         -- We need to gather the type variables mentioned on the LHS so we can 
944         -- quantify over them.  Example:
945         --   data T a = C
946         -- 
947         --   foo :: T a -> Int
948         --   foo C = 1
949         --
950         --   {-# RULES "myrule"  foo C = 1 #-}
951         -- 
952         -- After type checking the LHS becomes (foo a (C a))
953         -- and we do not want to zap the unbound tyvar 'a' to (), because
954         -- that limits the applicability of the rule.  Instead, we
955         -- want to quantify over it!  
956         --
957         -- It's easiest to find the free tyvars here. Attempts to do so earlier
958         -- are tiresome, because (a) the data type is big and (b) finding the 
959         -- free type vars of an expression is necessarily monadic operation.
960         --      (consider /\a -> f @ b, where b is side-effected to a)
961     in
962     zonkLExpr env_lhs lhs               `thenM` \ new_lhs ->
963     zonkLExpr env_rhs rhs               `thenM` \ new_rhs ->
964
965     readMutVar unbound_tv_set           `thenM` \ unbound_tvs ->
966     let
967         final_bndrs :: [Located Var]
968         final_bndrs = map noLoc (varSetElems unbound_tvs) ++ new_bndrs
969     in
970     returnM (HsRule name act (map RuleBndr final_bndrs) new_lhs fv_lhs new_rhs fv_rhs)
971                 -- I hate this map RuleBndr stuff
972   where
973    zonk_bndr (RuleBndr v) 
974         | isId (unLoc v) = wrapLocM (zonkIdBndr env)   v
975         | otherwise      = ASSERT( isImmutableTyVar (unLoc v) )
976                            return v
977    zonk_bndr (RuleBndrSig {}) = panic "zonk_bndr RuleBndrSig"
978 \end{code}
979
980
981 %************************************************************************
982 %*                                                                      *
983 \subsection[BackSubst-Foreign]{Foreign exports}
984 %*                                                                      *
985 %************************************************************************
986
987 \begin{code}
988 zonkTcTypeToType :: ZonkEnv -> TcType -> TcM Type
989 zonkTcTypeToType (ZonkEnv zonk_ty _) ty = zonk_ty ty
990
991 zonkTcTypeToTypes :: ZonkEnv -> [TcType] -> TcM [Type]
992 zonkTcTypeToTypes env tys = mapM (zonkTcTypeToType env) tys
993
994 zonkTypeCollecting :: TcRef TyVarSet -> TcType -> TcM Type
995 -- This variant collects unbound type variables in a mutable variable
996 zonkTypeCollecting unbound_tv_set
997   = zonkType zonk_unbound_tyvar
998   where
999     zonk_unbound_tyvar tv 
1000         = zonkQuantifiedTyVar tv                                `thenM` \ tv' ->
1001           readMutVar unbound_tv_set                             `thenM` \ tv_set ->
1002           writeMutVar unbound_tv_set (extendVarSet tv_set tv')  `thenM_`
1003           return (mkTyVarTy tv')
1004
1005 zonkTypeZapping :: TcType -> TcM Type
1006 -- This variant is used for everything except the LHS of rules
1007 -- It zaps unbound type variables to (), or some other arbitrary type
1008 zonkTypeZapping ty 
1009   = zonkType zonk_unbound_tyvar ty 
1010   where
1011         -- Zonk a mutable but unbound type variable to an arbitrary type
1012         -- We know it's unbound even though we don't carry an environment,
1013         -- because at the binding site for a type variable we bind the
1014         -- mutable tyvar to a fresh immutable one.  So the mutable store
1015         -- plays the role of an environment.  If we come across a mutable
1016         -- type variable that isn't so bound, it must be completely free.
1017     zonk_unbound_tyvar tv = do { ty <- mkArbitraryType warn tv
1018                                ; writeMetaTyVar tv ty
1019                                ; return ty }
1020         where
1021             warn span msg = setSrcSpan span (addWarnTc msg)
1022
1023
1024 {-      Note [Strangely-kinded void TyCons]
1025         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1026         See Trac #959 for more examples
1027
1028 When the type checker finds a type variable with no binding, which
1029 means it can be instantiated with an arbitrary type, it usually
1030 instantiates it to Void.  Eg.
1031
1032         length []
1033 ===>
1034         length Void (Nil Void)
1035
1036 But in really obscure programs, the type variable might have a kind
1037 other than *, so we need to invent a suitably-kinded type.
1038
1039 This commit uses
1040         Void for kind *
1041         List for kind *->*
1042         Tuple for kind *->...*->*
1043
1044 which deals with most cases.  (Previously, it only dealt with
1045 kind *.)   
1046
1047 In the other cases, it just makes up a TyCon with a suitable kind.  If
1048 this gets into an interface file, anyone reading that file won't
1049 understand it.  This is fixable (by making the client of the interface
1050 file make up a TyCon too) but it is tiresome and never happens, so I
1051 am leaving it.
1052
1053 Meanwhile I have now fixed GHC to emit a civilized warning.
1054  -}
1055
1056 mkArbitraryType :: (SrcSpan -> SDoc -> TcRnIf g l a)    -- How to complain
1057                 -> TcTyVar
1058                 -> TcRnIf g l Type              -- Used by desugarer too
1059 -- Make up an arbitrary type whose kind is the same as the tyvar.
1060 -- We'll use this to instantiate the (unbound) tyvar.
1061 --
1062 -- Also used by the desugarer; hence the (tiresome) parameter
1063 -- to use when generating a warning
1064 mkArbitraryType warn tv 
1065   | liftedTypeKind `isSubKind` kind             -- The vastly common case
1066   = return anyPrimTy
1067   | eqKind kind (tyConKind anyPrimTyCon1)       -- @*->*@
1068   = return (mkTyConApp anyPrimTyCon1 [])        --     No tuples this size
1069   | all isLiftedTypeKind args                   -- @*-> ... ->*->*@
1070   , isLiftedTypeKind res                        --    Horrible hack to make less use 
1071   = return (mkTyConApp tup_tc [])               --    of mkAnyPrimTyCon
1072   | otherwise
1073   = do  { warn (getSrcSpan tv) msg
1074         ; return (mkTyConApp (mkAnyPrimTyCon (getUnique tv) kind) []) }
1075                 -- Same name as the tyvar, apart from making it start with a colon (sigh)
1076                 -- I dread to think what will happen if this gets out into an 
1077                 -- interface file.  Catastrophe likely.  Major sigh.
1078   where
1079     kind       = tyVarKind tv
1080     (args,res) = splitKindFunTys kind
1081     tup_tc     = tupleTyCon Boxed (length args)
1082                 
1083     msg = vcat [ hang (ptext (sLit "Inventing strangely-kinded Any TyCon"))
1084                     2 (ptext (sLit "of kind") <+> quotes (ppr kind))
1085                , nest 2 (ptext (sLit "from an instantiation of type variable") <+> quotes (ppr tv))
1086                , ptext (sLit "This warning can be suppressed by a type signature fixing") <+> quotes (ppr tv)
1087                , nest 2 (ptext (sLit "but is harmless without -O (and usually harmless anyway)."))
1088                , ptext (sLit "See http://hackage.haskell.org/trac/ghc/ticket/959 for details")  ]
1089 \end{code}