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 )
35 import TcKind ( TcKind )
37 import Class ( Class(..), getClassSig )
38 import Id ( Id(..), GenId, idType )
39 import Kind ( Kind, mkBoxedTypeKind, mkTypeKind )
40 import GenSpecEtc ( checkSigTyVars, checkSigTyVarsGivenGlobals, specTy )
41 import PrelInfo ( intPrimTy, charPrimTy, doublePrimTy,
42 floatPrimTy, addrPrimTy, addrTy,
43 boolTy, charTy, stringTy, mkListTy,
44 mkTupleTy, mkPrimIoTy )
45 import Type ( mkFunTy, mkAppTy, mkTyVarTy, mkTyVarTys,
46 getTyVar_maybe, getFunTy_maybe,
47 splitForAllTy, splitRhoTy, splitSigmaTy,
48 isTauTy, mkFunTys, tyVarsOfType, getForAllTy_maybe )
49 import TyVar ( GenTyVar, TyVarSet(..), unionTyVarSets, mkTyVarSet )
50 import Unify ( unifyTauTy, unifyTauTyList, unifyTauTyLists )
51 import Unique ( Unique, cCallableClassKey, cReturnableClassKey,
52 enumFromClassOpKey, enumFromThenClassOpKey,
53 enumFromToClassOpKey, enumFromThenToClassOpKey,
54 monadClassKey, monadZeroClassKey )
56 import Name ( Name ) -- Instance
57 import PprType ( GenType, GenTyVar ) -- Instances
58 import Maybes ( maybeToBool )
64 tcExpr :: RenamedHsExpr -> TcM s (TcExpr s, LIE s, TcType s)
67 %************************************************************************
69 \subsection{The TAUT rules for variables}
71 %************************************************************************
75 = tcId name `thenTc` \ (expr', lie, res_ty) ->
77 -- Check that the result type doesn't have any nested for-alls.
78 -- For example, a "build" on its own is no good; it must be
79 -- applied to something.
80 checkTc (isTauTy res_ty)
81 (lurkingRank2Err name res_ty) `thenTc_`
83 returnTc (expr', lie, res_ty)
86 %************************************************************************
90 %************************************************************************
95 tcExpr (HsLit (HsInt i))
96 = newTyVarTy mkBoxedTypeKind `thenNF_Tc` \ ty ->
98 newOverloadedLit (LiteralOrigin (HsInt i))
99 (OverloadedIntegral i)
100 ty `thenNF_Tc` \ (lie, over_lit_id) ->
102 returnTc (HsVar over_lit_id, lie, ty)
104 tcExpr (HsLit (HsFrac f))
105 = newTyVarTy mkBoxedTypeKind `thenNF_Tc` \ ty ->
107 newOverloadedLit (LiteralOrigin (HsFrac f))
108 (OverloadedFractional f)
109 ty `thenNF_Tc` \ (lie, over_lit_id) ->
111 returnTc (HsVar over_lit_id, lie, ty)
113 tcExpr (HsLit lit@(HsLitLit s))
114 = tcLookupClassByKey cCallableClassKey `thenNF_Tc` \ cCallableClass ->
115 newTyVarTy mkBoxedTypeKind `thenNF_Tc` \ ty ->
116 newDicts (LitLitOrigin (_UNPK_ s))
117 [(cCallableClass, ty)] `thenNF_Tc` \ (dicts, _) ->
118 returnTc (HsLitOut lit ty, dicts, ty)
124 tcExpr (HsLit lit@(HsCharPrim c))
125 = returnTc (HsLitOut lit charPrimTy, emptyLIE, charPrimTy)
127 tcExpr (HsLit lit@(HsStringPrim s))
128 = returnTc (HsLitOut lit addrPrimTy, emptyLIE, addrPrimTy)
130 tcExpr (HsLit lit@(HsIntPrim i))
131 = returnTc (HsLitOut lit intPrimTy, emptyLIE, intPrimTy)
133 tcExpr (HsLit lit@(HsFloatPrim f))
134 = returnTc (HsLitOut lit floatPrimTy, emptyLIE, floatPrimTy)
136 tcExpr (HsLit lit@(HsDoublePrim d))
137 = returnTc (HsLitOut lit doublePrimTy, emptyLIE, doublePrimTy)
140 Unoverloaded literals:
143 tcExpr (HsLit lit@(HsChar c))
144 = returnTc (HsLitOut lit charTy, emptyLIE, charTy)
146 tcExpr (HsLit lit@(HsString str))
147 = returnTc (HsLitOut lit stringTy, emptyLIE, stringTy)
150 %************************************************************************
152 \subsection{Other expression forms}
154 %************************************************************************
158 = tcMatch match `thenTc` \ (match',lie,ty) ->
159 returnTc (HsLam match', lie, ty)
161 tcExpr (HsApp e1 e2) = accum e1 [e2]
163 accum (HsApp e1 e2) args = accum e1 (e2:args)
165 = tcApp fun args `thenTc` \ (fun', args', lie, res_ty) ->
166 returnTc (foldl HsApp fun' args', lie, res_ty)
168 -- equivalent to (op e1) e2:
169 tcExpr (OpApp arg1 op arg2)
170 = tcApp op [arg1,arg2] `thenTc` \ (op', [arg1', arg2'], lie, res_ty) ->
171 returnTc (OpApp arg1' op' arg2', lie, res_ty)
174 Note that the operators in sections are expected to be binary, and
175 a type error will occur if they aren't.
178 -- Left sections, equivalent to
185 tcExpr in_expr@(SectionL arg op)
186 = tcApp op [arg] `thenTc` \ (op', [arg'], lie, res_ty) ->
188 -- Check that res_ty is a function type
189 -- Without this check we barf in the desugarer on
191 -- because it tries to desugar to
192 -- f op = \r -> 3 op r
193 -- so (3 `op`) had better be a function!
194 newTyVarTy mkTypeKind `thenNF_Tc` \ ty1 ->
195 newTyVarTy mkTypeKind `thenNF_Tc` \ ty2 ->
196 tcAddErrCtxt (sectionLAppCtxt in_expr) $
197 unifyTauTy (mkFunTy ty1 ty2) res_ty `thenTc_`
199 returnTc (SectionL arg' op', lie, res_ty)
201 -- Right sections, equivalent to \ x -> x op expr, or
204 tcExpr in_expr@(SectionR op expr)
205 = tcExpr op `thenTc` \ (op', lie1, op_ty) ->
206 tcExpr expr `thenTc` \ (expr',lie2, expr_ty) ->
208 newTyVarTy mkTypeKind `thenNF_Tc` \ ty1 ->
209 newTyVarTy mkTypeKind `thenNF_Tc` \ ty2 ->
210 tcAddErrCtxt (sectionRAppCtxt in_expr) $
211 unifyTauTy op_ty (mkFunTys [ty1, expr_ty] ty2) `thenTc_`
213 returnTc (SectionR op' expr', lie1 `plusLIE` lie2, mkFunTy ty1 ty2)
216 The interesting thing about @ccall@ is that it is just a template
217 which we instantiate by filling in details about the types of its
218 argument and result (ie minimal typechecking is performed). So, the
219 basic story is that we allocate a load of type variables (to hold the
220 arg/result types); unify them with the args/result; and store them for
224 tcExpr (CCall lbl args may_gc is_asm ignored_fake_result_ty)
225 = -- Get the callable and returnable classes.
226 tcLookupClassByKey cCallableClassKey `thenNF_Tc` \ cCallableClass ->
227 tcLookupClassByKey cReturnableClassKey `thenNF_Tc` \ cReturnableClass ->
230 new_arg_dict (arg, arg_ty)
231 = newDicts (CCallOrigin (_UNPK_ lbl) (Just arg))
232 [(cCallableClass, arg_ty)] `thenNF_Tc` \ (arg_dicts, _) ->
233 returnNF_Tc arg_dicts -- Actually a singleton bag
235 result_origin = CCallOrigin (_UNPK_ lbl) Nothing {- Not an arg -}
239 tcExprs args `thenTc` \ (args', args_lie, arg_tys) ->
241 -- The argument types can be unboxed or boxed; the result
242 -- type must, however, be boxed since it's an argument to the PrimIO
244 newTyVarTy mkBoxedTypeKind `thenNF_Tc` \ result_ty ->
246 -- Construct the extra insts, which encode the
247 -- constraints on the argument and result types.
248 mapNF_Tc new_arg_dict (args `zip` arg_tys) `thenNF_Tc` \ ccarg_dicts_s ->
249 newDicts result_origin [(cReturnableClass, result_ty)] `thenNF_Tc` \ (ccres_dict, _) ->
251 returnTc (CCall lbl args' may_gc is_asm result_ty,
252 foldr plusLIE ccres_dict ccarg_dicts_s `plusLIE` args_lie,
253 mkPrimIoTy result_ty)
257 tcExpr (HsSCC label expr)
258 = tcExpr expr `thenTc` \ (expr', lie, expr_ty) ->
259 -- No unification. Give SCC the type of expr
260 returnTc (HsSCC label expr', lie, expr_ty)
262 tcExpr (HsLet binds expr)
264 HsLet -- The combiner
265 binds -- Bindings to check
266 (tcExpr expr) -- Typechecker for the expression
268 tcExpr in_expr@(HsCase expr matches src_loc)
269 = tcAddSrcLoc src_loc $
270 tcExpr expr `thenTc` \ (expr',lie1,expr_ty) ->
271 newTyVarTy mkTypeKind `thenNF_Tc` \ result_ty ->
273 tcAddErrCtxt (caseCtxt in_expr) $
274 tcMatchesCase (mkFunTy expr_ty result_ty) matches
275 `thenTc` \ (matches',lie2) ->
277 returnTc (HsCase expr' matches' src_loc, plusLIE lie1 lie2, result_ty)
279 tcExpr (HsIf pred b1 b2 src_loc)
280 = tcAddSrcLoc src_loc $
281 tcExpr pred `thenTc` \ (pred',lie1,predTy) ->
283 tcAddErrCtxt (predCtxt pred) (
284 unifyTauTy predTy boolTy
287 tcExpr b1 `thenTc` \ (b1',lie2,result_ty) ->
288 tcExpr b2 `thenTc` \ (b2',lie3,b2Ty) ->
290 tcAddErrCtxt (branchCtxt b1 b2) $
291 unifyTauTy result_ty b2Ty `thenTc_`
293 returnTc (HsIf pred' b1' b2' src_loc, plusLIE lie1 (plusLIE lie2 lie3), result_ty)
295 tcExpr (ListComp expr quals)
296 = tcListComp expr quals `thenTc` \ ((expr',quals'), lie, ty) ->
297 returnTc (ListComp expr' quals', lie, ty)
301 tcExpr (HsDo stmts src_loc)
302 = -- get the Monad and MonadZero classes
303 -- create type consisting of a fresh monad tyvar
304 tcAddSrcLoc src_loc $
305 tcLookupClassByKey monadClassKey `thenNF_Tc` \ monadClass ->
306 tcLookupClassByKey monadZeroClassKey `thenNF_Tc` \ monadZeroClass ->
308 (tv,_,_) = getClassSig monadClass
310 tcInstTyVar tv `thenNF_Tc` \ m_tyvar ->
312 m = mkTyVarTy m_tyvar
314 tcDoStmts False m stmts `thenTc` \ ((stmts',monad,mzero), lie, do_ty) ->
316 -- create dictionaries for monad and possibly monadzero
318 newDicts DoOrigin [(monadClass, m)]
320 returnNF_Tc (emptyLIE, [panic "TcExpr: MonadZero dictionary"])
321 ) `thenNF_Tc` \ (m_lie, [m_id]) ->
323 newDicts DoOrigin [(monadZeroClass, m)]
325 returnNF_Tc (emptyLIE, [panic "TcExpr: MonadZero dictionary"])
326 ) `thenNF_Tc` \ (mz_lie, [mz_id]) ->
328 returnTc (HsDoOut stmts' m_id mz_id src_loc,
329 lie `plusLIE` m_lie `plusLIE` mz_lie,
334 tcExpr (ExplicitList [])
335 = newTyVarTy mkBoxedTypeKind `thenNF_Tc` \ tyvar_ty ->
336 returnTc (ExplicitListOut tyvar_ty [], emptyLIE, mkListTy tyvar_ty)
339 tcExpr in_expr@(ExplicitList exprs) -- Non-empty list
340 = tcExprs exprs `thenTc` \ (exprs', lie, tys@(elt_ty:_)) ->
341 tcAddErrCtxt (listCtxt in_expr) $
342 unifyTauTyList tys `thenTc_`
343 returnTc (ExplicitListOut elt_ty exprs', lie, mkListTy elt_ty)
345 tcExpr (ExplicitTuple exprs)
346 = tcExprs exprs `thenTc` \ (exprs', lie, tys) ->
347 returnTc (ExplicitTuple exprs', lie, mkTupleTy (length tys) tys)
349 tcExpr (RecordCon con rbinds)
350 = panic "tcExpr:RecordCon"
351 tcExpr (RecordUpd exp rbinds)
352 = panic "tcExpr:RecordUpd"
354 tcExpr (ArithSeqIn seq@(From expr))
355 = tcExpr expr `thenTc` \ (expr', lie1, ty) ->
357 tcLookupGlobalValueByKey enumFromClassOpKey `thenNF_Tc` \ sel_id ->
358 newMethod (ArithSeqOrigin seq)
359 (RealId sel_id) [ty] `thenNF_Tc` \ (lie2, enum_from_id) ->
361 returnTc (ArithSeqOut (HsVar enum_from_id) (From expr'),
365 tcExpr in_expr@(ArithSeqIn seq@(FromThen expr1 expr2))
366 = tcExpr expr1 `thenTc` \ (expr1',lie1,ty1) ->
367 tcExpr expr2 `thenTc` \ (expr2',lie2,ty2) ->
369 tcAddErrCtxt (arithSeqCtxt in_expr) $
370 unifyTauTyList [ty1, ty2] `thenTc_`
372 tcLookupGlobalValueByKey enumFromThenClassOpKey `thenNF_Tc` \ sel_id ->
373 newMethod (ArithSeqOrigin seq)
374 (RealId sel_id) [ty1] `thenNF_Tc` \ (lie3, enum_from_then_id) ->
376 returnTc (ArithSeqOut (HsVar enum_from_then_id)
377 (FromThen expr1' expr2'),
378 lie1 `plusLIE` lie2 `plusLIE` lie3,
381 tcExpr in_expr@(ArithSeqIn seq@(FromTo expr1 expr2))
382 = tcExpr expr1 `thenTc` \ (expr1',lie1,ty1) ->
383 tcExpr expr2 `thenTc` \ (expr2',lie2,ty2) ->
385 tcAddErrCtxt (arithSeqCtxt in_expr) $
386 unifyTauTyList [ty1,ty2] `thenTc_`
388 tcLookupGlobalValueByKey enumFromToClassOpKey `thenNF_Tc` \ sel_id ->
389 newMethod (ArithSeqOrigin seq)
390 (RealId sel_id) [ty1] `thenNF_Tc` \ (lie3, enum_from_to_id) ->
392 returnTc (ArithSeqOut (HsVar enum_from_to_id)
393 (FromTo expr1' expr2'),
394 lie1 `plusLIE` lie2 `plusLIE` lie3,
397 tcExpr in_expr@(ArithSeqIn seq@(FromThenTo expr1 expr2 expr3))
398 = tcExpr expr1 `thenTc` \ (expr1',lie1,ty1) ->
399 tcExpr expr2 `thenTc` \ (expr2',lie2,ty2) ->
400 tcExpr expr3 `thenTc` \ (expr3',lie3,ty3) ->
402 tcAddErrCtxt (arithSeqCtxt in_expr) $
403 unifyTauTyList [ty1,ty2,ty3] `thenTc_`
405 tcLookupGlobalValueByKey enumFromThenToClassOpKey `thenNF_Tc` \ sel_id ->
406 newMethod (ArithSeqOrigin seq)
407 (RealId sel_id) [ty1] `thenNF_Tc` \ (lie4, eft_id) ->
409 returnTc (ArithSeqOut (HsVar eft_id)
410 (FromThenTo expr1' expr2' expr3'),
411 lie1 `plusLIE` lie2 `plusLIE` lie3 `plusLIE` lie4,
415 %************************************************************************
417 \subsection{Expressions type signatures}
419 %************************************************************************
422 tcExpr in_expr@(ExprWithTySig expr poly_ty)
423 = tcExpr expr `thenTc` \ (texpr, lie, tau_ty) ->
424 tcPolyType poly_ty `thenTc` \ sigma_sig ->
426 -- Check the tau-type part
427 tcSetErrCtxt (exprSigCtxt in_expr) $
428 specTy SignatureOrigin sigma_sig `thenNF_Tc` \ (sig_tyvars, sig_dicts, sig_tau, _) ->
429 unifyTauTy tau_ty sig_tau `thenTc_`
431 -- Check the type variables of the signature
432 checkSigTyVars sig_tyvars sig_tau tau_ty `thenTc` \ sig_tyvars' ->
434 -- Check overloading constraints
436 (mkTyVarSet sig_tyvars')
437 sig_dicts lie `thenTc_`
439 -- If everything is ok, return the stuff unchanged, except for
440 -- the effect of any substutions etc. We simply discard the
441 -- result of the tcSimplifyAndCheck, except for any default
442 -- resolution it may have done, which is recorded in the
444 returnTc (texpr, lie, tau_ty)
447 %************************************************************************
449 \subsection{@tcApp@ typchecks an application}
451 %************************************************************************
454 tcApp :: RenamedHsExpr -> [RenamedHsExpr] -- Function and args
455 -> TcM s (TcExpr s, [TcExpr s], -- Translated fun and args
457 TcType s) -- Type of the application
460 = -- First type-check the function
461 -- In the HsVar case we go straight to tcId to avoid hitting the
462 -- rank-2 check, which we check later here anyway
464 HsVar name -> tcId name
466 ) `thenTc` \ (fun', lie_fun, fun_ty) ->
468 tcApp_help fun 1 fun_ty args `thenTc` \ (args', lie_args, res_ty) ->
470 -- Check that the result type doesn't have any nested for-alls.
471 -- For example, a "build" on its own is no good; it must be applied to something.
472 checkTc (isTauTy res_ty)
473 (lurkingRank2Err fun fun_ty) `thenTc_`
475 returnTc (fun', args', lie_fun `plusLIE` lie_args, res_ty)
478 tcApp_help :: RenamedHsExpr -> Int -- Function and arg position, used in error message(s)
479 -> TcType s -- The type of the function
480 -> [RenamedHsExpr] -- Arguments
481 -> TcM s ([TcExpr s], -- Typechecked args
483 TcType s) -- Result type of the application
485 tcApp_help orig_fun arg_no fun_ty []
486 = returnTc ([], emptyLIE, fun_ty)
488 tcApp_help orig_fun arg_no fun_ty (arg:args)
489 | maybeToBool maybe_arrow_ty
490 = -- The function's type is A->B
491 tcAddErrCtxt (funAppCtxt orig_fun arg_no arg) (
492 tcArg expected_arg_ty arg
493 ) `thenTc` \ (arg', lie_arg) ->
495 tcApp_help orig_fun (arg_no+1) result_ty args `thenTc` \ (args', lie_args, res_ty) ->
496 returnTc (arg':args', lie_arg `plusLIE` lie_args, res_ty)
498 | maybeToBool maybe_tyvar_ty
499 = -- The function's type is just a type variable
500 tcReadTyVar fun_tyvar `thenNF_Tc` \ maybe_fun_ty ->
503 BoundTo new_fun_ty -> -- The tyvar in the corner of the function is bound
504 -- to something ... so carry on ....
505 tcApp_help orig_fun arg_no new_fun_ty (arg:args)
507 UnBound -> -- Extra args match against an unbound type
508 -- variable as the final result type, so unify the tyvar.
509 newTyVarTy mkTypeKind `thenNF_Tc` \ result_ty ->
510 tcExprs args `thenTc` \ (args', lie_args, arg_tys) ->
512 -- Unification can't fail, since we're unifying against a tyvar
513 unifyTauTy fun_ty (mkFunTys arg_tys result_ty) `thenTc_`
515 returnTc (args', lie_args, result_ty)
518 = -- Must be an error: a lurking for-all, or (more commonly)
519 -- a TyConTy... we've applied the function to too many args
520 failTc (tooManyArgs orig_fun)
523 maybe_arrow_ty = getFunTy_maybe fun_ty
524 Just (expected_arg_ty, result_ty) = maybe_arrow_ty
526 maybe_tyvar_ty = getTyVar_maybe fun_ty
527 Just fun_tyvar = maybe_tyvar_ty
531 tcArg :: TcType s -- Expected arg type
532 -> RenamedHsExpr -- Actual argument
533 -> TcM s (TcExpr s, LIE s) -- Resulting argument and LIE
535 tcArg expected_arg_ty arg
536 | not (maybeToBool (getForAllTy_maybe expected_arg_ty))
537 = -- The ordinary, non-rank-2 polymorphic case
538 tcExpr arg `thenTc` \ (arg', lie_arg, actual_arg_ty) ->
539 unifyTauTy expected_arg_ty actual_arg_ty `thenTc_`
540 returnTc (arg', lie_arg)
543 = -- Ha! The argument type of the function is a for-all type,
544 -- An example of rank-2 polymorphism.
546 -- No need to instantiate the argument type... it's must be the result
547 -- of instantiating a function involving rank-2 polymorphism, so there
548 -- isn't any danger of using the same tyvars twice
549 -- The argument type shouldn't be overloaded type (hence ASSERT)
551 (expected_tyvars, expected_theta, expected_tau) = splitSigmaTy expected_arg_ty
553 ASSERT( null expected_theta )
555 -- Type-check the arg and unify with expected type
556 tcExpr arg `thenTc` \ (arg', lie_arg, actual_arg_ty) ->
557 unifyTauTy expected_tau actual_arg_ty `thenTc_` (
559 -- Check that the arg_tyvars havn't been constrained
560 -- The interesting bit here is that we must include the free variables
561 -- of the expected arg ty. Here's an example:
562 -- runST (newVar True)
563 -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
564 -- for (newVar True), with s fresh. Then we unify with the runST's arg type
565 -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
566 -- So now s' isn't unconstrained because it's linked to a.
567 -- Conclusion: include the free vars of the expected arg type in the
568 -- list of "free vars" for the signature check.
569 tcAddErrCtxt (rank2ArgCtxt arg expected_arg_ty) $
570 tcGetGlobalTyVars `thenNF_Tc` \ env_tyvars ->
571 zonkTcTyVars (tyVarsOfType expected_arg_ty) `thenNF_Tc` \ free_tyvars ->
572 checkSigTyVarsGivenGlobals
573 (env_tyvars `unionTyVarSets` free_tyvars)
574 expected_tyvars expected_tau actual_arg_ty `thenTc` \ arg_tyvars' ->
576 -- Check that there's no overloading involved
577 -- Even if there isn't, there may be some Insts which mention the arg_tyvars,
578 -- but which, on simplification, don't actually need a dictionary involving
579 -- the tyvar. So we have to do a proper simplification right here.
580 tcSimplifyRank2 (mkTyVarSet arg_tyvars')
581 lie_arg `thenTc` \ (free_insts, inst_binds) ->
583 -- This HsLet binds any Insts which came out of the simplification.
584 -- It's a bit out of place here, but using AbsBind involves inventing
585 -- a couple of new names which seems worse.
586 returnTc (TyLam arg_tyvars' (HsLet (mk_binds inst_binds) arg'), free_insts)
592 mk_binds ((inst,rhs):inst_binds)
593 = (SingleBind (NonRecBind (VarMonoBind inst rhs)))
598 %************************************************************************
600 \subsection{@tcId@ typchecks an identifier occurrence}
602 %************************************************************************
605 tcId :: Name -> TcM s (TcExpr s, LIE s, TcType s)
607 = -- Look up the Id and instantiate its type
608 (tcLookupLocalValue name `thenNF_Tc` \ maybe_local ->
610 Just tc_id -> tcInstTcType [] (idType tc_id) `thenNF_Tc` \ ty ->
611 returnNF_Tc (TcId tc_id, ty)
613 Nothing -> tcLookupGlobalValue name `thenNF_Tc` \ id ->
614 tcInstType [] (idType id) `thenNF_Tc` \ ty ->
615 returnNF_Tc (RealId id, ty)
616 ) `thenNF_Tc` \ (tc_id_occ, ty) ->
618 (tyvars, rho) = splitForAllTy ty
619 (theta,tau) = splitRhoTy rho
620 arg_tys = mkTyVarTys tyvars
624 [] -> -- Not overloaded, so just make a type application
625 returnTc (TyApp (HsVar tc_id_occ) arg_tys, emptyLIE, tau)
627 _ -> -- Overloaded, so make a Method inst
628 newMethodWithGivenTy (OccurrenceOf tc_id_occ)
629 tc_id_occ arg_tys rho `thenNF_Tc` \ (lie, meth_id) ->
630 returnTc (HsVar meth_id, lie, tau)
635 %************************************************************************
637 \subsection{@tcQuals@ typchecks list comprehension qualifiers}
639 %************************************************************************
643 = tcExpr expr `thenTc` \ (expr', lie, ty) ->
644 returnTc ((expr',[]), lie, mkListTy ty)
646 tcListComp expr (qual@(FilterQual filter) : quals)
647 = tcAddErrCtxt (qualCtxt qual) (
648 tcExpr filter `thenTc` \ (filter', filter_lie, filter_ty) ->
649 unifyTauTy boolTy filter_ty `thenTc_`
650 returnTc (FilterQual filter', filter_lie)
651 ) `thenTc` \ (qual', qual_lie) ->
653 tcListComp expr quals `thenTc` \ ((expr',quals'), rest_lie, res_ty) ->
655 returnTc ((expr', qual' : quals'),
656 qual_lie `plusLIE` rest_lie,
659 tcListComp expr (qual@(GeneratorQual pat rhs) : quals)
660 = newMonoIds binder_names mkBoxedTypeKind (\ ids ->
662 tcAddErrCtxt (qualCtxt qual) (
663 tcPat pat `thenTc` \ (pat', lie_pat, pat_ty) ->
664 tcExpr rhs `thenTc` \ (rhs', lie_rhs, rhs_ty) ->
665 unifyTauTy (mkListTy pat_ty) rhs_ty `thenTc_`
666 returnTc (GeneratorQual pat' rhs',
667 lie_pat `plusLIE` lie_rhs)
668 ) `thenTc` \ (qual', lie_qual) ->
670 tcListComp expr quals `thenTc` \ ((expr',quals'), lie_rest, res_ty) ->
672 returnTc ((expr', qual' : quals'),
673 lie_qual `plusLIE` lie_rest,
677 binder_names = collectPatBinders pat
679 tcListComp expr (LetQual binds : quals)
680 = tcBindsAndThen -- No error context, but a binding group is
681 combine -- rather a large thing for an error context anyway
683 (tcListComp expr quals)
685 combine binds' (expr',quals') = (expr', LetQual binds' : quals')
689 %************************************************************************
691 \subsection{@tcDoStmts@ typechecks a {\em list} of do statements}
693 %************************************************************************
696 tcDoStmts :: Bool -- True => require a monad
699 -> TcM s (([TcStmt s],
700 Bool, -- True => Monad
701 Bool), -- True => MonadZero
705 tcDoStmts monad m [stmt@(ExprStmt exp src_loc)]
706 = tcAddSrcLoc src_loc $
707 tcSetErrCtxt (stmtCtxt stmt) $
708 tcExpr exp `thenTc` \ (exp', exp_lie, exp_ty) ->
710 newTyVarTy mkTypeKind `thenNF_Tc` \ a ->
711 unifyTauTy (mkAppTy m a) exp_ty
715 returnTc (([ExprStmt exp' src_loc], monad, False), exp_lie, exp_ty)
717 tcDoStmts _ m (stmt@(ExprStmt exp src_loc) : stmts)
718 = tcAddSrcLoc src_loc (
719 tcSetErrCtxt (stmtCtxt stmt) (
720 tcExpr exp `thenTc` \ (exp', exp_lie, exp_ty) ->
721 newTyVarTy mkTypeKind `thenNF_Tc` \ a ->
722 unifyTauTy (mkAppTy m a) exp_ty `thenTc_`
723 returnTc (ExprStmt exp' src_loc, exp_lie)
724 )) `thenTc` \ (stmt', stmt_lie) ->
725 tcDoStmts True m stmts `thenTc` \ ((stmts', _, mzero), stmts_lie, stmts_ty) ->
726 returnTc ((stmt':stmts', True, mzero),
727 stmt_lie `plusLIE` stmts_lie,
730 tcDoStmts _ m (stmt@(BindStmt pat exp src_loc) : stmts)
731 = tcAddSrcLoc src_loc (
732 tcSetErrCtxt (stmtCtxt stmt) (
733 tcPat pat `thenTc` \ (pat', pat_lie, pat_ty) ->
734 tcExpr exp `thenTc` \ (exp', exp_lie, exp_ty) ->
735 newTyVarTy mkTypeKind `thenNF_Tc` \ a ->
736 unifyTauTy a pat_ty `thenTc_`
737 unifyTauTy (mkAppTy m a) exp_ty `thenTc_`
738 returnTc (BindStmt pat' exp' src_loc, pat_lie `plusLIE` exp_lie, irrefutablePat pat')
739 )) `thenTc` \ (stmt', stmt_lie, failure_free) ->
740 tcDoStmts True m stmts `thenTc` \ ((stmts', _, mzero), stmts_lie, stmts_ty) ->
741 returnTc ((stmt':stmts', True, mzero || not failure_free),
742 stmt_lie `plusLIE` stmts_lie,
745 tcDoStmts monad m (LetStmt binds : stmts)
746 = tcBindsAndThen -- No error context, but a binding group is
747 combine -- rather a large thing for an error context anyway
749 (tcDoStmts monad m stmts)
751 combine binds' (stmts', monad, mzero) = ((LetStmt binds' : stmts'), monad, mzero)
755 %************************************************************************
757 \subsection{@tcExprs@ typechecks a {\em list} of expressions}
759 %************************************************************************
762 tcExprs :: [RenamedHsExpr] -> TcM s ([TcExpr s], LIE s, [TcType s])
764 tcExprs [] = returnTc ([], emptyLIE, [])
766 = tcExpr expr `thenTc` \ (expr', lie1, ty) ->
767 tcExprs exprs `thenTc` \ (exprs', lie2, tys) ->
768 returnTc (expr':exprs', lie1 `plusLIE` lie2, ty:tys)
772 % =================================================
779 pp_nest_hang :: String -> Pretty -> Pretty
780 pp_nest_hang label stuff = ppNest 2 (ppHang (ppStr label) 4 stuff)
783 Boring and alphabetical:
785 arithSeqCtxt expr sty
786 = ppHang (ppStr "In an arithmetic sequence:") 4 (ppr sty expr)
789 = ppSep [ppStr "In the branches of a conditional:",
790 pp_nest_hang "`then' branch:" (ppr sty b1),
791 pp_nest_hang "`else' branch:" (ppr sty b2)]
794 = ppHang (ppStr "In a case expression:") 4 (ppr sty expr)
797 = ppHang (ppStr "In an expression with a type signature:")
801 = ppHang (ppStr "In a list expression:") 4 (ppr sty expr)
804 = ppHang (ppStr "In a predicate expression:") 4 (ppr sty expr)
806 sectionRAppCtxt expr sty
807 = ppHang (ppStr "In a right section:") 4 (ppr sty expr)
809 sectionLAppCtxt expr sty
810 = ppHang (ppStr "In a left section:") 4 (ppr sty expr)
812 funAppCtxt fun arg_no arg sty
813 = ppHang (ppCat [ ppStr "In the", speakNth arg_no, ppStr "argument of", ppr sty fun])
814 4 (ppCat [ppStr "namely", ppr sty arg])
817 = ppHang (ppStr "In a list-comprehension qualifer:")
821 = ppHang (ppStr "In a do statement:")
825 = ppHang (ppStr "Too many arguments in an application of the function")
828 lurkingRank2Err fun fun_ty sty
829 = ppHang (ppCat [ppStr "Illegal use of", ppr sty fun])
830 4 (ppAboves [ppStr "It is applied to too few arguments,",
831 ppStr "so that the result type has for-alls in it"])
833 rank2ArgCtxt arg expected_arg_ty sty
834 = ppHang (ppStr "In a polymorphic function argument:")
835 4 (ppSep [ppBeside (ppr sty arg) (ppStr " ::"),
836 ppr sty expected_arg_ty])