2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcExpr]{Typecheck an expression}
7 module TcExpr ( tcExpr, tcMonoExpr, tcId ) where
9 #include "HsVersions.h"
11 import HsSyn ( HsExpr(..), HsLit(..), ArithSeqInfo(..),
12 HsMatchContext(..), HsDoContext(..), mkMonoBind
14 import RnHsSyn ( RenamedHsExpr, RenamedRecordBinds )
15 import TcHsSyn ( TcExpr, TcRecordBinds, simpleHsLitTy )
18 import TcUnify ( tcSub, tcGen, (<$>),
19 unifyTauTy, unifyFunTy, unifyListTy, unifyTupleTy
21 import BasicTypes ( RecFlag(..), isMarkedStrict )
22 import Inst ( InstOrigin(..),
23 LIE, mkLIE, emptyLIE, unitLIE, plusLIE, plusLIEs,
24 newOverloadedLit, newMethod, newIPDict,
28 import TcBinds ( tcBindsAndThen )
29 import TcEnv ( tcLookupClass, tcLookupGlobalId, tcLookupGlobal_maybe,
30 tcLookupTyCon, tcLookupDataCon, tcLookupId
32 import TcMatches ( tcMatchesCase, tcMatchLambda, tcStmts )
33 import TcMonoType ( tcHsSigType, UserTypeCtxt(..) )
34 import TcPat ( badFieldCon )
35 import TcSimplify ( tcSimplifyIPs )
36 import TcMType ( tcInstTyVars, newTyVarTy, newTyVarTys, zonkTcType )
37 import TcType ( TcType, TcSigmaType, TcPhiType,
38 tcSplitFunTys, tcSplitTyConApp,
39 isSigmaTy, mkFunTy, mkAppTy, mkTyConTy,
40 mkTyConApp, mkClassPred, tcFunArgTy,
42 liftedTypeKind, openTypeKind, mkArrowKind,
43 tcSplitSigmaTy, tcTyConAppTyCon,
46 import FieldLabel ( FieldLabel, fieldLabelName, fieldLabelType, fieldLabelTyCon )
47 import Id ( idType, recordSelectorFieldLabel, isRecordSelector )
48 import DataCon ( dataConFieldLabels, dataConSig,
52 import TyCon ( TyCon, tyConTyVars, isAlgTyCon, tyConDataCons )
53 import Subst ( mkTopTyVarSubst, substTheta, substTy )
54 import VarSet ( elemVarSet )
55 import TysWiredIn ( boolTy, mkListTy, listTyCon )
56 import PrelNames ( cCallableClassName,
58 enumFromName, enumFromThenName,
59 enumFromToName, enumFromThenToName,
60 thenMName, failMName, returnMName, ioTyConName
63 import ListSetOps ( minusList )
66 import HscTypes ( TyThing(..) )
70 %************************************************************************
72 \subsection{Main wrappers}
74 %************************************************************************
77 tcExpr :: RenamedHsExpr -- Expession to type check
78 -> TcSigmaType -- Expected type (could be a polytpye)
79 -> TcM (TcExpr, LIE) -- Generalised expr with expected type, and LIE
81 tcExpr expr expected_ty
82 | not (isSigmaTy expected_ty) -- Monomorphic case
83 = tcMonoExpr expr expected_ty
86 = tcGen expected_ty (tcMonoExpr expr) `thenTc` \ (gen_fn, expr', lie) ->
87 returnTc (gen_fn <$> expr', lie)
91 %************************************************************************
93 \subsection{The TAUT rules for variables}
95 %************************************************************************
98 tcMonoExpr :: RenamedHsExpr -- Expession to type check
99 -> TcPhiType -- Expected type (could be a type variable)
100 -- Definitely no foralls at the top
104 tcMonoExpr (HsVar name) res_ty
105 = tcId name `thenNF_Tc` \ (expr', lie1, id_ty) ->
106 tcSub res_ty id_ty `thenTc` \ (co_fn, lie2) ->
107 returnTc (co_fn <$> expr', lie1 `plusLIE` lie2)
109 tcMonoExpr (HsIPVar ip) res_ty
110 = -- Implicit parameters must have a *tau-type* not a
111 -- type scheme. We enforce this by creating a fresh
112 -- type variable as its type. (Because res_ty may not
114 newTyVarTy openTypeKind `thenNF_Tc` \ ip_ty ->
115 newIPDict (IPOcc ip) ip ip_ty `thenNF_Tc` \ (ip', inst) ->
116 tcSub res_ty ip_ty `thenTc` \ (co_fn, lie) ->
117 returnNF_Tc (co_fn <$> HsIPVar ip', lie `plusLIE` unitLIE inst)
121 %************************************************************************
123 \subsection{Expressions type signatures}
125 %************************************************************************
128 tcMonoExpr in_expr@(ExprWithTySig expr poly_ty) res_ty
129 = tcHsSigType ExprSigCtxt poly_ty `thenTc` \ sig_tc_ty ->
130 tcAddErrCtxt (exprSigCtxt in_expr) $
131 tcExpr expr sig_tc_ty `thenTc` \ (expr', lie1) ->
132 tcSub res_ty sig_tc_ty `thenTc` \ (co_fn, lie2) ->
133 returnTc (co_fn <$> expr', lie1 `plusLIE` lie2)
137 %************************************************************************
139 \subsection{Other expression forms}
141 %************************************************************************
144 tcMonoExpr (HsLit lit) res_ty = tcLit lit res_ty
145 tcMonoExpr (HsOverLit lit) res_ty = newOverloadedLit (LiteralOrigin lit) lit res_ty
146 tcMonoExpr (HsPar expr) res_ty = tcMonoExpr expr res_ty
148 tcMonoExpr (NegApp expr neg_name) res_ty
149 = tcMonoExpr (HsApp (HsVar neg_name) expr) res_ty
151 tcMonoExpr (HsLam match) res_ty
152 = tcMatchLambda match res_ty `thenTc` \ (match',lie) ->
153 returnTc (HsLam match', lie)
155 tcMonoExpr (HsApp e1 e2) res_ty
156 = tcApp e1 [e2] res_ty
159 Note that the operators in sections are expected to be binary, and
160 a type error will occur if they aren't.
163 -- Left sections, equivalent to
170 tcMonoExpr in_expr@(SectionL arg1 op) res_ty
171 = tcExpr_id op `thenTc` \ (op', lie1, op_ty) ->
172 split_fun_ty op_ty 2 {- two args -} `thenTc` \ ([arg1_ty, arg2_ty], op_res_ty) ->
173 tcArg op (arg1, arg1_ty, 1) `thenTc` \ (arg1',lie2) ->
174 tcAddErrCtxt (exprCtxt in_expr) $
175 tcSub res_ty (mkFunTy arg2_ty op_res_ty) `thenTc` \ (co_fn, lie3) ->
176 returnTc (co_fn <$> SectionL arg1' op', lie1 `plusLIE` lie2 `plusLIE` lie3)
178 -- Right sections, equivalent to \ x -> x op expr, or
181 tcMonoExpr in_expr@(SectionR op arg2) res_ty
182 = tcExpr_id op `thenTc` \ (op', lie1, op_ty) ->
183 split_fun_ty op_ty 2 {- two args -} `thenTc` \ ([arg1_ty, arg2_ty], op_res_ty) ->
184 tcArg op (arg2, arg2_ty, 2) `thenTc` \ (arg2',lie2) ->
185 tcAddErrCtxt (exprCtxt in_expr) $
186 tcSub res_ty (mkFunTy arg1_ty op_res_ty) `thenTc` \ (co_fn, lie3) ->
187 returnTc (co_fn <$> SectionR op' arg2', lie1 `plusLIE` lie2 `plusLIE` lie3)
189 -- equivalent to (op e1) e2:
191 tcMonoExpr in_expr@(OpApp arg1 op fix arg2) res_ty
192 = tcExpr_id op `thenTc` \ (op', lie1, op_ty) ->
193 split_fun_ty op_ty 2 {- two args -} `thenTc` \ ([arg1_ty, arg2_ty], op_res_ty) ->
194 tcArg op (arg1, arg1_ty, 1) `thenTc` \ (arg1',lie2a) ->
195 tcArg op (arg2, arg2_ty, 2) `thenTc` \ (arg2',lie2b) ->
196 tcAddErrCtxt (exprCtxt in_expr) $
197 tcSub res_ty op_res_ty `thenTc` \ (co_fn, lie3) ->
198 returnTc (OpApp arg1' op' fix arg2',
199 lie1 `plusLIE` lie2a `plusLIE` lie2b `plusLIE` lie3)
202 The interesting thing about @ccall@ is that it is just a template
203 which we instantiate by filling in details about the types of its
204 argument and result (ie minimal typechecking is performed). So, the
205 basic story is that we allocate a load of type variables (to hold the
206 arg/result types); unify them with the args/result; and store them for
210 tcMonoExpr e0@(HsCCall lbl args may_gc is_casm ignored_fake_result_ty) res_ty
212 = getDOptsTc `thenNF_Tc` \ dflags ->
214 checkTc (not (is_casm && dopt_HscLang dflags /= HscC))
215 (vcat [text "_casm_ is only supported when compiling via C (-fvia-C).",
216 text "Either compile with -fvia-C, or, better, rewrite your code",
217 text "to use the foreign function interface. _casm_s are deprecated",
218 text "and support for them may one day disappear."])
221 -- Get the callable and returnable classes.
222 tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
223 tcLookupClass cReturnableClassName `thenNF_Tc` \ cReturnableClass ->
224 tcLookupTyCon ioTyConName `thenNF_Tc` \ ioTyCon ->
226 new_arg_dict (arg, arg_ty)
227 = newDicts (CCallOrigin (_UNPK_ lbl) (Just arg))
228 [mkClassPred cCallableClass [arg_ty]] `thenNF_Tc` \ arg_dicts ->
229 returnNF_Tc arg_dicts -- Actually a singleton bag
231 result_origin = CCallOrigin (_UNPK_ lbl) Nothing {- Not an arg -}
235 let tv_idxs | null args = []
236 | otherwise = [1..length args]
238 newTyVarTys (length tv_idxs) openTypeKind `thenNF_Tc` \ arg_tys ->
239 tcMonoExprs args arg_tys `thenTc` \ (args', args_lie) ->
241 -- The argument types can be unlifted or lifted; the result
242 -- type must, however, be lifted since it's an argument to the IO
244 newTyVarTy liftedTypeKind `thenNF_Tc` \ result_ty ->
246 io_result_ty = mkTyConApp ioTyCon [result_ty]
248 unifyTauTy res_ty io_result_ty `thenTc_`
250 -- Construct the extra insts, which encode the
251 -- constraints on the argument and result types.
252 mapNF_Tc new_arg_dict (zipEqual "tcMonoExpr:CCall" args arg_tys) `thenNF_Tc` \ ccarg_dicts_s ->
253 newDicts result_origin [mkClassPred cReturnableClass [result_ty]] `thenNF_Tc` \ ccres_dict ->
254 returnTc (HsCCall lbl args' may_gc is_casm io_result_ty,
255 mkLIE (ccres_dict ++ concat ccarg_dicts_s) `plusLIE` args_lie)
259 tcMonoExpr (HsSCC lbl expr) res_ty
260 = tcMonoExpr expr res_ty `thenTc` \ (expr', lie) ->
261 returnTc (HsSCC lbl expr', lie)
263 tcMonoExpr (HsLet binds expr) res_ty
266 binds -- Bindings to check
267 tc_expr `thenTc` \ (expr', lie) ->
268 returnTc (expr', lie)
270 tc_expr = tcMonoExpr expr res_ty `thenTc` \ (expr', lie) ->
271 returnTc (expr', lie)
272 combiner is_rec bind expr = HsLet (mkMonoBind bind [] is_rec) expr
274 tcMonoExpr in_expr@(HsCase scrut matches src_loc) res_ty
275 = tcAddSrcLoc src_loc $
276 tcAddErrCtxt (caseCtxt in_expr) $
278 -- Typecheck the case alternatives first.
279 -- The case patterns tend to give good type info to use
280 -- when typechecking the scrutinee. For example
283 -- will report that map is applied to too few arguments
285 -- Not only that, but it's better to check the matches on their
286 -- own, so that we get the expected results for scoped type variables.
288 -- (p::a, q::b) -> (q,p)
289 -- The above should work: the match (p,q) -> (q,p) is polymorphic as
290 -- claimed by the pattern signatures. But if we typechecked the
291 -- match with x in scope and x's type as the expected type, we'd be hosed.
293 tcMatchesCase matches res_ty `thenTc` \ (scrut_ty, matches', lie2) ->
295 tcAddErrCtxt (caseScrutCtxt scrut) (
296 tcMonoExpr scrut scrut_ty
297 ) `thenTc` \ (scrut',lie1) ->
299 returnTc (HsCase scrut' matches' src_loc, plusLIE lie1 lie2)
301 tcMonoExpr (HsIf pred b1 b2 src_loc) res_ty
302 = tcAddSrcLoc src_loc $
303 tcAddErrCtxt (predCtxt pred) (
304 tcMonoExpr pred boolTy ) `thenTc` \ (pred',lie1) ->
306 tcMonoExpr b1 res_ty `thenTc` \ (b1',lie2) ->
307 tcMonoExpr b2 res_ty `thenTc` \ (b2',lie3) ->
308 returnTc (HsIf pred' b1' b2' src_loc, plusLIE lie1 (plusLIE lie2 lie3))
312 tcMonoExpr expr@(HsDo do_or_lc stmts src_loc) res_ty
313 = tcDoStmts do_or_lc stmts src_loc res_ty
317 tcMonoExpr in_expr@(ExplicitList _ exprs) res_ty -- Non-empty list
318 = unifyListTy res_ty `thenTc` \ elt_ty ->
319 mapAndUnzipTc (tc_elt elt_ty) exprs `thenTc` \ (exprs', lies) ->
320 returnTc (ExplicitList elt_ty exprs', plusLIEs lies)
323 = tcAddErrCtxt (listCtxt expr) $
324 tcMonoExpr expr elt_ty
326 tcMonoExpr (ExplicitTuple exprs boxity) res_ty
327 = unifyTupleTy boxity (length exprs) res_ty `thenTc` \ arg_tys ->
328 mapAndUnzipTc (\ (expr, arg_ty) -> tcMonoExpr expr arg_ty)
329 (exprs `zip` arg_tys) -- we know they're of equal length.
330 `thenTc` \ (exprs', lies) ->
331 returnTc (ExplicitTuple exprs' boxity, plusLIEs lies)
333 tcMonoExpr expr@(RecordCon con_name rbinds) res_ty
334 = tcAddErrCtxt (recordConCtxt expr) $
335 tcId con_name `thenNF_Tc` \ (con_expr, con_lie, con_tau) ->
337 (_, record_ty) = tcSplitFunTys con_tau
338 (tycon, ty_args) = tcSplitTyConApp record_ty
340 ASSERT( isAlgTyCon tycon )
341 unifyTauTy res_ty record_ty `thenTc_`
343 -- Check that the record bindings match the constructor
344 -- con_name is syntactically constrained to be a data constructor
345 tcLookupDataCon con_name `thenTc` \ data_con ->
347 bad_fields = badFields rbinds data_con
349 if not (null bad_fields) then
350 mapNF_Tc (addErrTc . badFieldCon con_name) bad_fields `thenNF_Tc_`
351 failTc -- Fail now, because tcRecordBinds will crash on a bad field
354 -- Typecheck the record bindings
355 tcRecordBinds tycon ty_args rbinds `thenTc` \ (rbinds', rbinds_lie) ->
358 (missing_s_fields, missing_fields) = missingFields rbinds data_con
360 checkTcM (null missing_s_fields)
361 (mapNF_Tc (addErrTc . missingStrictFieldCon con_name) missing_s_fields `thenNF_Tc_`
362 returnNF_Tc ()) `thenNF_Tc_`
363 doptsTc Opt_WarnMissingFields `thenNF_Tc` \ warn ->
364 checkTcM (not (warn && not (null missing_fields)))
365 (mapNF_Tc ((warnTc True) . missingFieldCon con_name) missing_fields `thenNF_Tc_`
366 returnNF_Tc ()) `thenNF_Tc_`
368 returnTc (RecordConOut data_con con_expr rbinds', con_lie `plusLIE` rbinds_lie)
370 -- The main complication with RecordUpd is that we need to explicitly
371 -- handle the *non-updated* fields. Consider:
373 -- data T a b = MkT1 { fa :: a, fb :: b }
374 -- | MkT2 { fa :: a, fc :: Int -> Int }
375 -- | MkT3 { fd :: a }
377 -- upd :: T a b -> c -> T a c
378 -- upd t x = t { fb = x}
380 -- The type signature on upd is correct (i.e. the result should not be (T a b))
381 -- because upd should be equivalent to:
383 -- upd t x = case t of
384 -- MkT1 p q -> MkT1 p x
385 -- MkT2 a b -> MkT2 p b
386 -- MkT3 d -> error ...
388 -- So we need to give a completely fresh type to the result record,
389 -- and then constrain it by the fields that are *not* updated ("p" above).
391 -- Note that because MkT3 doesn't contain all the fields being updated,
392 -- its RHS is simply an error, so it doesn't impose any type constraints
394 -- All this is done in STEP 4 below.
396 tcMonoExpr expr@(RecordUpd record_expr rbinds) res_ty
397 = tcAddErrCtxt (recordUpdCtxt expr) $
400 -- Check that the field names are really field names
401 ASSERT( not (null rbinds) )
403 field_names = [field_name | (field_name, _, _) <- rbinds]
405 mapNF_Tc tcLookupGlobal_maybe field_names `thenNF_Tc` \ maybe_sel_ids ->
407 bad_guys = [ addErrTc (notSelector field_name)
408 | (field_name, maybe_sel_id) <- field_names `zip` maybe_sel_ids,
410 Just (AnId sel_id) -> not (isRecordSelector sel_id)
414 checkTcM (null bad_guys) (listNF_Tc bad_guys `thenNF_Tc_` failTc) `thenTc_`
417 -- Figure out the tycon and data cons from the first field name
419 -- It's OK to use the non-tc splitters here (for a selector)
420 (Just (AnId sel_id) : _) = maybe_sel_ids
421 (_, _, tau) = tcSplitSigmaTy (idType sel_id) -- Selectors can be overloaded
422 -- when the data type has a context
423 data_ty = tcFunArgTy tau -- Must succeed since sel_id is a selector
424 tycon = tcTyConAppTyCon data_ty
425 data_cons = tyConDataCons tycon
426 (con_tyvars, _, _, _, _, _) = dataConSig (head data_cons)
428 tcInstTyVars con_tyvars `thenNF_Tc` \ (_, result_inst_tys, _) ->
431 -- Check that at least one constructor has all the named fields
432 -- i.e. has an empty set of bad fields returned by badFields
433 checkTc (any (null . badFields rbinds) data_cons)
434 (badFieldsUpd rbinds) `thenTc_`
437 -- Typecheck the update bindings.
438 -- (Do this after checking for bad fields in case there's a field that
439 -- doesn't match the constructor.)
441 result_record_ty = mkTyConApp tycon result_inst_tys
443 unifyTauTy res_ty result_record_ty `thenTc_`
444 tcRecordBinds tycon result_inst_tys rbinds `thenTc` \ (rbinds', rbinds_lie) ->
447 -- Use the un-updated fields to find a vector of booleans saying
448 -- which type arguments must be the same in updatee and result.
450 -- WARNING: this code assumes that all data_cons in a common tycon
451 -- have FieldLabels abstracted over the same tyvars.
453 upd_field_lbls = [recordSelectorFieldLabel sel_id | (sel_id, _, _) <- rbinds']
454 con_field_lbls_s = map dataConFieldLabels data_cons
456 -- A constructor is only relevant to this process if
457 -- it contains all the fields that are being updated
458 relevant_field_lbls_s = filter is_relevant con_field_lbls_s
459 is_relevant con_field_lbls = all (`elem` con_field_lbls) upd_field_lbls
461 non_upd_field_lbls = concat relevant_field_lbls_s `minusList` upd_field_lbls
462 common_tyvars = tyVarsOfTypes (map fieldLabelType non_upd_field_lbls)
464 mk_inst_ty (tyvar, result_inst_ty)
465 | tyvar `elemVarSet` common_tyvars = returnNF_Tc result_inst_ty -- Same as result type
466 | otherwise = newTyVarTy liftedTypeKind -- Fresh type
468 mapNF_Tc mk_inst_ty (zip con_tyvars result_inst_tys) `thenNF_Tc` \ inst_tys ->
471 -- Typecheck the expression to be updated
473 record_ty = mkTyConApp tycon inst_tys
475 tcMonoExpr record_expr record_ty `thenTc` \ (record_expr', record_lie) ->
478 -- Figure out the LIE we need. We have to generate some
479 -- dictionaries for the data type context, since we are going to
480 -- do some construction.
482 -- What dictionaries do we need? For the moment we assume that all
483 -- data constructors have the same context, and grab it from the first
484 -- constructor. If they have varying contexts then we'd have to
485 -- union the ones that could participate in the update.
487 (tyvars, theta, _, _, _, _) = dataConSig (head data_cons)
488 inst_env = mkTopTyVarSubst tyvars result_inst_tys
489 theta' = substTheta inst_env theta
491 newDicts RecordUpdOrigin theta' `thenNF_Tc` \ dicts ->
494 returnTc (RecordUpdOut record_expr' record_ty result_record_ty (map instToId dicts) rbinds',
495 mkLIE dicts `plusLIE` record_lie `plusLIE` rbinds_lie)
497 tcMonoExpr (ArithSeqIn seq@(From expr)) res_ty
498 = unifyListTy res_ty `thenTc` \ elt_ty ->
499 tcMonoExpr expr elt_ty `thenTc` \ (expr', lie1) ->
501 tcLookupGlobalId enumFromName `thenNF_Tc` \ sel_id ->
502 newMethod (ArithSeqOrigin seq)
503 sel_id [elt_ty] `thenNF_Tc` \ enum_from ->
505 returnTc (ArithSeqOut (HsVar (instToId enum_from)) (From expr'),
506 lie1 `plusLIE` unitLIE enum_from)
508 tcMonoExpr in_expr@(ArithSeqIn seq@(FromThen expr1 expr2)) res_ty
509 = tcAddErrCtxt (arithSeqCtxt in_expr) $
510 unifyListTy res_ty `thenTc` \ elt_ty ->
511 tcMonoExpr expr1 elt_ty `thenTc` \ (expr1',lie1) ->
512 tcMonoExpr expr2 elt_ty `thenTc` \ (expr2',lie2) ->
513 tcLookupGlobalId enumFromThenName `thenNF_Tc` \ sel_id ->
514 newMethod (ArithSeqOrigin seq) sel_id [elt_ty] `thenNF_Tc` \ enum_from_then ->
516 returnTc (ArithSeqOut (HsVar (instToId enum_from_then))
517 (FromThen expr1' expr2'),
518 lie1 `plusLIE` lie2 `plusLIE` unitLIE enum_from_then)
520 tcMonoExpr in_expr@(ArithSeqIn seq@(FromTo expr1 expr2)) res_ty
521 = tcAddErrCtxt (arithSeqCtxt in_expr) $
522 unifyListTy res_ty `thenTc` \ elt_ty ->
523 tcMonoExpr expr1 elt_ty `thenTc` \ (expr1',lie1) ->
524 tcMonoExpr expr2 elt_ty `thenTc` \ (expr2',lie2) ->
525 tcLookupGlobalId enumFromToName `thenNF_Tc` \ sel_id ->
526 newMethod (ArithSeqOrigin seq) sel_id [elt_ty] `thenNF_Tc` \ enum_from_to ->
528 returnTc (ArithSeqOut (HsVar (instToId enum_from_to))
529 (FromTo expr1' expr2'),
530 lie1 `plusLIE` lie2 `plusLIE` unitLIE enum_from_to)
532 tcMonoExpr in_expr@(ArithSeqIn seq@(FromThenTo expr1 expr2 expr3)) res_ty
533 = tcAddErrCtxt (arithSeqCtxt in_expr) $
534 unifyListTy res_ty `thenTc` \ elt_ty ->
535 tcMonoExpr expr1 elt_ty `thenTc` \ (expr1',lie1) ->
536 tcMonoExpr expr2 elt_ty `thenTc` \ (expr2',lie2) ->
537 tcMonoExpr expr3 elt_ty `thenTc` \ (expr3',lie3) ->
538 tcLookupGlobalId enumFromThenToName `thenNF_Tc` \ sel_id ->
539 newMethod (ArithSeqOrigin seq) sel_id [elt_ty] `thenNF_Tc` \ eft ->
541 returnTc (ArithSeqOut (HsVar (instToId eft))
542 (FromThenTo expr1' expr2' expr3'),
543 lie1 `plusLIE` lie2 `plusLIE` lie3 `plusLIE` unitLIE eft)
546 %************************************************************************
548 \subsection{Implicit Parameter bindings}
550 %************************************************************************
553 tcMonoExpr (HsWith expr binds) res_ty
554 = tcMonoExpr expr res_ty `thenTc` \ (expr', expr_lie) ->
555 mapAndUnzip3Tc tcIPBind binds `thenTc` \ (avail_ips, binds', bind_lies) ->
557 -- If the binding binds ?x = E, we must now
558 -- discharge any ?x constraints in expr_lie
559 tcSimplifyIPs avail_ips expr_lie `thenTc` \ (expr_lie', dict_binds) ->
561 expr'' = HsLet (mkMonoBind dict_binds [] Recursive) expr'
563 returnTc (HsWith expr'' binds', expr_lie' `plusLIE` plusLIEs bind_lies)
566 = newTyVarTy openTypeKind `thenTc` \ ty ->
567 tcGetSrcLoc `thenTc` \ loc ->
568 newIPDict (IPBind ip) ip ty `thenNF_Tc` \ (ip', ip_inst) ->
569 tcMonoExpr expr ty `thenTc` \ (expr', lie) ->
570 returnTc (ip_inst, (ip', expr'), lie)
573 %************************************************************************
575 \subsection{@tcApp@ typchecks an application}
577 %************************************************************************
581 tcApp :: RenamedHsExpr -> [RenamedHsExpr] -- Function and args
582 -> TcType -- Expected result type of application
583 -> TcM (TcExpr, LIE) -- Translated fun and args
585 tcApp (HsApp e1 e2) args res_ty
586 = tcApp e1 (e2:args) res_ty -- Accumulate the arguments
588 tcApp fun args res_ty
589 = -- First type-check the function
590 tcExpr_id fun `thenTc` \ (fun', lie_fun, fun_ty) ->
592 tcAddErrCtxt (wrongArgsCtxt "too many" fun args) (
593 split_fun_ty fun_ty (length args)
594 ) `thenTc` \ (expected_arg_tys, actual_result_ty) ->
596 -- Now typecheck the args
597 mapAndUnzipTc (tcArg fun)
598 (zip3 args expected_arg_tys [1..]) `thenTc` \ (args', lie_args_s) ->
600 -- Unify with expected result after type-checking the args
601 -- so that the info from args percolates to actual_result_ty.
602 -- This is when we might detect a too-few args situation.
603 -- (One can think of cases when the opposite order would give
604 -- a better error message.)
605 tcAddErrCtxtM (checkArgsCtxt fun args res_ty actual_result_ty)
606 (tcSub res_ty actual_result_ty) `thenTc` \ (co_fn, lie_res) ->
608 returnTc (co_fn <$> foldl HsApp fun' args',
609 lie_res `plusLIE` lie_fun `plusLIE` plusLIEs lie_args_s)
612 -- If an error happens we try to figure out whether the
613 -- function has been given too many or too few arguments,
615 checkArgsCtxt fun args expected_res_ty actual_res_ty tidy_env
616 = zonkTcType expected_res_ty `thenNF_Tc` \ exp_ty' ->
617 zonkTcType actual_res_ty `thenNF_Tc` \ act_ty' ->
619 (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
620 (env2, act_ty'') = tidyOpenType env1 act_ty'
621 (exp_args, _) = tcSplitFunTys exp_ty''
622 (act_args, _) = tcSplitFunTys act_ty''
624 len_act_args = length act_args
625 len_exp_args = length exp_args
627 message | len_exp_args < len_act_args = wrongArgsCtxt "too few" fun args
628 | len_exp_args > len_act_args = wrongArgsCtxt "too many" fun args
629 | otherwise = appCtxt fun args
631 returnNF_Tc (env2, message)
634 split_fun_ty :: TcType -- The type of the function
635 -> Int -- Number of arguments
636 -> TcM ([TcType], -- Function argument types
637 TcType) -- Function result types
639 split_fun_ty fun_ty 0
640 = returnTc ([], fun_ty)
642 split_fun_ty fun_ty n
643 = -- Expect the function to have type A->B
644 unifyFunTy fun_ty `thenTc` \ (arg_ty, res_ty) ->
645 split_fun_ty res_ty (n-1) `thenTc` \ (arg_tys, final_res_ty) ->
646 returnTc (arg_ty:arg_tys, final_res_ty)
650 tcArg :: RenamedHsExpr -- The function (for error messages)
651 -> (RenamedHsExpr, TcSigmaType, Int) -- Actual argument and expected arg type
652 -> TcM (TcExpr, LIE) -- Resulting argument and LIE
654 tcArg the_fun (arg, expected_arg_ty, arg_no)
655 = tcAddErrCtxt (funAppCtxt the_fun arg arg_no) $
656 tcExpr arg expected_arg_ty
660 %************************************************************************
662 \subsection{@tcId@ typchecks an identifier occurrence}
664 %************************************************************************
667 tcId :: Name -> NF_TcM (TcExpr, LIE, TcType)
668 tcId name -- Look up the Id and instantiate its type
669 = tcLookupId name `thenNF_Tc` \ id ->
673 Typecheck expression which in most cases will be an Id.
676 tcExpr_id :: RenamedHsExpr -> TcM (TcExpr, LIE, TcType)
677 tcExpr_id (HsVar name) = tcId name
678 tcExpr_id expr = newTyVarTy openTypeKind `thenNF_Tc` \ id_ty ->
679 tcMonoExpr expr id_ty `thenTc` \ (expr', lie_id) ->
680 returnTc (expr', lie_id, id_ty)
684 %************************************************************************
686 \subsection{@tcDoStmts@ typechecks a {\em list} of do statements}
688 %************************************************************************
691 tcDoStmts do_or_lc stmts src_loc res_ty
692 = -- get the Monad and MonadZero classes
693 -- create type consisting of a fresh monad tyvar
694 ASSERT( not (null stmts) )
695 tcAddSrcLoc src_loc $
697 -- If it's a comprehension we're dealing with,
698 -- force it to be a list comprehension.
699 -- (as of Haskell 98, monad comprehensions are no more.)
701 ListComp -> unifyListTy res_ty `thenTc` \ elt_ty ->
702 returnNF_Tc (mkTyConTy listTyCon, (mkListTy, elt_ty))
704 _ -> newTyVarTy (mkArrowKind liftedTypeKind liftedTypeKind) `thenNF_Tc` \ m_ty ->
705 newTyVarTy liftedTypeKind `thenNF_Tc` \ elt_ty ->
706 unifyTauTy res_ty (mkAppTy m_ty elt_ty) `thenTc_`
707 returnNF_Tc (m_ty, (mkAppTy m_ty, elt_ty))
708 ) `thenNF_Tc` \ (tc_ty, m_ty) ->
710 tcStmts (DoCtxt do_or_lc) m_ty stmts `thenTc` \ (stmts', stmts_lie) ->
712 -- Build the then and zero methods in case we need them
713 -- It's important that "then" and "return" appear just once in the final LIE,
714 -- not only for typechecker efficiency, but also because otherwise during
715 -- simplification we end up with silly stuff like
716 -- then = case d of (t,r) -> t
718 -- where the second "then" sees that it already exists in the "available" stuff.
720 tcLookupGlobalId returnMName `thenNF_Tc` \ return_sel_id ->
721 tcLookupGlobalId thenMName `thenNF_Tc` \ then_sel_id ->
722 tcLookupGlobalId failMName `thenNF_Tc` \ fail_sel_id ->
723 newMethod DoOrigin return_sel_id [tc_ty] `thenNF_Tc` \ return_inst ->
724 newMethod DoOrigin then_sel_id [tc_ty] `thenNF_Tc` \ then_inst ->
725 newMethod DoOrigin fail_sel_id [tc_ty] `thenNF_Tc` \ fail_inst ->
727 monad_lie = mkLIE [return_inst, then_inst, fail_inst]
729 returnTc (HsDoOut do_or_lc stmts'
730 (instToId return_inst) (instToId then_inst) (instToId fail_inst)
732 stmts_lie `plusLIE` monad_lie)
736 %************************************************************************
738 \subsection{Record bindings}
740 %************************************************************************
742 Game plan for record bindings
743 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
744 1. Find the TyCon for the bindings, from the first field label.
746 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
748 For each binding field = value
750 3. Instantiate the field type (from the field label) using the type
753 4 Type check the value using tcArg, passing the field type as
754 the expected argument type.
756 This extends OK when the field types are universally quantified.
761 :: TyCon -- Type constructor for the record
762 -> [TcType] -- Args of this type constructor
763 -> RenamedRecordBinds
764 -> TcM (TcRecordBinds, LIE)
766 tcRecordBinds tycon ty_args rbinds
767 = mapAndUnzipTc do_bind rbinds `thenTc` \ (rbinds', lies) ->
768 returnTc (rbinds', plusLIEs lies)
770 tenv = mkTopTyVarSubst (tyConTyVars tycon) ty_args
772 do_bind (field_lbl_name, rhs, pun_flag)
773 = tcLookupGlobalId field_lbl_name `thenNF_Tc` \ sel_id ->
775 field_lbl = recordSelectorFieldLabel sel_id
776 field_ty = substTy tenv (fieldLabelType field_lbl)
778 ASSERT( isRecordSelector sel_id )
779 -- This lookup and assertion will surely succeed, because
780 -- we check that the fields are indeed record selectors
781 -- before calling tcRecordBinds
782 ASSERT2( fieldLabelTyCon field_lbl == tycon, ppr field_lbl )
783 -- The caller of tcRecordBinds has already checked
784 -- that all the fields come from the same type
786 tcExpr rhs field_ty `thenTc` \ (rhs', lie) ->
788 returnTc ((sel_id, rhs', pun_flag), lie)
790 badFields rbinds data_con
791 = [field_name | (field_name, _, _) <- rbinds,
792 not (field_name `elem` field_names)
795 field_names = map fieldLabelName (dataConFieldLabels data_con)
797 missingFields rbinds data_con
798 | null field_labels = ([], []) -- Not declared as a record;
799 -- But C{} is still valid
801 = (missing_strict_fields, other_missing_fields)
803 missing_strict_fields
804 = [ fl | (fl, str) <- field_info,
806 not (fieldLabelName fl `elem` field_names_used)
809 = [ fl | (fl, str) <- field_info,
810 not (isMarkedStrict str),
811 not (fieldLabelName fl `elem` field_names_used)
814 field_names_used = [ field_name | (field_name, _, _) <- rbinds ]
815 field_labels = dataConFieldLabels data_con
817 field_info = zipEqual "missingFields"
819 (dropList ex_theta (dataConStrictMarks data_con))
820 -- The 'drop' is because dataConStrictMarks
821 -- includes the existential dictionaries
822 (_, _, _, ex_theta, _, _) = dataConSig data_con
825 %************************************************************************
827 \subsection{@tcMonoExprs@ typechecks a {\em list} of expressions}
829 %************************************************************************
832 tcMonoExprs :: [RenamedHsExpr] -> [TcType] -> TcM ([TcExpr], LIE)
834 tcMonoExprs [] [] = returnTc ([], emptyLIE)
835 tcMonoExprs (expr:exprs) (ty:tys)
836 = tcMonoExpr expr ty `thenTc` \ (expr', lie1) ->
837 tcMonoExprs exprs tys `thenTc` \ (exprs', lie2) ->
838 returnTc (expr':exprs', lie1 `plusLIE` lie2)
842 %************************************************************************
844 \subsection{Literals}
846 %************************************************************************
851 tcLit :: HsLit -> TcType -> TcM (TcExpr, LIE)
852 tcLit (HsLitLit s _) res_ty
853 = tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
854 newDicts (LitLitOrigin (_UNPK_ s))
855 [mkClassPred cCallableClass [res_ty]] `thenNF_Tc` \ dicts ->
856 returnTc (HsLit (HsLitLit s res_ty), mkLIE dicts)
859 = unifyTauTy res_ty (simpleHsLitTy lit) `thenTc_`
860 returnTc (HsLit lit, emptyLIE)
864 %************************************************************************
866 \subsection{Errors and contexts}
868 %************************************************************************
872 Boring and alphabetical:
875 = hang (ptext SLIT("In an arithmetic sequence:")) 4 (ppr expr)
878 = hang (ptext SLIT("In the case expression:")) 4 (ppr expr)
881 = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
884 = hang (ptext SLIT("In an expression with a type signature:"))
888 = hang (ptext SLIT("In the list element:")) 4 (ppr expr)
891 = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
894 = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
896 funAppCtxt fun arg arg_no
897 = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"),
898 quotes (ppr fun) <> text ", namely"])
901 wrongArgsCtxt too_many_or_few fun args
902 = hang (ptext SLIT("Probable cause:") <+> quotes (ppr fun)
903 <+> ptext SLIT("is applied to") <+> text too_many_or_few
904 <+> ptext SLIT("arguments in the call"))
905 4 (parens (ppr the_app))
907 the_app = foldl HsApp fun args -- Used in error messages
910 = ptext SLIT("In the application") <+> quotes (ppr the_app)
912 the_app = foldl HsApp fun args -- Used in error messages
914 lurkingRank2Err fun fun_ty
915 = hang (hsep [ptext SLIT("Illegal use of"), quotes (ppr fun)])
916 4 (vcat [ptext SLIT("It is applied to too few arguments"),
917 ptext SLIT("so that the result type has for-alls in it:") <+> ppr fun_ty])
920 = hang (ptext SLIT("No constructor has all these fields:"))
921 4 (pprQuotedList fields)
923 fields = [field | (field, _, _) <- rbinds]
925 recordUpdCtxt expr = ptext SLIT("In the record update:") <+> ppr expr
926 recordConCtxt expr = ptext SLIT("In the record construction:") <+> ppr expr
929 = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
931 missingStrictFieldCon :: Name -> FieldLabel -> SDoc
932 missingStrictFieldCon con field
933 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
934 ptext SLIT("does not have the required strict field"), quotes (ppr field)]
936 missingFieldCon :: Name -> FieldLabel -> SDoc
937 missingFieldCon con field
938 = hsep [ptext SLIT("Field") <+> quotes (ppr field),
939 ptext SLIT("is not initialised")]