0d3470e663edea8aab727e2f18c4fd0095f04be7
[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 {-# OPTIONS_GHC -w #-}
13 -- The above warning supression flag is a temporary kludge.
14 -- While working on this module you are encouraged to remove it and fix
15 -- any warnings in the module. See
16 --     http://hackage.haskell.org/trac/ghc/wiki/WorkingConventions#Warnings
17 -- for details
18
19 module TcHsSyn (
20         mkHsConApp, mkHsDictLet, mkHsApp,
21         hsLitType, hsLPatType, hsPatType, 
22         mkHsAppTy, mkSimpleHsAlt,
23         nlHsIntLit, mkVanillaTuplePat,
24         
25         mkArbitraryType,        -- Put this elsewhere?
26
27         -- re-exported from TcMonad
28         TcId, TcIdSet, TcDictBinds,
29
30         zonkTopDecls, zonkTopExpr, zonkTopLExpr,
31         zonkId, zonkTopBndrs
32   ) where
33
34 #include "HsVersions.h"
35
36 -- friends:
37 import HsSyn    -- oodles of it
38
39 -- others:
40 import Id
41
42 import TcRnMonad
43 import Type
44 import TcType
45 import TcMType
46 import TysPrim
47 import TysWiredIn
48 import TyCon
49 import Name
50 import Var
51 import VarSet
52 import VarEnv
53 import BasicTypes
54 import Maybes
55 import Unique
56 import SrcLoc
57 import Util
58 import Bag
59 import Outputable
60 \end{code}
61
62
63 %************************************************************************
64 %*                                                                      *
65 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
66 %*                                                                      *
67 %************************************************************************
68
69 Note: If @hsLPatType@ doesn't bear a strong resemblance to @exprType@,
70 then something is wrong.
71 \begin{code}
72 mkVanillaTuplePat :: [OutPat Id] -> Boxity -> Pat Id
73 -- A vanilla tuple pattern simply gets its type from its sub-patterns
74 mkVanillaTuplePat pats box 
75   = TuplePat pats box (mkTupleTy box (length pats) (map hsLPatType pats))
76
77 hsLPatType :: OutPat Id -> Type
78 hsLPatType (L _ pat) = hsPatType pat
79
80 hsPatType (ParPat pat)              = hsLPatType pat
81 hsPatType (WildPat ty)              = ty
82 hsPatType (VarPat var)              = idType var
83 hsPatType (VarPatOut var _)         = idType var
84 hsPatType (BangPat pat)             = hsLPatType pat
85 hsPatType (LazyPat pat)             = hsLPatType pat
86 hsPatType (LitPat lit)              = hsLitType lit
87 hsPatType (AsPat var pat)           = idType (unLoc var)
88 hsPatType (ListPat _ ty)            = mkListTy ty
89 hsPatType (PArrPat _ ty)            = mkPArrTy ty
90 hsPatType (TuplePat pats box ty)    = ty
91 hsPatType (ConPatOut{ pat_ty = ty })= ty
92 hsPatType (SigPatOut pat ty)        = ty
93 hsPatType (NPat lit _ _ ty)         = ty
94 hsPatType (NPlusKPat id _ _ _)      = idType (unLoc id)
95 hsPatType (CoPat _ _ ty)            = ty
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@(L _ (InlinePrag {}))  = return prag
308     zonk_prag (L loc (SpecPrag expr ty ds inl))
309         = do { expr' <- zonkExpr env expr 
310              ; ty'   <- zonkTcTypeToType env ty
311              ; let ds' = zonkIdOccs env ds
312              ; return (L loc (SpecPrag expr' ty' ds' inl)) }
313 \end{code}
314
315 %************************************************************************
316 %*                                                                      *
317 \subsection[BackSubst-Match-GRHSs]{Match and GRHSs}
318 %*                                                                      *
319 %************************************************************************
320
321 \begin{code}
322 zonkMatchGroup :: ZonkEnv -> MatchGroup TcId-> TcM (MatchGroup Id)
323 zonkMatchGroup env (MatchGroup ms ty) 
324   = do  { ms' <- mapM (zonkMatch env) ms
325         ; ty' <- zonkTcTypeToType env ty
326         ; return (MatchGroup ms' ty') }
327
328 zonkMatch :: ZonkEnv -> LMatch TcId-> TcM (LMatch Id)
329 zonkMatch env (L loc (Match pats _ grhss))
330   = do  { (env1, new_pats) <- zonkPats env pats
331         ; new_grhss <- zonkGRHSs env1 grhss
332         ; return (L loc (Match new_pats Nothing new_grhss)) }
333
334 -------------------------------------------------------------------------
335 zonkGRHSs :: ZonkEnv -> GRHSs TcId -> TcM (GRHSs Id)
336
337 zonkGRHSs env (GRHSs grhss binds)
338   = zonkLocalBinds env binds    `thenM` \ (new_env, new_binds) ->
339     let
340         zonk_grhs (GRHS guarded rhs)
341           = zonkStmts new_env guarded   `thenM` \ (env2, new_guarded) ->
342             zonkLExpr env2 rhs          `thenM` \ new_rhs ->
343             returnM (GRHS new_guarded new_rhs)
344     in
345     mappM (wrapLocM zonk_grhs) grhss    `thenM` \ new_grhss ->
346     returnM (GRHSs new_grhss new_binds)
347 \end{code}
348
349 %************************************************************************
350 %*                                                                      *
351 \subsection[BackSubst-HsExpr]{Running a zonkitution over a TypeCheckedExpr}
352 %*                                                                      *
353 %************************************************************************
354
355 \begin{code}
356 zonkLExprs :: ZonkEnv -> [LHsExpr TcId] -> TcM [LHsExpr Id]
357 zonkLExpr  :: ZonkEnv -> LHsExpr TcId   -> TcM (LHsExpr Id)
358 zonkExpr   :: ZonkEnv -> HsExpr TcId    -> TcM (HsExpr Id)
359
360 zonkLExprs env exprs = mappM (zonkLExpr env) exprs
361 zonkLExpr  env expr  = wrapLocM (zonkExpr env) expr
362
363 zonkExpr env (HsVar id)
364   = returnM (HsVar (zonkIdOcc env id))
365
366 zonkExpr env (HsIPVar id)
367   = returnM (HsIPVar (mapIPName (zonkIdOcc env) id))
368
369 zonkExpr env (HsLit (HsRat f ty))
370   = zonkTcTypeToType env ty        `thenM` \ new_ty  ->
371     returnM (HsLit (HsRat f new_ty))
372
373 zonkExpr env (HsLit lit)
374   = returnM (HsLit lit)
375
376 zonkExpr env (HsOverLit lit)
377   = do  { lit' <- zonkOverLit env lit
378         ; return (HsOverLit lit') }
379
380 zonkExpr env (HsLam matches)
381   = zonkMatchGroup env matches  `thenM` \ new_matches ->
382     returnM (HsLam new_matches)
383
384 zonkExpr env (HsApp e1 e2)
385   = zonkLExpr env e1    `thenM` \ new_e1 ->
386     zonkLExpr env e2    `thenM` \ new_e2 ->
387     returnM (HsApp new_e1 new_e2)
388
389 zonkExpr env (HsBracketOut body bs) 
390   = mappM zonk_b bs     `thenM` \ bs' ->
391     returnM (HsBracketOut body bs')
392   where
393     zonk_b (n,e) = zonkLExpr env e      `thenM` \ e' ->
394                    returnM (n,e')
395
396 zonkExpr env (HsSpliceE s) = WARN( True, ppr s )        -- Should not happen
397                              returnM (HsSpliceE s)
398
399 zonkExpr env (OpApp e1 op fixity e2)
400   = zonkLExpr env e1    `thenM` \ new_e1 ->
401     zonkLExpr env op    `thenM` \ new_op ->
402     zonkLExpr env e2    `thenM` \ new_e2 ->
403     returnM (OpApp new_e1 new_op fixity new_e2)
404
405 zonkExpr env (NegApp expr op)
406   = zonkLExpr env expr  `thenM` \ new_expr ->
407     zonkExpr env op     `thenM` \ new_op ->
408     returnM (NegApp new_expr new_op)
409
410 zonkExpr env (HsPar e)    
411   = zonkLExpr env e     `thenM` \new_e ->
412     returnM (HsPar new_e)
413
414 zonkExpr env (SectionL expr op)
415   = zonkLExpr env expr  `thenM` \ new_expr ->
416     zonkLExpr env op            `thenM` \ new_op ->
417     returnM (SectionL new_expr new_op)
418
419 zonkExpr env (SectionR op expr)
420   = zonkLExpr env op            `thenM` \ new_op ->
421     zonkLExpr env expr          `thenM` \ new_expr ->
422     returnM (SectionR new_op new_expr)
423
424 zonkExpr env (HsCase expr ms)
425   = zonkLExpr env expr          `thenM` \ new_expr ->
426     zonkMatchGroup env ms       `thenM` \ new_ms ->
427     returnM (HsCase new_expr new_ms)
428
429 zonkExpr env (HsIf e1 e2 e3)
430   = zonkLExpr env e1    `thenM` \ new_e1 ->
431     zonkLExpr env e2    `thenM` \ new_e2 ->
432     zonkLExpr env e3    `thenM` \ new_e3 ->
433     returnM (HsIf new_e1 new_e2 new_e3)
434
435 zonkExpr env (HsLet binds expr)
436   = zonkLocalBinds env binds    `thenM` \ (new_env, new_binds) ->
437     zonkLExpr new_env expr      `thenM` \ new_expr ->
438     returnM (HsLet new_binds new_expr)
439
440 zonkExpr env (HsDo do_or_lc stmts body ty)
441   = zonkStmts env stmts         `thenM` \ (new_env, new_stmts) ->
442     zonkLExpr new_env body      `thenM` \ new_body ->
443     zonkTcTypeToType env ty     `thenM` \ new_ty   ->
444     returnM (HsDo (zonkDo env do_or_lc) 
445                   new_stmts new_body new_ty)
446
447 zonkExpr env (ExplicitList ty exprs)
448   = zonkTcTypeToType env ty     `thenM` \ new_ty ->
449     zonkLExprs env exprs        `thenM` \ new_exprs ->
450     returnM (ExplicitList new_ty new_exprs)
451
452 zonkExpr env (ExplicitPArr ty exprs)
453   = zonkTcTypeToType env ty     `thenM` \ new_ty ->
454     zonkLExprs env exprs        `thenM` \ new_exprs ->
455     returnM (ExplicitPArr new_ty new_exprs)
456
457 zonkExpr env (ExplicitTuple exprs boxed)
458   = zonkLExprs env exprs        `thenM` \ new_exprs ->
459     returnM (ExplicitTuple new_exprs boxed)
460
461 zonkExpr env (RecordCon data_con con_expr rbinds)
462   = do  { new_con_expr <- zonkExpr env con_expr
463         ; new_rbinds   <- zonkRecFields env rbinds
464         ; return (RecordCon data_con new_con_expr new_rbinds) }
465
466 zonkExpr env (RecordUpd expr rbinds cons in_tys out_tys)
467   = do  { new_expr    <- zonkLExpr env expr
468         ; new_in_tys  <- mapM (zonkTcTypeToType env) in_tys
469         ; new_out_tys <- mapM (zonkTcTypeToType env) out_tys
470         ; new_rbinds  <- zonkRecFields env rbinds
471         ; return (RecordUpd new_expr new_rbinds cons new_in_tys new_out_tys) }
472
473 zonkExpr env (ExprWithTySigOut e ty) 
474   = do { e' <- zonkLExpr env e
475        ; return (ExprWithTySigOut e' ty) }
476
477 zonkExpr env (ExprWithTySig _ _) = panic "zonkExpr env:ExprWithTySig"
478
479 zonkExpr env (ArithSeq expr info)
480   = zonkExpr env expr           `thenM` \ new_expr ->
481     zonkArithSeq env info       `thenM` \ new_info ->
482     returnM (ArithSeq new_expr new_info)
483
484 zonkExpr env (PArrSeq expr info)
485   = zonkExpr env expr           `thenM` \ new_expr ->
486     zonkArithSeq env info       `thenM` \ new_info ->
487     returnM (PArrSeq new_expr new_info)
488
489 zonkExpr env (HsSCC lbl expr)
490   = zonkLExpr env expr  `thenM` \ new_expr ->
491     returnM (HsSCC lbl new_expr)
492
493 zonkExpr env (HsTickPragma info expr)
494   = zonkLExpr env expr  `thenM` \ new_expr ->
495     returnM (HsTickPragma info new_expr)
496
497 -- hdaume: core annotations
498 zonkExpr env (HsCoreAnn lbl expr)
499   = zonkLExpr env expr   `thenM` \ new_expr ->
500     returnM (HsCoreAnn lbl new_expr)
501
502 -- arrow notation extensions
503 zonkExpr env (HsProc pat body)
504   = do  { (env1, new_pat) <- zonkPat env pat
505         ; new_body <- zonkCmdTop env1 body
506         ; return (HsProc new_pat new_body) }
507
508 zonkExpr env (HsArrApp e1 e2 ty ho rl)
509   = zonkLExpr env e1                    `thenM` \ new_e1 ->
510     zonkLExpr env e2                    `thenM` \ new_e2 ->
511     zonkTcTypeToType env ty             `thenM` \ new_ty ->
512     returnM (HsArrApp new_e1 new_e2 new_ty ho rl)
513
514 zonkExpr env (HsArrForm op fixity args)
515   = zonkLExpr env op                    `thenM` \ new_op ->
516     mappM (zonkCmdTop env) args         `thenM` \ new_args ->
517     returnM (HsArrForm new_op fixity new_args)
518
519 zonkExpr env (HsWrap co_fn expr)
520   = zonkCoFn env co_fn  `thenM` \ (env1, new_co_fn) ->
521     zonkExpr env1 expr  `thenM` \ new_expr ->
522     return (HsWrap new_co_fn new_expr)
523
524 zonkExpr env other = pprPanic "zonkExpr" (ppr other)
525
526 zonkCmdTop :: ZonkEnv -> LHsCmdTop TcId -> TcM (LHsCmdTop Id)
527 zonkCmdTop env cmd = wrapLocM (zonk_cmd_top env) cmd
528
529 zonk_cmd_top env (HsCmdTop cmd stack_tys ty ids)
530   = zonkLExpr env cmd                   `thenM` \ new_cmd ->
531     zonkTcTypeToTypes env stack_tys     `thenM` \ new_stack_tys ->
532     zonkTcTypeToType env ty             `thenM` \ new_ty ->
533     mapSndM (zonkExpr env) ids          `thenM` \ new_ids ->
534     returnM (HsCmdTop new_cmd new_stack_tys new_ty new_ids)
535
536 -------------------------------------------------------------------------
537 zonkCoFn :: ZonkEnv -> HsWrapper -> TcM (ZonkEnv, HsWrapper)
538 zonkCoFn env WpHole = return (env, WpHole)
539 zonkCoFn env (WpCompose c1 c2) = do { (env1, c1') <- zonkCoFn env c1
540                                     ; (env2, c2') <- zonkCoFn env1 c2
541                                     ; return (env2, WpCompose c1' c2') }
542 zonkCoFn env (WpCo co)      = do { co' <- zonkTcTypeToType env co
543                                  ; return (env, WpCo co') }
544 zonkCoFn env (WpLam id)     = do { id' <- zonkIdBndr env id
545                                  ; let env1 = extendZonkEnv1 env id'
546                                  ; return (env1, WpLam id') }
547 zonkCoFn env (WpTyLam tv)   = ASSERT( isImmutableTyVar tv )
548                               do { return (env, WpTyLam tv) }
549 zonkCoFn env (WpApp id)     = do { return (env, WpApp (zonkIdOcc env id)) }
550 zonkCoFn env (WpTyApp ty)   = do { ty' <- zonkTcTypeToType env ty
551                                  ; return (env, WpTyApp ty') }
552 zonkCoFn env (WpLet bs)     = do { (env1, bs') <- zonkRecMonoBinds env bs
553                                  ; return (env1, WpLet bs') }
554
555
556 -------------------------------------------------------------------------
557 zonkDo :: ZonkEnv -> HsStmtContext Name -> HsStmtContext Name
558 -- Only used for 'do', so the only Ids are in a MDoExpr table
559 zonkDo env (MDoExpr tbl) = MDoExpr (mapSnd (zonkIdOcc env) tbl)
560 zonkDo env do_or_lc      = do_or_lc
561
562 -------------------------------------------------------------------------
563 zonkOverLit :: ZonkEnv -> HsOverLit TcId -> TcM (HsOverLit Id)
564 zonkOverLit env (HsIntegral i e)
565   = do  { e' <- zonkExpr env e; return (HsIntegral i e') }
566 zonkOverLit env (HsFractional r e)
567   = do  { e' <- zonkExpr env e; return (HsFractional r e') }
568 zonkOverLit env (HsIsString s e)
569   = do  { e' <- zonkExpr env e; return (HsIsString s e') }
570
571 -------------------------------------------------------------------------
572 zonkArithSeq :: ZonkEnv -> ArithSeqInfo TcId -> TcM (ArithSeqInfo Id)
573
574 zonkArithSeq env (From e)
575   = zonkLExpr env e             `thenM` \ new_e ->
576     returnM (From new_e)
577
578 zonkArithSeq env (FromThen e1 e2)
579   = zonkLExpr env e1    `thenM` \ new_e1 ->
580     zonkLExpr env e2    `thenM` \ new_e2 ->
581     returnM (FromThen new_e1 new_e2)
582
583 zonkArithSeq env (FromTo e1 e2)
584   = zonkLExpr env e1    `thenM` \ new_e1 ->
585     zonkLExpr env e2    `thenM` \ new_e2 ->
586     returnM (FromTo new_e1 new_e2)
587
588 zonkArithSeq env (FromThenTo e1 e2 e3)
589   = zonkLExpr env e1    `thenM` \ new_e1 ->
590     zonkLExpr env e2    `thenM` \ new_e2 ->
591     zonkLExpr env e3    `thenM` \ new_e3 ->
592     returnM (FromThenTo new_e1 new_e2 new_e3)
593
594
595 -------------------------------------------------------------------------
596 zonkStmts :: ZonkEnv -> [LStmt TcId] -> TcM (ZonkEnv, [LStmt Id])
597 zonkStmts env []     = return (env, [])
598 zonkStmts env (s:ss) = do { (env1, s')  <- wrapLocSndM (zonkStmt env) s
599                           ; (env2, ss') <- zonkStmts env1 ss
600                           ; return (env2, s' : ss') }
601
602 zonkStmt :: ZonkEnv -> Stmt TcId -> TcM (ZonkEnv, Stmt Id)
603 zonkStmt env (ParStmt stmts_w_bndrs)
604   = mappM zonk_branch stmts_w_bndrs     `thenM` \ new_stmts_w_bndrs ->
605     let 
606         new_binders = concat (map snd new_stmts_w_bndrs)
607         env1 = extendZonkEnv env new_binders
608     in
609     return (env1, ParStmt new_stmts_w_bndrs)
610   where
611     zonk_branch (stmts, bndrs) = zonkStmts env stmts    `thenM` \ (env1, new_stmts) ->
612                                  returnM (new_stmts, zonkIdOccs env1 bndrs)
613
614 zonkStmt env (RecStmt segStmts lvs rvs rets binds)
615   = zonkIdBndrs env rvs         `thenM` \ new_rvs ->
616     let
617         env1 = extendZonkEnv env new_rvs
618     in
619     zonkStmts env1 segStmts     `thenM` \ (env2, new_segStmts) ->
620         -- Zonk the ret-expressions in an envt that 
621         -- has the polymorphic bindings in the envt
622     mapM (zonkExpr env2) rets   `thenM` \ new_rets ->
623     let
624         new_lvs = zonkIdOccs env2 lvs
625         env3 = extendZonkEnv env new_lvs        -- Only the lvs are needed
626     in
627     zonkRecMonoBinds env3 binds `thenM` \ (env4, new_binds) ->
628     returnM (env4, RecStmt new_segStmts new_lvs new_rvs new_rets new_binds)
629
630 zonkStmt env (ExprStmt expr then_op ty)
631   = zonkLExpr env expr          `thenM` \ new_expr ->
632     zonkExpr env then_op        `thenM` \ new_then ->
633     zonkTcTypeToType env ty     `thenM` \ new_ty ->
634     returnM (env, ExprStmt new_expr new_then new_ty)
635
636 zonkStmt env (LetStmt binds)
637   = zonkLocalBinds env binds    `thenM` \ (env1, new_binds) ->
638     returnM (env1, LetStmt new_binds)
639
640 zonkStmt env (BindStmt pat expr bind_op fail_op)
641   = do  { new_expr <- zonkLExpr env expr
642         ; (env1, new_pat) <- zonkPat env pat
643         ; new_bind <- zonkExpr env bind_op
644         ; new_fail <- zonkExpr env fail_op
645         ; return (env1, BindStmt new_pat new_expr new_bind new_fail) }
646
647
648 -------------------------------------------------------------------------
649 zonkRecFields :: ZonkEnv -> HsRecordBinds TcId -> TcM (HsRecordBinds TcId)
650 zonkRecFields env (HsRecFields flds dd)
651   = do  { flds' <- mappM zonk_rbind flds
652         ; return (HsRecFields flds' dd) }
653   where
654     zonk_rbind fld
655       = do { new_expr <- zonkLExpr env (hsRecFieldArg fld)
656            ; return (fld { hsRecFieldArg = new_expr }) }
657         -- Field selectors have declared types; hence no zonking
658
659 -------------------------------------------------------------------------
660 mapIPNameTc :: (a -> TcM b) -> IPName a -> TcM (IPName b)
661 mapIPNameTc f (IPName n) = f n  `thenM` \ r -> returnM (IPName r)
662 \end{code}
663
664
665 %************************************************************************
666 %*                                                                      *
667 \subsection[BackSubst-Pats]{Patterns}
668 %*                                                                      *
669 %************************************************************************
670
671 \begin{code}
672 zonkPat :: ZonkEnv -> OutPat TcId -> TcM (ZonkEnv, OutPat Id)
673 -- Extend the environment as we go, because it's possible for one
674 -- pattern to bind something that is used in another (inside or
675 -- to the right)
676 zonkPat env pat = wrapLocSndM (zonk_pat env) pat
677
678 zonk_pat env (ParPat p)
679   = do  { (env', p') <- zonkPat env p
680         ; return (env', ParPat p') }
681
682 zonk_pat env (WildPat ty)
683   = do  { ty' <- zonkTcTypeToType env ty
684         ; return (env, WildPat ty') }
685
686 zonk_pat env (VarPat v)
687   = do  { v' <- zonkIdBndr env v
688         ; return (extendZonkEnv1 env v', VarPat v') }
689
690 zonk_pat env (VarPatOut v binds)
691   = do  { v' <- zonkIdBndr env v
692         ; (env', binds') <- zonkRecMonoBinds (extendZonkEnv1 env v') binds
693         ; returnM (env', VarPatOut v' binds') }
694
695 zonk_pat env (LazyPat pat)
696   = do  { (env', pat') <- zonkPat env pat
697         ; return (env',  LazyPat pat') }
698
699 zonk_pat env (BangPat pat)
700   = do  { (env', pat') <- zonkPat env pat
701         ; return (env',  BangPat pat') }
702
703 zonk_pat env (AsPat (L loc v) pat)
704   = do  { v' <- zonkIdBndr env v
705         ; (env', pat') <- zonkPat (extendZonkEnv1 env v') pat
706         ; return (env', AsPat (L loc v') pat') }
707
708 zonk_pat env (ListPat pats ty)
709   = do  { ty' <- zonkTcTypeToType env ty
710         ; (env', pats') <- zonkPats env pats
711         ; return (env', ListPat pats' ty') }
712
713 zonk_pat env (PArrPat pats ty)
714   = do  { ty' <- zonkTcTypeToType env ty
715         ; (env', pats') <- zonkPats env pats
716         ; return (env', PArrPat pats' ty') }
717
718 zonk_pat env (TuplePat pats boxed ty)
719   = do  { ty' <- zonkTcTypeToType env ty
720         ; (env', pats') <- zonkPats env pats
721         ; return (env', TuplePat pats' boxed ty') }
722
723 zonk_pat env p@(ConPatOut { pat_ty = ty, pat_dicts = dicts, pat_binds = binds, pat_args = args })
724   = ASSERT( all isImmutableTyVar (pat_tvs p) ) 
725     do  { new_ty <- zonkTcTypeToType env ty
726         ; new_dicts <- zonkIdBndrs env dicts
727         ; let env1 = extendZonkEnv env new_dicts
728         ; (env2, new_binds) <- zonkRecMonoBinds env1 binds
729         ; (env', new_args) <- zonkConStuff env2 args
730         ; returnM (env', p { pat_ty = new_ty, pat_dicts = new_dicts, 
731                              pat_binds = new_binds, pat_args = new_args }) }
732
733 zonk_pat env (LitPat lit) = return (env, LitPat lit)
734
735 zonk_pat env (SigPatOut pat ty)
736   = do  { ty' <- zonkTcTypeToType env ty
737         ; (env', pat') <- zonkPat env pat
738         ; return (env', SigPatOut pat' ty') }
739
740 zonk_pat env (NPat lit mb_neg eq_expr ty)
741   = do  { lit' <- zonkOverLit env lit
742         ; mb_neg' <- case mb_neg of
743                         Nothing  -> return Nothing
744                         Just neg -> do { neg' <- zonkExpr env neg
745                                        ; return (Just neg') }
746         ; eq_expr' <- zonkExpr env eq_expr
747         ; ty' <- zonkTcTypeToType env ty
748         ; return (env, NPat lit' mb_neg' eq_expr' ty') }
749
750 zonk_pat env (NPlusKPat (L loc n) lit e1 e2)
751   = do  { n' <- zonkIdBndr env n
752         ; lit' <- zonkOverLit env lit
753         ; e1' <- zonkExpr env e1
754         ; e2' <- zonkExpr env e2
755         ; return (extendZonkEnv1 env n', NPlusKPat (L loc n') lit' e1' e2') }
756
757 zonk_pat env (CoPat co_fn pat ty) 
758   = do { (env', co_fn') <- zonkCoFn env co_fn
759        ; (env'', pat') <- zonkPat env' (noLoc pat)
760        ; ty' <- zonkTcTypeToType env'' ty
761        ; return (env'', CoPat co_fn' (unLoc pat') ty') }
762
763 zonk_pat env pat = pprPanic "zonk_pat" (ppr pat)
764
765 ---------------------------
766 zonkConStuff env (PrefixCon pats)
767   = do  { (env', pats') <- zonkPats env pats
768         ; return (env', PrefixCon pats') }
769
770 zonkConStuff env (InfixCon p1 p2)
771   = do  { (env1, p1') <- zonkPat env  p1
772         ; (env', p2') <- zonkPat env1 p2
773         ; return (env', InfixCon p1' p2') }
774
775 zonkConStuff env (RecCon (HsRecFields rpats dd))
776   = do  { (env', pats') <- zonkPats env (map hsRecFieldArg rpats)
777         ; let rpats' = zipWith (\rp p' -> rp { hsRecFieldArg = p' }) rpats pats'
778         ; returnM (env', RecCon (HsRecFields rpats' dd)) }
779         -- Field selectors have declared types; hence no zonking
780
781 ---------------------------
782 zonkPats env []         = return (env, [])
783 zonkPats env (pat:pats) = do { (env1, pat') <- zonkPat env pat
784                      ; (env', pats') <- zonkPats env1 pats
785                      ; return (env', pat':pats') }
786 \end{code}
787
788 %************************************************************************
789 %*                                                                      *
790 \subsection[BackSubst-Foreign]{Foreign exports}
791 %*                                                                      *
792 %************************************************************************
793
794
795 \begin{code}
796 zonkForeignExports :: ZonkEnv -> [LForeignDecl TcId] -> TcM [LForeignDecl Id]
797 zonkForeignExports env ls = mappM (wrapLocM (zonkForeignExport env)) ls
798
799 zonkForeignExport :: ZonkEnv -> ForeignDecl TcId -> TcM (ForeignDecl Id)
800 zonkForeignExport env (ForeignExport i hs_ty spec) =
801    returnM (ForeignExport (fmap (zonkIdOcc env) i) undefined spec)
802 zonkForeignExport env for_imp 
803   = returnM for_imp     -- Foreign imports don't need zonking
804 \end{code}
805
806 \begin{code}
807 zonkRules :: ZonkEnv -> [LRuleDecl TcId] -> TcM [LRuleDecl Id]
808 zonkRules env rs = mappM (wrapLocM (zonkRule env)) rs
809
810 zonkRule :: ZonkEnv -> RuleDecl TcId -> TcM (RuleDecl Id)
811 zonkRule env (HsRule name act (vars::[RuleBndr TcId]) lhs fv_lhs rhs fv_rhs)
812   = mappM zonk_bndr vars                `thenM` \ new_bndrs ->
813     newMutVar emptyVarSet               `thenM` \ unbound_tv_set ->
814     let
815         env_rhs = extendZonkEnv env [id | b <- new_bndrs, let id = unLoc b, isId id]
816         -- Type variables don't need an envt
817         -- They are bound through the mutable mechanism
818
819         env_lhs = setZonkType env_rhs (zonkTypeCollecting unbound_tv_set)
820         -- We need to gather the type variables mentioned on the LHS so we can 
821         -- quantify over them.  Example:
822         --   data T a = C
823         -- 
824         --   foo :: T a -> Int
825         --   foo C = 1
826         --
827         --   {-# RULES "myrule"  foo C = 1 #-}
828         -- 
829         -- After type checking the LHS becomes (foo a (C a))
830         -- and we do not want to zap the unbound tyvar 'a' to (), because
831         -- that limits the applicability of the rule.  Instead, we
832         -- want to quantify over it!  
833         --
834         -- It's easiest to find the free tyvars here. Attempts to do so earlier
835         -- are tiresome, because (a) the data type is big and (b) finding the 
836         -- free type vars of an expression is necessarily monadic operation.
837         --      (consider /\a -> f @ b, where b is side-effected to a)
838     in
839     zonkLExpr env_lhs lhs               `thenM` \ new_lhs ->
840     zonkLExpr env_rhs rhs               `thenM` \ new_rhs ->
841
842     readMutVar unbound_tv_set           `thenM` \ unbound_tvs ->
843     let
844         final_bndrs :: [Located Var]
845         final_bndrs = map noLoc (varSetElems unbound_tvs) ++ new_bndrs
846     in
847     returnM (HsRule name act (map RuleBndr final_bndrs) new_lhs fv_lhs new_rhs fv_rhs)
848                 -- I hate this map RuleBndr stuff
849   where
850    zonk_bndr (RuleBndr v) 
851         | isId (unLoc v) = wrapLocM (zonkIdBndr env)   v
852         | otherwise      = ASSERT( isImmutableTyVar (unLoc v) )
853                            return v
854 \end{code}
855
856
857 %************************************************************************
858 %*                                                                      *
859 \subsection[BackSubst-Foreign]{Foreign exports}
860 %*                                                                      *
861 %************************************************************************
862
863 \begin{code}
864 zonkTcTypeToType :: ZonkEnv -> TcType -> TcM Type
865 zonkTcTypeToType (ZonkEnv zonk_ty _) ty = zonk_ty ty
866
867 zonkTcTypeToTypes :: ZonkEnv -> [TcType] -> TcM [Type]
868 zonkTcTypeToTypes env tys = mapM (zonkTcTypeToType env) tys
869
870 zonkTypeCollecting :: TcRef TyVarSet -> TcType -> TcM Type
871 -- This variant collects unbound type variables in a mutable variable
872 zonkTypeCollecting unbound_tv_set
873   = zonkType zonk_unbound_tyvar
874   where
875     zonk_unbound_tyvar tv 
876         = zonkQuantifiedTyVar tv                                `thenM` \ tv' ->
877           readMutVar unbound_tv_set                             `thenM` \ tv_set ->
878           writeMutVar unbound_tv_set (extendVarSet tv_set tv')  `thenM_`
879           return (mkTyVarTy tv')
880
881 zonkTypeZapping :: TcType -> TcM Type
882 -- This variant is used for everything except the LHS of rules
883 -- It zaps unbound type variables to (), or some other arbitrary type
884 zonkTypeZapping ty 
885   = zonkType zonk_unbound_tyvar ty 
886   where
887         -- Zonk a mutable but unbound type variable to an arbitrary type
888         -- We know it's unbound even though we don't carry an environment,
889         -- because at the binding site for a type variable we bind the
890         -- mutable tyvar to a fresh immutable one.  So the mutable store
891         -- plays the role of an environment.  If we come across a mutable
892         -- type variable that isn't so bound, it must be completely free.
893     zonk_unbound_tyvar tv = do { writeMetaTyVar tv ty; return ty }
894                           where 
895                             ty = mkArbitraryType tv
896
897
898 -- When the type checker finds a type variable with no binding,
899 -- which means it can be instantiated with an arbitrary type, it
900 -- usually instantiates it to Void.  Eg.
901 -- 
902 --      length []
903 -- ===>
904 --      length Void (Nil Void)
905 -- 
906 -- But in really obscure programs, the type variable might have
907 -- a kind other than *, so we need to invent a suitably-kinded type.
908 -- 
909 -- This commit uses
910 --      Void for kind *
911 --      List for kind *->*
912 --      Tuple for kind *->...*->*
913 -- 
914 -- which deals with most cases.  (Previously, it only dealt with
915 -- kind *.)   
916 -- 
917 -- In the other cases, it just makes up a TyCon with a suitable
918 -- kind.  If this gets into an interface file, anyone reading that
919 -- file won't understand it.  This is fixable (by making the client
920 -- of the interface file make up a TyCon too) but it is tiresome and
921 -- never happens, so I am leaving it 
922
923 mkArbitraryType :: TcTyVar -> Type
924 -- Make up an arbitrary type whose kind is the same as the tyvar.
925 -- We'll use this to instantiate the (unbound) tyvar.
926 mkArbitraryType tv 
927   | liftedTypeKind `isSubKind` kind = anyPrimTy         -- The vastly common case
928   | otherwise                       = mkTyConApp tycon []
929   where
930     kind       = tyVarKind tv
931     (args,res) = splitKindFunTys kind
932
933     tycon | eqKind kind (tyConKind anyPrimTyCon1)       --  *->*
934           = anyPrimTyCon1                               -- No tuples this size
935
936           | all isLiftedTypeKind args && isLiftedTypeKind res
937           = tupleTyCon Boxed (length args)      --  *-> ... ->*->*
938                 -- Horrible hack to make less use of mkAnyPrimTyCon
939
940           | otherwise
941           = mkAnyPrimTyCon (getUnique tv) kind
942                 -- Same name as the tyvar, apart from making it start with a colon (sigh)
943                 -- I dread to think what will happen if this gets out into an 
944                 -- interface file.  Catastrophe likely.  Major sigh.
945 \end{code}