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