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 = return var
255 | otherwise = zonkIdBndr env var
257 zonkTopBndrs :: [TcId] -> TcM [Id]
258 zonkTopBndrs ids = zonkIdBndrs emptyZonkEnv ids
263 zonkTopExpr :: HsExpr TcId -> TcM (HsExpr Id)
264 zonkTopExpr e = zonkExpr emptyZonkEnv e
266 zonkTopLExpr :: LHsExpr TcId -> TcM (LHsExpr Id)
267 zonkTopLExpr e = zonkLExpr emptyZonkEnv e
269 zonkTopDecls :: LHsBinds TcId -> [LRuleDecl TcId] -> [LForeignDecl TcId]
274 zonkTopDecls binds rules fords
275 = do { (env, binds') <- zonkRecMonoBinds emptyZonkEnv binds
276 -- Top level is implicitly recursive
277 ; rules' <- zonkRules env rules
278 ; fords' <- zonkForeignExports env fords
279 ; return (zonkEnvIds env, binds', fords', rules') }
281 ---------------------------------------------
282 zonkLocalBinds :: ZonkEnv -> HsLocalBinds TcId -> TcM (ZonkEnv, HsLocalBinds Id)
283 zonkLocalBinds env EmptyLocalBinds
284 = return (env, EmptyLocalBinds)
286 zonkLocalBinds env (HsValBinds binds)
287 = do { (env1, new_binds) <- zonkValBinds env binds
288 ; return (env1, HsValBinds new_binds) }
290 zonkLocalBinds env (HsIPBinds (IPBinds binds dict_binds))
291 = mappM (wrapLocM zonk_ip_bind) binds `thenM` \ new_binds ->
293 env1 = extendZonkEnv env [ipNameName n | L _ (IPBind n _) <- new_binds]
295 zonkRecMonoBinds env1 dict_binds `thenM` \ (env2, new_dict_binds) ->
296 returnM (env2, HsIPBinds (IPBinds new_binds new_dict_binds))
298 zonk_ip_bind (IPBind n e)
299 = mapIPNameTc (zonkIdBndr env) n `thenM` \ n' ->
300 zonkLExpr env e `thenM` \ e' ->
301 returnM (IPBind n' e')
304 ---------------------------------------------
305 zonkValBinds :: ZonkEnv -> HsValBinds TcId -> TcM (ZonkEnv, HsValBinds Id)
306 zonkValBinds _ (ValBindsIn _ _)
307 = panic "zonkValBinds" -- Not in typechecker output
308 zonkValBinds env (ValBindsOut binds sigs)
309 = do { (env1, new_binds) <- go env binds
310 ; return (env1, ValBindsOut new_binds sigs) }
312 go env [] = return (env, [])
313 go env ((r,b):bs) = do { (env1, b') <- zonkRecMonoBinds env b
314 ; (env2, bs') <- go env1 bs
315 ; return (env2, (r,b'):bs') }
317 ---------------------------------------------
318 zonkRecMonoBinds :: ZonkEnv -> LHsBinds TcId -> TcM (ZonkEnv, LHsBinds Id)
319 zonkRecMonoBinds env binds
320 = fixM (\ ~(_, new_binds) -> do
321 { let env1 = extendZonkEnv env (collectHsBindBinders new_binds)
322 ; binds' <- zonkMonoBinds env1 binds
323 ; return (env1, binds') })
325 ---------------------------------------------
326 zonkMonoBinds :: ZonkEnv -> LHsBinds TcId -> TcM (LHsBinds Id)
327 zonkMonoBinds env binds = mapBagM (wrapLocM (zonk_bind env)) binds
329 zonk_bind :: ZonkEnv -> HsBind TcId -> TcM (HsBind Id)
330 zonk_bind env bind@(PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty})
331 = do { (_env, new_pat) <- zonkPat env pat -- Env already extended
332 ; new_grhss <- zonkGRHSs env grhss
333 ; new_ty <- zonkTcTypeToType env ty
334 ; return (bind { pat_lhs = new_pat, pat_rhs = new_grhss, pat_rhs_ty = new_ty }) }
336 zonk_bind env (VarBind { var_id = var, var_rhs = expr })
337 = zonkIdBndr env var `thenM` \ new_var ->
338 zonkLExpr env expr `thenM` \ new_expr ->
339 returnM (VarBind { var_id = new_var, var_rhs = new_expr })
341 zonk_bind env bind@(FunBind { fun_id = var, fun_matches = ms, fun_co_fn = co_fn })
342 = wrapLocM (zonkIdBndr env) var `thenM` \ new_var ->
343 zonkCoFn env co_fn `thenM` \ (env1, new_co_fn) ->
344 zonkMatchGroup env1 ms `thenM` \ new_ms ->
345 returnM (bind { fun_id = new_var, fun_matches = new_ms, fun_co_fn = new_co_fn })
347 zonk_bind env (AbsBinds { abs_tvs = tyvars, abs_dicts = dicts,
348 abs_exports = exports, abs_binds = val_binds })
349 = ASSERT( all isImmutableTyVar tyvars )
350 zonkDictBndrs env dicts `thenM` \ new_dicts ->
351 fixM (\ ~(new_val_binds, _) ->
353 env1 = extendZonkEnv env new_dicts
354 env2 = extendZonkEnv env1 (collectHsBindBinders new_val_binds)
356 zonkMonoBinds env2 val_binds `thenM` \ new_val_binds ->
357 mappM (zonkExport env2) exports `thenM` \ new_exports ->
358 returnM (new_val_binds, new_exports)
359 ) `thenM` \ (new_val_bind, new_exports) ->
360 returnM (AbsBinds { abs_tvs = tyvars, abs_dicts = new_dicts,
361 abs_exports = new_exports, abs_binds = new_val_bind })
363 zonkExport env (tyvars, global, local, prags)
364 -- The tyvars are already zonked
365 = zonkIdBndr env global `thenM` \ new_global ->
366 mapM zonk_prag prags `thenM` \ new_prags ->
367 returnM (tyvars, new_global, zonkIdOcc env local, new_prags)
368 zonk_prag prag@(L _ (InlinePrag {})) = return prag
369 zonk_prag (L loc (SpecPrag expr ty inl))
370 = do { expr' <- zonkExpr env expr
371 ; ty' <- zonkTcTypeToType env ty
372 ; return (L loc (SpecPrag expr' ty' inl)) }
375 %************************************************************************
377 \subsection[BackSubst-Match-GRHSs]{Match and GRHSs}
379 %************************************************************************
382 zonkMatchGroup :: ZonkEnv -> MatchGroup TcId-> TcM (MatchGroup Id)
383 zonkMatchGroup env (MatchGroup ms ty)
384 = do { ms' <- mapM (zonkMatch env) ms
385 ; ty' <- zonkTcTypeToType env ty
386 ; return (MatchGroup ms' ty') }
388 zonkMatch :: ZonkEnv -> LMatch TcId-> TcM (LMatch Id)
389 zonkMatch env (L loc (Match pats _ grhss))
390 = do { (env1, new_pats) <- zonkPats env pats
391 ; new_grhss <- zonkGRHSs env1 grhss
392 ; return (L loc (Match new_pats Nothing new_grhss)) }
394 -------------------------------------------------------------------------
395 zonkGRHSs :: ZonkEnv -> GRHSs TcId -> TcM (GRHSs Id)
397 zonkGRHSs env (GRHSs grhss binds)
398 = zonkLocalBinds env binds `thenM` \ (new_env, new_binds) ->
400 zonk_grhs (GRHS guarded rhs)
401 = zonkStmts new_env guarded `thenM` \ (env2, new_guarded) ->
402 zonkLExpr env2 rhs `thenM` \ new_rhs ->
403 returnM (GRHS new_guarded new_rhs)
405 mappM (wrapLocM zonk_grhs) grhss `thenM` \ new_grhss ->
406 returnM (GRHSs new_grhss new_binds)
409 %************************************************************************
411 \subsection[BackSubst-HsExpr]{Running a zonkitution over a TypeCheckedExpr}
413 %************************************************************************
416 zonkLExprs :: ZonkEnv -> [LHsExpr TcId] -> TcM [LHsExpr Id]
417 zonkLExpr :: ZonkEnv -> LHsExpr TcId -> TcM (LHsExpr Id)
418 zonkExpr :: ZonkEnv -> HsExpr TcId -> TcM (HsExpr Id)
420 zonkLExprs env exprs = mappM (zonkLExpr env) exprs
421 zonkLExpr env expr = wrapLocM (zonkExpr env) expr
423 zonkExpr env (HsVar id)
424 = returnM (HsVar (zonkIdOcc env id))
426 zonkExpr env (HsIPVar id)
427 = returnM (HsIPVar (mapIPName (zonkIdOcc env) id))
429 zonkExpr env (HsLit (HsRat f ty))
430 = zonkTcTypeToType env ty `thenM` \ new_ty ->
431 returnM (HsLit (HsRat f new_ty))
433 zonkExpr _ (HsLit lit)
434 = returnM (HsLit lit)
436 zonkExpr env (HsOverLit lit)
437 = do { lit' <- zonkOverLit env lit
438 ; return (HsOverLit lit') }
440 zonkExpr env (HsLam matches)
441 = zonkMatchGroup env matches `thenM` \ new_matches ->
442 returnM (HsLam new_matches)
444 zonkExpr env (HsApp e1 e2)
445 = zonkLExpr env e1 `thenM` \ new_e1 ->
446 zonkLExpr env e2 `thenM` \ new_e2 ->
447 returnM (HsApp new_e1 new_e2)
449 zonkExpr env (HsBracketOut body bs)
450 = mappM zonk_b bs `thenM` \ bs' ->
451 returnM (HsBracketOut body bs')
453 zonk_b (n,e) = zonkLExpr env e `thenM` \ e' ->
456 zonkExpr _ (HsSpliceE s) = WARN( True, ppr s ) -- Should not happen
457 returnM (HsSpliceE s)
459 zonkExpr env (OpApp e1 op fixity e2)
460 = zonkLExpr env e1 `thenM` \ new_e1 ->
461 zonkLExpr env op `thenM` \ new_op ->
462 zonkLExpr env e2 `thenM` \ new_e2 ->
463 returnM (OpApp new_e1 new_op fixity new_e2)
465 zonkExpr env (NegApp expr op)
466 = zonkLExpr env expr `thenM` \ new_expr ->
467 zonkExpr env op `thenM` \ new_op ->
468 returnM (NegApp new_expr new_op)
470 zonkExpr env (HsPar e)
471 = zonkLExpr env e `thenM` \new_e ->
472 returnM (HsPar new_e)
474 zonkExpr env (SectionL expr op)
475 = zonkLExpr env expr `thenM` \ new_expr ->
476 zonkLExpr env op `thenM` \ new_op ->
477 returnM (SectionL new_expr new_op)
479 zonkExpr env (SectionR op expr)
480 = zonkLExpr env op `thenM` \ new_op ->
481 zonkLExpr env expr `thenM` \ new_expr ->
482 returnM (SectionR new_op new_expr)
484 zonkExpr env (HsCase expr ms)
485 = zonkLExpr env expr `thenM` \ new_expr ->
486 zonkMatchGroup env ms `thenM` \ new_ms ->
487 returnM (HsCase new_expr new_ms)
489 zonkExpr env (HsIf e1 e2 e3)
490 = zonkLExpr env e1 `thenM` \ new_e1 ->
491 zonkLExpr env e2 `thenM` \ new_e2 ->
492 zonkLExpr env e3 `thenM` \ new_e3 ->
493 returnM (HsIf new_e1 new_e2 new_e3)
495 zonkExpr env (HsLet binds expr)
496 = zonkLocalBinds env binds `thenM` \ (new_env, new_binds) ->
497 zonkLExpr new_env expr `thenM` \ new_expr ->
498 returnM (HsLet new_binds new_expr)
500 zonkExpr env (HsDo do_or_lc stmts body ty)
501 = zonkStmts env stmts `thenM` \ (new_env, new_stmts) ->
502 zonkLExpr new_env body `thenM` \ new_body ->
503 zonkTcTypeToType env ty `thenM` \ new_ty ->
504 returnM (HsDo (zonkDo env do_or_lc)
505 new_stmts new_body new_ty)
507 zonkExpr env (ExplicitList ty exprs)
508 = zonkTcTypeToType env ty `thenM` \ new_ty ->
509 zonkLExprs env exprs `thenM` \ new_exprs ->
510 returnM (ExplicitList new_ty new_exprs)
512 zonkExpr env (ExplicitPArr ty exprs)
513 = zonkTcTypeToType env ty `thenM` \ new_ty ->
514 zonkLExprs env exprs `thenM` \ new_exprs ->
515 returnM (ExplicitPArr new_ty new_exprs)
517 zonkExpr env (ExplicitTuple exprs boxed)
518 = zonkLExprs env exprs `thenM` \ new_exprs ->
519 returnM (ExplicitTuple new_exprs boxed)
521 zonkExpr env (RecordCon data_con con_expr rbinds)
522 = do { new_con_expr <- zonkExpr env con_expr
523 ; new_rbinds <- zonkRecFields env rbinds
524 ; return (RecordCon data_con new_con_expr new_rbinds) }
526 zonkExpr env (RecordUpd expr rbinds cons in_tys out_tys)
527 = do { new_expr <- zonkLExpr env expr
528 ; new_in_tys <- mapM (zonkTcTypeToType env) in_tys
529 ; new_out_tys <- mapM (zonkTcTypeToType env) out_tys
530 ; new_rbinds <- zonkRecFields env rbinds
531 ; return (RecordUpd new_expr new_rbinds cons new_in_tys new_out_tys) }
533 zonkExpr env (ExprWithTySigOut e ty)
534 = do { e' <- zonkLExpr env e
535 ; return (ExprWithTySigOut e' ty) }
537 zonkExpr _ (ExprWithTySig _ _) = panic "zonkExpr env:ExprWithTySig"
539 zonkExpr env (ArithSeq expr info)
540 = zonkExpr env expr `thenM` \ new_expr ->
541 zonkArithSeq env info `thenM` \ new_info ->
542 returnM (ArithSeq new_expr new_info)
544 zonkExpr env (PArrSeq expr info)
545 = zonkExpr env expr `thenM` \ new_expr ->
546 zonkArithSeq env info `thenM` \ new_info ->
547 returnM (PArrSeq new_expr new_info)
549 zonkExpr env (HsSCC lbl expr)
550 = zonkLExpr env expr `thenM` \ new_expr ->
551 returnM (HsSCC lbl new_expr)
553 zonkExpr env (HsTickPragma info expr)
554 = zonkLExpr env expr `thenM` \ new_expr ->
555 returnM (HsTickPragma info new_expr)
557 -- hdaume: core annotations
558 zonkExpr env (HsCoreAnn lbl expr)
559 = zonkLExpr env expr `thenM` \ new_expr ->
560 returnM (HsCoreAnn lbl new_expr)
562 -- arrow notation extensions
563 zonkExpr env (HsProc pat body)
564 = do { (env1, new_pat) <- zonkPat env pat
565 ; new_body <- zonkCmdTop env1 body
566 ; return (HsProc new_pat new_body) }
568 zonkExpr env (HsArrApp e1 e2 ty ho rl)
569 = zonkLExpr env e1 `thenM` \ new_e1 ->
570 zonkLExpr env e2 `thenM` \ new_e2 ->
571 zonkTcTypeToType env ty `thenM` \ new_ty ->
572 returnM (HsArrApp new_e1 new_e2 new_ty ho rl)
574 zonkExpr env (HsArrForm op fixity args)
575 = zonkLExpr env op `thenM` \ new_op ->
576 mappM (zonkCmdTop env) args `thenM` \ new_args ->
577 returnM (HsArrForm new_op fixity new_args)
579 zonkExpr env (HsWrap co_fn expr)
580 = zonkCoFn env co_fn `thenM` \ (env1, new_co_fn) ->
581 zonkExpr env1 expr `thenM` \ new_expr ->
582 return (HsWrap new_co_fn new_expr)
584 zonkExpr _ expr = pprPanic "zonkExpr" (ppr expr)
586 zonkCmdTop :: ZonkEnv -> LHsCmdTop TcId -> TcM (LHsCmdTop Id)
587 zonkCmdTop env cmd = wrapLocM (zonk_cmd_top env) cmd
589 zonk_cmd_top :: ZonkEnv -> HsCmdTop TcId -> TcM (HsCmdTop Id)
590 zonk_cmd_top env (HsCmdTop cmd stack_tys ty ids)
591 = zonkLExpr env cmd `thenM` \ new_cmd ->
592 zonkTcTypeToTypes env stack_tys `thenM` \ new_stack_tys ->
593 zonkTcTypeToType env ty `thenM` \ new_ty ->
594 mapSndM (zonkExpr env) ids `thenM` \ new_ids ->
595 returnM (HsCmdTop new_cmd new_stack_tys new_ty new_ids)
597 -------------------------------------------------------------------------
598 zonkCoFn :: ZonkEnv -> HsWrapper -> TcM (ZonkEnv, HsWrapper)
599 zonkCoFn env WpHole = return (env, WpHole)
600 zonkCoFn env WpInline = return (env, WpInline)
601 zonkCoFn env (WpCompose c1 c2) = do { (env1, c1') <- zonkCoFn env c1
602 ; (env2, c2') <- zonkCoFn env1 c2
603 ; return (env2, WpCompose c1' c2') }
604 zonkCoFn env (WpCast co) = do { co' <- zonkTcTypeToType env co
605 ; return (env, WpCast co') }
606 zonkCoFn env (WpLam id) = do { id' <- zonkDictBndr env id
607 ; let env1 = extendZonkEnv1 env id'
608 ; return (env1, WpLam id') }
609 zonkCoFn env (WpTyLam tv) = ASSERT( isImmutableTyVar tv )
610 do { return (env, WpTyLam tv) }
611 zonkCoFn env (WpApp id) = do { return (env, WpApp (zonkIdOcc env id)) }
612 zonkCoFn env (WpTyApp ty) = do { ty' <- zonkTcTypeToType env ty
613 ; return (env, WpTyApp ty') }
614 zonkCoFn env (WpLet bs) = do { (env1, bs') <- zonkRecMonoBinds env bs
615 ; return (env1, WpLet bs') }
618 -------------------------------------------------------------------------
619 zonkDo :: ZonkEnv -> HsStmtContext Name -> HsStmtContext Name
620 -- Only used for 'do', so the only Ids are in a MDoExpr table
621 zonkDo env (MDoExpr tbl) = MDoExpr (mapSnd (zonkIdOcc env) tbl)
622 zonkDo _ do_or_lc = do_or_lc
624 -------------------------------------------------------------------------
625 zonkOverLit :: ZonkEnv -> HsOverLit TcId -> TcM (HsOverLit Id)
626 zonkOverLit env lit@(OverLit { ol_witness = e, ol_type = ty })
627 = do { ty' <- zonkTcTypeToType env ty
628 ; e' <- zonkExpr env e
629 ; return (lit { ol_witness = e', ol_type = ty' }) }
631 -------------------------------------------------------------------------
632 zonkArithSeq :: ZonkEnv -> ArithSeqInfo TcId -> TcM (ArithSeqInfo Id)
634 zonkArithSeq env (From e)
635 = zonkLExpr env e `thenM` \ new_e ->
638 zonkArithSeq env (FromThen e1 e2)
639 = zonkLExpr env e1 `thenM` \ new_e1 ->
640 zonkLExpr env e2 `thenM` \ new_e2 ->
641 returnM (FromThen new_e1 new_e2)
643 zonkArithSeq env (FromTo e1 e2)
644 = zonkLExpr env e1 `thenM` \ new_e1 ->
645 zonkLExpr env e2 `thenM` \ new_e2 ->
646 returnM (FromTo new_e1 new_e2)
648 zonkArithSeq env (FromThenTo e1 e2 e3)
649 = zonkLExpr env e1 `thenM` \ new_e1 ->
650 zonkLExpr env e2 `thenM` \ new_e2 ->
651 zonkLExpr env e3 `thenM` \ new_e3 ->
652 returnM (FromThenTo new_e1 new_e2 new_e3)
655 -------------------------------------------------------------------------
656 zonkStmts :: ZonkEnv -> [LStmt TcId] -> TcM (ZonkEnv, [LStmt Id])
657 zonkStmts env [] = return (env, [])
658 zonkStmts env (s:ss) = do { (env1, s') <- wrapLocSndM (zonkStmt env) s
659 ; (env2, ss') <- zonkStmts env1 ss
660 ; return (env2, s' : ss') }
662 zonkStmt :: ZonkEnv -> Stmt TcId -> TcM (ZonkEnv, Stmt Id)
663 zonkStmt env (ParStmt stmts_w_bndrs)
664 = mappM zonk_branch stmts_w_bndrs `thenM` \ new_stmts_w_bndrs ->
666 new_binders = concat (map snd new_stmts_w_bndrs)
667 env1 = extendZonkEnv env new_binders
669 return (env1, ParStmt new_stmts_w_bndrs)
671 zonk_branch (stmts, bndrs) = zonkStmts env stmts `thenM` \ (env1, new_stmts) ->
672 returnM (new_stmts, zonkIdOccs env1 bndrs)
674 zonkStmt env (RecStmt segStmts lvs rvs rets binds)
675 = zonkIdBndrs env rvs `thenM` \ new_rvs ->
677 env1 = extendZonkEnv env new_rvs
679 zonkStmts env1 segStmts `thenM` \ (env2, new_segStmts) ->
680 -- Zonk the ret-expressions in an envt that
681 -- has the polymorphic bindings in the envt
682 mapM (zonkExpr env2) rets `thenM` \ new_rets ->
684 new_lvs = zonkIdOccs env2 lvs
685 env3 = extendZonkEnv env new_lvs -- Only the lvs are needed
687 zonkRecMonoBinds env3 binds `thenM` \ (env4, new_binds) ->
688 returnM (env4, RecStmt new_segStmts new_lvs new_rvs new_rets new_binds)
690 zonkStmt env (ExprStmt expr then_op ty)
691 = zonkLExpr env expr `thenM` \ new_expr ->
692 zonkExpr env then_op `thenM` \ new_then ->
693 zonkTcTypeToType env ty `thenM` \ new_ty ->
694 returnM (env, ExprStmt new_expr new_then new_ty)
696 zonkStmt env (TransformStmt (stmts, binders) usingExpr maybeByExpr)
697 = do { (env', stmts') <- zonkStmts env stmts
698 ; let binders' = zonkIdOccs env' binders
699 ; usingExpr' <- zonkLExpr env' usingExpr
700 ; maybeByExpr' <- zonkMaybeLExpr env' maybeByExpr
701 ; return (env', TransformStmt (stmts', binders') usingExpr' maybeByExpr') }
703 zonkStmt env (GroupStmt (stmts, binderMap) groupByClause)
704 = do { (env', stmts') <- zonkStmts env stmts
705 ; binderMap' <- mappM (zonkBinderMapEntry env') binderMap
707 case groupByClause of
708 GroupByNothing usingExpr -> (zonkLExpr env' usingExpr) >>= (return . GroupByNothing)
709 GroupBySomething eitherUsingExpr byExpr -> do
710 eitherUsingExpr' <- mapEitherM (zonkLExpr env') (zonkExpr env') eitherUsingExpr
711 byExpr' <- zonkLExpr env' byExpr
712 return $ GroupBySomething eitherUsingExpr' byExpr'
714 ; let env'' = extendZonkEnv env' (map snd binderMap')
715 ; return (env'', GroupStmt (stmts', binderMap') groupByClause') }
717 mapEitherM f g x = do
719 Left a -> f a >>= (return . Left)
720 Right b -> g b >>= (return . Right)
722 zonkBinderMapEntry env (oldBinder, newBinder) = do
723 let oldBinder' = zonkIdOcc env oldBinder
724 newBinder' <- zonkIdBndr env newBinder
725 return (oldBinder', newBinder')
727 zonkStmt env (LetStmt binds)
728 = zonkLocalBinds env binds `thenM` \ (env1, new_binds) ->
729 returnM (env1, LetStmt new_binds)
731 zonkStmt env (BindStmt pat expr bind_op fail_op)
732 = do { new_expr <- zonkLExpr env expr
733 ; (env1, new_pat) <- zonkPat env pat
734 ; new_bind <- zonkExpr env bind_op
735 ; new_fail <- zonkExpr env fail_op
736 ; return (env1, BindStmt new_pat new_expr new_bind new_fail) }
738 zonkMaybeLExpr :: ZonkEnv -> Maybe (LHsExpr TcId) -> TcM (Maybe (LHsExpr Id))
739 zonkMaybeLExpr _ Nothing = return Nothing
740 zonkMaybeLExpr env (Just e) = (zonkLExpr env e) >>= (return . Just)
743 -------------------------------------------------------------------------
744 zonkRecFields :: ZonkEnv -> HsRecordBinds TcId -> TcM (HsRecordBinds TcId)
745 zonkRecFields env (HsRecFields flds dd)
746 = do { flds' <- mappM zonk_rbind flds
747 ; return (HsRecFields flds' dd) }
750 = do { new_expr <- zonkLExpr env (hsRecFieldArg fld)
751 ; return (fld { hsRecFieldArg = new_expr }) }
752 -- Field selectors have declared types; hence no zonking
754 -------------------------------------------------------------------------
755 mapIPNameTc :: (a -> TcM b) -> IPName a -> TcM (IPName b)
756 mapIPNameTc f (IPName n) = f n `thenM` \ r -> returnM (IPName r)
760 %************************************************************************
762 \subsection[BackSubst-Pats]{Patterns}
764 %************************************************************************
767 zonkPat :: ZonkEnv -> OutPat TcId -> TcM (ZonkEnv, OutPat Id)
768 -- Extend the environment as we go, because it's possible for one
769 -- pattern to bind something that is used in another (inside or
771 zonkPat env pat = wrapLocSndM (zonk_pat env) pat
773 zonk_pat :: ZonkEnv -> Pat TcId -> TcM (ZonkEnv, Pat Id)
774 zonk_pat env (ParPat p)
775 = do { (env', p') <- zonkPat env p
776 ; return (env', ParPat p') }
778 zonk_pat env (WildPat ty)
779 = do { ty' <- zonkTcTypeToType env ty
780 ; return (env, WildPat ty') }
782 zonk_pat env (VarPat v)
783 = do { v' <- zonkIdBndr env v
784 ; return (extendZonkEnv1 env v', VarPat v') }
786 zonk_pat env (VarPatOut v binds)
787 = do { v' <- zonkIdBndr env v
788 ; (env', binds') <- zonkRecMonoBinds (extendZonkEnv1 env v') binds
789 ; returnM (env', VarPatOut v' binds') }
791 zonk_pat env (LazyPat pat)
792 = do { (env', pat') <- zonkPat env pat
793 ; return (env', LazyPat pat') }
795 zonk_pat env (BangPat pat)
796 = do { (env', pat') <- zonkPat env pat
797 ; return (env', BangPat pat') }
799 zonk_pat env (AsPat (L loc v) pat)
800 = do { v' <- zonkIdBndr env v
801 ; (env', pat') <- zonkPat (extendZonkEnv1 env v') pat
802 ; return (env', AsPat (L loc v') pat') }
804 zonk_pat env (ViewPat expr pat ty)
805 = do { expr' <- zonkLExpr env expr
806 ; (env', pat') <- zonkPat env pat
807 ; return (env', ViewPat expr' pat' ty) }
809 zonk_pat env (ListPat pats ty)
810 = do { ty' <- zonkTcTypeToType env ty
811 ; (env', pats') <- zonkPats env pats
812 ; return (env', ListPat pats' ty') }
814 zonk_pat env (PArrPat pats ty)
815 = do { ty' <- zonkTcTypeToType env ty
816 ; (env', pats') <- zonkPats env pats
817 ; return (env', PArrPat pats' ty') }
819 zonk_pat env (TuplePat pats boxed ty)
820 = do { ty' <- zonkTcTypeToType env ty
821 ; (env', pats') <- zonkPats env pats
822 ; return (env', TuplePat pats' boxed ty') }
824 zonk_pat env p@(ConPatOut { pat_ty = ty, pat_dicts = dicts, pat_binds = binds, pat_args = args })
825 = ASSERT( all isImmutableTyVar (pat_tvs p) )
826 do { new_ty <- zonkTcTypeToType env ty
827 ; new_dicts <- zonkDictBndrs env dicts
828 ; let env1 = extendZonkEnv env new_dicts
829 ; (env2, new_binds) <- zonkRecMonoBinds env1 binds
830 ; (env', new_args) <- zonkConStuff env2 args
831 ; returnM (env', p { pat_ty = new_ty, pat_dicts = new_dicts,
832 pat_binds = new_binds, pat_args = new_args }) }
834 zonk_pat env (LitPat lit) = return (env, LitPat lit)
836 zonk_pat env (SigPatOut pat ty)
837 = do { ty' <- zonkTcTypeToType env ty
838 ; (env', pat') <- zonkPat env pat
839 ; return (env', SigPatOut pat' ty') }
841 zonk_pat env (NPat lit mb_neg eq_expr)
842 = do { lit' <- zonkOverLit env lit
843 ; mb_neg' <- case mb_neg of
844 Nothing -> return Nothing
845 Just neg -> do { neg' <- zonkExpr env neg
846 ; return (Just neg') }
847 ; eq_expr' <- zonkExpr env eq_expr
848 ; return (env, NPat lit' mb_neg' eq_expr') }
850 zonk_pat env (NPlusKPat (L loc n) lit e1 e2)
851 = do { n' <- zonkIdBndr env n
852 ; lit' <- zonkOverLit env lit
853 ; e1' <- zonkExpr env e1
854 ; e2' <- zonkExpr env e2
855 ; return (extendZonkEnv1 env n', NPlusKPat (L loc n') lit' e1' e2') }
857 zonk_pat env (CoPat co_fn pat ty)
858 = do { (env', co_fn') <- zonkCoFn env co_fn
859 ; (env'', pat') <- zonkPat env' (noLoc pat)
860 ; ty' <- zonkTcTypeToType env'' ty
861 ; return (env'', CoPat co_fn' (unLoc pat') ty') }
863 zonk_pat _ pat = pprPanic "zonk_pat" (ppr pat)
865 ---------------------------
866 zonkConStuff :: ZonkEnv
867 -> HsConDetails (OutPat TcId) (HsRecFields id (OutPat TcId))
869 HsConDetails (OutPat Id) (HsRecFields id (OutPat Id)))
870 zonkConStuff env (PrefixCon pats)
871 = do { (env', pats') <- zonkPats env pats
872 ; return (env', PrefixCon pats') }
874 zonkConStuff env (InfixCon p1 p2)
875 = do { (env1, p1') <- zonkPat env p1
876 ; (env', p2') <- zonkPat env1 p2
877 ; return (env', InfixCon p1' p2') }
879 zonkConStuff env (RecCon (HsRecFields rpats dd))
880 = do { (env', pats') <- zonkPats env (map hsRecFieldArg rpats)
881 ; let rpats' = zipWith (\rp p' -> rp { hsRecFieldArg = p' }) rpats pats'
882 ; returnM (env', RecCon (HsRecFields rpats' dd)) }
883 -- Field selectors have declared types; hence no zonking
885 ---------------------------
886 zonkPats :: ZonkEnv -> [OutPat TcId] -> TcM (ZonkEnv, [OutPat Id])
887 zonkPats env [] = return (env, [])
888 zonkPats env (pat:pats) = do { (env1, pat') <- zonkPat env pat
889 ; (env', pats') <- zonkPats env1 pats
890 ; return (env', pat':pats') }
893 %************************************************************************
895 \subsection[BackSubst-Foreign]{Foreign exports}
897 %************************************************************************
901 zonkForeignExports :: ZonkEnv -> [LForeignDecl TcId] -> TcM [LForeignDecl Id]
902 zonkForeignExports env ls = mappM (wrapLocM (zonkForeignExport env)) ls
904 zonkForeignExport :: ZonkEnv -> ForeignDecl TcId -> TcM (ForeignDecl Id)
905 zonkForeignExport env (ForeignExport i _hs_ty spec) =
906 returnM (ForeignExport (fmap (zonkIdOcc env) i) undefined spec)
907 zonkForeignExport _ for_imp
908 = returnM for_imp -- Foreign imports don't need zonking
912 zonkRules :: ZonkEnv -> [LRuleDecl TcId] -> TcM [LRuleDecl Id]
913 zonkRules env rs = mappM (wrapLocM (zonkRule env)) rs
915 zonkRule :: ZonkEnv -> RuleDecl TcId -> TcM (RuleDecl Id)
916 zonkRule env (HsRule name act (vars{-::[RuleBndr TcId]-}) lhs fv_lhs rhs fv_rhs)
917 = mappM zonk_bndr vars `thenM` \ new_bndrs ->
918 newMutVar emptyVarSet `thenM` \ unbound_tv_set ->
920 env_rhs = extendZonkEnv env [id | b <- new_bndrs, let id = unLoc b, isId id]
921 -- Type variables don't need an envt
922 -- They are bound through the mutable mechanism
924 env_lhs = setZonkType env_rhs (zonkTypeCollecting unbound_tv_set)
925 -- We need to gather the type variables mentioned on the LHS so we can
926 -- quantify over them. Example:
932 -- {-# RULES "myrule" foo C = 1 #-}
934 -- After type checking the LHS becomes (foo a (C a))
935 -- and we do not want to zap the unbound tyvar 'a' to (), because
936 -- that limits the applicability of the rule. Instead, we
937 -- want to quantify over it!
939 -- It's easiest to find the free tyvars here. Attempts to do so earlier
940 -- are tiresome, because (a) the data type is big and (b) finding the
941 -- free type vars of an expression is necessarily monadic operation.
942 -- (consider /\a -> f @ b, where b is side-effected to a)
944 zonkLExpr env_lhs lhs `thenM` \ new_lhs ->
945 zonkLExpr env_rhs rhs `thenM` \ new_rhs ->
947 readMutVar unbound_tv_set `thenM` \ unbound_tvs ->
949 final_bndrs :: [Located Var]
950 final_bndrs = map noLoc (varSetElems unbound_tvs) ++ new_bndrs
952 returnM (HsRule name act (map RuleBndr final_bndrs) new_lhs fv_lhs new_rhs fv_rhs)
953 -- I hate this map RuleBndr stuff
955 zonk_bndr (RuleBndr v)
956 | isId (unLoc v) = wrapLocM (zonkIdBndr env) v
957 | otherwise = ASSERT( isImmutableTyVar (unLoc v) )
959 zonk_bndr (RuleBndrSig {}) = panic "zonk_bndr RuleBndrSig"
963 %************************************************************************
965 \subsection[BackSubst-Foreign]{Foreign exports}
967 %************************************************************************
970 zonkTcTypeToType :: ZonkEnv -> TcType -> TcM Type
971 zonkTcTypeToType (ZonkEnv zonk_ty _) ty = zonk_ty ty
973 zonkTcTypeToTypes :: ZonkEnv -> [TcType] -> TcM [Type]
974 zonkTcTypeToTypes env tys = mapM (zonkTcTypeToType env) tys
976 zonkTypeCollecting :: TcRef TyVarSet -> TcType -> TcM Type
977 -- This variant collects unbound type variables in a mutable variable
978 zonkTypeCollecting unbound_tv_set
979 = zonkType zonk_unbound_tyvar
981 zonk_unbound_tyvar tv
982 = zonkQuantifiedTyVar tv `thenM` \ tv' ->
983 readMutVar unbound_tv_set `thenM` \ tv_set ->
984 writeMutVar unbound_tv_set (extendVarSet tv_set tv') `thenM_`
985 return (mkTyVarTy tv')
987 zonkTypeZapping :: TcType -> TcM Type
988 -- This variant is used for everything except the LHS of rules
989 -- It zaps unbound type variables to (), or some other arbitrary type
991 = zonkType zonk_unbound_tyvar ty
993 -- Zonk a mutable but unbound type variable to an arbitrary type
994 -- We know it's unbound even though we don't carry an environment,
995 -- because at the binding site for a type variable we bind the
996 -- mutable tyvar to a fresh immutable one. So the mutable store
997 -- plays the role of an environment. If we come across a mutable
998 -- type variable that isn't so bound, it must be completely free.
999 zonk_unbound_tyvar tv = do { ty <- mkArbitraryType warn tv
1000 ; writeMetaTyVar tv ty
1003 warn span msg = setSrcSpan span (addWarnTc msg)
1006 {- Note [Strangely-kinded void TyCons]
1007 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1008 See Trac #959 for more examples
1010 When the type checker finds a type variable with no binding, which
1011 means it can be instantiated with an arbitrary type, it usually
1012 instantiates it to Void. Eg.
1016 length Void (Nil Void)
1018 But in really obscure programs, the type variable might have a kind
1019 other than *, so we need to invent a suitably-kinded type.
1024 Tuple for kind *->...*->*
1026 which deals with most cases. (Previously, it only dealt with
1029 In the other cases, it just makes up a TyCon with a suitable kind. If
1030 this gets into an interface file, anyone reading that file won't
1031 understand it. This is fixable (by making the client of the interface
1032 file make up a TyCon too) but it is tiresome and never happens, so I
1035 Meanwhile I have now fixed GHC to emit a civilized warning.
1038 mkArbitraryType :: (SrcSpan -> SDoc -> TcRnIf g l a) -- How to complain
1040 -> TcRnIf g l Type -- Used by desugarer too
1041 -- Make up an arbitrary type whose kind is the same as the tyvar.
1042 -- We'll use this to instantiate the (unbound) tyvar.
1044 -- Also used by the desugarer; hence the (tiresome) parameter
1045 -- to use when generating a warning
1046 mkArbitraryType warn tv
1047 | liftedTypeKind `isSubKind` kind -- The vastly common case
1049 | eqKind kind (tyConKind anyPrimTyCon1) -- *->*
1050 = return (mkTyConApp anyPrimTyCon1 []) -- No tuples this size
1051 | all isLiftedTypeKind args -- *-> ... ->*->*
1052 , isLiftedTypeKind res -- Horrible hack to make less use
1053 = return (mkTyConApp tup_tc []) -- of mkAnyPrimTyCon
1055 = do { warn (getSrcSpan tv) msg
1056 ; return (mkTyConApp (mkAnyPrimTyCon (getUnique tv) kind) []) }
1057 -- Same name as the tyvar, apart from making it start with a colon (sigh)
1058 -- I dread to think what will happen if this gets out into an
1059 -- interface file. Catastrophe likely. Major sigh.
1062 (args,res) = splitKindFunTys kind
1063 tup_tc = tupleTyCon Boxed (length args)
1065 msg = vcat [ hang (ptext (sLit "Inventing strangely-kinded Any TyCon"))
1066 2 (ptext (sLit "of kind") <+> quotes (ppr kind))
1067 , nest 2 (ptext (sLit "from an instantiation of type variable") <+> quotes (ppr tv))
1068 , ptext (sLit "This warning can be suppressed by a type signature fixing") <+> quotes (ppr tv)
1069 , nest 2 (ptext (sLit "but is harmless without -O (and usually harmless anyway)."))
1070 , ptext (sLit "See http://hackage.haskell.org/trac/ghc/ticket/959 for details") ]