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