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