122b74374230e063aa36d39cb0452903a1115e92
[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] -> [LVectDecl TcId] -> [LTcSpecPrag] -> [LForeignDecl TcId]
273              -> TcM ([Id], 
274                      Bag EvBind,
275                      Bag (LHsBind  Id),
276                      [LForeignDecl Id],
277                      [LTcSpecPrag],
278                      [LRuleDecl    Id],
279                      [LVectDecl    Id])
280 zonkTopDecls ev_binds binds sig_ns rules vects imp_specs fords
281   = do  { (env1, ev_binds') <- zonkEvBinds emptyZonkEnv ev_binds
282
283          -- Warn about missing signatures
284          -- Do this only when we we have a type to offer
285         ; warn_missing_sigs <- doptM Opt_WarnMissingSigs
286         ; let sig_warn | warn_missing_sigs = topSigWarn sig_ns
287                        | otherwise         = noSigWarn
288
289         ; (env2, binds') <- zonkRecMonoBinds env1 sig_warn binds
290                         -- Top level is implicitly recursive
291         ; rules' <- zonkRules env2 rules
292         ; vects' <- zonkVects env2 vects
293         ; specs' <- zonkLTcSpecPrags env2 imp_specs
294         ; fords' <- zonkForeignExports env2 fords
295         ; return (zonkEnvIds env2, ev_binds', binds', fords', specs', rules', vects') }
296
297 ---------------------------------------------
298 zonkLocalBinds :: ZonkEnv -> HsLocalBinds TcId -> TcM (ZonkEnv, HsLocalBinds Id)
299 zonkLocalBinds env EmptyLocalBinds
300   = return (env, EmptyLocalBinds)
301
302 zonkLocalBinds _ (HsValBinds (ValBindsIn {}))
303   = panic "zonkLocalBinds" -- Not in typechecker output
304
305 zonkLocalBinds env (HsValBinds vb@(ValBindsOut binds sigs))
306   = do  { warn_missing_sigs <- doptM Opt_WarnMissingLocalSigs
307         ; let sig_warn | not warn_missing_sigs = noSigWarn
308                        | otherwise             = localSigWarn sig_ns
309               sig_ns = getTypeSigNames vb
310         ; (env1, new_binds) <- go env sig_warn binds
311         ; return (env1, HsValBinds (ValBindsOut new_binds sigs)) }
312   where
313     go env _ []
314       = return (env, [])
315     go env sig_warn ((r,b):bs) 
316       = do { (env1, b')  <- zonkRecMonoBinds env sig_warn b
317            ; (env2, bs') <- go env1 sig_warn bs
318            ; return (env2, (r,b'):bs') }
319
320 zonkLocalBinds env (HsIPBinds (IPBinds binds dict_binds))
321   = mappM (wrapLocM zonk_ip_bind) binds `thenM` \ new_binds ->
322     let
323         env1 = extendZonkEnv env [ipNameName n | L _ (IPBind n _) <- new_binds]
324     in
325     zonkTcEvBinds env1 dict_binds       `thenM` \ (env2, new_dict_binds) -> 
326     returnM (env2, HsIPBinds (IPBinds new_binds new_dict_binds))
327   where
328     zonk_ip_bind (IPBind n e)
329         = mapIPNameTc (zonkIdBndr env) n        `thenM` \ n' ->
330           zonkLExpr env e                       `thenM` \ e' ->
331           returnM (IPBind n' e')
332
333 ---------------------------------------------
334 zonkRecMonoBinds :: ZonkEnv -> SigWarn -> LHsBinds TcId -> TcM (ZonkEnv, LHsBinds Id)
335 zonkRecMonoBinds env sig_warn binds 
336  = fixM (\ ~(_, new_binds) -> do 
337         { let env1 = extendZonkEnv env (collectHsBindsBinders new_binds)
338         ; binds' <- zonkMonoBinds env1 sig_warn binds
339         ; return (env1, binds') })
340
341 ---------------------------------------------
342 type SigWarn = Bool -> [Id] -> TcM ()   
343      -- Missing-signature warning
344      -- The Bool is True for an AbsBinds, False otherwise
345
346 noSigWarn :: SigWarn
347 noSigWarn _ _ = return ()
348
349 topSigWarn :: NameSet -> SigWarn
350 topSigWarn sig_ns _ ids = mapM_ (topSigWarnId sig_ns) ids
351
352 topSigWarnId :: NameSet -> Id -> TcM ()
353 -- The NameSet is the Ids that *lack* a signature
354 -- We have to do it this way round because there are
355 -- lots of top-level bindings that are generated by GHC
356 -- and that don't have signatures
357 topSigWarnId sig_ns id
358   | idName id `elemNameSet` sig_ns = warnMissingSig msg id
359   | otherwise                      = return ()
360   where
361     msg = ptext (sLit "Top-level binding with no type signature:")
362
363 localSigWarn :: NameSet -> SigWarn
364 localSigWarn sig_ns is_abs_bind ids
365   | not is_abs_bind = return ()
366   | otherwise       = mapM_ (localSigWarnId sig_ns) ids
367
368 localSigWarnId :: NameSet -> Id -> TcM ()
369 -- NameSet are the Ids that *have* type signatures
370 localSigWarnId sig_ns id
371   | not (isSigmaTy (idType id))    = return ()
372   | idName id `elemNameSet` sig_ns = return ()
373   | otherwise                      = warnMissingSig msg id
374   where
375     msg = ptext (sLit "Polymophic local binding with no type signature:")
376
377 warnMissingSig :: SDoc -> Id -> TcM ()
378 warnMissingSig msg id
379   = do  { env0 <- tcInitTidyEnv
380         ; let (env1, tidy_ty) = tidyOpenType env0 (idType id)
381         ; addWarnTcM (env1, mk_msg tidy_ty) }
382   where
383     mk_msg ty = sep [ msg, nest 2 $ pprHsVar (idName id) <+> dcolon <+> ppr ty ]
384
385 ---------------------------------------------
386 zonkMonoBinds :: ZonkEnv -> SigWarn -> LHsBinds TcId -> TcM (LHsBinds Id)
387 zonkMonoBinds env sig_warn binds = mapBagM (wrapLocM (zonk_bind env sig_warn)) binds
388
389 zonk_bind :: ZonkEnv -> SigWarn -> HsBind TcId -> TcM (HsBind Id)
390 zonk_bind env sig_warn bind@(PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty})
391   = do  { (_env, new_pat) <- zonkPat env pat            -- Env already extended
392         ; sig_warn False (collectPatBinders new_pat)
393         ; new_grhss <- zonkGRHSs env grhss
394         ; new_ty    <- zonkTcTypeToType env ty
395         ; return (bind { pat_lhs = new_pat, pat_rhs = new_grhss, pat_rhs_ty = new_ty }) }
396
397 zonk_bind env sig_warn (VarBind { var_id = var, var_rhs = expr, var_inline = inl })
398   = do { new_var  <- zonkIdBndr env var
399        ; sig_warn False [new_var]
400        ; new_expr <- zonkLExpr env expr
401        ; return (VarBind { var_id = new_var, var_rhs = new_expr, var_inline = inl }) }
402
403 zonk_bind env sig_warn bind@(FunBind { fun_id = L loc var, fun_matches = ms
404                                      , fun_co_fn = co_fn })
405   = do { new_var <- zonkIdBndr env var
406        ; sig_warn False [new_var]
407        ; (env1, new_co_fn) <- zonkCoFn env co_fn
408        ; new_ms <- zonkMatchGroup env1 ms
409        ; return (bind { fun_id = L loc new_var, fun_matches = new_ms
410                       , fun_co_fn = new_co_fn }) }
411
412 zonk_bind env sig_warn (AbsBinds { abs_tvs = tyvars, abs_ev_vars = evs
413                                  , abs_ev_binds = ev_binds
414                                  , abs_exports = exports
415                                  , abs_binds = val_binds })
416   = ASSERT( all isImmutableTyVar tyvars )
417     do { (env1, new_evs) <- zonkEvBndrsX env evs
418        ; (env2, new_ev_binds) <- zonkTcEvBinds env1 ev_binds
419        ; (new_val_bind, new_exports) <- fixM $ \ ~(new_val_binds, _) ->
420          do { let env3 = extendZonkEnv env2 (collectHsBindsBinders new_val_binds)
421             ; new_val_binds <- zonkMonoBinds env3 noSigWarn val_binds
422             ; new_exports   <- mapM (zonkExport env3) exports
423             ; return (new_val_binds, new_exports) } 
424        ; sig_warn True [b | (_,b,_,_) <- new_exports]
425        ; return (AbsBinds { abs_tvs = tyvars, abs_ev_vars = new_evs, abs_ev_binds = new_ev_binds
426                           , abs_exports = new_exports, abs_binds = new_val_bind }) }
427   where
428     zonkExport env (tyvars, global, local, prags)
429         -- The tyvars are already zonked
430         = zonkIdBndr env global                 `thenM` \ new_global ->
431           zonkSpecPrags env prags               `thenM` \ new_prags -> 
432           returnM (tyvars, new_global, zonkIdOcc env local, new_prags)
433
434 zonkSpecPrags :: ZonkEnv -> TcSpecPrags -> TcM TcSpecPrags
435 zonkSpecPrags _   IsDefaultMethod = return IsDefaultMethod
436 zonkSpecPrags env (SpecPrags ps)  = do { ps' <- zonkLTcSpecPrags env ps
437                                        ; return (SpecPrags ps') }
438
439 zonkLTcSpecPrags :: ZonkEnv -> [LTcSpecPrag] -> TcM [LTcSpecPrag]
440 zonkLTcSpecPrags env ps
441   = mapM zonk_prag ps
442   where
443     zonk_prag (L loc (SpecPrag id co_fn inl))
444         = do { (_, co_fn') <- zonkCoFn env co_fn
445              ; return (L loc (SpecPrag (zonkIdOcc env id) co_fn' inl)) }
446 \end{code}
447
448 %************************************************************************
449 %*                                                                      *
450 \subsection[BackSubst-Match-GRHSs]{Match and GRHSs}
451 %*                                                                      *
452 %************************************************************************
453
454 \begin{code}
455 zonkMatchGroup :: ZonkEnv -> MatchGroup TcId-> TcM (MatchGroup Id)
456 zonkMatchGroup env (MatchGroup ms ty) 
457   = do  { ms' <- mapM (zonkMatch env) ms
458         ; ty' <- zonkTcTypeToType env ty
459         ; return (MatchGroup ms' ty') }
460
461 zonkMatch :: ZonkEnv -> LMatch TcId-> TcM (LMatch Id)
462 zonkMatch env (L loc (Match pats _ grhss))
463   = do  { (env1, new_pats) <- zonkPats env pats
464         ; new_grhss <- zonkGRHSs env1 grhss
465         ; return (L loc (Match new_pats Nothing new_grhss)) }
466
467 -------------------------------------------------------------------------
468 zonkGRHSs :: ZonkEnv -> GRHSs TcId -> TcM (GRHSs Id)
469
470 zonkGRHSs env (GRHSs grhss binds)
471   = zonkLocalBinds env binds    `thenM` \ (new_env, new_binds) ->
472     let
473         zonk_grhs (GRHS guarded rhs)
474           = zonkStmts new_env guarded   `thenM` \ (env2, new_guarded) ->
475             zonkLExpr env2 rhs          `thenM` \ new_rhs ->
476             returnM (GRHS new_guarded new_rhs)
477     in
478     mappM (wrapLocM zonk_grhs) grhss    `thenM` \ new_grhss ->
479     returnM (GRHSs new_grhss new_binds)
480 \end{code}
481
482 %************************************************************************
483 %*                                                                      *
484 \subsection[BackSubst-HsExpr]{Running a zonkitution over a TypeCheckedExpr}
485 %*                                                                      *
486 %************************************************************************
487
488 \begin{code}
489 zonkLExprs :: ZonkEnv -> [LHsExpr TcId] -> TcM [LHsExpr Id]
490 zonkLExpr  :: ZonkEnv -> LHsExpr TcId   -> TcM (LHsExpr Id)
491 zonkExpr   :: ZonkEnv -> HsExpr TcId    -> TcM (HsExpr Id)
492
493 zonkLExprs env exprs = mappM (zonkLExpr env) exprs
494 zonkLExpr  env expr  = wrapLocM (zonkExpr env) expr
495
496 zonkExpr env (HsVar id)
497   = returnM (HsVar (zonkIdOcc env id))
498
499 zonkExpr env (HsIPVar id)
500   = returnM (HsIPVar (mapIPName (zonkIdOcc env) id))
501
502 zonkExpr env (HsLit (HsRat f ty))
503   = zonkTcTypeToType env ty        `thenM` \ new_ty  ->
504     returnM (HsLit (HsRat f new_ty))
505
506 zonkExpr _ (HsLit lit)
507   = returnM (HsLit lit)
508
509 zonkExpr env (HsOverLit lit)
510   = do  { lit' <- zonkOverLit env lit
511         ; return (HsOverLit lit') }
512
513 zonkExpr env (HsLam matches)
514   = zonkMatchGroup env matches  `thenM` \ new_matches ->
515     returnM (HsLam new_matches)
516
517 zonkExpr env (HsApp e1 e2)
518   = zonkLExpr env e1    `thenM` \ new_e1 ->
519     zonkLExpr env e2    `thenM` \ new_e2 ->
520     returnM (HsApp new_e1 new_e2)
521
522 zonkExpr env (HsBracketOut body bs) 
523   = mappM zonk_b bs     `thenM` \ bs' ->
524     returnM (HsBracketOut body bs')
525   where
526     zonk_b (n,e) = zonkLExpr env e      `thenM` \ e' ->
527                    returnM (n,e')
528
529 zonkExpr _ (HsSpliceE s) = WARN( True, ppr s ) -- Should not happen
530                              returnM (HsSpliceE s)
531
532 zonkExpr env (OpApp e1 op fixity e2)
533   = zonkLExpr env e1    `thenM` \ new_e1 ->
534     zonkLExpr env op    `thenM` \ new_op ->
535     zonkLExpr env e2    `thenM` \ new_e2 ->
536     returnM (OpApp new_e1 new_op fixity new_e2)
537
538 zonkExpr env (NegApp expr op)
539   = zonkLExpr env expr  `thenM` \ new_expr ->
540     zonkExpr env op     `thenM` \ new_op ->
541     returnM (NegApp new_expr new_op)
542
543 zonkExpr env (HsPar e)    
544   = zonkLExpr env e     `thenM` \new_e ->
545     returnM (HsPar new_e)
546
547 zonkExpr env (SectionL expr op)
548   = zonkLExpr env expr  `thenM` \ new_expr ->
549     zonkLExpr env op            `thenM` \ new_op ->
550     returnM (SectionL new_expr new_op)
551
552 zonkExpr env (SectionR op expr)
553   = zonkLExpr env op            `thenM` \ new_op ->
554     zonkLExpr env expr          `thenM` \ new_expr ->
555     returnM (SectionR new_op new_expr)
556
557 zonkExpr env (ExplicitTuple tup_args boxed)
558   = do { new_tup_args <- mapM zonk_tup_arg tup_args
559        ; return (ExplicitTuple new_tup_args boxed) }
560   where
561     zonk_tup_arg (Present e) = do { e' <- zonkLExpr env e; return (Present e') }
562     zonk_tup_arg (Missing t) = do { t' <- zonkTcTypeToType env t; return (Missing t') }
563
564 zonkExpr env (HsCase expr ms)
565   = zonkLExpr env expr          `thenM` \ new_expr ->
566     zonkMatchGroup env ms       `thenM` \ new_ms ->
567     returnM (HsCase new_expr new_ms)
568
569 zonkExpr env (HsIf e0 e1 e2 e3)
570   = do { new_e0 <- fmapMaybeM (zonkExpr env) e0
571        ; new_e1 <- zonkLExpr env e1
572        ; new_e2 <- zonkLExpr env e2
573        ; new_e3 <- zonkLExpr env e3
574        ; returnM (HsIf new_e0 new_e1 new_e2 new_e3) }
575
576 zonkExpr env (HsLet binds expr)
577   = zonkLocalBinds env binds    `thenM` \ (new_env, new_binds) ->
578     zonkLExpr new_env expr      `thenM` \ new_expr ->
579     returnM (HsLet new_binds new_expr)
580
581 zonkExpr env (HsDo do_or_lc stmts body ty)
582   = zonkStmts env stmts         `thenM` \ (new_env, new_stmts) ->
583     zonkLExpr new_env body      `thenM` \ new_body ->
584     zonkTcTypeToType env ty     `thenM` \ new_ty   ->
585     returnM (HsDo do_or_lc new_stmts new_body new_ty)
586
587 zonkExpr env (ExplicitList ty exprs)
588   = zonkTcTypeToType env ty     `thenM` \ new_ty ->
589     zonkLExprs env exprs        `thenM` \ new_exprs ->
590     returnM (ExplicitList new_ty new_exprs)
591
592 zonkExpr env (ExplicitPArr ty exprs)
593   = zonkTcTypeToType env ty     `thenM` \ new_ty ->
594     zonkLExprs env exprs        `thenM` \ new_exprs ->
595     returnM (ExplicitPArr new_ty new_exprs)
596
597 zonkExpr env (RecordCon data_con con_expr rbinds)
598   = do  { new_con_expr <- zonkExpr env con_expr
599         ; new_rbinds   <- zonkRecFields env rbinds
600         ; return (RecordCon data_con new_con_expr new_rbinds) }
601
602 zonkExpr env (RecordUpd expr rbinds cons in_tys out_tys)
603   = do  { new_expr    <- zonkLExpr env expr
604         ; new_in_tys  <- mapM (zonkTcTypeToType env) in_tys
605         ; new_out_tys <- mapM (zonkTcTypeToType env) out_tys
606         ; new_rbinds  <- zonkRecFields env rbinds
607         ; return (RecordUpd new_expr new_rbinds cons new_in_tys new_out_tys) }
608
609 zonkExpr env (ExprWithTySigOut e ty) 
610   = do { e' <- zonkLExpr env e
611        ; return (ExprWithTySigOut e' ty) }
612
613 zonkExpr _ (ExprWithTySig _ _) = panic "zonkExpr env:ExprWithTySig"
614
615 zonkExpr env (ArithSeq expr info)
616   = zonkExpr env expr           `thenM` \ new_expr ->
617     zonkArithSeq env info       `thenM` \ new_info ->
618     returnM (ArithSeq new_expr new_info)
619
620 zonkExpr env (PArrSeq expr info)
621   = zonkExpr env expr           `thenM` \ new_expr ->
622     zonkArithSeq env info       `thenM` \ new_info ->
623     returnM (PArrSeq new_expr new_info)
624
625 zonkExpr env (HsSCC lbl expr)
626   = zonkLExpr env expr  `thenM` \ new_expr ->
627     returnM (HsSCC lbl new_expr)
628
629 zonkExpr env (HsTickPragma info expr)
630   = zonkLExpr env expr  `thenM` \ new_expr ->
631     returnM (HsTickPragma info new_expr)
632
633 -- hdaume: core annotations
634 zonkExpr env (HsCoreAnn lbl expr)
635   = zonkLExpr env expr   `thenM` \ new_expr ->
636     returnM (HsCoreAnn lbl new_expr)
637
638 -- arrow notation extensions
639 zonkExpr env (HsProc pat body)
640   = do  { (env1, new_pat) <- zonkPat env pat
641         ; new_body <- zonkCmdTop env1 body
642         ; return (HsProc new_pat new_body) }
643
644 zonkExpr env (HsArrApp e1 e2 ty ho rl)
645   = zonkLExpr env e1                    `thenM` \ new_e1 ->
646     zonkLExpr env e2                    `thenM` \ new_e2 ->
647     zonkTcTypeToType env ty             `thenM` \ new_ty ->
648     returnM (HsArrApp new_e1 new_e2 new_ty ho rl)
649
650 zonkExpr env (HsArrForm op fixity args)
651   = zonkLExpr env op                    `thenM` \ new_op ->
652     mappM (zonkCmdTop env) args         `thenM` \ new_args ->
653     returnM (HsArrForm new_op fixity new_args)
654
655 zonkExpr env (HsWrap co_fn expr)
656   = zonkCoFn env co_fn  `thenM` \ (env1, new_co_fn) ->
657     zonkExpr env1 expr  `thenM` \ new_expr ->
658     return (HsWrap new_co_fn new_expr)
659
660 zonkExpr _ expr = pprPanic "zonkExpr" (ppr expr)
661
662 zonkCmdTop :: ZonkEnv -> LHsCmdTop TcId -> TcM (LHsCmdTop Id)
663 zonkCmdTop env cmd = wrapLocM (zonk_cmd_top env) cmd
664
665 zonk_cmd_top :: ZonkEnv -> HsCmdTop TcId -> TcM (HsCmdTop Id)
666 zonk_cmd_top env (HsCmdTop cmd stack_tys ty ids)
667   = zonkLExpr env cmd                   `thenM` \ new_cmd ->
668     zonkTcTypeToTypes env stack_tys     `thenM` \ new_stack_tys ->
669     zonkTcTypeToType env ty             `thenM` \ new_ty ->
670     mapSndM (zonkExpr env) ids          `thenM` \ new_ids ->
671     returnM (HsCmdTop new_cmd new_stack_tys new_ty new_ids)
672
673 -------------------------------------------------------------------------
674 zonkCoFn :: ZonkEnv -> HsWrapper -> TcM (ZonkEnv, HsWrapper)
675 zonkCoFn env WpHole   = return (env, WpHole)
676 zonkCoFn env (WpCompose c1 c2) = do { (env1, c1') <- zonkCoFn env c1
677                                     ; (env2, c2') <- zonkCoFn env1 c2
678                                     ; return (env2, WpCompose c1' c2') }
679 zonkCoFn env (WpCast co)    = do { co' <- zonkTcTypeToType env co
680                                  ; return (env, WpCast co') }
681 zonkCoFn env (WpEvLam ev)   = do { (env', ev') <- zonkEvBndrX env ev
682                                  ; return (env', WpEvLam ev') }
683 zonkCoFn env (WpEvApp arg)  = do { arg' <- zonkEvTerm env arg 
684                                  ; return (env, WpEvApp arg') }
685 zonkCoFn env (WpTyLam tv)   = ASSERT( isImmutableTyVar tv )
686                               return (env, WpTyLam tv) 
687 zonkCoFn env (WpTyApp ty)   = do { ty' <- zonkTcTypeToType env ty
688                                  ; return (env, WpTyApp ty') }
689 zonkCoFn env (WpLet bs)     = do { (env1, bs') <- zonkTcEvBinds env bs
690                                  ; return (env1, WpLet bs') }
691
692 -------------------------------------------------------------------------
693 zonkOverLit :: ZonkEnv -> HsOverLit TcId -> TcM (HsOverLit Id)
694 zonkOverLit env lit@(OverLit { ol_witness = e, ol_type = ty })
695   = do  { ty' <- zonkTcTypeToType env ty
696         ; e' <- zonkExpr env e
697         ; return (lit { ol_witness = e', ol_type = ty' }) }
698
699 -------------------------------------------------------------------------
700 zonkArithSeq :: ZonkEnv -> ArithSeqInfo TcId -> TcM (ArithSeqInfo Id)
701
702 zonkArithSeq env (From e)
703   = zonkLExpr env e             `thenM` \ new_e ->
704     returnM (From new_e)
705
706 zonkArithSeq env (FromThen e1 e2)
707   = zonkLExpr env e1    `thenM` \ new_e1 ->
708     zonkLExpr env e2    `thenM` \ new_e2 ->
709     returnM (FromThen new_e1 new_e2)
710
711 zonkArithSeq env (FromTo e1 e2)
712   = zonkLExpr env e1    `thenM` \ new_e1 ->
713     zonkLExpr env e2    `thenM` \ new_e2 ->
714     returnM (FromTo new_e1 new_e2)
715
716 zonkArithSeq env (FromThenTo e1 e2 e3)
717   = zonkLExpr env e1    `thenM` \ new_e1 ->
718     zonkLExpr env e2    `thenM` \ new_e2 ->
719     zonkLExpr env e3    `thenM` \ new_e3 ->
720     returnM (FromThenTo new_e1 new_e2 new_e3)
721
722
723 -------------------------------------------------------------------------
724 zonkStmts :: ZonkEnv -> [LStmt TcId] -> TcM (ZonkEnv, [LStmt Id])
725 zonkStmts env []     = return (env, [])
726 zonkStmts env (s:ss) = do { (env1, s')  <- wrapLocSndM (zonkStmt env) s
727                           ; (env2, ss') <- zonkStmts env1 ss
728                           ; return (env2, s' : ss') }
729
730 zonkStmt :: ZonkEnv -> Stmt TcId -> TcM (ZonkEnv, Stmt Id)
731 zonkStmt env (ParStmt stmts_w_bndrs)
732   = mappM zonk_branch stmts_w_bndrs     `thenM` \ new_stmts_w_bndrs ->
733     let 
734         new_binders = concat (map snd new_stmts_w_bndrs)
735         env1 = extendZonkEnv env new_binders
736     in
737     return (env1, ParStmt new_stmts_w_bndrs)
738   where
739     zonk_branch (stmts, bndrs) = zonkStmts env stmts    `thenM` \ (env1, new_stmts) ->
740                                  returnM (new_stmts, zonkIdOccs env1 bndrs)
741
742 zonkStmt env (RecStmt { recS_stmts = segStmts, recS_later_ids = lvs, recS_rec_ids = rvs
743                       , recS_ret_fn = ret_id, recS_mfix_fn = mfix_id, recS_bind_fn = bind_id
744                       , recS_rec_rets = rets })
745   = do { new_rvs <- zonkIdBndrs env rvs
746        ; new_lvs <- zonkIdBndrs env lvs
747        ; new_ret_id  <- zonkExpr env ret_id
748        ; new_mfix_id <- zonkExpr env mfix_id
749        ; new_bind_id <- zonkExpr env bind_id
750        ; let env1 = extendZonkEnv env new_rvs
751        ; (env2, new_segStmts) <- zonkStmts env1 segStmts
752         -- Zonk the ret-expressions in an envt that 
753         -- has the polymorphic bindings in the envt
754        ; new_rets <- mapM (zonkExpr env2) rets
755        ; return (extendZonkEnv env new_lvs,     -- Only the lvs are needed
756                  RecStmt { recS_stmts = new_segStmts, recS_later_ids = new_lvs
757                          , recS_rec_ids = new_rvs, recS_ret_fn = new_ret_id
758                          , recS_mfix_fn = new_mfix_id, recS_bind_fn = new_bind_id
759                          , recS_rec_rets = new_rets }) }
760
761 zonkStmt env (ExprStmt expr then_op ty)
762   = zonkLExpr env expr          `thenM` \ new_expr ->
763     zonkExpr env then_op        `thenM` \ new_then ->
764     zonkTcTypeToType env ty     `thenM` \ new_ty ->
765     returnM (env, ExprStmt new_expr new_then new_ty)
766
767 zonkStmt env (TransformStmt stmts binders usingExpr maybeByExpr)
768   = do { (env', stmts') <- zonkStmts env stmts 
769     ; let binders' = zonkIdOccs env' binders
770     ; usingExpr' <- zonkLExpr env' usingExpr
771     ; maybeByExpr' <- zonkMaybeLExpr env' maybeByExpr
772     ; return (env', TransformStmt stmts' binders' usingExpr' maybeByExpr') }
773     
774 zonkStmt env (GroupStmt stmts binderMap by using)
775   = do { (env', stmts') <- zonkStmts env stmts 
776     ; binderMap' <- mappM (zonkBinderMapEntry env') binderMap
777     ; by' <- fmapMaybeM (zonkLExpr env') by
778     ; using' <- fmapEitherM (zonkLExpr env) (zonkExpr env) using
779     ; let env'' = extendZonkEnv env' (map snd binderMap')
780     ; return (env'', GroupStmt stmts' binderMap' by' using') }
781   where
782     zonkBinderMapEntry env (oldBinder, newBinder) = do 
783         let oldBinder' = zonkIdOcc env oldBinder
784         newBinder' <- zonkIdBndr env newBinder
785         return (oldBinder', newBinder') 
786
787 zonkStmt env (LetStmt binds)
788   = zonkLocalBinds env binds    `thenM` \ (env1, new_binds) ->
789     returnM (env1, LetStmt new_binds)
790
791 zonkStmt env (BindStmt pat expr bind_op fail_op)
792   = do  { new_expr <- zonkLExpr env expr
793         ; (env1, new_pat) <- zonkPat env pat
794         ; new_bind <- zonkExpr env bind_op
795         ; new_fail <- zonkExpr env fail_op
796         ; return (env1, BindStmt new_pat new_expr new_bind new_fail) }
797
798 zonkMaybeLExpr :: ZonkEnv -> Maybe (LHsExpr TcId) -> TcM (Maybe (LHsExpr Id))
799 zonkMaybeLExpr _   Nothing  = return Nothing
800 zonkMaybeLExpr env (Just e) = (zonkLExpr env e) >>= (return . Just)
801
802
803 -------------------------------------------------------------------------
804 zonkRecFields :: ZonkEnv -> HsRecordBinds TcId -> TcM (HsRecordBinds TcId)
805 zonkRecFields env (HsRecFields flds dd)
806   = do  { flds' <- mappM zonk_rbind flds
807         ; return (HsRecFields flds' dd) }
808   where
809     zonk_rbind fld
810       = do { new_id   <- wrapLocM (zonkIdBndr env) (hsRecFieldId fld)
811            ; new_expr <- zonkLExpr env (hsRecFieldArg fld)
812            ; return (fld { hsRecFieldId = new_id, hsRecFieldArg = new_expr }) }
813
814 -------------------------------------------------------------------------
815 mapIPNameTc :: (a -> TcM b) -> IPName a -> TcM (IPName b)
816 mapIPNameTc f (IPName n) = f n  `thenM` \ r -> returnM (IPName r)
817 \end{code}
818
819
820 %************************************************************************
821 %*                                                                      *
822 \subsection[BackSubst-Pats]{Patterns}
823 %*                                                                      *
824 %************************************************************************
825
826 \begin{code}
827 zonkPat :: ZonkEnv -> OutPat TcId -> TcM (ZonkEnv, OutPat Id)
828 -- Extend the environment as we go, because it's possible for one
829 -- pattern to bind something that is used in another (inside or
830 -- to the right)
831 zonkPat env pat = wrapLocSndM (zonk_pat env) pat
832
833 zonk_pat :: ZonkEnv -> Pat TcId -> TcM (ZonkEnv, Pat Id)
834 zonk_pat env (ParPat p)
835   = do  { (env', p') <- zonkPat env p
836         ; return (env', ParPat p') }
837
838 zonk_pat env (WildPat ty)
839   = do  { ty' <- zonkTcTypeToType env ty
840         ; return (env, WildPat ty') }
841
842 zonk_pat env (VarPat v)
843   = do  { v' <- zonkIdBndr env v
844         ; return (extendZonkEnv1 env v', VarPat v') }
845
846 zonk_pat env (LazyPat pat)
847   = do  { (env', pat') <- zonkPat env pat
848         ; return (env',  LazyPat pat') }
849
850 zonk_pat env (BangPat pat)
851   = do  { (env', pat') <- zonkPat env pat
852         ; return (env',  BangPat pat') }
853
854 zonk_pat env (AsPat (L loc v) pat)
855   = do  { v' <- zonkIdBndr env v
856         ; (env', pat') <- zonkPat (extendZonkEnv1 env v') pat
857         ; return (env', AsPat (L loc v') pat') }
858
859 zonk_pat env (ViewPat expr pat ty)
860   = do  { expr' <- zonkLExpr env expr
861         ; (env', pat') <- zonkPat env pat
862         ; ty' <- zonkTcTypeToType env ty
863         ; return (env', ViewPat expr' pat' ty') }
864
865 zonk_pat env (ListPat pats ty)
866   = do  { ty' <- zonkTcTypeToType env ty
867         ; (env', pats') <- zonkPats env pats
868         ; return (env', ListPat pats' ty') }
869
870 zonk_pat env (PArrPat pats ty)
871   = do  { ty' <- zonkTcTypeToType env ty
872         ; (env', pats') <- zonkPats env pats
873         ; return (env', PArrPat pats' ty') }
874
875 zonk_pat env (TuplePat pats boxed ty)
876   = do  { ty' <- zonkTcTypeToType env ty
877         ; (env', pats') <- zonkPats env pats
878         ; return (env', TuplePat pats' boxed ty') }
879
880 zonk_pat env p@(ConPatOut { pat_ty = ty, pat_dicts = evs, pat_binds = binds, pat_args = args })
881   = ASSERT( all isImmutableTyVar (pat_tvs p) ) 
882     do  { new_ty <- zonkTcTypeToType env ty
883         ; (env1, new_evs) <- zonkEvBndrsX env evs
884         ; (env2, new_binds) <- zonkTcEvBinds env1 binds
885         ; (env', new_args) <- zonkConStuff env2 args
886         ; returnM (env', p { pat_ty = new_ty, pat_dicts = new_evs, 
887                              pat_binds = new_binds, pat_args = new_args }) }
888
889 zonk_pat env (LitPat lit) = return (env, LitPat lit)
890
891 zonk_pat env (SigPatOut pat ty)
892   = do  { ty' <- zonkTcTypeToType env ty
893         ; (env', pat') <- zonkPat env pat
894         ; return (env', SigPatOut pat' ty') }
895
896 zonk_pat env (NPat lit mb_neg eq_expr)
897   = do  { lit' <- zonkOverLit env lit
898         ; mb_neg' <- fmapMaybeM (zonkExpr env) mb_neg
899         ; eq_expr' <- zonkExpr env eq_expr
900         ; return (env, NPat lit' mb_neg' eq_expr') }
901
902 zonk_pat env (NPlusKPat (L loc n) lit e1 e2)
903   = do  { n' <- zonkIdBndr env n
904         ; lit' <- zonkOverLit env lit
905         ; e1' <- zonkExpr env e1
906         ; e2' <- zonkExpr env e2
907         ; return (extendZonkEnv1 env n', NPlusKPat (L loc n') lit' e1' e2') }
908
909 zonk_pat env (CoPat co_fn pat ty) 
910   = do { (env', co_fn') <- zonkCoFn env co_fn
911        ; (env'', pat') <- zonkPat env' (noLoc pat)
912        ; ty' <- zonkTcTypeToType env'' ty
913        ; return (env'', CoPat co_fn' (unLoc pat') ty') }
914
915 zonk_pat _ pat = pprPanic "zonk_pat" (ppr pat)
916
917 ---------------------------
918 zonkConStuff :: ZonkEnv
919              -> HsConDetails (OutPat TcId) (HsRecFields id (OutPat TcId))
920              -> TcM (ZonkEnv,
921                      HsConDetails (OutPat Id) (HsRecFields id (OutPat Id)))
922 zonkConStuff env (PrefixCon pats)
923   = do  { (env', pats') <- zonkPats env pats
924         ; return (env', PrefixCon pats') }
925
926 zonkConStuff env (InfixCon p1 p2)
927   = do  { (env1, p1') <- zonkPat env  p1
928         ; (env', p2') <- zonkPat env1 p2
929         ; return (env', InfixCon p1' p2') }
930
931 zonkConStuff env (RecCon (HsRecFields rpats dd))
932   = do  { (env', pats') <- zonkPats env (map hsRecFieldArg rpats)
933         ; let rpats' = zipWith (\rp p' -> rp { hsRecFieldArg = p' }) rpats pats'
934         ; returnM (env', RecCon (HsRecFields rpats' dd)) }
935         -- Field selectors have declared types; hence no zonking
936
937 ---------------------------
938 zonkPats :: ZonkEnv -> [OutPat TcId] -> TcM (ZonkEnv, [OutPat Id])
939 zonkPats env []         = return (env, [])
940 zonkPats env (pat:pats) = do { (env1, pat') <- zonkPat env pat
941                      ; (env', pats') <- zonkPats env1 pats
942                      ; return (env', pat':pats') }
943 \end{code}
944
945 %************************************************************************
946 %*                                                                      *
947 \subsection[BackSubst-Foreign]{Foreign exports}
948 %*                                                                      *
949 %************************************************************************
950
951
952 \begin{code}
953 zonkForeignExports :: ZonkEnv -> [LForeignDecl TcId] -> TcM [LForeignDecl Id]
954 zonkForeignExports env ls = mappM (wrapLocM (zonkForeignExport env)) ls
955
956 zonkForeignExport :: ZonkEnv -> ForeignDecl TcId -> TcM (ForeignDecl Id)
957 zonkForeignExport env (ForeignExport i _hs_ty spec) =
958    returnM (ForeignExport (fmap (zonkIdOcc env) i) undefined spec)
959 zonkForeignExport _ for_imp 
960   = returnM for_imp     -- Foreign imports don't need zonking
961 \end{code}
962
963 \begin{code}
964 zonkRules :: ZonkEnv -> [LRuleDecl TcId] -> TcM [LRuleDecl Id]
965 zonkRules env rs = mappM (wrapLocM (zonkRule env)) rs
966
967 zonkRule :: ZonkEnv -> RuleDecl TcId -> TcM (RuleDecl Id)
968 zonkRule env (HsRule name act (vars{-::[RuleBndr TcId]-}) lhs fv_lhs rhs fv_rhs)
969   = do { (env_rhs, new_bndrs) <- mapAccumLM zonk_bndr env vars
970
971        ; unbound_tv_set <- newMutVar emptyVarSet
972        ; let env_lhs = setZonkType env_rhs (zonkTypeCollecting unbound_tv_set)
973         -- We need to gather the type variables mentioned on the LHS so we can 
974         -- quantify over them.  Example:
975         --   data T a = C
976         -- 
977         --   foo :: T a -> Int
978         --   foo C = 1
979         --
980         --   {-# RULES "myrule"  foo C = 1 #-}
981         -- 
982         -- After type checking the LHS becomes (foo a (C a))
983         -- and we do not want to zap the unbound tyvar 'a' to (), because
984         -- that limits the applicability of the rule.  Instead, we
985         -- want to quantify over it!  
986         --
987         -- It's easiest to find the free tyvars here. Attempts to do so earlier
988         -- are tiresome, because (a) the data type is big and (b) finding the 
989         -- free type vars of an expression is necessarily monadic operation.
990         --      (consider /\a -> f @ b, where b is side-effected to a)
991
992        ; new_lhs <- zonkLExpr env_lhs lhs
993        ; new_rhs <- zonkLExpr env_rhs rhs
994
995        ; unbound_tvs <- readMutVar unbound_tv_set
996        ; let final_bndrs :: [RuleBndr Var]
997              final_bndrs = map (RuleBndr . noLoc) (varSetElems unbound_tvs) ++ new_bndrs
998
999        ; return (HsRule name act final_bndrs new_lhs fv_lhs new_rhs fv_rhs) }
1000   where
1001    zonk_bndr env (RuleBndr (L loc v)) 
1002       = do { (env', v') <- zonk_it env v; return (env', RuleBndr (L loc v')) }
1003    zonk_bndr _ (RuleBndrSig {}) = panic "zonk_bndr RuleBndrSig"
1004
1005    zonk_it env v
1006      | isId v     = do { v' <- zonkIdBndr env v; return (extendZonkEnv1 env v', v') }
1007      | isCoVar v  = do { v' <- zonkEvBndr env v; return (extendZonkEnv1 env v', v') }
1008      | otherwise  = ASSERT( isImmutableTyVar v) return (env, v)
1009 \end{code}
1010
1011 \begin{code}
1012 zonkVects :: ZonkEnv -> [LVectDecl TcId] -> TcM [LVectDecl Id]
1013 zonkVects env = mappM (wrapLocM (zonkVect env))
1014
1015 zonkVect :: ZonkEnv -> VectDecl TcId -> TcM (VectDecl Id)
1016 zonkVect env (HsVect v Nothing)
1017   = do { v' <- wrapLocM (zonkIdBndr env) v
1018        ; return $ HsVect v' Nothing
1019        }
1020 zonkVect env (HsVect v (Just e))
1021   = do { v' <- wrapLocM (zonkIdBndr env) v
1022        ; e' <- zonkLExpr env e
1023        ; return $ HsVect v' (Just e')
1024        }
1025 \end{code}
1026
1027 %************************************************************************
1028 %*                                                                      *
1029               Constraints and evidence
1030 %*                                                                      *
1031 %************************************************************************
1032
1033 \begin{code}
1034 zonkEvTerm :: ZonkEnv -> EvTerm -> TcM EvTerm
1035 zonkEvTerm env (EvId v)           = ASSERT2( isId v, ppr v ) 
1036                                     return (EvId (zonkIdOcc env v))
1037 zonkEvTerm env (EvCoercion co)    = do { co' <- zonkTcTypeToType env co
1038                                        ; return (EvCoercion co') }
1039 zonkEvTerm env (EvCast v co)      = ASSERT( isId v) 
1040                                     do { co' <- zonkTcTypeToType env co
1041                                        ; return (EvCast (zonkIdOcc env v) co') }
1042 zonkEvTerm env (EvSuperClass d n) = return (EvSuperClass (zonkIdOcc env d) n)
1043 zonkEvTerm env (EvDFunApp df tys tms)
1044   = do { tys' <- zonkTcTypeToTypes env tys
1045        ; let tms' = map (zonkEvVarOcc env) tms
1046        ; return (EvDFunApp (zonkIdOcc env df) tys' tms') }
1047
1048 zonkTcEvBinds :: ZonkEnv -> TcEvBinds -> TcM (ZonkEnv, TcEvBinds)
1049 zonkTcEvBinds env (TcEvBinds var) = do { (env', bs') <- zonkEvBindsVar env var
1050                                        ; return (env', EvBinds bs') }
1051 zonkTcEvBinds env (EvBinds bs)    = do { (env', bs') <- zonkEvBinds env bs
1052                                        ; return (env', EvBinds bs') }
1053
1054 zonkEvBindsVar :: ZonkEnv -> EvBindsVar -> TcM (ZonkEnv, Bag EvBind)
1055 zonkEvBindsVar env (EvBindsVar ref _) = do { bs <- readMutVar ref
1056                                            ; zonkEvBinds env (evBindMapBinds bs) }
1057
1058 zonkEvBinds :: ZonkEnv -> Bag EvBind -> TcM (ZonkEnv, Bag EvBind)
1059 zonkEvBinds env binds
1060   = fixM (\ ~( _, new_binds) -> do
1061          { let env1 = extendZonkEnv env (collect_ev_bndrs new_binds)
1062          ; binds' <- mapBagM (zonkEvBind env1) binds
1063          ; return (env1, binds') })
1064   where
1065     collect_ev_bndrs :: Bag EvBind -> [EvVar]
1066     collect_ev_bndrs = foldrBag add [] 
1067     add (EvBind var _) vars = var : vars
1068
1069 zonkEvBind :: ZonkEnv -> EvBind -> TcM EvBind
1070 zonkEvBind env (EvBind var term)
1071   = do { var' <- zonkEvBndr env var
1072        ; term' <- zonkEvTerm env term
1073        ; return (EvBind var' term') }
1074 \end{code}
1075
1076 %************************************************************************
1077 %*                                                                      *
1078                          Zonking types
1079 %*                                                                      *
1080 %************************************************************************
1081
1082 \begin{code}
1083 zonkTcTypeToType :: ZonkEnv -> TcType -> TcM Type
1084 zonkTcTypeToType (ZonkEnv zonk_ty _) ty = zonk_ty ty
1085
1086 zonkTcTypeToTypes :: ZonkEnv -> [TcType] -> TcM [Type]
1087 zonkTcTypeToTypes env tys = mapM (zonkTcTypeToType env) tys
1088
1089 zonkTypeCollecting :: TcRef TyVarSet -> TcType -> TcM Type
1090 -- This variant collects unbound type variables in a mutable variable
1091 zonkTypeCollecting unbound_tv_set
1092   = zonkType (mkZonkTcTyVar zonk_unbound_tyvar)
1093   where
1094     zonk_unbound_tyvar tv 
1095         = do { tv' <- zonkQuantifiedTyVar tv
1096              ; tv_set <- readMutVar unbound_tv_set
1097              ; writeMutVar unbound_tv_set (extendVarSet tv_set tv')
1098              ; return (mkTyVarTy tv') }
1099
1100 zonkTypeZapping :: TcType -> TcM Type
1101 -- This variant is used for everything except the LHS of rules
1102 -- It zaps unbound type variables to (), or some other arbitrary type
1103 zonkTypeZapping ty 
1104   = zonkType (mkZonkTcTyVar zonk_unbound_tyvar) ty 
1105   where
1106         -- Zonk a mutable but unbound type variable to an arbitrary type
1107         -- We know it's unbound even though we don't carry an environment,
1108         -- because at the binding site for a type variable we bind the
1109         -- mutable tyvar to a fresh immutable one.  So the mutable store
1110         -- plays the role of an environment.  If we come across a mutable
1111         -- type variable that isn't so bound, it must be completely free.
1112     zonk_unbound_tyvar tv = do { let ty = anyTypeOfKind (tyVarKind tv)
1113                                ; writeMetaTyVar tv ty
1114                                ; return ty }
1115 \end{code}