2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcExpr]{Typecheck an expression}
7 module TcExpr ( tcExpr, tcExpr_id, tcMonoExpr ) where
9 #include "HsVersions.h"
11 #ifdef GHCI /* Only if bootstrapped */
12 import {-# SOURCE #-} TcSplice( tcSpliceExpr, tcBracket )
13 import HsSyn ( HsReify(..), ReifyFlavour(..) )
14 import TcType ( isTauTy )
15 import TcEnv ( bracketOK, tcMetaTy, checkWellStaged, metaLevel )
16 import Name ( isExternalName )
17 import qualified DsMeta
20 import HsSyn ( HsExpr(..), HsLit(..), ArithSeqInfo(..), recBindFields )
21 import RnHsSyn ( RenamedHsExpr, RenamedRecordBinds )
22 import TcHsSyn ( TcExpr, TcRecordBinds, hsLitType, mkHsDictApp, mkHsTyApp, mkHsLet )
24 import TcUnify ( tcSubExp, tcGen, (<$>),
25 unifyTauTy, unifyFunTy, unifyListTy, unifyPArrTy,
27 import BasicTypes ( isMarkedStrict )
28 import Inst ( InstOrigin(..),
29 newOverloadedLit, newMethodFromName, newIPDict,
30 newDicts, newMethodWithGivenTy,
31 instToId, tcInstCall, tcInstDataCon
33 import TcBinds ( tcBindsAndThen )
34 import TcEnv ( tcLookupClass, tcLookupGlobal_maybe, tcLookupIdLvl,
35 tcLookupTyCon, tcLookupDataCon, tcLookupId
37 import TcMatches ( tcMatchesCase, tcMatchLambda, tcDoStmts )
38 import TcMonoType ( tcHsSigType, UserTypeCtxt(..) )
39 import TcPat ( badFieldCon )
40 import TcMType ( tcInstTyVars, tcInstType, newHoleTyVarTy, zapToType,
41 newTyVarTy, newTyVarTys, zonkTcType, readHoleResult )
42 import TcType ( TcType, TcSigmaType, TcRhoType, TyVarDetails(VanillaTv),
43 tcSplitFunTys, tcSplitTyConApp, mkTyVarTys,
44 isSigmaTy, mkFunTy, mkFunTys,
45 mkTyConApp, mkClassPred, tcFunArgTy,
46 tyVarsOfTypes, isLinearPred,
47 liftedTypeKind, openTypeKind,
48 tcSplitSigmaTy, tcTyConAppTyCon,
51 import FieldLabel ( FieldLabel, fieldLabelName, fieldLabelType, fieldLabelTyCon )
52 import Id ( Id, idType, recordSelectorFieldLabel, isRecordSelector )
53 import DataCon ( DataCon, dataConFieldLabels, dataConSig, dataConStrictMarks, dataConWrapId )
55 import TyCon ( TyCon, tyConTyVars, tyConTheta, isAlgTyCon, tyConDataCons, isClassTyCon )
56 import Subst ( mkTopTyVarSubst, substTheta, substTy )
57 import VarSet ( emptyVarSet, elemVarSet )
58 import TysWiredIn ( boolTy )
59 import PrelNames ( cCallableClassName, cReturnableClassName,
60 enumFromName, enumFromThenName,
61 enumFromToName, enumFromThenToName,
62 enumFromToPName, enumFromThenToPName,
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 -- Generalised expr with expected type
85 tcExpr expr expected_ty
86 = traceTc (text "tcExpr" <+> (ppr expected_ty $$ ppr expr)) `thenM_`
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 ) `thenM` \ (gen_fn, expr') ->
97 returnM (gen_fn <$> expr')
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 `thenM` \ (expr', id_ty) ->
116 tcSubExp res_ty id_ty `thenM` \ co_fn ->
117 returnM (co_fn <$> expr')
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 `thenM` \ ip_ty ->
125 newIPDict (IPOcc ip) ip ip_ty `thenM` \ (ip', inst) ->
126 extendLIE inst `thenM_`
127 tcSubExp res_ty ip_ty `thenM` \ co_fn ->
128 returnM (co_fn <$> HsIPVar ip')
132 %************************************************************************
134 \subsection{Expressions type signatures}
136 %************************************************************************
139 tcMonoExpr in_expr@(ExprWithTySig expr poly_ty) res_ty
140 = addErrCtxt (exprSigCtxt in_expr) $
141 tcHsSigType ExprSigCtxt poly_ty `thenM` \ sig_tc_ty ->
142 tcExpr expr sig_tc_ty `thenM` \ expr' ->
144 -- Must instantiate the outer for-alls of sig_tc_ty
145 -- else we risk instantiating a ? res_ty to a forall-type
146 -- which breaks the invariant that tcMonoExpr only returns phi-types
147 tcInstCall SignatureOrigin sig_tc_ty `thenM` \ (inst_fn, inst_sig_ty) ->
148 tcSubExp res_ty inst_sig_ty `thenM` \ co_fn ->
150 returnM (co_fn <$> inst_fn expr')
152 tcMonoExpr (HsType ty) res_ty
153 = failWithTc (text "Can't handle type argument:" <+> ppr ty)
154 -- This is the syntax for type applications that I was planning
155 -- but there are difficulties (e.g. what order for type args)
156 -- so it's not enabled yet.
157 -- Can't eliminate it altogether from the parser, because the
158 -- same parser parses *patterns*.
162 %************************************************************************
164 \subsection{Other expression forms}
166 %************************************************************************
169 tcMonoExpr (HsLit lit) res_ty = tcLit lit res_ty
170 tcMonoExpr (HsOverLit lit) res_ty = newOverloadedLit (LiteralOrigin lit) lit res_ty
171 tcMonoExpr (HsPar expr) res_ty = tcMonoExpr expr res_ty `thenM` \ expr' ->
172 returnM (HsPar expr')
173 tcMonoExpr (HsSCC lbl expr) res_ty = tcMonoExpr expr res_ty `thenM` \ expr' ->
174 returnM (HsSCC lbl expr')
176 tcMonoExpr (HsCoreAnn lbl expr) res_ty = tcMonoExpr expr res_ty `thenM` \ expr' -> -- hdaume: core annotation
177 returnM (HsCoreAnn lbl expr')
178 tcMonoExpr (NegApp expr neg_name) res_ty
179 = tcMonoExpr (HsApp (HsVar neg_name) expr) res_ty
180 -- ToDo: use tcSyntaxName
182 tcMonoExpr (HsLam match) res_ty
183 = tcMatchLambda match res_ty `thenM` \ match' ->
184 returnM (HsLam match')
186 tcMonoExpr (HsApp e1 e2) res_ty
187 = tcApp e1 [e2] res_ty
190 Note that the operators in sections are expected to be binary, and
191 a type error will occur if they aren't.
194 -- Left sections, equivalent to
201 tcMonoExpr in_expr@(SectionL arg1 op) res_ty
202 = tcExpr_id op `thenM` \ (op', op_ty) ->
203 split_fun_ty op_ty 2 {- two args -} `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
204 tcArg op (arg1, arg1_ty, 1) `thenM` \ arg1' ->
205 addErrCtxt (exprCtxt in_expr) $
206 tcSubExp res_ty (mkFunTy arg2_ty op_res_ty) `thenM` \ co_fn ->
207 returnM (co_fn <$> SectionL arg1' op')
209 -- Right sections, equivalent to \ x -> x op expr, or
212 tcMonoExpr in_expr@(SectionR op arg2) res_ty
213 = tcExpr_id op `thenM` \ (op', op_ty) ->
214 split_fun_ty op_ty 2 {- two args -} `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
215 tcArg op (arg2, arg2_ty, 2) `thenM` \ arg2' ->
216 addErrCtxt (exprCtxt in_expr) $
217 tcSubExp res_ty (mkFunTy arg1_ty op_res_ty) `thenM` \ co_fn ->
218 returnM (co_fn <$> SectionR op' arg2')
220 -- equivalent to (op e1) e2:
222 tcMonoExpr in_expr@(OpApp arg1 op fix arg2) res_ty
223 = tcExpr_id op `thenM` \ (op', op_ty) ->
224 split_fun_ty op_ty 2 {- two args -} `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
225 tcArg op (arg1, arg1_ty, 1) `thenM` \ arg1' ->
226 tcArg op (arg2, arg2_ty, 2) `thenM` \ arg2' ->
227 addErrCtxt (exprCtxt in_expr) $
228 tcSubExp res_ty op_res_ty `thenM` \ co_fn ->
229 returnM (OpApp arg1' op' fix arg2')
233 tcMonoExpr (HsLet binds expr) res_ty
236 binds -- Bindings to check
237 (tcMonoExpr expr res_ty)
239 tcMonoExpr in_expr@(HsCase scrut matches src_loc) res_ty
240 = addSrcLoc src_loc $
241 addErrCtxt (caseCtxt in_expr) $
243 -- Typecheck the case alternatives first.
244 -- The case patterns tend to give good type info to use
245 -- when typechecking the scrutinee. For example
248 -- will report that map is applied to too few arguments
250 -- Not only that, but it's better to check the matches on their
251 -- own, so that we get the expected results for scoped type variables.
253 -- (p::a, q::b) -> (q,p)
254 -- The above should work: the match (p,q) -> (q,p) is polymorphic as
255 -- claimed by the pattern signatures. But if we typechecked the
256 -- match with x in scope and x's type as the expected type, we'd be hosed.
258 tcMatchesCase matches res_ty `thenM` \ (scrut_ty, matches') ->
260 addErrCtxt (caseScrutCtxt scrut) (
261 tcMonoExpr scrut scrut_ty
262 ) `thenM` \ scrut' ->
264 returnM (HsCase scrut' matches' src_loc)
266 tcMonoExpr (HsIf pred b1 b2 src_loc) res_ty
267 = addSrcLoc src_loc $
268 addErrCtxt (predCtxt pred) (
269 tcMonoExpr pred boolTy ) `thenM` \ pred' ->
271 zapToType res_ty `thenM` \ res_ty' ->
272 -- C.f. the call to zapToType in TcMatches.tcMatches
274 tcMonoExpr b1 res_ty' `thenM` \ b1' ->
275 tcMonoExpr b2 res_ty' `thenM` \ b2' ->
276 returnM (HsIf pred' b1' b2' src_loc)
278 tcMonoExpr (HsDo do_or_lc stmts method_names _ src_loc) res_ty
279 = addSrcLoc src_loc $
280 tcDoStmts do_or_lc stmts method_names res_ty `thenM` \ (binds, stmts', methods') ->
281 returnM (mkHsLet binds (HsDo do_or_lc stmts' methods' res_ty src_loc))
283 tcMonoExpr in_expr@(ExplicitList _ exprs) res_ty -- Non-empty list
284 = unifyListTy res_ty `thenM` \ elt_ty ->
285 mappM (tc_elt elt_ty) exprs `thenM` \ exprs' ->
286 returnM (ExplicitList elt_ty exprs')
289 = addErrCtxt (listCtxt expr) $
290 tcMonoExpr expr elt_ty
292 tcMonoExpr in_expr@(ExplicitPArr _ exprs) res_ty -- maybe empty
293 = unifyPArrTy res_ty `thenM` \ elt_ty ->
294 mappM (tc_elt elt_ty) exprs `thenM` \ exprs' ->
295 returnM (ExplicitPArr elt_ty exprs')
298 = addErrCtxt (parrCtxt expr) $
299 tcMonoExpr expr elt_ty
301 tcMonoExpr (ExplicitTuple exprs boxity) res_ty
302 = unifyTupleTy boxity (length exprs) res_ty `thenM` \ arg_tys ->
303 tcMonoExprs exprs arg_tys `thenM` \ exprs' ->
304 returnM (ExplicitTuple exprs' boxity)
308 %************************************************************************
312 %************************************************************************
314 The interesting thing about @ccall@ is that it is just a template
315 which we instantiate by filling in details about the types of its
316 argument and result (ie minimal typechecking is performed). So, the
317 basic story is that we allocate a load of type variables (to hold the
318 arg/result types); unify them with the args/result; and store them for
322 tcMonoExpr e0@(HsCCall lbl args may_gc is_casm ignored_fake_result_ty) res_ty
324 = getDOpts `thenM` \ dflags ->
326 checkTc (not (is_casm && dopt_HscLang dflags /= HscC))
327 (vcat [text "_casm_ is only supported when compiling via C (-fvia-C).",
328 text "Either compile with -fvia-C, or, better, rewrite your code",
329 text "to use the foreign function interface. _casm_s are deprecated",
330 text "and support for them may one day disappear."])
333 -- Get the callable and returnable classes.
334 tcLookupClass cCallableClassName `thenM` \ cCallableClass ->
335 tcLookupClass cReturnableClassName `thenM` \ cReturnableClass ->
336 tcLookupTyCon ioTyConName `thenM` \ ioTyCon ->
338 new_arg_dict (arg, arg_ty)
339 = newDicts (CCallOrigin (unpackFS lbl) (Just arg))
340 [mkClassPred cCallableClass [arg_ty]] `thenM` \ arg_dicts ->
341 returnM arg_dicts -- Actually a singleton bag
343 result_origin = CCallOrigin (unpackFS lbl) Nothing {- Not an arg -}
347 let tv_idxs | null args = []
348 | otherwise = [1..length args]
350 newTyVarTys (length tv_idxs) openTypeKind `thenM` \ arg_tys ->
351 tcMonoExprs args arg_tys `thenM` \ args' ->
353 -- The argument types can be unlifted or lifted; the result
354 -- type must, however, be lifted since it's an argument to the IO
356 newTyVarTy liftedTypeKind `thenM` \ result_ty ->
358 io_result_ty = mkTyConApp ioTyCon [result_ty]
360 unifyTauTy res_ty io_result_ty `thenM_`
362 -- Construct the extra insts, which encode the
363 -- constraints on the argument and result types.
364 mappM new_arg_dict (zipEqual "tcMonoExpr:CCall" args arg_tys) `thenM` \ ccarg_dicts_s ->
365 newDicts result_origin [mkClassPred cReturnableClass [result_ty]] `thenM` \ ccres_dict ->
366 extendLIEs (ccres_dict ++ concat ccarg_dicts_s) `thenM_`
367 returnM (HsCCall lbl args' may_gc is_casm io_result_ty)
371 %************************************************************************
373 Record construction and update
375 %************************************************************************
378 tcMonoExpr expr@(RecordCon con_name rbinds) res_ty
379 = addErrCtxt (recordConCtxt expr) $
380 tcId con_name `thenM` \ (con_expr, con_tau) ->
382 (_, record_ty) = tcSplitFunTys con_tau
383 (tycon, ty_args) = tcSplitTyConApp record_ty
385 ASSERT( isAlgTyCon tycon )
386 unifyTauTy res_ty record_ty `thenM_`
388 -- Check that the record bindings match the constructor
389 -- con_name is syntactically constrained to be a data constructor
390 tcLookupDataCon con_name `thenM` \ data_con ->
392 bad_fields = badFields rbinds data_con
394 if notNull bad_fields then
395 mappM (addErrTc . badFieldCon data_con) bad_fields `thenM_`
396 failM -- Fail now, because tcRecordBinds will crash on a bad field
399 -- Typecheck the record bindings
400 tcRecordBinds tycon ty_args rbinds `thenM` \ rbinds' ->
402 -- Check for missing fields
403 checkMissingFields data_con rbinds `thenM_`
405 returnM (RecordConOut data_con con_expr rbinds')
407 -- The main complication with RecordUpd is that we need to explicitly
408 -- handle the *non-updated* fields. Consider:
410 -- data T a b = MkT1 { fa :: a, fb :: b }
411 -- | MkT2 { fa :: a, fc :: Int -> Int }
412 -- | MkT3 { fd :: a }
414 -- upd :: T a b -> c -> T a c
415 -- upd t x = t { fb = x}
417 -- The type signature on upd is correct (i.e. the result should not be (T a b))
418 -- because upd should be equivalent to:
420 -- upd t x = case t of
421 -- MkT1 p q -> MkT1 p x
422 -- MkT2 a b -> MkT2 p b
423 -- MkT3 d -> error ...
425 -- So we need to give a completely fresh type to the result record,
426 -- and then constrain it by the fields that are *not* updated ("p" above).
428 -- Note that because MkT3 doesn't contain all the fields being updated,
429 -- its RHS is simply an error, so it doesn't impose any type constraints
431 -- All this is done in STEP 4 below.
433 tcMonoExpr expr@(RecordUpd record_expr rbinds) res_ty
434 = addErrCtxt (recordUpdCtxt expr) $
437 -- Check that the field names are really field names
438 ASSERT( notNull rbinds )
440 field_names = recBindFields rbinds
442 mappM tcLookupGlobal_maybe field_names `thenM` \ maybe_sel_ids ->
444 bad_guys = [ addErrTc (notSelector field_name)
445 | (field_name, maybe_sel_id) <- field_names `zip` maybe_sel_ids,
446 not (is_selector maybe_sel_id)
448 is_selector (Just (AnId sel_id)) = isRecordSelector sel_id -- Excludes class ops
449 is_selector other = False
451 checkM (null bad_guys) (sequenceM bad_guys `thenM_` failM) `thenM_`
454 -- Figure out the tycon and data cons from the first field name
456 -- It's OK to use the non-tc splitters here (for a selector)
457 (Just (AnId sel_id) : _) = maybe_sel_ids
458 field_lbl = recordSelectorFieldLabel sel_id -- We've failed already if
459 tycon = fieldLabelTyCon field_lbl -- it's not a field label
460 data_cons = tyConDataCons tycon
461 tycon_tyvars = tyConTyVars tycon -- The data cons use the same type vars
463 tcInstTyVars VanillaTv tycon_tyvars `thenM` \ (_, result_inst_tys, inst_env) ->
466 -- Check that at least one constructor has all the named fields
467 -- i.e. has an empty set of bad fields returned by badFields
468 checkTc (any (null . badFields rbinds) data_cons)
469 (badFieldsUpd rbinds) `thenM_`
472 -- Typecheck the update bindings.
473 -- (Do this after checking for bad fields in case there's a field that
474 -- doesn't match the constructor.)
476 result_record_ty = mkTyConApp tycon result_inst_tys
478 unifyTauTy res_ty result_record_ty `thenM_`
479 tcRecordBinds tycon result_inst_tys rbinds `thenM` \ rbinds' ->
482 -- Use the un-updated fields to find a vector of booleans saying
483 -- which type arguments must be the same in updatee and result.
485 -- WARNING: this code assumes that all data_cons in a common tycon
486 -- have FieldLabels abstracted over the same tyvars.
488 upd_field_lbls = map recordSelectorFieldLabel (recBindFields rbinds')
489 con_field_lbls_s = map dataConFieldLabels data_cons
491 -- A constructor is only relevant to this process if
492 -- it contains all the fields that are being updated
493 relevant_field_lbls_s = filter is_relevant con_field_lbls_s
494 is_relevant con_field_lbls = all (`elem` con_field_lbls) upd_field_lbls
496 non_upd_field_lbls = concat relevant_field_lbls_s `minusList` upd_field_lbls
497 common_tyvars = tyVarsOfTypes (map fieldLabelType non_upd_field_lbls)
499 mk_inst_ty (tyvar, result_inst_ty)
500 | tyvar `elemVarSet` common_tyvars = returnM result_inst_ty -- Same as result type
501 | otherwise = newTyVarTy liftedTypeKind -- Fresh type
503 mappM mk_inst_ty (zip tycon_tyvars result_inst_tys) `thenM` \ inst_tys ->
506 -- Typecheck the expression to be updated
508 record_ty = mkTyConApp tycon inst_tys
510 tcMonoExpr record_expr record_ty `thenM` \ record_expr' ->
513 -- Figure out the LIE we need. We have to generate some
514 -- dictionaries for the data type context, since we are going to
515 -- do pattern matching over the data cons.
517 -- What dictionaries do we need?
518 -- We just take the context of the type constructor
520 theta' = substTheta inst_env (tyConTheta tycon)
522 newDicts RecordUpdOrigin theta' `thenM` \ dicts ->
523 extendLIEs dicts `thenM_`
526 returnM (RecordUpdOut record_expr' record_ty result_record_ty rbinds')
530 %************************************************************************
532 Arithmetic sequences e.g. [a,b..]
533 and their parallel-array counterparts e.g. [: a,b.. :]
536 %************************************************************************
539 tcMonoExpr (ArithSeqIn seq@(From expr)) res_ty
540 = unifyListTy res_ty `thenM` \ elt_ty ->
541 tcMonoExpr expr elt_ty `thenM` \ expr' ->
543 newMethodFromName (ArithSeqOrigin seq)
544 elt_ty enumFromName `thenM` \ enum_from ->
546 returnM (ArithSeqOut (HsVar enum_from) (From expr'))
548 tcMonoExpr in_expr@(ArithSeqIn seq@(FromThen expr1 expr2)) res_ty
549 = addErrCtxt (arithSeqCtxt in_expr) $
550 unifyListTy res_ty `thenM` \ elt_ty ->
551 tcMonoExpr expr1 elt_ty `thenM` \ expr1' ->
552 tcMonoExpr expr2 elt_ty `thenM` \ expr2' ->
553 newMethodFromName (ArithSeqOrigin seq)
554 elt_ty enumFromThenName `thenM` \ enum_from_then ->
556 returnM (ArithSeqOut (HsVar enum_from_then) (FromThen expr1' expr2'))
559 tcMonoExpr in_expr@(ArithSeqIn seq@(FromTo expr1 expr2)) res_ty
560 = addErrCtxt (arithSeqCtxt in_expr) $
561 unifyListTy res_ty `thenM` \ elt_ty ->
562 tcMonoExpr expr1 elt_ty `thenM` \ expr1' ->
563 tcMonoExpr expr2 elt_ty `thenM` \ expr2' ->
564 newMethodFromName (ArithSeqOrigin seq)
565 elt_ty enumFromToName `thenM` \ enum_from_to ->
567 returnM (ArithSeqOut (HsVar enum_from_to) (FromTo expr1' expr2'))
569 tcMonoExpr in_expr@(ArithSeqIn seq@(FromThenTo expr1 expr2 expr3)) res_ty
570 = addErrCtxt (arithSeqCtxt in_expr) $
571 unifyListTy res_ty `thenM` \ elt_ty ->
572 tcMonoExpr expr1 elt_ty `thenM` \ expr1' ->
573 tcMonoExpr expr2 elt_ty `thenM` \ expr2' ->
574 tcMonoExpr expr3 elt_ty `thenM` \ expr3' ->
575 newMethodFromName (ArithSeqOrigin seq)
576 elt_ty enumFromThenToName `thenM` \ eft ->
578 returnM (ArithSeqOut (HsVar eft) (FromThenTo expr1' expr2' expr3'))
580 tcMonoExpr in_expr@(PArrSeqIn seq@(FromTo expr1 expr2)) res_ty
581 = addErrCtxt (parrSeqCtxt in_expr) $
582 unifyPArrTy res_ty `thenM` \ elt_ty ->
583 tcMonoExpr expr1 elt_ty `thenM` \ expr1' ->
584 tcMonoExpr expr2 elt_ty `thenM` \ expr2' ->
585 newMethodFromName (PArrSeqOrigin seq)
586 elt_ty enumFromToPName `thenM` \ enum_from_to ->
588 returnM (PArrSeqOut (HsVar enum_from_to) (FromTo expr1' expr2'))
590 tcMonoExpr in_expr@(PArrSeqIn seq@(FromThenTo expr1 expr2 expr3)) res_ty
591 = addErrCtxt (parrSeqCtxt in_expr) $
592 unifyPArrTy res_ty `thenM` \ elt_ty ->
593 tcMonoExpr expr1 elt_ty `thenM` \ expr1' ->
594 tcMonoExpr expr2 elt_ty `thenM` \ expr2' ->
595 tcMonoExpr expr3 elt_ty `thenM` \ expr3' ->
596 newMethodFromName (PArrSeqOrigin seq)
597 elt_ty enumFromThenToPName `thenM` \ eft ->
599 returnM (PArrSeqOut (HsVar eft) (FromThenTo expr1' expr2' expr3'))
601 tcMonoExpr (PArrSeqIn _) _
602 = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
603 -- the parser shouldn't have generated it and the renamer shouldn't have
608 %************************************************************************
612 %************************************************************************
615 #ifdef GHCI /* Only if bootstrapped */
616 -- Rename excludes these cases otherwise
618 tcMonoExpr (HsSplice n expr loc) res_ty = addSrcLoc loc (tcSpliceExpr n expr res_ty)
619 tcMonoExpr (HsBracket brack loc) res_ty = addSrcLoc loc (tcBracket brack res_ty)
621 tcMonoExpr (HsReify (Reify flavour name)) res_ty
622 = addErrCtxt (ptext SLIT("At the reification of") <+> ppr name) $
623 tcMetaTy tycon_name `thenM` \ reify_ty ->
624 unifyTauTy res_ty reify_ty `thenM_`
625 returnM (HsReify (ReifyOut flavour name))
627 tycon_name = case flavour of
628 ReifyDecl -> DsMeta.declTyConName
629 ReifyType -> DsMeta.typeTyConName
630 ReifyFixity -> pprPanic "tcMonoExpr: cant do reifyFixity yet" (ppr name)
635 %************************************************************************
639 %************************************************************************
642 tcMonoExpr other _ = pprPanic "tcMonoExpr" (ppr other)
646 %************************************************************************
648 \subsection{@tcApp@ typchecks an application}
650 %************************************************************************
654 tcApp :: RenamedHsExpr -> [RenamedHsExpr] -- Function and args
655 -> TcType -- Expected result type of application
656 -> TcM TcExpr -- Translated fun and args
658 tcApp (HsApp e1 e2) args res_ty
659 = tcApp e1 (e2:args) res_ty -- Accumulate the arguments
661 tcApp fun args res_ty
662 = -- First type-check the function
663 tcExpr_id fun `thenM` \ (fun', fun_ty) ->
665 addErrCtxt (wrongArgsCtxt "too many" fun args) (
666 traceTc (text "tcApp" <+> (ppr fun $$ ppr fun_ty)) `thenM_`
667 split_fun_ty fun_ty (length args)
668 ) `thenM` \ (expected_arg_tys, actual_result_ty) ->
670 -- Now typecheck the args
672 (zip3 args expected_arg_tys [1..]) `thenM` \ args' ->
674 -- Unify with expected result after type-checking the args
675 -- so that the info from args percolates to actual_result_ty.
676 -- This is when we might detect a too-few args situation.
677 -- (One can think of cases when the opposite order would give
678 -- a better error message.)
679 addErrCtxtM (checkArgsCtxt fun args res_ty actual_result_ty)
680 (tcSubExp res_ty actual_result_ty) `thenM` \ co_fn ->
682 returnM (co_fn <$> foldl HsApp fun' args')
685 -- If an error happens we try to figure out whether the
686 -- function has been given too many or too few arguments,
688 checkArgsCtxt fun args expected_res_ty actual_res_ty tidy_env
689 = zonkTcType expected_res_ty `thenM` \ exp_ty' ->
690 zonkTcType actual_res_ty `thenM` \ act_ty' ->
692 (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
693 (env2, act_ty'') = tidyOpenType env1 act_ty'
694 (exp_args, _) = tcSplitFunTys exp_ty''
695 (act_args, _) = tcSplitFunTys act_ty''
697 len_act_args = length act_args
698 len_exp_args = length exp_args
700 message | len_exp_args < len_act_args = wrongArgsCtxt "too few" fun args
701 | len_exp_args > len_act_args = wrongArgsCtxt "too many" fun args
702 | otherwise = appCtxt fun args
704 returnM (env2, message)
707 split_fun_ty :: TcType -- The type of the function
708 -> Int -- Number of arguments
709 -> TcM ([TcType], -- Function argument types
710 TcType) -- Function result types
712 split_fun_ty fun_ty 0
713 = returnM ([], fun_ty)
715 split_fun_ty fun_ty n
716 = -- Expect the function to have type A->B
717 unifyFunTy fun_ty `thenM` \ (arg_ty, res_ty) ->
718 split_fun_ty res_ty (n-1) `thenM` \ (arg_tys, final_res_ty) ->
719 returnM (arg_ty:arg_tys, final_res_ty)
723 tcArg :: RenamedHsExpr -- The function (for error messages)
724 -> (RenamedHsExpr, TcSigmaType, Int) -- Actual argument and expected arg type
725 -> TcM TcExpr -- Resulting argument and LIE
727 tcArg the_fun (arg, expected_arg_ty, arg_no)
728 = addErrCtxt (funAppCtxt the_fun arg arg_no) $
729 tcExpr arg expected_arg_ty
733 %************************************************************************
735 \subsection{@tcId@ typchecks an identifier occurrence}
737 %************************************************************************
739 tcId instantiates an occurrence of an Id.
740 The instantiate_it loop runs round instantiating the Id.
741 It has to be a loop because we are now prepared to entertain
743 f:: forall a. Eq a => forall b. Baz b => tau
744 We want to instantiate this to
745 f2::tau {f2 = f1 b (Baz b), f1 = f a (Eq a)}
747 The -fno-method-sharing flag controls what happens so far as the LIE
748 is concerned. The default case is that for an overloaded function we
749 generate a "method" Id, and add the Method Inst to the LIE. So you get
752 f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
753 If you specify -fno-method-sharing, the dictionary application
754 isn't shared, so we get
756 f = /\a (d:Num a) (x:a) -> (+) a d x x
757 This gets a bit less sharing, but
758 a) it's better for RULEs involving overloaded functions
759 b) perhaps fewer separated lambdas
762 tcId :: Name -> TcM (TcExpr, TcType)
763 tcId name -- Look up the Id and instantiate its type
764 = -- First check whether it's a DataCon
765 -- Reason: we must not forget to chuck in the
766 -- constraints from their "silly context"
767 tcLookupGlobal_maybe name `thenM` \ maybe_thing ->
768 case maybe_thing of {
769 Just (ADataCon data_con) -> inst_data_con data_con ;
772 -- OK, so now look for ordinary Ids
773 tcLookupIdLvl name `thenM` \ (id, bind_lvl) ->
776 loop (HsVar id) (idType id) -- Non-TH case
778 #else /* GHCI is on */
779 -- Check for cross-stage lifting
780 getStage `thenM` \ use_stage ->
782 Brack use_lvl ps_var lie_var
783 | use_lvl > bind_lvl && not (isExternalName name)
784 -> -- E.g. \x -> [| h x |]
785 -- We must behave as if the reference to x was
787 -- We use 'x' itself as the splice proxy, used by
788 -- the desugarer to stitch it all back together.
789 -- If 'x' occurs many times we may get many identical
790 -- bindings of the same splice proxy, but that doesn't
791 -- matter, although it's a mite untidy.
793 -- NB: During type-checking, isExernalName is true of
794 -- top level things, and false of nested bindings
795 -- Top-level things don't need lifting.
800 checkTc (isTauTy id_ty) (polySpliceErr id) `thenM_`
801 -- If x is polymorphic, its occurrence sites might
802 -- have different instantiations, so we can't use plain
803 -- 'x' as the splice proxy name. I don't know how to
804 -- solve this, and it's probably unimportant, so I'm
805 -- just going to flag an error for now
808 newMethodFromName orig id_ty DsMeta.liftName `thenM` \ lift ->
809 -- Put the 'lift' constraint into the right LIE
811 -- Update the pending splices
812 readMutVar ps_var `thenM` \ ps ->
813 writeMutVar ps_var ((name, HsApp (HsVar lift) (HsVar id)) : ps) `thenM_`
815 returnM (HsVar id, id_ty))
818 checkWellStaged (quotes (ppr id)) bind_lvl use_stage `thenM_`
819 loop (HsVar id) (idType id)
824 orig = OccurrenceOf name
826 loop (HsVar fun_id) fun_ty
827 | want_method_inst fun_ty
828 = tcInstType VanillaTv fun_ty `thenM` \ (tyvars, theta, tau) ->
829 newMethodWithGivenTy orig fun_id
830 (mkTyVarTys tyvars) theta tau `thenM` \ meth_id ->
831 loop (HsVar meth_id) tau
835 = tcInstCall orig fun_ty `thenM` \ (inst_fn, tau) ->
836 loop (inst_fn fun) tau
839 = returnM (fun, fun_ty)
841 -- Hack Alert (want_method_inst)!
842 -- If f :: (%x :: T) => Int -> Int
843 -- Then if we have two separate calls, (f 3, f 4), we cannot
844 -- make a method constraint that then gets shared, thus:
845 -- let m = f %x in (m 3, m 4)
846 -- because that loses the linearity of the constraint.
847 -- The simplest thing to do is never to construct a method constraint
848 -- in the first place that has a linear implicit parameter in it.
849 want_method_inst fun_ty
850 | opt_NoMethodSharing = False
851 | otherwise = case tcSplitSigmaTy fun_ty of
852 (_,[],_) -> False -- Not overloaded
853 (_,theta,_) -> not (any isLinearPred theta)
856 -- We treat data constructors differently, because we have to generate
857 -- constraints for their silly theta, which no longer appears in
858 -- the type of dataConWrapId. It's dual to TcPat.tcConstructor
859 inst_data_con data_con
860 = tcInstDataCon orig data_con `thenM` \ (ty_args, ex_dicts, arg_tys, result_ty, _) ->
861 extendLIEs ex_dicts `thenM_`
862 returnM (mkHsDictApp (mkHsTyApp (HsVar (dataConWrapId data_con)) ty_args)
863 (map instToId ex_dicts),
864 mkFunTys arg_tys result_ty)
867 Typecheck expression which in most cases will be an Id.
868 The expression can return a higher-ranked type, such as
869 (forall a. a->a) -> Int
870 so we must create a HoleTyVarTy to pass in as the expected tyvar.
873 tcExpr_id :: RenamedHsExpr -> TcM (TcExpr, TcType)
874 tcExpr_id (HsVar name) = tcId name
875 tcExpr_id expr = newHoleTyVarTy `thenM` \ id_ty ->
876 tcMonoExpr expr id_ty `thenM` \ expr' ->
877 readHoleResult id_ty `thenM` \ id_ty' ->
878 returnM (expr', id_ty')
882 %************************************************************************
884 \subsection{Record bindings}
886 %************************************************************************
888 Game plan for record bindings
889 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
890 1. Find the TyCon for the bindings, from the first field label.
892 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
894 For each binding field = value
896 3. Instantiate the field type (from the field label) using the type
899 4 Type check the value using tcArg, passing the field type as
900 the expected argument type.
902 This extends OK when the field types are universally quantified.
907 :: TyCon -- Type constructor for the record
908 -> [TcType] -- Args of this type constructor
909 -> RenamedRecordBinds
912 tcRecordBinds tycon ty_args rbinds
913 = mappM do_bind rbinds
915 tenv = mkTopTyVarSubst (tyConTyVars tycon) ty_args
917 do_bind (field_lbl_name, rhs)
918 = addErrCtxt (fieldCtxt field_lbl_name) $
919 tcLookupId field_lbl_name `thenM` \ sel_id ->
921 field_lbl = recordSelectorFieldLabel sel_id
922 field_ty = substTy tenv (fieldLabelType field_lbl)
924 ASSERT( isRecordSelector sel_id )
925 -- This lookup and assertion will surely succeed, because
926 -- we check that the fields are indeed record selectors
927 -- before calling tcRecordBinds
928 ASSERT2( fieldLabelTyCon field_lbl == tycon, ppr field_lbl )
929 -- The caller of tcRecordBinds has already checked
930 -- that all the fields come from the same type
932 tcExpr rhs field_ty `thenM` \ rhs' ->
934 returnM (sel_id, rhs')
936 badFields rbinds data_con
937 = filter (not . (`elem` field_names)) (recBindFields rbinds)
939 field_names = map fieldLabelName (dataConFieldLabels data_con)
941 checkMissingFields :: DataCon -> RenamedRecordBinds -> TcM ()
942 checkMissingFields data_con rbinds
943 | null field_labels -- Not declared as a record;
944 -- But C{} is still valid if no strict fields
945 = if any isMarkedStrict field_strs then
946 -- Illegal if any arg is strict
947 addErrTc (missingStrictFields data_con [])
951 | otherwise -- A record
952 = checkM (null missing_s_fields)
953 (addErrTc (missingStrictFields data_con missing_s_fields)) `thenM_`
955 doptM Opt_WarnMissingFields `thenM` \ warn ->
956 checkM (not (warn && notNull missing_ns_fields))
957 (warnTc True (missingFields data_con missing_ns_fields))
961 = [ fl | (fl, str) <- field_info,
963 not (fieldLabelName fl `elem` field_names_used)
966 = [ fl | (fl, str) <- field_info,
967 not (isMarkedStrict str),
968 not (fieldLabelName fl `elem` field_names_used)
971 field_names_used = recBindFields rbinds
972 field_labels = dataConFieldLabels data_con
974 field_info = zipEqual "missingFields"
978 field_strs = dropList ex_theta (dataConStrictMarks data_con)
979 -- The 'drop' is because dataConStrictMarks
980 -- includes the existential dictionaries
981 (_, _, _, ex_theta, _, _) = dataConSig data_con
984 %************************************************************************
986 \subsection{@tcMonoExprs@ typechecks a {\em list} of expressions}
988 %************************************************************************
991 tcMonoExprs :: [RenamedHsExpr] -> [TcType] -> TcM [TcExpr]
993 tcMonoExprs [] [] = returnM []
994 tcMonoExprs (expr:exprs) (ty:tys)
995 = tcMonoExpr expr ty `thenM` \ expr' ->
996 tcMonoExprs exprs tys `thenM` \ exprs' ->
997 returnM (expr':exprs')
1001 %************************************************************************
1003 \subsection{Literals}
1005 %************************************************************************
1007 Overloaded literals.
1010 tcLit :: HsLit -> TcType -> TcM TcExpr
1011 tcLit (HsLitLit s _) res_ty
1012 = tcLookupClass cCallableClassName `thenM` \ cCallableClass ->
1013 newDicts (LitLitOrigin (unpackFS s))
1014 [mkClassPred cCallableClass [res_ty]] `thenM` \ dicts ->
1015 extendLIEs dicts `thenM_`
1016 returnM (HsLit (HsLitLit s res_ty))
1019 = unifyTauTy res_ty (hsLitType lit) `thenM_`
1024 %************************************************************************
1026 \subsection{Errors and contexts}
1028 %************************************************************************
1030 Boring and alphabetical:
1033 = hang (ptext SLIT("In an arithmetic sequence:")) 4 (ppr expr)
1036 = hang (ptext SLIT("In a parallel array sequence:")) 4 (ppr expr)
1039 = hang (ptext SLIT("In the case expression:")) 4 (ppr expr)
1042 = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1045 = hang (ptext SLIT("When checking the type signature of the expression:"))
1049 = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1051 fieldCtxt field_name
1052 = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1054 funAppCtxt fun arg arg_no
1055 = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"),
1056 quotes (ppr fun) <> text ", namely"])
1057 4 (quotes (ppr arg))
1060 = hang (ptext SLIT("In the list element:")) 4 (ppr expr)
1063 = hang (ptext SLIT("In the parallel array element:")) 4 (ppr expr)
1066 = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1069 = ptext SLIT("In the application") <+> quotes (ppr the_app)
1071 the_app = foldl HsApp fun args -- Used in error messages
1073 lurkingRank2Err fun fun_ty
1074 = hang (hsep [ptext SLIT("Illegal use of"), quotes (ppr fun)])
1075 4 (vcat [ptext SLIT("It is applied to too few arguments"),
1076 ptext SLIT("so that the result type has for-alls in it:") <+> ppr fun_ty])
1079 = hang (ptext SLIT("No constructor has all these fields:"))
1080 4 (pprQuotedList (recBindFields rbinds))
1082 recordUpdCtxt expr = ptext SLIT("In the record update:") <+> ppr expr
1083 recordConCtxt expr = ptext SLIT("In the record construction:") <+> ppr expr
1086 = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1088 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1089 missingStrictFields con fields
1092 rest | null fields = empty -- Happens for non-record constructors
1093 -- with strict fields
1094 | otherwise = colon <+> pprWithCommas ppr fields
1096 header = ptext SLIT("Constructor") <+> quotes (ppr con) <+>
1097 ptext SLIT("does not have the required strict field(s)")
1099 missingFields :: DataCon -> [FieldLabel] -> SDoc
1100 missingFields con fields
1101 = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:")
1102 <+> pprWithCommas ppr fields
1104 polySpliceErr :: Id -> SDoc
1106 = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)
1108 wrongArgsCtxt too_many_or_few fun args
1109 = hang (ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1110 <+> ptext SLIT("is applied to") <+> text too_many_or_few
1111 <+> ptext SLIT("arguments in the call"))
1112 4 (parens (ppr the_app))
1114 the_app = foldl HsApp fun args -- Used in error messages