2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1996-1998
6 TcHsSyn: Specialisations of the @HsSyn@ syntax for the typechecker
8 This module is an extension of @HsSyn@ syntax, for use in the type
13 mkHsConApp, mkHsDictLet, mkHsApp,
14 hsLitType, hsLPatType, hsPatType,
15 mkHsAppTy, mkSimpleHsAlt,
17 shortCutLit, hsOverLitName,
19 mkArbitraryType, -- Put this elsewhere?
21 -- re-exported from TcMonad
22 TcId, TcIdSet, TcDictBinds,
24 zonkTopDecls, zonkTopExpr, zonkTopLExpr,
28 #include "HsVersions.h"
31 import HsSyn -- oodles of it
60 thenM :: Monad a => a b -> (b -> a c) -> a c
63 thenM_ :: Monad a => a b -> a c -> a c
66 returnM :: Monad m => a -> m a
69 mappM :: (Monad m) => (a -> m b) -> [a] -> m [b]
74 %************************************************************************
76 \subsection[mkFailurePair]{Code for pattern-matching and other failures}
78 %************************************************************************
80 Note: If @hsLPatType@ doesn't bear a strong resemblance to @exprType@,
81 then something is wrong.
83 hsLPatType :: OutPat Id -> Type
84 hsLPatType (L _ pat) = hsPatType pat
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)
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
120 Overloaded literals. Here mainly becuase it uses isIntTy etc
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
135 shortCutLit (HsFractional f) ty
136 | isFloatTy ty = Just (mkLit floatDataCon (HsFloatPrim f))
137 | isDoubleTy ty = Just (mkLit doubleDataCon (HsDoublePrim f))
138 | otherwise = Nothing
140 shortCutLit (HsIsString s) ty
141 | isStringTy ty = Just (HsLit (HsString s))
142 | otherwise = Nothing
144 mkLit :: DataCon -> HsLit -> HsExpr Id
145 mkLit con lit = HsApp (nlHsVar (dataConWrapId con)) (nlHsLit lit)
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
155 %************************************************************************
157 \subsection[BackSubst-HsBinds]{Running a substitution over @HsBinds@}
159 %************************************************************************
162 -- zonkId is used *during* typechecking just to zonk the Id's type
163 zonkId :: TcId -> TcM TcId
165 = zonkTcType (idType id) `thenM` \ ty' ->
166 returnM (Id.setIdType id ty')
169 The rest of the zonking is done *after* typechecking.
170 The main zonking pass runs over the bindings
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
176 The type variables are converted by binding mutable tyvars to immutable ones
177 and then zonking as normal.
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
183 It's all pretty boring stuff, because HsSyn is such a large type, and
184 the environment manipulation is tiresome.
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
192 emptyZonkEnv :: ZonkEnv
193 emptyZonkEnv = ZonkEnv zonkTypeZapping emptyVarEnv
195 extendZonkEnv :: ZonkEnv -> [Id] -> ZonkEnv
196 extendZonkEnv (ZonkEnv zonk_ty env) ids
197 = ZonkEnv zonk_ty (extendVarEnvList env [(id,id) | id <- ids])
199 extendZonkEnv1 :: ZonkEnv -> Id -> ZonkEnv
200 extendZonkEnv1 (ZonkEnv zonk_ty env) id
201 = ZonkEnv zonk_ty (extendVarEnv env id id)
203 setZonkType :: ZonkEnv -> (TcType -> TcM Type) -> ZonkEnv
204 setZonkType (ZonkEnv _ env) zonk_ty = ZonkEnv zonk_ty env
206 zonkEnvIds :: ZonkEnv -> [Id]
207 zonkEnvIds (ZonkEnv _ env) = varEnvElts env
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.)
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.
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
229 zonkIdOccs :: ZonkEnv -> [TcId] -> [Id]
230 zonkIdOccs env ids = map (zonkIdOcc env) ids
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
236 = zonkTcTypeToType env (idType id) `thenM` \ ty' ->
237 returnM (Id.setIdType id ty')
239 zonkIdBndrs :: ZonkEnv -> [TcId] -> TcM [Id]
240 zonkIdBndrs env ids = mappM (zonkIdBndr env) ids
242 zonkDictBndrs :: ZonkEnv -> [Var] -> TcM [Var]
243 -- "Dictionary" binders can be coercion variables or dictionary variables
244 zonkDictBndrs env ids = mappM (zonkDictBndr env) ids
246 zonkDictBndr :: ZonkEnv -> Var -> TcM Var
247 zonkDictBndr env var | isTyVar var = zonkTyVarBndr env var
248 | otherwise = zonkIdBndr env var
250 zonkTopBndrs :: [TcId] -> TcM [Id]
251 zonkTopBndrs ids = zonkIdBndrs emptyZonkEnv ids
253 -- Zonk the kind of a non-TC tyvar in case it is a coercion variable (their
254 -- kind contains types).
256 zonkTyVarBndr :: ZonkEnv -> TyVar -> TcM TyVar
259 = do { kind <- zonkTcTypeToType env (tyVarKind tv)
260 ; return $ setTyVarKind tv kind
262 | otherwise = return tv
267 zonkTopExpr :: HsExpr TcId -> TcM (HsExpr Id)
268 zonkTopExpr e = zonkExpr emptyZonkEnv e
270 zonkTopLExpr :: LHsExpr TcId -> TcM (LHsExpr Id)
271 zonkTopLExpr e = zonkLExpr emptyZonkEnv e
273 zonkTopDecls :: LHsBinds TcId -> [LRuleDecl TcId] -> [LForeignDecl TcId]
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') }
285 ---------------------------------------------
286 zonkLocalBinds :: ZonkEnv -> HsLocalBinds TcId -> TcM (ZonkEnv, HsLocalBinds Id)
287 zonkLocalBinds env EmptyLocalBinds
288 = return (env, EmptyLocalBinds)
290 zonkLocalBinds env (HsValBinds binds)
291 = do { (env1, new_binds) <- zonkValBinds env binds
292 ; return (env1, HsValBinds new_binds) }
294 zonkLocalBinds env (HsIPBinds (IPBinds binds dict_binds))
295 = mappM (wrapLocM zonk_ip_bind) binds `thenM` \ new_binds ->
297 env1 = extendZonkEnv env [ipNameName n | L _ (IPBind n _) <- new_binds]
299 zonkRecMonoBinds env1 dict_binds `thenM` \ (env2, new_dict_binds) ->
300 returnM (env2, HsIPBinds (IPBinds new_binds new_dict_binds))
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')
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) }
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') }
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') })
329 ---------------------------------------------
330 zonkMonoBinds :: ZonkEnv -> LHsBinds TcId -> TcM (LHsBinds Id)
331 zonkMonoBinds env binds = mapBagM (wrapLocM (zonk_bind env)) binds
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 }) }
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 })
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 })
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, _) ->
357 env1 = extendZonkEnv env new_dicts
358 env2 = extendZonkEnv env1 (collectHsBindBinders new_val_binds)
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 })
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)) }
379 %************************************************************************
381 \subsection[BackSubst-Match-GRHSs]{Match and GRHSs}
383 %************************************************************************
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') }
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)) }
398 -------------------------------------------------------------------------
399 zonkGRHSs :: ZonkEnv -> GRHSs TcId -> TcM (GRHSs Id)
401 zonkGRHSs env (GRHSs grhss binds)
402 = zonkLocalBinds env binds `thenM` \ (new_env, new_binds) ->
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)
409 mappM (wrapLocM zonk_grhs) grhss `thenM` \ new_grhss ->
410 returnM (GRHSs new_grhss new_binds)
413 %************************************************************************
415 \subsection[BackSubst-HsExpr]{Running a zonkitution over a TypeCheckedExpr}
417 %************************************************************************
420 zonkLExprs :: ZonkEnv -> [LHsExpr TcId] -> TcM [LHsExpr Id]
421 zonkLExpr :: ZonkEnv -> LHsExpr TcId -> TcM (LHsExpr Id)
422 zonkExpr :: ZonkEnv -> HsExpr TcId -> TcM (HsExpr Id)
424 zonkLExprs env exprs = mappM (zonkLExpr env) exprs
425 zonkLExpr env expr = wrapLocM (zonkExpr env) expr
427 zonkExpr env (HsVar id)
428 = returnM (HsVar (zonkIdOcc env id))
430 zonkExpr env (HsIPVar id)
431 = returnM (HsIPVar (mapIPName (zonkIdOcc env) id))
433 zonkExpr env (HsLit (HsRat f ty))
434 = zonkTcTypeToType env ty `thenM` \ new_ty ->
435 returnM (HsLit (HsRat f new_ty))
437 zonkExpr _ (HsLit lit)
438 = returnM (HsLit lit)
440 zonkExpr env (HsOverLit lit)
441 = do { lit' <- zonkOverLit env lit
442 ; return (HsOverLit lit') }
444 zonkExpr env (HsLam matches)
445 = zonkMatchGroup env matches `thenM` \ new_matches ->
446 returnM (HsLam new_matches)
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)
453 zonkExpr env (HsBracketOut body bs)
454 = mappM zonk_b bs `thenM` \ bs' ->
455 returnM (HsBracketOut body bs')
457 zonk_b (n,e) = zonkLExpr env e `thenM` \ e' ->
460 zonkExpr _ (HsSpliceE s) = WARN( True, ppr s ) -- Should not happen
461 returnM (HsSpliceE s)
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)
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)
474 zonkExpr env (HsPar e)
475 = zonkLExpr env e `thenM` \new_e ->
476 returnM (HsPar new_e)
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)
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)
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) }
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') }
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)
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)
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)
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)
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)
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)
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) }
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) }
540 zonkExpr env (ExprWithTySigOut e ty)
541 = do { e' <- zonkLExpr env e
542 ; return (ExprWithTySigOut e' ty) }
544 zonkExpr _ (ExprWithTySig _ _) = panic "zonkExpr env:ExprWithTySig"
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)
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)
556 zonkExpr env (HsSCC lbl expr)
557 = zonkLExpr env expr `thenM` \ new_expr ->
558 returnM (HsSCC lbl new_expr)
560 zonkExpr env (HsTickPragma info expr)
561 = zonkLExpr env expr `thenM` \ new_expr ->
562 returnM (HsTickPragma info new_expr)
564 -- hdaume: core annotations
565 zonkExpr env (HsCoreAnn lbl expr)
566 = zonkLExpr env expr `thenM` \ new_expr ->
567 returnM (HsCoreAnn lbl new_expr)
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) }
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)
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)
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)
591 zonkExpr _ expr = pprPanic "zonkExpr" (ppr expr)
593 zonkCmdTop :: ZonkEnv -> LHsCmdTop TcId -> TcM (LHsCmdTop Id)
594 zonkCmdTop env cmd = wrapLocM (zonk_cmd_top env) cmd
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)
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') }
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
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' }) }
646 -------------------------------------------------------------------------
647 zonkArithSeq :: ZonkEnv -> ArithSeqInfo TcId -> TcM (ArithSeqInfo Id)
649 zonkArithSeq env (From e)
650 = zonkLExpr env e `thenM` \ new_e ->
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)
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)
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)
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') }
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 ->
681 new_binders = concat (map snd new_stmts_w_bndrs)
682 env1 = extendZonkEnv env new_binders
684 return (env1, ParStmt new_stmts_w_bndrs)
686 zonk_branch (stmts, bndrs) = zonkStmts env stmts `thenM` \ (env1, new_stmts) ->
687 returnM (new_stmts, zonkIdOccs env1 bndrs)
689 zonkStmt env (RecStmt segStmts lvs rvs rets binds)
690 = zonkIdBndrs env rvs `thenM` \ new_rvs ->
692 env1 = extendZonkEnv env new_rvs
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 ->
699 new_lvs = zonkIdOccs env2 lvs
700 env3 = extendZonkEnv env new_lvs -- Only the lvs are needed
702 zonkRecMonoBinds env3 binds `thenM` \ (env4, new_binds) ->
703 returnM (env4, RecStmt new_segStmts new_lvs new_rvs new_rets new_binds)
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)
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') }
718 zonkStmt env (GroupStmt (stmts, binderMap) groupByClause)
719 = do { (env', stmts') <- zonkStmts env stmts
720 ; binderMap' <- mappM (zonkBinderMapEntry env') binderMap
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'
729 ; let env'' = extendZonkEnv env' (map snd binderMap')
730 ; return (env'', GroupStmt (stmts', binderMap') groupByClause') }
732 mapEitherM f g x = do
734 Left a -> f a >>= (return . Left)
735 Right b -> g b >>= (return . Right)
737 zonkBinderMapEntry env (oldBinder, newBinder) = do
738 let oldBinder' = zonkIdOcc env oldBinder
739 newBinder' <- zonkIdBndr env newBinder
740 return (oldBinder', newBinder')
742 zonkStmt env (LetStmt binds)
743 = zonkLocalBinds env binds `thenM` \ (env1, new_binds) ->
744 returnM (env1, LetStmt new_binds)
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) }
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)
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) }
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 }) }
769 -------------------------------------------------------------------------
770 mapIPNameTc :: (a -> TcM b) -> IPName a -> TcM (IPName b)
771 mapIPNameTc f (IPName n) = f n `thenM` \ r -> returnM (IPName r)
775 %************************************************************************
777 \subsection[BackSubst-Pats]{Patterns}
779 %************************************************************************
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
786 zonkPat env pat = wrapLocSndM (zonk_pat env) pat
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') }
793 zonk_pat env (WildPat ty)
794 = do { ty' <- zonkTcTypeToType env ty
795 ; return (env, WildPat ty') }
797 zonk_pat env (VarPat v)
798 = do { v' <- zonkIdBndr env v
799 ; return (extendZonkEnv1 env v', VarPat v') }
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') }
806 zonk_pat env (LazyPat pat)
807 = do { (env', pat') <- zonkPat env pat
808 ; return (env', LazyPat pat') }
810 zonk_pat env (BangPat pat)
811 = do { (env', pat') <- zonkPat env pat
812 ; return (env', BangPat pat') }
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') }
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') }
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') }
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') }
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') }
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 }) }
850 zonk_pat env (LitPat lit) = return (env, LitPat lit)
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') }
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') }
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') }
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') }
879 zonk_pat _ pat = pprPanic "zonk_pat" (ppr pat)
881 ---------------------------
882 zonkConStuff :: ZonkEnv
883 -> HsConDetails (OutPat TcId) (HsRecFields id (OutPat TcId))
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') }
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') }
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
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') }
909 %************************************************************************
911 \subsection[BackSubst-Foreign]{Foreign exports}
913 %************************************************************************
917 zonkForeignExports :: ZonkEnv -> [LForeignDecl TcId] -> TcM [LForeignDecl Id]
918 zonkForeignExports env ls = mappM (wrapLocM (zonkForeignExport env)) ls
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
928 zonkRules :: ZonkEnv -> [LRuleDecl TcId] -> TcM [LRuleDecl Id]
929 zonkRules env rs = mappM (wrapLocM (zonkRule env)) rs
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 ->
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
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:
948 -- {-# RULES "myrule" foo C = 1 #-}
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!
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)
960 zonkLExpr env_lhs lhs `thenM` \ new_lhs ->
961 zonkLExpr env_rhs rhs `thenM` \ new_rhs ->
963 readMutVar unbound_tv_set `thenM` \ unbound_tvs ->
965 final_bndrs :: [Located Var]
966 final_bndrs = map noLoc (varSetElems unbound_tvs) ++ new_bndrs
968 returnM (HsRule name act (map RuleBndr final_bndrs) new_lhs fv_lhs new_rhs fv_rhs)
969 -- I hate this map RuleBndr stuff
971 zonk_bndr (RuleBndr v)
972 | isId (unLoc v) = wrapLocM (zonkIdBndr env) v
973 | otherwise = ASSERT( isImmutableTyVar (unLoc v) )
975 zonk_bndr (RuleBndrSig {}) = panic "zonk_bndr RuleBndrSig"
979 %************************************************************************
981 \subsection[BackSubst-Foreign]{Foreign exports}
983 %************************************************************************
986 zonkTcTypeToType :: ZonkEnv -> TcType -> TcM Type
987 zonkTcTypeToType (ZonkEnv zonk_ty _) ty = zonk_ty ty
989 zonkTcTypeToTypes :: ZonkEnv -> [TcType] -> TcM [Type]
990 zonkTcTypeToTypes env tys = mapM (zonkTcTypeToType env) tys
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
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')
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
1007 = zonkType zonk_unbound_tyvar ty
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
1019 warn span msg = setSrcSpan span (addWarnTc msg)
1022 {- Note [Strangely-kinded void TyCons]
1023 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1024 See Trac #959 for more examples
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.
1032 length Void (Nil Void)
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.
1040 Tuple for kind *->...*->*
1042 which deals with most cases. (Previously, it only dealt with
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
1051 Meanwhile I have now fixed GHC to emit a civilized warning.
1054 mkArbitraryType :: (SrcSpan -> SDoc -> TcRnIf g l a) -- How to complain
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.
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
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
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.
1078 (args,res) = splitKindFunTys kind
1079 tup_tc = tupleTyCon Boxed (length args)
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") ]