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