2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[TcExpr]{Typecheck an expression}
7 #include "HsVersions.h"
9 module TcExpr ( tcExpr ) where
13 import HsSyn ( HsExpr(..), Qual(..), Stmt(..),
14 HsBinds(..), Bind(..), MonoBinds(..),
15 ArithSeqInfo(..), HsLit(..), Sig, GRHSsAndBinds,
16 Match, Fake, InPat, OutPat, PolyType,
17 irrefutablePat, collectPatBinders )
18 import RnHsSyn ( RenamedHsExpr(..), RenamedQual(..), RenamedStmt(..) )
19 import TcHsSyn ( TcExpr(..), TcQual(..), TcStmt(..), TcIdOcc(..) )
22 import Inst ( Inst, InstOrigin(..), OverloadedLit(..),
23 LIE(..), emptyLIE, plusLIE, newOverloadedLit,
24 newMethod, newMethodWithGivenTy, newDicts )
25 import TcBinds ( tcBindsAndThen )
26 import TcEnv ( tcLookupLocalValue, tcLookupGlobalValue, tcLookupClassByKey,
27 tcLookupGlobalValueByKey, newMonoIds, tcGetGlobalTyVars )
28 import TcMatches ( tcMatchesCase, tcMatch )
29 import TcMonoType ( tcPolyType )
30 import TcPat ( tcPat )
31 import TcSimplify ( tcSimplifyAndCheck, tcSimplifyRank2 )
32 import TcType ( TcType(..), TcMaybe(..), tcReadTyVar,
33 tcInstType, tcInstTcType,
34 tcInstTyVar, newTyVarTy, zonkTcTyVars )
36 import Class ( Class(..), getClassSig )
37 import Id ( Id(..), GenId, idType )
38 import Kind ( Kind, mkBoxedTypeKind, mkTypeKind )
39 import GenSpecEtc ( checkSigTyVars, checkSigTyVarsGivenGlobals, specTy )
40 import PrelInfo ( intPrimTy, charPrimTy, doublePrimTy,
41 floatPrimTy, addrPrimTy, addrTy,
42 boolTy, charTy, stringTy, mkListTy,
43 mkTupleTy, mkPrimIoTy )
44 import Type ( mkFunTy, mkAppTy, mkTyVarTy,
45 getTyVar_maybe, getFunTy_maybe,
46 splitForAllTy, splitRhoTy, splitSigmaTy,
47 isTauTy, mkFunTys, tyVarsOfType, getForAllTy_maybe )
48 import TyVar ( GenTyVar, TyVarSet(..), unionTyVarSets, tyVarListToSet )
49 import Unify ( unifyTauTy, unifyTauTyList, unifyTauTyLists )
50 import Unique ( Unique, cCallableClassKey, cReturnableClassKey,
51 enumFromClassOpKey, enumFromThenClassOpKey,
52 enumFromToClassOpKey, enumFromThenToClassOpKey,
53 monadClassKey, monadZeroClassKey )
55 import Name ( Name ) -- Instance
56 import PprType ( GenType, GenTyVar ) -- Instances
57 import Maybes ( maybeToBool )
63 tcExpr :: RenamedHsExpr -> TcM s (TcExpr s, LIE s, TcType s)
66 %************************************************************************
68 \subsection{The TAUT rules for variables}
70 %************************************************************************
74 = tcId name `thenTc` \ (expr', lie, res_ty) ->
76 -- Check that the result type doesn't have any nested for-alls.
77 -- For example, a "build" on its own is no good; it must be
78 -- applied to something.
79 checkTc (isTauTy res_ty)
80 (lurkingRank2Err name res_ty) `thenTc_`
82 returnTc (expr', lie, res_ty)
85 %************************************************************************
89 %************************************************************************
94 tcExpr (HsLit (HsInt i))
95 = newTyVarTy mkBoxedTypeKind `thenNF_Tc` \ ty ->
97 newOverloadedLit (LiteralOrigin (HsInt i))
98 (OverloadedIntegral i)
99 ty `thenNF_Tc` \ (lie, over_lit_id) ->
101 returnTc (HsVar over_lit_id, lie, ty)
103 tcExpr (HsLit (HsFrac f))
104 = newTyVarTy mkBoxedTypeKind `thenNF_Tc` \ ty ->
106 newOverloadedLit (LiteralOrigin (HsFrac f))
107 (OverloadedFractional f)
108 ty `thenNF_Tc` \ (lie, over_lit_id) ->
110 returnTc (HsVar over_lit_id, lie, ty)
112 tcExpr (HsLit lit@(HsLitLit s))
113 = tcLookupClassByKey cCallableClassKey `thenNF_Tc` \ cCallableClass ->
114 newTyVarTy mkBoxedTypeKind `thenNF_Tc` \ ty ->
115 newDicts (LitLitOrigin (_UNPK_ s))
116 [(cCallableClass, ty)] `thenNF_Tc` \ (dicts, _) ->
117 returnTc (HsLitOut lit ty, dicts, ty)
123 tcExpr (HsLit lit@(HsCharPrim c))
124 = returnTc (HsLitOut lit charPrimTy, emptyLIE, charPrimTy)
126 tcExpr (HsLit lit@(HsStringPrim s))
127 = returnTc (HsLitOut lit addrPrimTy, emptyLIE, addrPrimTy)
129 tcExpr (HsLit lit@(HsIntPrim i))
130 = returnTc (HsLitOut lit intPrimTy, emptyLIE, intPrimTy)
132 tcExpr (HsLit lit@(HsFloatPrim f))
133 = returnTc (HsLitOut lit floatPrimTy, emptyLIE, floatPrimTy)
135 tcExpr (HsLit lit@(HsDoublePrim d))
136 = returnTc (HsLitOut lit doublePrimTy, emptyLIE, doublePrimTy)
139 Unoverloaded literals:
142 tcExpr (HsLit lit@(HsChar c))
143 = returnTc (HsLitOut lit charTy, emptyLIE, charTy)
145 tcExpr (HsLit lit@(HsString str))
146 = returnTc (HsLitOut lit stringTy, emptyLIE, stringTy)
149 %************************************************************************
151 \subsection{Other expression forms}
153 %************************************************************************
157 = tcMatch match `thenTc` \ (match',lie,ty) ->
158 returnTc (HsLam match', lie, ty)
160 tcExpr (HsApp e1 e2) = accum e1 [e2]
162 accum (HsApp e1 e2) args = accum e1 (e2:args)
164 = tcApp fun args `thenTc` \ (fun', args', lie, res_ty) ->
165 returnTc (foldl HsApp fun' args', lie, res_ty)
167 -- equivalent to (op e1) e2:
168 tcExpr (OpApp arg1 op arg2)
169 = tcApp op [arg1,arg2] `thenTc` \ (op', [arg1', arg2'], lie, res_ty) ->
170 returnTc (OpApp arg1' op' arg2', lie, res_ty)
173 Note that the operators in sections are expected to be binary, and
174 a type error will occur if they aren't.
177 -- Left sections, equivalent to
184 tcExpr in_expr@(SectionL arg op)
185 = tcApp op [arg] `thenTc` \ (op', [arg'], lie, res_ty) ->
187 -- Check that res_ty is a function type
188 -- Without this check we barf in the desugarer on
190 -- because it tries to desugar to
191 -- f op = \r -> 3 op r
192 -- so (3 `op`) had better be a function!
193 newTyVarTy mkTypeKind `thenNF_Tc` \ ty1 ->
194 newTyVarTy mkTypeKind `thenNF_Tc` \ ty2 ->
195 tcAddErrCtxt (sectionLAppCtxt in_expr) $
196 unifyTauTy (mkFunTy ty1 ty2) res_ty `thenTc_`
198 returnTc (SectionL arg' op', lie, res_ty)
200 -- Right sections, equivalent to \ x -> x op expr, or
203 tcExpr in_expr@(SectionR op expr)
204 = tcExpr op `thenTc` \ (op', lie1, op_ty) ->
205 tcExpr expr `thenTc` \ (expr',lie2, expr_ty) ->
207 newTyVarTy mkTypeKind `thenNF_Tc` \ ty1 ->
208 newTyVarTy mkTypeKind `thenNF_Tc` \ ty2 ->
209 tcAddErrCtxt (sectionRAppCtxt in_expr) $
210 unifyTauTy op_ty (mkFunTys [ty1, expr_ty] ty2) `thenTc_`
212 returnTc (SectionR op' expr', lie1 `plusLIE` lie2, mkFunTy ty1 ty2)
215 The interesting thing about @ccall@ is that it is just a template
216 which we instantiate by filling in details about the types of its
217 argument and result (ie minimal typechecking is performed). So, the
218 basic story is that we allocate a load of type variables (to hold the
219 arg/result types); unify them with the args/result; and store them for
223 tcExpr (CCall lbl args may_gc is_asm ignored_fake_result_ty)
224 = -- Get the callable and returnable classes.
225 tcLookupClassByKey cCallableClassKey `thenNF_Tc` \ cCallableClass ->
226 tcLookupClassByKey cReturnableClassKey `thenNF_Tc` \ cReturnableClass ->
229 new_arg_dict (arg, arg_ty)
230 = newDicts (CCallOrigin (_UNPK_ lbl) (Just arg))
231 [(cCallableClass, arg_ty)] `thenNF_Tc` \ (arg_dicts, _) ->
232 returnNF_Tc arg_dicts -- Actually a singleton bag
234 result_origin = CCallOrigin (_UNPK_ lbl) Nothing {- Not an arg -}
238 tcExprs args `thenTc` \ (args', args_lie, arg_tys) ->
240 -- The argument types can be unboxed or boxed; the result
241 -- type must, however, be boxed since it's an argument to the PrimIO
243 newTyVarTy mkBoxedTypeKind `thenNF_Tc` \ result_ty ->
245 -- Construct the extra insts, which encode the
246 -- constraints on the argument and result types.
247 mapNF_Tc new_arg_dict (args `zip` arg_tys) `thenNF_Tc` \ ccarg_dicts_s ->
248 newDicts result_origin [(cReturnableClass, result_ty)] `thenNF_Tc` \ (ccres_dict, _) ->
250 returnTc (CCall lbl args' may_gc is_asm result_ty,
251 foldr plusLIE ccres_dict ccarg_dicts_s `plusLIE` args_lie,
252 mkPrimIoTy result_ty)
256 tcExpr (HsSCC label expr)
257 = tcExpr expr `thenTc` \ (expr', lie, expr_ty) ->
258 -- No unification. Give SCC the type of expr
259 returnTc (HsSCC label expr', lie, expr_ty)
261 tcExpr (HsLet binds expr)
263 HsLet -- The combiner
264 binds -- Bindings to check
265 (tcExpr expr) -- Typechecker for the expression
267 tcExpr in_expr@(HsCase expr matches src_loc)
268 = tcAddSrcLoc src_loc $
269 tcExpr expr `thenTc` \ (expr',lie1,expr_ty) ->
270 newTyVarTy mkTypeKind `thenNF_Tc` \ result_ty ->
272 tcAddErrCtxt (caseCtxt in_expr) $
273 tcMatchesCase (mkFunTy expr_ty result_ty) matches
274 `thenTc` \ (matches',lie2) ->
276 returnTc (HsCase expr' matches' src_loc, plusLIE lie1 lie2, result_ty)
278 tcExpr (HsIf pred b1 b2 src_loc)
279 = tcAddSrcLoc src_loc $
280 tcExpr pred `thenTc` \ (pred',lie1,predTy) ->
282 tcAddErrCtxt (predCtxt pred) (
283 unifyTauTy predTy boolTy
286 tcExpr b1 `thenTc` \ (b1',lie2,result_ty) ->
287 tcExpr b2 `thenTc` \ (b2',lie3,b2Ty) ->
289 tcAddErrCtxt (branchCtxt b1 b2) $
290 unifyTauTy result_ty b2Ty `thenTc_`
292 returnTc (HsIf pred' b1' b2' src_loc, plusLIE lie1 (plusLIE lie2 lie3), result_ty)
294 tcExpr (ListComp expr quals)
295 = tcListComp expr quals `thenTc` \ ((expr',quals'), lie, ty) ->
296 returnTc (ListComp expr' quals', lie, ty)
300 tcExpr (HsDo stmts src_loc)
301 = -- get the Monad and MonadZero classes
302 -- create type consisting of a fresh monad tyvar
303 tcAddSrcLoc src_loc $
304 tcLookupClassByKey monadClassKey `thenNF_Tc` \ monadClass ->
305 tcLookupClassByKey monadZeroClassKey `thenNF_Tc` \ monadZeroClass ->
307 (tv,_,_) = getClassSig monadClass
309 tcInstTyVar tv `thenNF_Tc` \ m_tyvar ->
311 m = mkTyVarTy m_tyvar
313 tcDoStmts False m stmts `thenTc` \ ((stmts',monad,mzero), lie, do_ty) ->
315 -- create dictionaries for monad and possibly monadzero
317 newDicts DoOrigin [(monadClass, m)]
319 returnNF_Tc (emptyLIE, [panic "TcExpr: MonadZero dictionary"])
320 ) `thenNF_Tc` \ (m_lie, [m_id]) ->
322 newDicts DoOrigin [(monadZeroClass, m)]
324 returnNF_Tc (emptyLIE, [panic "TcExpr: MonadZero dictionary"])
325 ) `thenNF_Tc` \ (mz_lie, [mz_id]) ->
327 returnTc (HsDoOut stmts' m_id mz_id src_loc,
328 lie `plusLIE` m_lie `plusLIE` mz_lie,
333 tcExpr (ExplicitList [])
334 = newTyVarTy mkBoxedTypeKind `thenNF_Tc` \ tyvar_ty ->
335 returnTc (ExplicitListOut tyvar_ty [], emptyLIE, mkListTy tyvar_ty)
338 tcExpr in_expr@(ExplicitList exprs) -- Non-empty list
339 = tcExprs exprs `thenTc` \ (exprs', lie, tys@(elt_ty:_)) ->
340 tcAddErrCtxt (listCtxt in_expr) $
341 unifyTauTyList tys `thenTc_`
342 returnTc (ExplicitListOut elt_ty exprs', lie, mkListTy elt_ty)
344 tcExpr (ExplicitTuple exprs)
345 = tcExprs exprs `thenTc` \ (exprs', lie, tys) ->
346 returnTc (ExplicitTuple exprs', lie, mkTupleTy (length tys) tys)
348 tcExpr (RecordCon con rbinds)
349 = panic "tcExpr:RecordCon"
350 tcExpr (RecordUpd exp rbinds)
351 = panic "tcExpr:RecordUpd"
353 tcExpr (ArithSeqIn seq@(From expr))
354 = tcExpr expr `thenTc` \ (expr', lie1, ty) ->
356 tcLookupGlobalValueByKey enumFromClassOpKey `thenNF_Tc` \ sel_id ->
357 newMethod (ArithSeqOrigin seq)
358 (RealId sel_id) [ty] `thenNF_Tc` \ (lie2, enum_from_id) ->
360 returnTc (ArithSeqOut (HsVar enum_from_id) (From expr'),
364 tcExpr in_expr@(ArithSeqIn seq@(FromThen expr1 expr2))
365 = tcExpr expr1 `thenTc` \ (expr1',lie1,ty1) ->
366 tcExpr expr2 `thenTc` \ (expr2',lie2,ty2) ->
368 tcAddErrCtxt (arithSeqCtxt in_expr) $
369 unifyTauTyList [ty1, ty2] `thenTc_`
371 tcLookupGlobalValueByKey enumFromThenClassOpKey `thenNF_Tc` \ sel_id ->
372 newMethod (ArithSeqOrigin seq)
373 (RealId sel_id) [ty1] `thenNF_Tc` \ (lie3, enum_from_then_id) ->
375 returnTc (ArithSeqOut (HsVar enum_from_then_id)
376 (FromThen expr1' expr2'),
377 lie1 `plusLIE` lie2 `plusLIE` lie3,
380 tcExpr in_expr@(ArithSeqIn seq@(FromTo expr1 expr2))
381 = tcExpr expr1 `thenTc` \ (expr1',lie1,ty1) ->
382 tcExpr expr2 `thenTc` \ (expr2',lie2,ty2) ->
384 tcAddErrCtxt (arithSeqCtxt in_expr) $
385 unifyTauTyList [ty1,ty2] `thenTc_`
387 tcLookupGlobalValueByKey enumFromToClassOpKey `thenNF_Tc` \ sel_id ->
388 newMethod (ArithSeqOrigin seq)
389 (RealId sel_id) [ty1] `thenNF_Tc` \ (lie3, enum_from_to_id) ->
391 returnTc (ArithSeqOut (HsVar enum_from_to_id)
392 (FromTo expr1' expr2'),
393 lie1 `plusLIE` lie2 `plusLIE` lie3,
396 tcExpr in_expr@(ArithSeqIn seq@(FromThenTo expr1 expr2 expr3))
397 = tcExpr expr1 `thenTc` \ (expr1',lie1,ty1) ->
398 tcExpr expr2 `thenTc` \ (expr2',lie2,ty2) ->
399 tcExpr expr3 `thenTc` \ (expr3',lie3,ty3) ->
401 tcAddErrCtxt (arithSeqCtxt in_expr) $
402 unifyTauTyList [ty1,ty2,ty3] `thenTc_`
404 tcLookupGlobalValueByKey enumFromThenToClassOpKey `thenNF_Tc` \ sel_id ->
405 newMethod (ArithSeqOrigin seq)
406 (RealId sel_id) [ty1] `thenNF_Tc` \ (lie4, eft_id) ->
408 returnTc (ArithSeqOut (HsVar eft_id)
409 (FromThenTo expr1' expr2' expr3'),
410 lie1 `plusLIE` lie2 `plusLIE` lie3 `plusLIE` lie4,
414 %************************************************************************
416 \subsection{Expressions type signatures}
418 %************************************************************************
421 tcExpr in_expr@(ExprWithTySig expr poly_ty)
422 = tcExpr expr `thenTc` \ (texpr, lie, tau_ty) ->
423 tcPolyType poly_ty `thenTc` \ sigma_sig ->
425 -- Check the tau-type part
426 tcSetErrCtxt (exprSigCtxt in_expr) $
427 specTy SignatureOrigin sigma_sig `thenNF_Tc` \ (sig_tyvars, sig_dicts, sig_tau, _) ->
428 unifyTauTy tau_ty sig_tau `thenTc_`
430 -- Check the type variables of the signature
431 checkSigTyVars sig_tyvars sig_tau tau_ty `thenTc` \ sig_tyvars' ->
433 -- Check overloading constraints
435 (tyVarListToSet sig_tyvars')
436 sig_dicts lie `thenTc_`
438 -- If everything is ok, return the stuff unchanged, except for
439 -- the effect of any substutions etc. We simply discard the
440 -- result of the tcSimplifyAndCheck, except for any default
441 -- resolution it may have done, which is recorded in the
443 returnTc (texpr, lie, tau_ty)
446 %************************************************************************
448 \subsection{@tcApp@ typchecks an application}
450 %************************************************************************
453 tcApp :: RenamedHsExpr -> [RenamedHsExpr] -- Function and args
454 -> TcM s (TcExpr s, [TcExpr s], -- Translated fun and args
456 TcType s) -- Type of the application
459 = -- First type-check the function
460 -- In the HsVar case we go straight to tcId to avoid hitting the
461 -- rank-2 check, which we check later here anyway
463 HsVar name -> tcId name
465 ) `thenTc` \ (fun', lie_fun, fun_ty) ->
467 tcApp_help fun 1 fun_ty args `thenTc` \ (args', lie_args, res_ty) ->
469 -- Check that the result type doesn't have any nested for-alls.
470 -- For example, a "build" on its own is no good; it must be applied to something.
471 checkTc (isTauTy res_ty)
472 (lurkingRank2Err fun fun_ty) `thenTc_`
474 returnTc (fun', args', lie_fun `plusLIE` lie_args, res_ty)
477 tcApp_help :: RenamedHsExpr -> Int -- Function and arg position, used in error message(s)
478 -> TcType s -- The type of the function
479 -> [RenamedHsExpr] -- Arguments
480 -> TcM s ([TcExpr s], -- Typechecked args
482 TcType s) -- Result type of the application
484 tcApp_help orig_fun arg_no fun_ty []
485 = returnTc ([], emptyLIE, fun_ty)
487 tcApp_help orig_fun arg_no fun_ty (arg:args)
488 | maybeToBool maybe_arrow_ty
489 = -- The function's type is A->B
490 tcAddErrCtxt (funAppCtxt orig_fun arg_no arg) (
491 tcArg expected_arg_ty arg
492 ) `thenTc` \ (arg', lie_arg) ->
494 tcApp_help orig_fun (arg_no+1) result_ty args `thenTc` \ (args', lie_args, res_ty) ->
495 returnTc (arg':args', lie_arg `plusLIE` lie_args, res_ty)
497 | maybeToBool maybe_tyvar_ty
498 = -- The function's type is just a type variable
499 tcReadTyVar fun_tyvar `thenNF_Tc` \ maybe_fun_ty ->
502 BoundTo new_fun_ty -> -- The tyvar in the corner of the function is bound
503 -- to something ... so carry on ....
504 tcApp_help orig_fun arg_no new_fun_ty (arg:args)
506 UnBound -> -- Extra args match against an unbound type
507 -- variable as the final result type, so unify the tyvar.
508 newTyVarTy mkTypeKind `thenNF_Tc` \ result_ty ->
509 tcExprs args `thenTc` \ (args', lie_args, arg_tys) ->
511 -- Unification can't fail, since we're unifying against a tyvar
512 unifyTauTy fun_ty (mkFunTys arg_tys result_ty) `thenTc_`
514 returnTc (args', lie_args, result_ty)
517 = -- Must be an error: a lurking for-all, or (more commonly)
518 -- a TyConTy... we've applied the function to too many args
519 failTc (tooManyArgs orig_fun)
522 maybe_arrow_ty = getFunTy_maybe fun_ty
523 Just (expected_arg_ty, result_ty) = maybe_arrow_ty
525 maybe_tyvar_ty = getTyVar_maybe fun_ty
526 Just fun_tyvar = maybe_tyvar_ty
530 tcArg :: TcType s -- Expected arg type
531 -> RenamedHsExpr -- Actual argument
532 -> TcM s (TcExpr s, LIE s) -- Resulting argument and LIE
534 tcArg expected_arg_ty arg
535 | not (maybeToBool (getForAllTy_maybe expected_arg_ty))
536 = -- The ordinary, non-rank-2 polymorphic case
537 tcExpr arg `thenTc` \ (arg', lie_arg, actual_arg_ty) ->
538 unifyTauTy expected_arg_ty actual_arg_ty `thenTc_`
539 returnTc (arg', lie_arg)
542 = -- Ha! The argument type of the function is a for-all type,
543 -- An example of rank-2 polymorphism.
545 -- No need to instantiate the argument type... it's must be the result
546 -- of instantiating a function involving rank-2 polymorphism, so there
547 -- isn't any danger of using the same tyvars twice
548 -- The argument type shouldn't be overloaded type (hence ASSERT)
550 (expected_tyvars, expected_theta, expected_tau) = splitSigmaTy expected_arg_ty
552 ASSERT( null expected_theta )
554 -- Type-check the arg and unify with expected type
555 tcExpr arg `thenTc` \ (arg', lie_arg, actual_arg_ty) ->
556 unifyTauTy expected_tau actual_arg_ty `thenTc_` (
558 -- Check that the arg_tyvars havn't been constrained
559 -- The interesting bit here is that we must include the free variables
560 -- of the expected arg ty. Here's an example:
561 -- runST (newVar True)
562 -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
563 -- for (newVar True), with s fresh. Then we unify with the runST's arg type
564 -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
565 -- So now s' isn't unconstrained because it's linked to a.
566 -- Conclusion: include the free vars of the expected arg type in the
567 -- list of "free vars" for the signature check.
568 tcAddErrCtxt (rank2ArgCtxt arg expected_arg_ty) $
569 tcGetGlobalTyVars `thenNF_Tc` \ env_tyvars ->
570 zonkTcTyVars (tyVarsOfType expected_arg_ty) `thenNF_Tc` \ free_tyvars ->
571 checkSigTyVarsGivenGlobals
572 (env_tyvars `unionTyVarSets` free_tyvars)
573 expected_tyvars expected_tau actual_arg_ty `thenTc` \ arg_tyvars' ->
575 -- Check that there's no overloading involved
576 -- Even if there isn't, there may be some Insts which mention the arg_tyvars,
577 -- but which, on simplification, don't actually need a dictionary involving
578 -- the tyvar. So we have to do a proper simplification right here.
579 tcSimplifyRank2 (tyVarListToSet arg_tyvars')
580 lie_arg `thenTc` \ (free_insts, inst_binds) ->
582 -- This HsLet binds any Insts which came out of the simplification.
583 -- It's a bit out of place here, but using AbsBind involves inventing
584 -- a couple of new names which seems worse.
585 returnTc (TyLam arg_tyvars' (HsLet (mk_binds inst_binds) arg'), free_insts)
591 mk_binds ((inst,rhs):inst_binds)
592 = (SingleBind (NonRecBind (VarMonoBind inst rhs)))
597 %************************************************************************
599 \subsection{@tcId@ typchecks an identifier occurrence}
601 %************************************************************************
604 tcId :: Name -> TcM s (TcExpr s, LIE s, TcType s)
606 = -- Look up the Id and instantiate its type
607 (tcLookupLocalValue name `thenNF_Tc` \ maybe_local ->
609 Just tc_id -> tcInstTcType [] (idType tc_id) `thenNF_Tc` \ ty ->
610 returnNF_Tc (TcId tc_id, ty)
612 Nothing -> tcLookupGlobalValue name `thenNF_Tc` \ id ->
613 tcInstType [] (idType id) `thenNF_Tc` \ ty ->
614 returnNF_Tc (RealId id, ty)
615 ) `thenNF_Tc` \ (tc_id_occ, ty) ->
617 (tyvars, rho) = splitForAllTy ty
618 (theta,tau) = splitRhoTy rho
619 arg_tys = map mkTyVarTy tyvars
623 [] -> -- Not overloaded, so just make a type application
624 returnTc (TyApp (HsVar tc_id_occ) arg_tys, emptyLIE, tau)
626 _ -> -- Overloaded, so make a Method inst
627 newMethodWithGivenTy (OccurrenceOf tc_id_occ)
628 tc_id_occ arg_tys rho `thenNF_Tc` \ (lie, meth_id) ->
629 returnTc (HsVar meth_id, lie, tau)
634 %************************************************************************
636 \subsection{@tcQuals@ typchecks list comprehension qualifiers}
638 %************************************************************************
642 = tcExpr expr `thenTc` \ (expr', lie, ty) ->
643 returnTc ((expr',[]), lie, mkListTy ty)
645 tcListComp expr (qual@(FilterQual filter) : quals)
646 = tcAddErrCtxt (qualCtxt qual) (
647 tcExpr filter `thenTc` \ (filter', filter_lie, filter_ty) ->
648 unifyTauTy boolTy filter_ty `thenTc_`
649 returnTc (FilterQual filter', filter_lie)
650 ) `thenTc` \ (qual', qual_lie) ->
652 tcListComp expr quals `thenTc` \ ((expr',quals'), rest_lie, res_ty) ->
654 returnTc ((expr', qual' : quals'),
655 qual_lie `plusLIE` rest_lie,
658 tcListComp expr (qual@(GeneratorQual pat rhs) : quals)
659 = newMonoIds binder_names mkBoxedTypeKind (\ ids ->
661 tcAddErrCtxt (qualCtxt qual) (
662 tcPat pat `thenTc` \ (pat', lie_pat, pat_ty) ->
663 tcExpr rhs `thenTc` \ (rhs', lie_rhs, rhs_ty) ->
664 unifyTauTy (mkListTy pat_ty) rhs_ty `thenTc_`
665 returnTc (GeneratorQual pat' rhs',
666 lie_pat `plusLIE` lie_rhs)
667 ) `thenTc` \ (qual', lie_qual) ->
669 tcListComp expr quals `thenTc` \ ((expr',quals'), lie_rest, res_ty) ->
671 returnTc ((expr', qual' : quals'),
672 lie_qual `plusLIE` lie_rest,
676 binder_names = collectPatBinders pat
678 tcListComp expr (LetQual binds : quals)
679 = tcBindsAndThen -- No error context, but a binding group is
680 combine -- rather a large thing for an error context anyway
682 (tcListComp expr quals)
684 combine binds' (expr',quals') = (expr', LetQual binds' : quals')
688 %************************************************************************
690 \subsection{@tcDoStmts@ typechecks a {\em list} of do statements}
692 %************************************************************************
695 tcDoStmts :: Bool -- True => require a monad
698 -> TcM s (([TcStmt s],
699 Bool, -- True => Monad
700 Bool), -- True => MonadZero
704 tcDoStmts monad m [stmt@(ExprStmt exp src_loc)]
705 = tcAddSrcLoc src_loc $
706 tcSetErrCtxt (stmtCtxt stmt) $
707 tcExpr exp `thenTc` \ (exp', exp_lie, exp_ty) ->
709 newTyVarTy mkTypeKind `thenNF_Tc` \ a ->
710 unifyTauTy (mkAppTy m a) exp_ty
714 returnTc (([ExprStmt exp' src_loc], monad, False), exp_lie, exp_ty)
716 tcDoStmts _ m (stmt@(ExprStmt exp src_loc) : stmts)
717 = tcAddSrcLoc src_loc (
718 tcSetErrCtxt (stmtCtxt stmt) (
719 tcExpr exp `thenTc` \ (exp', exp_lie, exp_ty) ->
720 newTyVarTy mkTypeKind `thenNF_Tc` \ a ->
721 unifyTauTy (mkAppTy m a) exp_ty `thenTc_`
722 returnTc (ExprStmt exp' src_loc, exp_lie)
723 )) `thenTc` \ (stmt', stmt_lie) ->
724 tcDoStmts True m stmts `thenTc` \ ((stmts', _, mzero), stmts_lie, stmts_ty) ->
725 returnTc ((stmt':stmts', True, mzero),
726 stmt_lie `plusLIE` stmts_lie,
729 tcDoStmts _ m (stmt@(BindStmt pat exp src_loc) : stmts)
730 = tcAddSrcLoc src_loc (
731 tcSetErrCtxt (stmtCtxt stmt) (
732 tcPat pat `thenTc` \ (pat', pat_lie, pat_ty) ->
733 tcExpr exp `thenTc` \ (exp', exp_lie, exp_ty) ->
734 newTyVarTy mkTypeKind `thenNF_Tc` \ a ->
735 unifyTauTy a pat_ty `thenTc_`
736 unifyTauTy (mkAppTy m a) exp_ty `thenTc_`
737 returnTc (BindStmt pat' exp' src_loc, pat_lie `plusLIE` exp_lie, irrefutablePat pat')
738 )) `thenTc` \ (stmt', stmt_lie, failure_free) ->
739 tcDoStmts True m stmts `thenTc` \ ((stmts', _, mzero), stmts_lie, stmts_ty) ->
740 returnTc ((stmt':stmts', True, mzero || not failure_free),
741 stmt_lie `plusLIE` stmts_lie,
744 tcDoStmts monad m (LetStmt binds : stmts)
745 = tcBindsAndThen -- No error context, but a binding group is
746 combine -- rather a large thing for an error context anyway
748 (tcDoStmts monad m stmts)
750 combine binds' (stmts', monad, mzero) = ((LetStmt binds' : stmts'), monad, mzero)
754 %************************************************************************
756 \subsection{@tcExprs@ typechecks a {\em list} of expressions}
758 %************************************************************************
761 tcExprs :: [RenamedHsExpr] -> TcM s ([TcExpr s], LIE s, [TcType s])
763 tcExprs [] = returnTc ([], emptyLIE, [])
765 = tcExpr expr `thenTc` \ (expr', lie1, ty) ->
766 tcExprs exprs `thenTc` \ (exprs', lie2, tys) ->
767 returnTc (expr':exprs', lie1 `plusLIE` lie2, ty:tys)
771 % =================================================
778 pp_nest_hang :: String -> Pretty -> Pretty
779 pp_nest_hang label stuff = ppNest 2 (ppHang (ppStr label) 4 stuff)
782 Boring and alphabetical:
784 arithSeqCtxt expr sty
785 = ppHang (ppStr "In an arithmetic sequence:") 4 (ppr sty expr)
788 = ppSep [ppStr "In the branches of a conditional:",
789 pp_nest_hang "`then' branch:" (ppr sty b1),
790 pp_nest_hang "`else' branch:" (ppr sty b2)]
793 = ppHang (ppStr "In a case expression:") 4 (ppr sty expr)
796 = ppHang (ppStr "In an expression with a type signature:")
800 = ppHang (ppStr "In a list expression:") 4 (ppr sty expr)
803 = ppHang (ppStr "In a predicate expression:") 4 (ppr sty expr)
805 sectionRAppCtxt expr sty
806 = ppHang (ppStr "In a right section:") 4 (ppr sty expr)
808 sectionLAppCtxt expr sty
809 = ppHang (ppStr "In a left section:") 4 (ppr sty expr)
811 funAppCtxt fun arg_no arg sty
812 = ppHang (ppCat [ ppStr "In the", speakNth arg_no, ppStr "argument of", ppr sty fun])
813 4 (ppCat [ppStr "namely", ppr sty arg])
816 = ppHang (ppStr "In a list-comprehension qualifer:")
820 = ppHang (ppStr "In a do statement:")
824 = ppHang (ppStr "Too many arguments in an application of the function")
827 lurkingRank2Err fun fun_ty sty
828 = ppHang (ppCat [ppStr "Illegal use of", ppr sty fun])
829 4 (ppAboves [ppStr "It is applied to too few arguments,",
830 ppStr "so that the result type has for-alls in it"])
832 rank2ArgCtxt arg expected_arg_ty sty
833 = ppHang (ppStr "In a polymorphic function argument:")
834 4 (ppSep [ppBeside (ppr sty arg) (ppStr " ::"),
835 ppr sty expected_arg_ty])