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