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