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