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(..),
15 import RnHsSyn ( RenamedHsExpr, RenamedRecordBinds )
16 import TcHsSyn ( TcExpr, TcRecordBinds, simpleHsLitTy, mkHsDictApp, mkHsTyApp )
19 import TcUnify ( tcSubExp, tcGen, (<$>),
20 unifyTauTy, unifyFunTy, unifyListTy, unifyPArrTy,
22 import BasicTypes ( RecFlag(..), isMarkedStrict )
23 import Inst ( InstOrigin(..),
24 LIE, mkLIE, emptyLIE, unitLIE, plusLIE, plusLIEs,
25 newOverloadedLit, newMethodFromName, newIPDict,
26 newDicts, newMethodWithGivenTy,
27 instToId, tcInstCall, tcInstDataCon
29 import TcBinds ( tcBindsAndThen )
30 import TcEnv ( tcLookupClass, tcLookupGlobalId, tcLookupGlobal_maybe,
31 tcLookupTyCon, tcLookupDataCon, tcLookupId
33 import TcMatches ( tcMatchesCase, tcMatchLambda, tcStmts )
34 import TcMonoType ( tcHsSigType, UserTypeCtxt(..) )
35 import TcPat ( badFieldCon )
36 import TcSimplify ( tcSimplifyIPs )
37 import TcMType ( tcInstTyVars, tcInstType, newHoleTyVarTy, zapToType,
38 newTyVarTy, newTyVarTys, zonkTcType, readHoleResult )
39 import TcType ( TcType, TcSigmaType, TcRhoType, TyVarDetails(VanillaTv),
40 tcSplitFunTys, tcSplitTyConApp, mkTyVarTys,
41 isSigmaTy, mkFunTy, mkAppTy, mkTyConTy, mkFunTys,
42 mkTyConApp, mkClassPred, tcFunArgTy,
43 tyVarsOfTypes, isLinearPred,
44 liftedTypeKind, openTypeKind, mkArrowKind,
45 tcSplitSigmaTy, tcTyConAppTyCon,
48 import FieldLabel ( FieldLabel, fieldLabelName, fieldLabelType, fieldLabelTyCon )
49 import Id ( idType, recordSelectorFieldLabel, isRecordSelector, isDataConWrapId_maybe )
50 import DataCon ( dataConFieldLabels, dataConSig,
54 import TyCon ( TyCon, tyConTyVars, tyConTheta, isAlgTyCon, tyConDataCons )
55 import Subst ( mkTopTyVarSubst, substTheta, substTy )
56 import VarSet ( emptyVarSet, elemVarSet )
57 import TysWiredIn ( boolTy, mkListTy, mkPArrTy, listTyCon, parrTyCon )
58 import PrelNames ( cCallableClassName,
60 enumFromName, enumFromThenName,
61 enumFromToName, enumFromThenToName,
62 enumFromToPName, enumFromThenToPName,
63 thenMName, bindMName, failMName, returnMName, ioTyConName
65 import ListSetOps ( minusList )
67 import HscTypes ( TyThing(..) )
74 %************************************************************************
76 \subsection{Main wrappers}
78 %************************************************************************
81 tcExpr :: RenamedHsExpr -- Expession to type check
82 -> TcSigmaType -- Expected type (could be a polytpye)
83 -> TcM (TcExpr, LIE) -- Generalised expr with expected type, and LIE
85 tcExpr expr expected_ty
86 = traceTc (text "tcExpr" <+> (ppr expected_ty $$ ppr expr)) `thenNF_Tc_`
87 tc_expr' expr expected_ty
89 tc_expr' expr expected_ty
90 | not (isSigmaTy expected_ty) -- Monomorphic case
91 = tcMonoExpr expr expected_ty
94 = tcGen expected_ty emptyVarSet (
96 ) `thenTc` \ (gen_fn, expr', lie) ->
97 returnTc (gen_fn <$> expr', lie)
101 %************************************************************************
103 \subsection{The TAUT rules for variables}
105 %************************************************************************
108 tcMonoExpr :: RenamedHsExpr -- Expession to type check
109 -> TcRhoType -- Expected type (could be a type variable)
110 -- Definitely no foralls at the top
114 tcMonoExpr (HsVar name) res_ty
115 = tcId name `thenNF_Tc` \ (expr', lie1, id_ty) ->
116 tcSubExp res_ty id_ty `thenTc` \ (co_fn, lie2) ->
117 returnTc (co_fn <$> expr', lie1 `plusLIE` lie2)
119 tcMonoExpr (HsIPVar ip) res_ty
120 = -- Implicit parameters must have a *tau-type* not a
121 -- type scheme. We enforce this by creating a fresh
122 -- type variable as its type. (Because res_ty may not
124 newTyVarTy openTypeKind `thenNF_Tc` \ ip_ty ->
125 newIPDict (IPOcc ip) ip ip_ty `thenNF_Tc` \ (ip', inst) ->
126 tcSubExp res_ty ip_ty `thenTc` \ (co_fn, lie) ->
127 returnNF_Tc (co_fn <$> HsIPVar ip', lie `plusLIE` unitLIE inst)
131 %************************************************************************
133 \subsection{Expressions type signatures}
135 %************************************************************************
138 tcMonoExpr in_expr@(ExprWithTySig expr poly_ty) res_ty
139 = tcHsSigType ExprSigCtxt poly_ty `thenTc` \ sig_tc_ty ->
140 tcExpr expr sig_tc_ty `thenTc` \ (expr', lie1) ->
142 -- Must instantiate the outer for-alls of sig_tc_ty
143 -- else we risk instantiating a ? res_ty to a forall-type
144 -- which breaks the invariant that tcMonoExpr only returns phi-types
145 tcAddErrCtxt (exprSigCtxt in_expr) $
146 tcInstCall SignatureOrigin sig_tc_ty `thenNF_Tc` \ (inst_fn, lie2, inst_sig_ty) ->
147 tcSubExp res_ty inst_sig_ty `thenTc` \ (co_fn, lie3) ->
149 returnTc (co_fn <$> inst_fn expr', lie1 `plusLIE` lie2 `plusLIE` lie3)
153 %************************************************************************
155 \subsection{Other expression forms}
157 %************************************************************************
160 tcMonoExpr (HsLit lit) res_ty = tcLit lit res_ty
161 tcMonoExpr (HsOverLit lit) res_ty = newOverloadedLit (LiteralOrigin lit) lit res_ty
162 tcMonoExpr (HsPar expr) res_ty = tcMonoExpr expr res_ty
164 tcMonoExpr (NegApp expr neg_name) res_ty
165 = tcMonoExpr (HsApp (HsVar neg_name) expr) res_ty
167 tcMonoExpr (HsLam match) res_ty
168 = tcMatchLambda match res_ty `thenTc` \ (match',lie) ->
169 returnTc (HsLam match', lie)
171 tcMonoExpr (HsApp e1 e2) res_ty
172 = tcApp e1 [e2] res_ty
175 Note that the operators in sections are expected to be binary, and
176 a type error will occur if they aren't.
179 -- Left sections, equivalent to
186 tcMonoExpr in_expr@(SectionL arg1 op) res_ty
187 = tcExpr_id op `thenTc` \ (op', lie1, op_ty) ->
188 split_fun_ty op_ty 2 {- two args -} `thenTc` \ ([arg1_ty, arg2_ty], op_res_ty) ->
189 tcArg op (arg1, arg1_ty, 1) `thenTc` \ (arg1',lie2) ->
190 tcAddErrCtxt (exprCtxt in_expr) $
191 tcSubExp res_ty (mkFunTy arg2_ty op_res_ty) `thenTc` \ (co_fn, lie3) ->
192 returnTc (co_fn <$> SectionL arg1' op', lie1 `plusLIE` lie2 `plusLIE` lie3)
194 -- Right sections, equivalent to \ x -> x op expr, or
197 tcMonoExpr in_expr@(SectionR op arg2) res_ty
198 = tcExpr_id op `thenTc` \ (op', lie1, op_ty) ->
199 split_fun_ty op_ty 2 {- two args -} `thenTc` \ ([arg1_ty, arg2_ty], op_res_ty) ->
200 tcArg op (arg2, arg2_ty, 2) `thenTc` \ (arg2',lie2) ->
201 tcAddErrCtxt (exprCtxt in_expr) $
202 tcSubExp res_ty (mkFunTy arg1_ty op_res_ty) `thenTc` \ (co_fn, lie3) ->
203 returnTc (co_fn <$> SectionR op' arg2', lie1 `plusLIE` lie2 `plusLIE` lie3)
205 -- equivalent to (op e1) e2:
207 tcMonoExpr in_expr@(OpApp arg1 op fix arg2) res_ty
208 = tcExpr_id op `thenTc` \ (op', lie1, op_ty) ->
209 split_fun_ty op_ty 2 {- two args -} `thenTc` \ ([arg1_ty, arg2_ty], op_res_ty) ->
210 tcArg op (arg1, arg1_ty, 1) `thenTc` \ (arg1',lie2a) ->
211 tcArg op (arg2, arg2_ty, 2) `thenTc` \ (arg2',lie2b) ->
212 tcAddErrCtxt (exprCtxt in_expr) $
213 tcSubExp res_ty op_res_ty `thenTc` \ (co_fn, lie3) ->
214 returnTc (OpApp arg1' op' fix arg2',
215 lie1 `plusLIE` lie2a `plusLIE` lie2b `plusLIE` lie3)
218 The interesting thing about @ccall@ is that it is just a template
219 which we instantiate by filling in details about the types of its
220 argument and result (ie minimal typechecking is performed). So, the
221 basic story is that we allocate a load of type variables (to hold the
222 arg/result types); unify them with the args/result; and store them for
226 tcMonoExpr e0@(HsCCall lbl args may_gc is_casm ignored_fake_result_ty) res_ty
228 = getDOptsTc `thenNF_Tc` \ dflags ->
230 checkTc (not (is_casm && dopt_HscLang dflags /= HscC))
231 (vcat [text "_casm_ is only supported when compiling via C (-fvia-C).",
232 text "Either compile with -fvia-C, or, better, rewrite your code",
233 text "to use the foreign function interface. _casm_s are deprecated",
234 text "and support for them may one day disappear."])
237 -- Get the callable and returnable classes.
238 tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
239 tcLookupClass cReturnableClassName `thenNF_Tc` \ cReturnableClass ->
240 tcLookupTyCon ioTyConName `thenNF_Tc` \ ioTyCon ->
242 new_arg_dict (arg, arg_ty)
243 = newDicts (CCallOrigin (unpackFS lbl) (Just arg))
244 [mkClassPred cCallableClass [arg_ty]] `thenNF_Tc` \ arg_dicts ->
245 returnNF_Tc arg_dicts -- Actually a singleton bag
247 result_origin = CCallOrigin (unpackFS lbl) Nothing {- Not an arg -}
251 let tv_idxs | null args = []
252 | otherwise = [1..length args]
254 newTyVarTys (length tv_idxs) openTypeKind `thenNF_Tc` \ arg_tys ->
255 tcMonoExprs args arg_tys `thenTc` \ (args', args_lie) ->
257 -- The argument types can be unlifted or lifted; the result
258 -- type must, however, be lifted since it's an argument to the IO
260 newTyVarTy liftedTypeKind `thenNF_Tc` \ result_ty ->
262 io_result_ty = mkTyConApp ioTyCon [result_ty]
264 unifyTauTy res_ty io_result_ty `thenTc_`
266 -- Construct the extra insts, which encode the
267 -- constraints on the argument and result types.
268 mapNF_Tc new_arg_dict (zipEqual "tcMonoExpr:CCall" args arg_tys) `thenNF_Tc` \ ccarg_dicts_s ->
269 newDicts result_origin [mkClassPred cReturnableClass [result_ty]] `thenNF_Tc` \ ccres_dict ->
270 returnTc (HsCCall lbl args' may_gc is_casm io_result_ty,
271 mkLIE (ccres_dict ++ concat ccarg_dicts_s) `plusLIE` args_lie)
275 tcMonoExpr (HsSCC lbl expr) res_ty
276 = tcMonoExpr expr res_ty `thenTc` \ (expr', lie) ->
277 returnTc (HsSCC lbl expr', lie)
279 tcMonoExpr (HsLet binds expr) res_ty
282 binds -- Bindings to check
283 tc_expr `thenTc` \ (expr', lie) ->
284 returnTc (expr', lie)
286 tc_expr = tcMonoExpr expr res_ty `thenTc` \ (expr', lie) ->
287 returnTc (expr', lie)
288 combiner is_rec bind expr = HsLet (mkMonoBind bind [] is_rec) expr
290 tcMonoExpr in_expr@(HsCase scrut matches src_loc) res_ty
291 = tcAddSrcLoc src_loc $
292 tcAddErrCtxt (caseCtxt in_expr) $
294 -- Typecheck the case alternatives first.
295 -- The case patterns tend to give good type info to use
296 -- when typechecking the scrutinee. For example
299 -- will report that map is applied to too few arguments
301 -- Not only that, but it's better to check the matches on their
302 -- own, so that we get the expected results for scoped type variables.
304 -- (p::a, q::b) -> (q,p)
305 -- The above should work: the match (p,q) -> (q,p) is polymorphic as
306 -- claimed by the pattern signatures. But if we typechecked the
307 -- match with x in scope and x's type as the expected type, we'd be hosed.
309 tcMatchesCase matches res_ty `thenTc` \ (scrut_ty, matches', lie2) ->
311 tcAddErrCtxt (caseScrutCtxt scrut) (
312 tcMonoExpr scrut scrut_ty
313 ) `thenTc` \ (scrut',lie1) ->
315 returnTc (HsCase scrut' matches' src_loc, plusLIE lie1 lie2)
317 tcMonoExpr (HsIf pred b1 b2 src_loc) res_ty
318 = tcAddSrcLoc src_loc $
319 tcAddErrCtxt (predCtxt pred) (
320 tcMonoExpr pred boolTy ) `thenTc` \ (pred',lie1) ->
322 zapToType res_ty `thenTc` \ res_ty' ->
323 -- C.f. the call to zapToType in TcMatches.tcMatches
325 tcMonoExpr b1 res_ty' `thenTc` \ (b1',lie2) ->
326 tcMonoExpr b2 res_ty' `thenTc` \ (b2',lie3) ->
327 returnTc (HsIf pred' b1' b2' src_loc, plusLIE lie1 (plusLIE lie2 lie3))
331 tcMonoExpr expr@(HsDo do_or_lc stmts src_loc) res_ty
332 = tcDoStmts do_or_lc stmts src_loc res_ty
336 tcMonoExpr in_expr@(ExplicitList _ exprs) res_ty -- Non-empty list
337 = unifyListTy res_ty `thenTc` \ elt_ty ->
338 mapAndUnzipTc (tc_elt elt_ty) exprs `thenTc` \ (exprs', lies) ->
339 returnTc (ExplicitList elt_ty exprs', plusLIEs lies)
342 = tcAddErrCtxt (listCtxt expr) $
343 tcMonoExpr expr elt_ty
345 tcMonoExpr in_expr@(ExplicitPArr _ exprs) res_ty -- maybe empty
346 = unifyPArrTy res_ty `thenTc` \ elt_ty ->
347 mapAndUnzipTc (tc_elt elt_ty) exprs `thenTc` \ (exprs', lies) ->
348 returnTc (ExplicitPArr elt_ty exprs', plusLIEs lies)
351 = tcAddErrCtxt (parrCtxt expr) $
352 tcMonoExpr expr elt_ty
354 tcMonoExpr (ExplicitTuple exprs boxity) res_ty
355 = unifyTupleTy boxity (length exprs) res_ty `thenTc` \ arg_tys ->
356 mapAndUnzipTc (\ (expr, arg_ty) -> tcMonoExpr expr arg_ty)
357 (exprs `zip` arg_tys) -- we know they're of equal length.
358 `thenTc` \ (exprs', lies) ->
359 returnTc (ExplicitTuple exprs' boxity, plusLIEs lies)
361 tcMonoExpr expr@(RecordCon con_name rbinds) res_ty
362 = tcAddErrCtxt (recordConCtxt expr) $
363 tcId con_name `thenNF_Tc` \ (con_expr, con_lie, con_tau) ->
365 (_, record_ty) = tcSplitFunTys con_tau
366 (tycon, ty_args) = tcSplitTyConApp record_ty
368 ASSERT( isAlgTyCon tycon )
369 unifyTauTy res_ty record_ty `thenTc_`
371 -- Check that the record bindings match the constructor
372 -- con_name is syntactically constrained to be a data constructor
373 tcLookupDataCon con_name `thenTc` \ data_con ->
375 bad_fields = badFields rbinds data_con
377 if notNull bad_fields then
378 mapNF_Tc (addErrTc . badFieldCon con_name) bad_fields `thenNF_Tc_`
379 failTc -- Fail now, because tcRecordBinds will crash on a bad field
382 -- Typecheck the record bindings
383 tcRecordBinds tycon ty_args rbinds `thenTc` \ (rbinds', rbinds_lie) ->
386 (missing_s_fields, missing_fields) = missingFields rbinds data_con
388 checkTcM (null missing_s_fields)
389 (mapNF_Tc (addErrTc . missingStrictFieldCon con_name) missing_s_fields `thenNF_Tc_`
390 returnNF_Tc ()) `thenNF_Tc_`
391 doptsTc Opt_WarnMissingFields `thenNF_Tc` \ warn ->
392 checkTcM (not (warn && notNull missing_fields))
393 (mapNF_Tc ((warnTc True) . missingFieldCon con_name) missing_fields `thenNF_Tc_`
394 returnNF_Tc ()) `thenNF_Tc_`
396 returnTc (RecordConOut data_con con_expr rbinds', con_lie `plusLIE` rbinds_lie)
398 -- The main complication with RecordUpd is that we need to explicitly
399 -- handle the *non-updated* fields. Consider:
401 -- data T a b = MkT1 { fa :: a, fb :: b }
402 -- | MkT2 { fa :: a, fc :: Int -> Int }
403 -- | MkT3 { fd :: a }
405 -- upd :: T a b -> c -> T a c
406 -- upd t x = t { fb = x}
408 -- The type signature on upd is correct (i.e. the result should not be (T a b))
409 -- because upd should be equivalent to:
411 -- upd t x = case t of
412 -- MkT1 p q -> MkT1 p x
413 -- MkT2 a b -> MkT2 p b
414 -- MkT3 d -> error ...
416 -- So we need to give a completely fresh type to the result record,
417 -- and then constrain it by the fields that are *not* updated ("p" above).
419 -- Note that because MkT3 doesn't contain all the fields being updated,
420 -- its RHS is simply an error, so it doesn't impose any type constraints
422 -- All this is done in STEP 4 below.
424 tcMonoExpr expr@(RecordUpd record_expr rbinds) res_ty
425 = tcAddErrCtxt (recordUpdCtxt expr) $
428 -- Check that the field names are really field names
429 ASSERT( notNull rbinds )
431 field_names = [field_name | (field_name, _, _) <- rbinds]
433 mapNF_Tc tcLookupGlobal_maybe field_names `thenNF_Tc` \ maybe_sel_ids ->
435 bad_guys = [ addErrTc (notSelector field_name)
436 | (field_name, maybe_sel_id) <- field_names `zip` maybe_sel_ids,
438 Just (AnId sel_id) -> not (isRecordSelector sel_id)
442 checkTcM (null bad_guys) (listNF_Tc bad_guys `thenNF_Tc_` failTc) `thenTc_`
445 -- Figure out the tycon and data cons from the first field name
447 -- It's OK to use the non-tc splitters here (for a selector)
448 (Just (AnId sel_id) : _) = maybe_sel_ids
450 (_, _, tau) = tcSplitSigmaTy (idType sel_id) -- Selectors can be overloaded
451 -- when the data type has a context
452 data_ty = tcFunArgTy tau -- Must succeed since sel_id is a selector
453 tycon = tcTyConAppTyCon data_ty
454 data_cons = tyConDataCons tycon
455 tycon_tyvars = tyConTyVars tycon -- The data cons use the same type vars
457 tcInstTyVars VanillaTv tycon_tyvars `thenNF_Tc` \ (_, result_inst_tys, inst_env) ->
460 -- Check that at least one constructor has all the named fields
461 -- i.e. has an empty set of bad fields returned by badFields
462 checkTc (any (null . badFields rbinds) data_cons)
463 (badFieldsUpd rbinds) `thenTc_`
466 -- Typecheck the update bindings.
467 -- (Do this after checking for bad fields in case there's a field that
468 -- doesn't match the constructor.)
470 result_record_ty = mkTyConApp tycon result_inst_tys
472 unifyTauTy res_ty result_record_ty `thenTc_`
473 tcRecordBinds tycon result_inst_tys rbinds `thenTc` \ (rbinds', rbinds_lie) ->
476 -- Use the un-updated fields to find a vector of booleans saying
477 -- which type arguments must be the same in updatee and result.
479 -- WARNING: this code assumes that all data_cons in a common tycon
480 -- have FieldLabels abstracted over the same tyvars.
482 upd_field_lbls = [recordSelectorFieldLabel sel_id | (sel_id, _, _) <- rbinds']
483 con_field_lbls_s = map dataConFieldLabels data_cons
485 -- A constructor is only relevant to this process if
486 -- it contains all the fields that are being updated
487 relevant_field_lbls_s = filter is_relevant con_field_lbls_s
488 is_relevant con_field_lbls = all (`elem` con_field_lbls) upd_field_lbls
490 non_upd_field_lbls = concat relevant_field_lbls_s `minusList` upd_field_lbls
491 common_tyvars = tyVarsOfTypes (map fieldLabelType non_upd_field_lbls)
493 mk_inst_ty (tyvar, result_inst_ty)
494 | tyvar `elemVarSet` common_tyvars = returnNF_Tc result_inst_ty -- Same as result type
495 | otherwise = newTyVarTy liftedTypeKind -- Fresh type
497 mapNF_Tc mk_inst_ty (zip tycon_tyvars result_inst_tys) `thenNF_Tc` \ inst_tys ->
500 -- Typecheck the expression to be updated
502 record_ty = mkTyConApp tycon inst_tys
504 tcMonoExpr record_expr record_ty `thenTc` \ (record_expr', record_lie) ->
507 -- Figure out the LIE we need. We have to generate some
508 -- dictionaries for the data type context, since we are going to
509 -- do pattern matching over the data cons.
511 -- What dictionaries do we need?
512 -- We just take the context of the type constructor
514 theta' = substTheta inst_env (tyConTheta tycon)
516 newDicts RecordUpdOrigin theta' `thenNF_Tc` \ dicts ->
519 returnTc (RecordUpdOut record_expr' record_ty result_record_ty rbinds',
520 mkLIE dicts `plusLIE` record_lie `plusLIE` rbinds_lie)
522 tcMonoExpr (ArithSeqIn seq@(From expr)) res_ty
523 = unifyListTy res_ty `thenTc` \ elt_ty ->
524 tcMonoExpr expr elt_ty `thenTc` \ (expr', lie1) ->
526 newMethodFromName (ArithSeqOrigin seq)
527 elt_ty enumFromName `thenNF_Tc` \ enum_from ->
529 returnTc (ArithSeqOut (HsVar (instToId enum_from)) (From expr'),
530 lie1 `plusLIE` unitLIE enum_from)
532 tcMonoExpr in_expr@(ArithSeqIn seq@(FromThen expr1 expr2)) 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 newMethodFromName (ArithSeqOrigin seq)
538 elt_ty enumFromThenName `thenNF_Tc` \ enum_from_then ->
540 returnTc (ArithSeqOut (HsVar (instToId enum_from_then))
541 (FromThen expr1' expr2'),
542 lie1 `plusLIE` lie2 `plusLIE` unitLIE enum_from_then)
544 tcMonoExpr in_expr@(ArithSeqIn seq@(FromTo expr1 expr2)) res_ty
545 = tcAddErrCtxt (arithSeqCtxt in_expr) $
546 unifyListTy res_ty `thenTc` \ elt_ty ->
547 tcMonoExpr expr1 elt_ty `thenTc` \ (expr1',lie1) ->
548 tcMonoExpr expr2 elt_ty `thenTc` \ (expr2',lie2) ->
549 newMethodFromName (ArithSeqOrigin seq)
550 elt_ty enumFromToName `thenNF_Tc` \ enum_from_to ->
552 returnTc (ArithSeqOut (HsVar (instToId enum_from_to))
553 (FromTo expr1' expr2'),
554 lie1 `plusLIE` lie2 `plusLIE` unitLIE enum_from_to)
556 tcMonoExpr in_expr@(ArithSeqIn seq@(FromThenTo expr1 expr2 expr3)) res_ty
557 = tcAddErrCtxt (arithSeqCtxt in_expr) $
558 unifyListTy res_ty `thenTc` \ elt_ty ->
559 tcMonoExpr expr1 elt_ty `thenTc` \ (expr1',lie1) ->
560 tcMonoExpr expr2 elt_ty `thenTc` \ (expr2',lie2) ->
561 tcMonoExpr expr3 elt_ty `thenTc` \ (expr3',lie3) ->
562 newMethodFromName (ArithSeqOrigin seq)
563 elt_ty enumFromThenToName `thenNF_Tc` \ eft ->
565 returnTc (ArithSeqOut (HsVar (instToId eft))
566 (FromThenTo expr1' expr2' expr3'),
567 lie1 `plusLIE` lie2 `plusLIE` lie3 `plusLIE` unitLIE eft)
569 tcMonoExpr in_expr@(PArrSeqIn seq@(FromTo expr1 expr2)) res_ty
570 = tcAddErrCtxt (parrSeqCtxt in_expr) $
571 unifyPArrTy res_ty `thenTc` \ elt_ty ->
572 tcMonoExpr expr1 elt_ty `thenTc` \ (expr1',lie1) ->
573 tcMonoExpr expr2 elt_ty `thenTc` \ (expr2',lie2) ->
574 newMethodFromName (PArrSeqOrigin seq)
575 elt_ty enumFromToPName `thenNF_Tc` \ enum_from_to ->
577 returnTc (PArrSeqOut (HsVar (instToId enum_from_to))
578 (FromTo expr1' expr2'),
579 lie1 `plusLIE` lie2 `plusLIE` unitLIE enum_from_to)
581 tcMonoExpr in_expr@(PArrSeqIn seq@(FromThenTo expr1 expr2 expr3)) res_ty
582 = tcAddErrCtxt (parrSeqCtxt in_expr) $
583 unifyPArrTy res_ty `thenTc` \ elt_ty ->
584 tcMonoExpr expr1 elt_ty `thenTc` \ (expr1',lie1) ->
585 tcMonoExpr expr2 elt_ty `thenTc` \ (expr2',lie2) ->
586 tcMonoExpr expr3 elt_ty `thenTc` \ (expr3',lie3) ->
587 newMethodFromName (PArrSeqOrigin seq)
588 elt_ty enumFromThenToPName `thenNF_Tc` \ eft ->
590 returnTc (PArrSeqOut (HsVar (instToId eft))
591 (FromThenTo expr1' expr2' expr3'),
592 lie1 `plusLIE` lie2 `plusLIE` lie3 `plusLIE` unitLIE eft)
594 tcMonoExpr (PArrSeqIn _) _
595 = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
596 -- the parser shouldn't have generated it and the renamer shouldn't have
600 %************************************************************************
602 \subsection{Implicit Parameter bindings}
604 %************************************************************************
607 tcMonoExpr (HsWith expr binds is_with) res_ty
608 = tcMonoExpr expr res_ty `thenTc` \ (expr', expr_lie) ->
609 mapAndUnzip3Tc tcIPBind binds `thenTc` \ (avail_ips, binds', bind_lies) ->
611 -- If the binding binds ?x = E, we must now
612 -- discharge any ?x constraints in expr_lie
613 tcSimplifyIPs avail_ips expr_lie `thenTc` \ (expr_lie', dict_binds) ->
615 expr'' = HsLet (mkMonoBind dict_binds [] Recursive) expr'
617 returnTc (HsWith expr'' binds' is_with, expr_lie' `plusLIE` plusLIEs bind_lies)
620 = newTyVarTy openTypeKind `thenTc` \ ty ->
621 tcGetSrcLoc `thenTc` \ loc ->
622 newIPDict (IPBind ip) ip ty `thenNF_Tc` \ (ip', ip_inst) ->
623 tcMonoExpr expr ty `thenTc` \ (expr', lie) ->
624 returnTc (ip_inst, (ip', expr'), lie)
627 %************************************************************************
629 \subsection{@tcApp@ typchecks an application}
631 %************************************************************************
635 tcApp :: RenamedHsExpr -> [RenamedHsExpr] -- Function and args
636 -> TcType -- Expected result type of application
637 -> TcM (TcExpr, LIE) -- Translated fun and args
639 tcApp (HsApp e1 e2) args res_ty
640 = tcApp e1 (e2:args) res_ty -- Accumulate the arguments
642 tcApp fun args res_ty
643 = -- First type-check the function
644 tcExpr_id fun `thenTc` \ (fun', lie_fun, fun_ty) ->
646 tcAddErrCtxt (wrongArgsCtxt "too many" fun args) (
647 traceTc (text "tcApp" <+> (ppr fun $$ ppr fun_ty)) `thenNF_Tc_`
648 split_fun_ty fun_ty (length args)
649 ) `thenTc` \ (expected_arg_tys, actual_result_ty) ->
651 -- Now typecheck the args
652 mapAndUnzipTc (tcArg fun)
653 (zip3 args expected_arg_tys [1..]) `thenTc` \ (args', lie_args_s) ->
655 -- Unify with expected result after type-checking the args
656 -- so that the info from args percolates to actual_result_ty.
657 -- This is when we might detect a too-few args situation.
658 -- (One can think of cases when the opposite order would give
659 -- a better error message.)
660 tcAddErrCtxtM (checkArgsCtxt fun args res_ty actual_result_ty)
661 (tcSubExp res_ty actual_result_ty) `thenTc` \ (co_fn, lie_res) ->
663 returnTc (co_fn <$> foldl HsApp fun' args',
664 lie_res `plusLIE` lie_fun `plusLIE` plusLIEs lie_args_s)
667 -- If an error happens we try to figure out whether the
668 -- function has been given too many or too few arguments,
670 checkArgsCtxt fun args expected_res_ty actual_res_ty tidy_env
671 = zonkTcType expected_res_ty `thenNF_Tc` \ exp_ty' ->
672 zonkTcType actual_res_ty `thenNF_Tc` \ act_ty' ->
674 (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
675 (env2, act_ty'') = tidyOpenType env1 act_ty'
676 (exp_args, _) = tcSplitFunTys exp_ty''
677 (act_args, _) = tcSplitFunTys act_ty''
679 len_act_args = length act_args
680 len_exp_args = length exp_args
682 message | len_exp_args < len_act_args = wrongArgsCtxt "too few" fun args
683 | len_exp_args > len_act_args = wrongArgsCtxt "too many" fun args
684 | otherwise = appCtxt fun args
686 returnNF_Tc (env2, message)
689 split_fun_ty :: TcType -- The type of the function
690 -> Int -- Number of arguments
691 -> TcM ([TcType], -- Function argument types
692 TcType) -- Function result types
694 split_fun_ty fun_ty 0
695 = returnTc ([], fun_ty)
697 split_fun_ty fun_ty n
698 = -- Expect the function to have type A->B
699 unifyFunTy fun_ty `thenTc` \ (arg_ty, res_ty) ->
700 split_fun_ty res_ty (n-1) `thenTc` \ (arg_tys, final_res_ty) ->
701 returnTc (arg_ty:arg_tys, final_res_ty)
705 tcArg :: RenamedHsExpr -- The function (for error messages)
706 -> (RenamedHsExpr, TcSigmaType, Int) -- Actual argument and expected arg type
707 -> TcM (TcExpr, LIE) -- Resulting argument and LIE
709 tcArg the_fun (arg, expected_arg_ty, arg_no)
710 = tcAddErrCtxt (funAppCtxt the_fun arg arg_no) $
711 tcExpr arg expected_arg_ty
715 %************************************************************************
717 \subsection{@tcId@ typchecks an identifier occurrence}
719 %************************************************************************
721 tcId instantiates an occurrence of an Id.
722 The instantiate_it loop runs round instantiating the Id.
723 It has to be a loop because we are now prepared to entertain
725 f:: forall a. Eq a => forall b. Baz b => tau
726 We want to instantiate this to
727 f2::tau {f2 = f1 b (Baz b), f1 = f a (Eq a)}
729 The -fno-method-sharing flag controls what happens so far as the LIE
730 is concerned. The default case is that for an overloaded function we
731 generate a "method" Id, and add the Method Inst to the LIE. So you get
734 f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
735 If you specify -fno-method-sharing, the dictionary application
736 isn't shared, so we get
738 f = /\a (d:Num a) (x:a) -> (+) a d x x
739 This gets a bit less sharing, but
740 a) it's better for RULEs involving overloaded functions
741 b) perhaps fewer separated lambdas
744 tcId :: Name -> NF_TcM (TcExpr, LIE, TcType)
745 tcId name -- Look up the Id and instantiate its type
746 = tcLookupId name `thenNF_Tc` \ id ->
747 case isDataConWrapId_maybe id of
748 Nothing -> loop (HsVar id) emptyLIE (idType id)
749 Just data_con -> inst_data_con id data_con
751 orig = OccurrenceOf name
753 loop (HsVar fun_id) lie fun_ty
754 | want_method_inst fun_ty
755 = tcInstType VanillaTv fun_ty `thenNF_Tc` \ (tyvars, theta, tau) ->
756 newMethodWithGivenTy orig fun_id
757 (mkTyVarTys tyvars) theta tau `thenNF_Tc` \ meth ->
758 loop (HsVar (instToId meth))
759 (unitLIE meth `plusLIE` lie) tau
763 = tcInstCall orig fun_ty `thenNF_Tc` \ (inst_fn, inst_lie, tau) ->
764 loop (inst_fn fun) (inst_lie `plusLIE` lie) tau
767 = returnNF_Tc (fun, lie, fun_ty)
769 want_method_inst fun_ty
770 | opt_NoMethodSharing = False
771 | otherwise = case tcSplitSigmaTy fun_ty of
772 (_,[],_) -> False -- Not overloaded
773 (_,theta,_) -> not (any isLinearPred theta)
774 -- This is a slight hack.
775 -- If f :: (%x :: T) => Int -> Int
776 -- Then if we have two separate calls, (f 3, f 4), we cannot
777 -- make a method constraint that then gets shared, thus:
778 -- let m = f %x in (m 3, m 4)
779 -- because that loses the linearity of the constraint.
780 -- The simplest thing to do is never to construct a method constraint
781 -- in the first place that has a linear implicit parameter in it.
783 -- We treat data constructors differently, because we have to generate
784 -- constraints for their silly theta, which no longer appears in
785 -- the type of dataConWrapId. It's dual to TcPat.tcConstructor
786 inst_data_con id data_con
787 = tcInstDataCon orig data_con `thenNF_Tc` \ (ty_args, ex_dicts, arg_tys, result_ty, stupid_lie, ex_lie, _) ->
788 returnNF_Tc (mkHsDictApp (mkHsTyApp (HsVar id) ty_args) ex_dicts,
789 stupid_lie `plusLIE` ex_lie,
790 mkFunTys arg_tys result_ty)
793 Typecheck expression which in most cases will be an Id.
794 The expression can return a higher-ranked type, such as
795 (forall a. a->a) -> Int
796 so we must create a HoleTyVarTy to pass in as the expected tyvar.
799 tcExpr_id :: RenamedHsExpr -> TcM (TcExpr, LIE, TcType)
800 tcExpr_id (HsVar name) = tcId name
801 tcExpr_id expr = newHoleTyVarTy `thenNF_Tc` \ id_ty ->
802 tcMonoExpr expr id_ty `thenTc` \ (expr', lie_id) ->
803 readHoleResult id_ty `thenTc` \ id_ty' ->
804 returnTc (expr', lie_id, id_ty')
808 %************************************************************************
810 \subsection{@tcDoStmts@ typechecks a {\em list} of do statements}
812 %************************************************************************
815 -- I don't like this lumping together of do expression and list/array
816 -- comprehensions; creating the monad instances is entirely pointless in the
817 -- latter case; I'll leave the list case as it is for the moment, but handle
818 -- arrays extra (would be better to handle arrays and lists together, though)
821 tcDoStmts PArrComp stmts src_loc res_ty
823 ASSERT( notNull stmts )
824 tcAddSrcLoc src_loc $
826 unifyPArrTy res_ty `thenTc` \elt_ty ->
827 let tc_ty = mkTyConTy parrTyCon
828 m_ty = (mkPArrTy, elt_ty)
830 tcStmts (DoCtxt PArrComp) m_ty stmts `thenTc` \(stmts', stmts_lie) ->
831 returnTc (HsDoOut PArrComp stmts'
832 undefined -- don't touch!
836 tcDoStmts do_or_lc stmts src_loc res_ty
837 = -- get the Monad and MonadZero classes
838 -- create type consisting of a fresh monad tyvar
839 ASSERT( notNull stmts )
840 tcAddSrcLoc src_loc $
842 -- If it's a comprehension we're dealing with,
843 -- force it to be a list comprehension.
844 -- (as of Haskell 98, monad comprehensions are no more.)
845 -- Similarily, array comprehensions must involve parallel arrays types
848 ListComp -> unifyListTy res_ty `thenTc` \ elt_ty ->
849 returnNF_Tc (mkTyConTy listTyCon, (mkListTy, elt_ty))
851 PArrComp -> panic "TcExpr.tcDoStmts: How did we get here?!?"
853 _ -> newTyVarTy (mkArrowKind liftedTypeKind liftedTypeKind) `thenNF_Tc` \ m_ty ->
854 newTyVarTy liftedTypeKind `thenNF_Tc` \ elt_ty ->
855 unifyTauTy res_ty (mkAppTy m_ty elt_ty) `thenTc_`
856 returnNF_Tc (m_ty, (mkAppTy m_ty, elt_ty))
857 ) `thenNF_Tc` \ (tc_ty, m_ty) ->
859 tcStmts (DoCtxt do_or_lc) m_ty stmts `thenTc` \ (stmts', stmts_lie) ->
861 -- Build the then and zero methods in case we need them
862 -- It's important that "then" and "return" appear just once in the final LIE,
863 -- not only for typechecker efficiency, but also because otherwise during
864 -- simplification we end up with silly stuff like
865 -- then = case d of (t,r) -> t
867 -- where the second "then" sees that it already exists in the "available" stuff.
869 mapNF_Tc (newMethodFromName DoOrigin tc_ty)
870 [returnMName, failMName, bindMName, thenMName] `thenNF_Tc` \ insts ->
872 returnTc (HsDoOut do_or_lc stmts'
875 stmts_lie `plusLIE` mkLIE insts)
879 %************************************************************************
881 \subsection{Record bindings}
883 %************************************************************************
885 Game plan for record bindings
886 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
887 1. Find the TyCon for the bindings, from the first field label.
889 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
891 For each binding field = value
893 3. Instantiate the field type (from the field label) using the type
896 4 Type check the value using tcArg, passing the field type as
897 the expected argument type.
899 This extends OK when the field types are universally quantified.
904 :: TyCon -- Type constructor for the record
905 -> [TcType] -- Args of this type constructor
906 -> RenamedRecordBinds
907 -> TcM (TcRecordBinds, LIE)
909 tcRecordBinds tycon ty_args rbinds
910 = mapAndUnzipTc do_bind rbinds `thenTc` \ (rbinds', lies) ->
911 returnTc (rbinds', plusLIEs lies)
913 tenv = mkTopTyVarSubst (tyConTyVars tycon) ty_args
915 do_bind (field_lbl_name, rhs, pun_flag)
916 = tcLookupGlobalId field_lbl_name `thenNF_Tc` \ sel_id ->
918 field_lbl = recordSelectorFieldLabel sel_id
919 field_ty = substTy tenv (fieldLabelType field_lbl)
921 ASSERT( isRecordSelector sel_id )
922 -- This lookup and assertion will surely succeed, because
923 -- we check that the fields are indeed record selectors
924 -- before calling tcRecordBinds
925 ASSERT2( fieldLabelTyCon field_lbl == tycon, ppr field_lbl )
926 -- The caller of tcRecordBinds has already checked
927 -- that all the fields come from the same type
929 tcExpr rhs field_ty `thenTc` \ (rhs', lie) ->
931 returnTc ((sel_id, rhs', pun_flag), lie)
933 badFields rbinds data_con
934 = [field_name | (field_name, _, _) <- rbinds,
935 not (field_name `elem` field_names)
938 field_names = map fieldLabelName (dataConFieldLabels data_con)
940 missingFields rbinds data_con
941 | null field_labels = ([], []) -- Not declared as a record;
942 -- But C{} is still valid
944 = (missing_strict_fields, other_missing_fields)
946 missing_strict_fields
947 = [ fl | (fl, str) <- field_info,
949 not (fieldLabelName fl `elem` field_names_used)
952 = [ fl | (fl, str) <- field_info,
953 not (isMarkedStrict str),
954 not (fieldLabelName fl `elem` field_names_used)
957 field_names_used = [ field_name | (field_name, _, _) <- rbinds ]
958 field_labels = dataConFieldLabels data_con
960 field_info = zipEqual "missingFields"
962 (dropList ex_theta (dataConStrictMarks data_con))
963 -- The 'drop' is because dataConStrictMarks
964 -- includes the existential dictionaries
965 (_, _, _, ex_theta, _, _) = dataConSig data_con
968 %************************************************************************
970 \subsection{@tcMonoExprs@ typechecks a {\em list} of expressions}
972 %************************************************************************
975 tcMonoExprs :: [RenamedHsExpr] -> [TcType] -> TcM ([TcExpr], LIE)
977 tcMonoExprs [] [] = returnTc ([], emptyLIE)
978 tcMonoExprs (expr:exprs) (ty:tys)
979 = tcMonoExpr expr ty `thenTc` \ (expr', lie1) ->
980 tcMonoExprs exprs tys `thenTc` \ (exprs', lie2) ->
981 returnTc (expr':exprs', lie1 `plusLIE` lie2)
985 %************************************************************************
987 \subsection{Literals}
989 %************************************************************************
994 tcLit :: HsLit -> TcType -> TcM (TcExpr, LIE)
995 tcLit (HsLitLit s _) res_ty
996 = tcLookupClass cCallableClassName `thenNF_Tc` \ cCallableClass ->
997 newDicts (LitLitOrigin (unpackFS s))
998 [mkClassPred cCallableClass [res_ty]] `thenNF_Tc` \ dicts ->
999 returnTc (HsLit (HsLitLit s res_ty), mkLIE dicts)
1002 = unifyTauTy res_ty (simpleHsLitTy lit) `thenTc_`
1003 returnTc (HsLit lit, emptyLIE)
1007 %************************************************************************
1009 \subsection{Errors and contexts}
1011 %************************************************************************
1015 Boring and alphabetical:
1018 = hang (ptext SLIT("In an arithmetic sequence:")) 4 (ppr expr)
1021 = hang (ptext SLIT("In a parallel array sequence:")) 4 (ppr expr)
1024 = hang (ptext SLIT("In the case expression:")) 4 (ppr expr)
1027 = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1030 = hang (ptext SLIT("When checking the type signature of the expression:"))
1034 = hang (ptext SLIT("In the list element:")) 4 (ppr expr)
1037 = hang (ptext SLIT("In the parallel array element:")) 4 (ppr expr)
1040 = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1043 = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1045 funAppCtxt fun arg arg_no
1046 = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"),
1047 quotes (ppr fun) <> text ", namely"])
1048 4 (quotes (ppr arg))
1050 wrongArgsCtxt too_many_or_few fun args
1051 = hang (ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1052 <+> ptext SLIT("is applied to") <+> text too_many_or_few
1053 <+> ptext SLIT("arguments in the call"))
1054 4 (parens (ppr the_app))
1056 the_app = foldl HsApp fun args -- Used in error messages
1059 = ptext SLIT("In the application") <+> quotes (ppr the_app)
1061 the_app = foldl HsApp fun args -- Used in error messages
1063 lurkingRank2Err fun fun_ty
1064 = hang (hsep [ptext SLIT("Illegal use of"), quotes (ppr fun)])
1065 4 (vcat [ptext SLIT("It is applied to too few arguments"),
1066 ptext SLIT("so that the result type has for-alls in it:") <+> ppr fun_ty])
1069 = hang (ptext SLIT("No constructor has all these fields:"))
1070 4 (pprQuotedList fields)
1072 fields = [field | (field, _, _) <- rbinds]
1074 recordUpdCtxt expr = ptext SLIT("In the record update:") <+> ppr expr
1075 recordConCtxt expr = ptext SLIT("In the record construction:") <+> ppr expr
1078 = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1080 missingStrictFieldCon :: Name -> FieldLabel -> SDoc
1081 missingStrictFieldCon con field
1082 = hsep [ptext SLIT("Constructor") <+> quotes (ppr con),
1083 ptext SLIT("does not have the required strict field"), quotes (ppr field)]
1085 missingFieldCon :: Name -> FieldLabel -> SDoc
1086 missingFieldCon con field
1087 = hsep [ptext SLIT("Field") <+> quotes (ppr field),
1088 ptext SLIT("is not initialised")]