2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcExpr]{Typecheck an expression}
7 module TcExpr ( tcPolyExpr, tcPolyExprNC,
8 tcMonoExpr, tcInferRho, tcSyntaxOp ) where
10 #include "HsVersions.h"
12 #ifdef GHCI /* Only if bootstrapped */
13 import {-# SOURCE #-} TcSplice( tcSpliceExpr, tcBracket )
14 import HsSyn ( nlHsVar )
16 import Name ( isExternalName )
17 import TcType ( isTauTy )
18 import TcEnv ( checkWellStaged )
19 import HsSyn ( nlHsApp )
20 import qualified DsMeta
23 import HsSyn ( HsExpr(..), LHsExpr, ArithSeqInfo(..), recBindFields,
24 HsMatchContext(..), HsRecordBinds, mkHsCoerce,
26 import TcHsSyn ( hsLitType )
28 import TcUnify ( tcInfer, tcSubExp, tcFunResTy, tcGen, boxyUnify, subFunTys, zapToMonotype, stripBoxyType,
29 boxySplitListTy, boxySplitTyConApp, wrapFunResCoercion, preSubType,
31 import BasicTypes ( Arity, isMarkedStrict )
32 import Inst ( newMethodFromName, newIPDict, mkInstCoFn,
33 newDicts, newMethodWithGivenTy, tcInstStupidTheta )
34 import TcBinds ( tcLocalBinds )
35 import TcEnv ( tcLookup, tcLookupDataCon, tcLookupField )
36 import TcArrows ( tcProc )
37 import TcMatches ( tcMatchesCase, tcMatchLambda, tcDoStmts, tcBody,
39 import TcHsType ( tcHsSigType, UserTypeCtxt(..) )
40 import TcPat ( tcOverloadedLit, badFieldCon )
41 import TcMType ( tcInstTyVars, newFlexiTyVarTy, newBoxyTyVars,
42 readFilledBox, zonkTcTypes )
43 import TcType ( TcType, TcSigmaType, TcRhoType, TvSubst,
44 BoxySigmaType, BoxyRhoType, ThetaType,
46 tcMultiSplitSigmaTy, tcSplitFunTysN,
47 tcSplitTyConApp_maybe,
48 isSigmaTy, mkFunTy, mkTyConApp, isLinearPred,
49 exactTyVarsOfType, exactTyVarsOfTypes,
50 zipTopTvSubst, zipOpenTvSubst, substTys, substTyVar
52 import {- Kind parts of -}
55 import Id ( Id, idType, recordSelectorFieldLabel,
56 isRecordSelector, isNaughtyRecordSelector,
58 import DataCon ( DataCon, dataConFieldLabels, dataConStrictMarks,
60 dataConWrapId, isVanillaDataCon, dataConUnivTyVars,
63 import TyCon ( FieldLabel, tyConStupidTheta, tyConDataCons,
65 import Type ( substTheta, substTy )
66 import Var ( TyVar, tyVarKind )
67 import VarSet ( emptyVarSet, elemVarSet, unionVarSet )
68 import TysWiredIn ( boolTy, parrTyCon, tupleTyCon )
69 import PrelNames ( enumFromName, enumFromThenName,
70 enumFromToName, enumFromThenToName,
71 enumFromToPName, enumFromThenToPName, negateName,
74 import PrimOp ( tagToEnumKey )
77 import StaticFlags ( opt_NoMethodSharing )
78 import HscTypes ( TyThing(..) )
79 import SrcLoc ( Located(..), unLoc, getLoc )
81 import ListSetOps ( assocMaybe )
82 import Maybes ( catMaybes )
87 import TyCon ( tyConArity )
91 %************************************************************************
93 \subsection{Main wrappers}
95 %************************************************************************
98 tcPolyExpr, tcPolyExprNC
99 :: LHsExpr Name -- Expession to type check
100 -> BoxySigmaType -- Expected type (could be a polytpye)
101 -> TcM (LHsExpr TcId) -- Generalised expr with expected type
103 -- tcPolyExpr is a convenient place (frequent but not too frequent) place
104 -- to add context information.
105 -- The NC version does not do so, usually because the caller wants
108 tcPolyExpr expr res_ty
109 = addErrCtxt (exprCtxt (unLoc expr)) $
110 tcPolyExprNC expr res_ty
112 tcPolyExprNC expr res_ty
114 = do { (gen_fn, expr') <- tcGen res_ty emptyVarSet (tcPolyExprNC expr)
115 -- Note the recursive call to tcPolyExpr, because the
116 -- type may have multiple layers of for-alls
117 ; return (L (getLoc expr') (mkHsCoerce gen_fn (unLoc expr'))) }
120 = tcMonoExpr expr res_ty
123 tcPolyExprs :: [LHsExpr Name] -> [TcType] -> TcM [LHsExpr TcId]
124 tcPolyExprs [] [] = returnM []
125 tcPolyExprs (expr:exprs) (ty:tys)
126 = do { expr' <- tcPolyExpr expr ty
127 ; exprs' <- tcPolyExprs exprs tys
128 ; returnM (expr':exprs') }
129 tcPolyExprs exprs tys = pprPanic "tcPolyExprs" (ppr exprs $$ ppr tys)
132 tcMonoExpr :: LHsExpr Name -- Expression to type check
133 -> BoxyRhoType -- Expected type (could be a type variable)
134 -- Definitely no foralls at the top
135 -- Can contain boxes, which will be filled in
136 -> TcM (LHsExpr TcId)
138 tcMonoExpr (L loc expr) res_ty
139 = ASSERT( not (isSigmaTy res_ty) )
141 do { expr' <- tcExpr expr res_ty
142 ; return (L loc expr') }
145 tcInferRho :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
146 tcInferRho expr = tcInfer (tcMonoExpr expr)
151 %************************************************************************
153 tcExpr: the main expression typechecker
155 %************************************************************************
158 tcExpr :: HsExpr Name -> BoxyRhoType -> TcM (HsExpr TcId)
159 tcExpr (HsVar name) res_ty = tcId (OccurrenceOf name) name res_ty
161 tcExpr (HsLit lit) res_ty = do { boxyUnify (hsLitType lit) res_ty
162 ; return (HsLit lit) }
164 tcExpr (HsPar expr) res_ty = do { expr' <- tcMonoExpr expr res_ty
165 ; return (HsPar expr') }
167 tcExpr (HsSCC lbl expr) res_ty = do { expr' <- tcMonoExpr expr res_ty
168 ; returnM (HsSCC lbl expr') }
170 tcExpr (HsCoreAnn lbl expr) res_ty -- hdaume: core annotation
171 = do { expr' <- tcMonoExpr expr res_ty
172 ; return (HsCoreAnn lbl expr') }
174 tcExpr (HsOverLit lit) res_ty
175 = do { lit' <- tcOverloadedLit (LiteralOrigin lit) lit res_ty
176 ; return (HsOverLit lit') }
178 tcExpr (NegApp expr neg_expr) res_ty
179 = do { neg_expr' <- tcSyntaxOp (OccurrenceOf negateName) neg_expr
180 (mkFunTy res_ty res_ty)
181 ; expr' <- tcMonoExpr expr res_ty
182 ; return (NegApp expr' neg_expr') }
184 tcExpr (HsIPVar ip) res_ty
185 = do { -- Implicit parameters must have a *tau-type* not a
186 -- type scheme. We enforce this by creating a fresh
187 -- type variable as its type. (Because res_ty may not
189 ip_ty <- newFlexiTyVarTy argTypeKind -- argTypeKind: it can't be an unboxed tuple
190 ; co_fn <- tcSubExp ip_ty res_ty
191 ; (ip', inst) <- newIPDict (IPOccOrigin ip) ip ip_ty
193 ; return (mkHsCoerce co_fn (HsIPVar ip')) }
195 tcExpr (HsApp e1 e2) res_ty
198 go :: LHsExpr Name -> [LHsExpr Name] -> TcM (HsExpr TcId)
199 go (L _ (HsApp e1 e2)) args = go e1 (e2:args)
200 go lfun@(L loc fun) args
201 = do { (fun', args') <- -- addErrCtxt (callCtxt lfun args) $
202 tcApp fun (length args) (tcArgs lfun args) res_ty
203 ; return (unLoc (foldl mkHsApp (L loc fun') args')) }
205 tcExpr (HsLam match) res_ty
206 = do { (co_fn, match') <- tcMatchLambda match res_ty
207 ; return (mkHsCoerce co_fn (HsLam match')) }
209 tcExpr in_expr@(ExprWithTySig expr sig_ty) res_ty
210 = do { sig_tc_ty <- tcHsSigType ExprSigCtxt sig_ty
211 ; expr' <- tcPolyExpr expr sig_tc_ty
212 ; co_fn <- tcSubExp sig_tc_ty res_ty
213 ; return (mkHsCoerce co_fn (ExprWithTySigOut expr' sig_ty)) }
215 tcExpr (HsType ty) res_ty
216 = failWithTc (text "Can't handle type argument:" <+> ppr ty)
217 -- This is the syntax for type applications that I was planning
218 -- but there are difficulties (e.g. what order for type args)
219 -- so it's not enabled yet.
220 -- Can't eliminate it altogether from the parser, because the
221 -- same parser parses *patterns*.
225 %************************************************************************
227 Infix operators and sections
229 %************************************************************************
232 tcExpr in_expr@(OpApp arg1 lop@(L loc op) fix arg2) res_ty
233 = do { (op', [arg1', arg2']) <- tcApp op 2 (tcArgs lop [arg1,arg2]) res_ty
234 ; return (OpApp arg1' (L loc op') fix arg2') }
236 -- Left sections, equivalent to
243 -- We treat it as similar to the latter, so we don't
244 -- actually require the function to take two arguments
245 -- at all. For example, (x `not`) means (not x);
246 -- you get postfix operators! Not really Haskell 98
247 -- I suppose, but it's less work and kind of useful.
249 tcExpr in_expr@(SectionL arg1 lop@(L loc op)) res_ty
250 = do { (op', [arg1']) <- tcApp op 1 (tcArgs lop [arg1]) res_ty
251 ; return (SectionL arg1' (L loc op')) }
253 -- Right sections, equivalent to \ x -> x `op` expr, or
256 tcExpr in_expr@(SectionR lop@(L loc op) arg2) res_ty
257 = do { (co_fn, (op', arg2')) <- subFunTys doc 1 res_ty $ \ [arg1_ty'] res_ty' ->
258 tcApp op 2 (tc_args arg1_ty') res_ty'
259 ; return (mkHsCoerce co_fn (SectionR (L loc op') arg2')) }
261 doc = ptext SLIT("The section") <+> quotes (ppr in_expr)
262 <+> ptext SLIT("takes one argument")
263 tc_args arg1_ty' [arg1_ty, arg2_ty]
264 = do { boxyUnify arg1_ty' arg1_ty
265 ; tcArg lop (arg2, arg2_ty, 2) }
266 tc_args arg1_ty' other = panic "tcExpr SectionR"
270 tcExpr (HsLet binds expr) res_ty
271 = do { (binds', expr') <- tcLocalBinds binds $
272 tcMonoExpr expr res_ty
273 ; return (HsLet binds' expr') }
275 tcExpr (HsCase scrut matches) exp_ty
276 = do { -- We used to typecheck the case alternatives first.
277 -- The case patterns tend to give good type info to use
278 -- when typechecking the scrutinee. For example
281 -- will report that map is applied to too few arguments
283 -- But now, in the GADT world, we need to typecheck the scrutinee
284 -- first, to get type info that may be refined in the case alternatives
285 (scrut', scrut_ty) <- addErrCtxt (caseScrutCtxt scrut)
288 ; traceTc (text "HsCase" <+> ppr scrut_ty)
289 ; matches' <- tcMatchesCase match_ctxt scrut_ty matches exp_ty
290 ; return (HsCase scrut' matches') }
292 match_ctxt = MC { mc_what = CaseAlt,
295 tcExpr (HsIf pred b1 b2) res_ty
296 = do { pred' <- addErrCtxt (predCtxt pred) $
297 tcMonoExpr pred boolTy
298 ; b1' <- tcMonoExpr b1 res_ty
299 ; b2' <- tcMonoExpr b2 res_ty
300 ; return (HsIf pred' b1' b2') }
302 tcExpr (HsDo do_or_lc stmts body _) res_ty
303 = tcDoStmts do_or_lc stmts body res_ty
305 tcExpr in_expr@(ExplicitList _ exprs) res_ty -- Non-empty list
306 = do { elt_ty <- boxySplitListTy res_ty
307 ; exprs' <- mappM (tc_elt elt_ty) exprs
308 ; return (ExplicitList elt_ty exprs') }
310 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
312 tcExpr in_expr@(ExplicitPArr _ exprs) res_ty -- maybe empty
313 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
314 ; exprs' <- mappM (tc_elt elt_ty) exprs
315 ; ifM (null exprs) (zapToMonotype elt_ty)
316 -- If there are no expressions in the comprehension
317 -- we must still fill in the box
318 -- (Not needed for [] and () becuase they happen
319 -- to parse as data constructors.)
320 ; return (ExplicitPArr elt_ty exprs') }
322 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
324 tcExpr (ExplicitTuple exprs boxity) res_ty
325 = do { arg_tys <- boxySplitTyConApp (tupleTyCon boxity (length exprs)) res_ty
326 ; exprs' <- tcPolyExprs exprs arg_tys
327 ; return (ExplicitTuple exprs' boxity) }
329 tcExpr (HsProc pat cmd) res_ty
330 = do { (pat', cmd') <- tcProc pat cmd res_ty
331 ; return (HsProc pat' cmd') }
333 tcExpr e@(HsArrApp _ _ _ _ _) _
334 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
335 ptext SLIT("was found where an expression was expected")])
337 tcExpr e@(HsArrForm _ _ _) _
338 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
339 ptext SLIT("was found where an expression was expected")])
342 %************************************************************************
344 Record construction and update
346 %************************************************************************
349 tcExpr expr@(RecordCon (L loc con_name) _ rbinds) res_ty
350 = do { data_con <- tcLookupDataCon con_name
352 -- Check for missing fields
353 ; checkMissingFields data_con rbinds
355 ; let arity = dataConSourceArity data_con
357 = do { rbinds' <- tcRecordBinds data_con arg_tys rbinds
360 -- The unBox ensures that all the boxes in arg_tys are indeed
361 -- filled, which is the invariant expected by tcIdApp
363 ; (con_expr, rbinds') <- tcIdApp con_name arity check_fields res_ty
365 ; returnM (RecordCon (L loc (dataConWrapId data_con)) con_expr rbinds') }
367 -- The main complication with RecordUpd is that we need to explicitly
368 -- handle the *non-updated* fields. Consider:
370 -- data T a b = MkT1 { fa :: a, fb :: b }
371 -- | MkT2 { fa :: a, fc :: Int -> Int }
372 -- | MkT3 { fd :: a }
374 -- upd :: T a b -> c -> T a c
375 -- upd t x = t { fb = x}
377 -- The type signature on upd is correct (i.e. the result should not be (T a b))
378 -- because upd should be equivalent to:
380 -- upd t x = case t of
381 -- MkT1 p q -> MkT1 p x
382 -- MkT2 a b -> MkT2 p b
383 -- MkT3 d -> error ...
385 -- So we need to give a completely fresh type to the result record,
386 -- and then constrain it by the fields that are *not* updated ("p" above).
388 -- Note that because MkT3 doesn't contain all the fields being updated,
389 -- its RHS is simply an error, so it doesn't impose any type constraints
391 -- All this is done in STEP 4 below.
395 -- For record update we require that every constructor involved in the
396 -- update (i.e. that has all the specified fields) is "vanilla". I
397 -- don't know how to do the update otherwise.
400 tcExpr expr@(RecordUpd record_expr rbinds _ _) res_ty
402 -- Check that the field names are really field names
403 ASSERT( notNull rbinds )
405 field_names = map fst rbinds
407 mappM (tcLookupField . unLoc) field_names `thenM` \ sel_ids ->
408 -- The renamer has already checked that they
411 bad_guys = [ setSrcSpan loc $ addErrTc (notSelector field_name)
412 | (L loc field_name, sel_id) <- field_names `zip` sel_ids,
413 not (isRecordSelector sel_id) -- Excludes class ops
416 checkM (null bad_guys) (sequenceM bad_guys `thenM_` failM) `thenM_`
419 -- Figure out the tycon and data cons from the first field name
421 -- It's OK to use the non-tc splitters here (for a selector)
422 upd_field_lbls = recBindFields rbinds
424 (tycon, _) = recordSelectorFieldLabel sel_id -- We've failed already if
425 data_cons = tyConDataCons tycon -- it's not a field label
426 relevant_cons = filter is_relevant data_cons
427 is_relevant con = all (`elem` dataConFieldLabels con) upd_field_lbls
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 (not (null relevant_cons))
434 (badFieldsUpd rbinds) `thenM_`
436 -- Check that all relevant data cons are vanilla. Doing record updates on
437 -- GADTs and/or existentials is more than my tiny brain can cope with today
438 checkTc (all isVanillaDataCon relevant_cons)
439 (nonVanillaUpd tycon) `thenM_`
442 -- Use the un-updated fields to find a vector of booleans saying
443 -- which type arguments must be the same in updatee and result.
445 -- WARNING: this code assumes that all data_cons in a common tycon
446 -- have FieldLabels abstracted over the same tyvars.
448 -- A constructor is only relevant to this process if
449 -- it contains *all* the fields that are being updated
450 con1 = head relevant_cons -- A representative constructor
451 con1_tyvars = dataConUnivTyVars con1
452 con1_flds = dataConFieldLabels con1
453 con1_arg_tys = dataConOrigArgTys con1
454 common_tyvars = exactTyVarsOfTypes [ty | (fld,ty) <- con1_flds `zip` con1_arg_tys
455 , not (fld `elem` upd_field_lbls) ]
457 is_common_tv tv = tv `elemVarSet` common_tyvars
459 mk_inst_ty tv result_inst_ty
460 | is_common_tv tv = returnM result_inst_ty -- Same as result type
461 | otherwise = newFlexiTyVarTy (tyVarKind tv) -- Fresh type, of correct kind
463 tcInstTyVars con1_tyvars `thenM` \ (_, result_inst_tys, inst_env) ->
464 zipWithM mk_inst_ty con1_tyvars result_inst_tys `thenM` \ inst_tys ->
467 -- Typecheck the update bindings.
468 -- (Do this after checking for bad fields in case there's a field that
469 -- doesn't match the constructor.)
471 result_record_ty = mkTyConApp tycon result_inst_tys
472 con1_arg_tys' = map (substTy inst_env) con1_arg_tys
474 tcSubExp result_record_ty res_ty `thenM` \ co_fn ->
475 tcRecordBinds con1 con1_arg_tys' rbinds `thenM` \ rbinds' ->
478 -- Typecheck the expression to be updated
480 record_ty = ASSERT( length inst_tys == tyConArity tycon )
481 mkTyConApp tycon inst_tys
482 -- This is one place where the isVanilla check is important
483 -- So that inst_tys matches the tycon
485 tcMonoExpr record_expr record_ty `thenM` \ record_expr' ->
488 -- Figure out the LIE we need. We have to generate some
489 -- dictionaries for the data type context, since we are going to
490 -- do pattern matching over the data cons.
492 -- What dictionaries do we need?
493 -- We just take the context of the first data constructor
494 -- This isn't right, but I just can't bear to union up all the relevant ones
496 theta' = substTheta inst_env (tyConStupidTheta tycon)
498 newDicts RecordUpdOrigin theta' `thenM` \ dicts ->
499 extendLIEs dicts `thenM_`
502 returnM (mkHsCoerce co_fn (RecordUpd record_expr' rbinds' record_ty result_record_ty))
506 %************************************************************************
508 Arithmetic sequences e.g. [a,b..]
509 and their parallel-array counterparts e.g. [: a,b.. :]
512 %************************************************************************
515 tcExpr (ArithSeq _ seq@(From expr)) res_ty
516 = do { elt_ty <- boxySplitListTy res_ty
517 ; expr' <- tcPolyExpr expr elt_ty
518 ; enum_from <- newMethodFromName (ArithSeqOrigin seq)
520 ; return (ArithSeq (HsVar enum_from) (From expr')) }
522 tcExpr in_expr@(ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
523 = do { elt_ty <- boxySplitListTy res_ty
524 ; expr1' <- tcPolyExpr expr1 elt_ty
525 ; expr2' <- tcPolyExpr expr2 elt_ty
526 ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq)
527 elt_ty enumFromThenName
528 ; return (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2')) }
531 tcExpr in_expr@(ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
532 = do { elt_ty <- boxySplitListTy res_ty
533 ; expr1' <- tcPolyExpr expr1 elt_ty
534 ; expr2' <- tcPolyExpr expr2 elt_ty
535 ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq)
536 elt_ty enumFromToName
537 ; return (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
539 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
540 = do { elt_ty <- boxySplitListTy res_ty
541 ; expr1' <- tcPolyExpr expr1 elt_ty
542 ; expr2' <- tcPolyExpr expr2 elt_ty
543 ; expr3' <- tcPolyExpr expr3 elt_ty
544 ; eft <- newMethodFromName (ArithSeqOrigin seq)
545 elt_ty enumFromThenToName
546 ; return (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
548 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
549 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
550 ; expr1' <- tcPolyExpr expr1 elt_ty
551 ; expr2' <- tcPolyExpr expr2 elt_ty
552 ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq)
553 elt_ty enumFromToPName
554 ; return (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
556 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
557 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
558 ; expr1' <- tcPolyExpr expr1 elt_ty
559 ; expr2' <- tcPolyExpr expr2 elt_ty
560 ; expr3' <- tcPolyExpr expr3 elt_ty
561 ; eft <- newMethodFromName (PArrSeqOrigin seq)
562 elt_ty enumFromThenToPName
563 ; return (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
565 tcExpr (PArrSeq _ _) _
566 = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
567 -- the parser shouldn't have generated it and the renamer shouldn't have
572 %************************************************************************
576 %************************************************************************
579 #ifdef GHCI /* Only if bootstrapped */
580 -- Rename excludes these cases otherwise
581 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
582 tcExpr (HsBracket brack) res_ty = do { e <- tcBracket brack res_ty
588 %************************************************************************
592 %************************************************************************
595 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
599 %************************************************************************
603 %************************************************************************
606 ---------------------------
607 tcApp :: HsExpr Name -- Function
608 -> Arity -- Number of args reqd
609 -> ([BoxySigmaType] -> TcM arg_results) -- Argument type-checker
610 -> BoxyRhoType -- Result type
611 -> TcM (HsExpr TcId, arg_results)
613 -- (tcFun fun n_args arg_checker res_ty)
614 -- The argument type checker, arg_checker, will be passed exactly n_args types
616 tcApp (HsVar fun_name) n_args arg_checker res_ty
617 = tcIdApp fun_name n_args arg_checker res_ty
619 tcApp fun n_args arg_checker res_ty -- The vanilla case (rula APP)
620 = do { arg_boxes <- newBoxyTyVars (replicate n_args argTypeKind)
621 ; fun' <- tcExpr fun (mkFunTys (mkTyVarTys arg_boxes) res_ty)
622 ; arg_tys' <- mapM readFilledBox arg_boxes
623 ; args' <- arg_checker arg_tys'
624 ; return (fun', args') }
626 ---------------------------
627 tcIdApp :: Name -- Function
628 -> Arity -- Number of args reqd
629 -> ([BoxySigmaType] -> TcM arg_results) -- Argument type-checker
630 -- The arg-checker guarantees to fill all boxes in the arg types
631 -> BoxyRhoType -- Result type
632 -> TcM (HsExpr TcId, arg_results)
634 -- Call (f e1 ... en) :: res_ty
635 -- Type f :: forall a b c. theta => fa_1 -> ... -> fa_k -> fres
636 -- (where k <= n; fres has the rest)
637 -- NB: if k < n then the function doesn't have enough args, and
638 -- presumably fres is a type variable that we are going to
639 -- instantiate with a function type
641 -- Then fres <= bx_(k+1) -> ... -> bx_n -> res_ty
643 tcIdApp fun_name n_args arg_checker res_ty
644 = do { let orig = OccurrenceOf fun_name
645 ; (fun, fun_ty) <- lookupFun orig fun_name
647 -- Split up the function type
648 ; let (tv_theta_prs, rho) = tcMultiSplitSigmaTy fun_ty
649 (fun_arg_tys, fun_res_ty) = tcSplitFunTysN rho n_args
651 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
652 arg_qtvs = exactTyVarsOfTypes fun_arg_tys
653 res_qtvs = exactTyVarsOfType fun_res_ty
654 -- NB: exactTyVarsOfType. See Note [Silly type synonyms in smart-app]
655 tau_qtvs = arg_qtvs `unionVarSet` res_qtvs
656 k = length fun_arg_tys -- k <= n_args
657 n_missing_args = n_args - k -- Always >= 0
659 -- Match the result type of the function with the
660 -- result type of the context, to get an inital substitution
661 ; extra_arg_boxes <- newBoxyTyVars (replicate n_missing_args argTypeKind)
662 ; let extra_arg_tys' = mkTyVarTys extra_arg_boxes
663 res_ty' = mkFunTys extra_arg_tys' res_ty
664 ; qtys' <- preSubType qtvs tau_qtvs fun_res_ty res_ty'
665 ; let arg_subst = zipOpenTvSubst qtvs qtys'
666 fun_arg_tys' = substTys arg_subst fun_arg_tys
668 -- Typecheck the arguments!
669 -- Doing so will fill arg_qtvs and extra_arg_tys'
670 ; args' <- arg_checker (fun_arg_tys' ++ extra_arg_tys')
672 -- Strip boxes from the qtvs that have been filled in by the arg checking
673 -- AND any variables that are mentioned in neither arg nor result
674 -- the latter are mentioned only in constraints; stripBoxyType will
675 -- fill them with a monotype
676 ; let strip qtv qty' | qtv `elemVarSet` arg_qtvs = stripBoxyType qty'
677 | otherwise = return qty'
678 ; qtys'' <- zipWithM strip qtvs qtys'
679 ; extra_arg_tys'' <- mapM readFilledBox extra_arg_boxes
681 -- Result subsumption
682 ; let res_subst = zipOpenTvSubst qtvs qtys''
683 fun_res_ty'' = substTy res_subst fun_res_ty
684 res_ty'' = mkFunTys extra_arg_tys'' res_ty
685 ; co_fn <- tcFunResTy fun_name fun_res_ty'' res_ty''
687 -- And pack up the results
688 -- By applying the coercion just to the *function* we can make
689 -- tcFun work nicely for OpApp and Sections too
690 ; fun' <- instFun orig fun res_subst tv_theta_prs
691 ; co_fn' <- wrapFunResCoercion fun_arg_tys' co_fn
692 ; return (mkHsCoerce co_fn' fun', args') }
695 Note [Silly type synonyms in smart-app]
696 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
697 When we call sripBoxyType, all of the boxes should be filled
698 in. But we need to be careful about type synonyms:
702 In the call (f x) we'll typecheck x, expecting it to have type
703 (T box). Usually that would fill in the box, but in this case not;
704 because 'a' is discarded by the silly type synonym T. So we must
705 use exactTyVarsOfType to figure out which type variables are free
706 in the argument type.
709 -- tcId is a specialisation of tcIdApp when there are no arguments
710 -- tcId f ty = do { (res, _) <- tcIdApp f [] (\[] -> return ()) ty
715 -> BoxyRhoType -- Result type
717 tcId orig fun_name res_ty
718 = do { traceTc (text "tcId" <+> ppr fun_name <+> ppr res_ty)
719 ; (fun, fun_ty) <- lookupFun orig fun_name
721 -- Split up the function type
722 ; let (tv_theta_prs, fun_tau) = tcMultiSplitSigmaTy fun_ty
723 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
724 tau_qtvs = exactTyVarsOfType fun_tau -- Mentioned in the tau part
725 ; qtv_tys <- preSubType qtvs tau_qtvs fun_tau res_ty
727 -- Do the subsumption check wrt the result type
728 ; let res_subst = zipTopTvSubst qtvs qtv_tys
729 fun_tau' = substTy res_subst fun_tau
731 ; co_fn <- tcFunResTy fun_name fun_tau' res_ty
733 -- And pack up the results
734 ; fun' <- instFun orig fun res_subst tv_theta_prs
735 ; return (mkHsCoerce co_fn fun') }
737 -- Note [Push result type in]
739 -- Unify with expected result before (was: after) type-checking the args
740 -- so that the info from res_ty (was: args) percolates to args (was actual_res_ty).
741 -- This is when we might detect a too-few args situation.
742 -- (One can think of cases when the opposite order would give
743 -- a better error message.)
744 -- [March 2003: I'm experimenting with putting this first. Here's an
745 -- example where it actually makes a real difference
746 -- class C t a b | t a -> b
747 -- instance C Char a Bool
749 -- data P t a = forall b. (C t a b) => MkP b
750 -- data Q t = MkQ (forall a. P t a)
753 -- f1 = MkQ (MkP True)
754 -- f2 = MkQ (MkP True :: forall a. P Char a)
756 -- With the change, f1 will type-check, because the 'Char' info from
757 -- the signature is propagated into MkQ's argument. With the check
758 -- in the other order, the extra signature in f2 is reqd.]
760 ---------------------------
761 tcSyntaxOp :: InstOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
762 -- Typecheck a syntax operator, checking that it has the specified type
763 -- The operator is always a variable at this stage (i.e. renamer output)
764 tcSyntaxOp orig (HsVar op) ty = tcId orig op ty
765 tcSyntaxOp orig other ty = pprPanic "tcSyntaxOp" (ppr other)
767 ---------------------------
768 instFun :: InstOrigin
770 -> TvSubst -- The instantiating substitution
771 -> [([TyVar], ThetaType)] -- Stuff to instantiate
774 instFun orig fun subst []
775 = return fun -- Common short cut
777 instFun orig fun subst tv_theta_prs
778 = do {-- !!!SPJ: -- Horrid check for tagToEnum; see Note [tagToEnum#]
779 -- !!!SPJ: checkBadTagToEnumCall fun_id qtv_tys
781 ; let ty_theta_prs' = map subst_pr tv_theta_prs
783 -- First, chuck in the constraints from
784 -- the "stupid theta" of a data constructor (sigh)
785 ; inst_stupid fun ty_theta_prs'
787 -- Now do normal instantiation
788 ; go True fun ty_theta_prs' }
790 subst_pr (tvs, theta)
791 = (map (substTyVar subst) tvs, substTheta subst theta)
793 inst_stupid (HsVar fun_id) ((tys,_):_)
794 | Just con <- isDataConId_maybe fun_id = tcInstStupidTheta con tys
795 inst_stupid _ _ = return ()
797 go _ fun [] = return fun
799 go True (HsVar fun_id) ((tys,theta) : prs)
800 | want_method_inst theta
801 = do { meth_id <- newMethodWithGivenTy orig fun_id tys
802 ; go False (HsVar meth_id) prs }
803 -- Go round with 'False' to prevent further use
804 -- of newMethod: see Note [Multiple instantiation]
806 go _ fun ((tys, theta) : prs)
807 = do { dicts <- newDicts orig theta
809 ; let co_fn = mkInstCoFn tys dicts
810 ; go False (HsCoerce co_fn fun) prs }
812 -- Hack Alert (want_method_inst)!
813 -- See Note [No method sharing]
814 -- If f :: (%x :: T) => Int -> Int
815 -- Then if we have two separate calls, (f 3, f 4), we cannot
816 -- make a method constraint that then gets shared, thus:
817 -- let m = f %x in (m 3, m 4)
818 -- because that loses the linearity of the constraint.
819 -- The simplest thing to do is never to construct a method constraint
820 -- in the first place that has a linear implicit parameter in it.
821 want_method_inst theta = not (null theta) -- Overloaded
822 && not (any isLinearPred theta) -- Not linear
823 && not opt_NoMethodSharing
824 -- See Note [No method sharing] below
827 Note [Multiple instantiation]
828 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
829 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
830 For example, consider
831 f :: forall a. Eq a => forall b. Ord b => a -> b
832 At a call to f, at say [Int, Bool], it's tempting to translate the call to
836 f_m1 :: forall b. Ord b => Int -> b
840 f_m2 = f_m1 Bool dOrdBool
842 But notice that f_m2 has f_m1 as its meth_id. Now the danger is that if we do
843 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
845 But it's entirely possible that f_m2 will continue to float out, because it
846 mentions no type variables. Result, f_m1 isn't in scope.
848 Here's a concrete example that does this (test tc200):
851 f :: Eq b => b -> a -> Int
852 baz :: Eq a => Int -> a -> Int
857 Current solution: only do the "method sharing" thing for the first type/dict
858 application, not for the iterated ones. A horribly subtle point.
860 Note [No method sharing]
861 ~~~~~~~~~~~~~~~~~~~~~~~~
862 The -fno-method-sharing flag controls what happens so far as the LIE
863 is concerned. The default case is that for an overloaded function we
864 generate a "method" Id, and add the Method Inst to the LIE. So you get
867 f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
868 If you specify -fno-method-sharing, the dictionary application
869 isn't shared, so we get
871 f = /\a (d:Num a) (x:a) -> (+) a d x x
872 This gets a bit less sharing, but
873 a) it's better for RULEs involving overloaded functions
874 b) perhaps fewer separated lambdas
877 tcArgs :: LHsExpr Name -- The function (for error messages)
878 -> [LHsExpr Name] -> [TcSigmaType] -- Actual arguments and expected arg types
879 -> TcM [LHsExpr TcId] -- Resulting args
881 tcArgs fun args expected_arg_tys
882 = mapM (tcArg fun) (zip3 args expected_arg_tys [1..])
884 tcArg :: LHsExpr Name -- The function (for error messages)
885 -> (LHsExpr Name, BoxySigmaType, Int) -- Actual argument and expected arg type
886 -> TcM (LHsExpr TcId) -- Resulting argument
887 tcArg fun (arg, ty, arg_no) = addErrCtxt (funAppCtxt fun arg arg_no) $
894 Nasty check to ensure that tagToEnum# is applied to a type that is an
895 enumeration TyCon. Unification may refine the type later, but this
896 check won't see that, alas. It's crude but it works.
898 Here's are two cases that should fail
900 f = tagToEnum# 0 -- Can't do tagToEnum# at a type variable
903 g = tagToEnum# 0 -- Int is not an enumeration
907 checkBadTagToEnumCall :: Id -> [TcType] -> TcM ()
908 checkBadTagToEnumCall fun_id tys
909 | fun_id `hasKey` tagToEnumKey
910 = do { tys' <- zonkTcTypes tys
911 ; checkTc (ok tys') (tagToEnumError tys')
913 | otherwise -- Vastly common case
917 ok (ty:tys) = case tcSplitTyConApp_maybe ty of
918 Just (tc,_) -> isEnumerationTyCon tc
922 = hang (ptext SLIT("Bad call to tagToEnum#") <+> at_type)
923 2 (vcat [ptext SLIT("Specify the type by giving a type signature"),
924 ptext SLIT("e.g. (tagToEnum# x) :: Bool")])
926 at_type | null tys = empty -- Probably never happens
927 | otherwise = ptext SLIT("at type") <+> ppr (head tys)
930 %************************************************************************
932 \subsection{@tcId@ typchecks an identifier occurrence}
934 %************************************************************************
937 lookupFun :: InstOrigin -> Name -> TcM (HsExpr TcId, TcType)
938 lookupFun orig id_name
939 = do { thing <- tcLookup id_name
941 AGlobal (ADataCon con) -> return (HsVar wrap_id, idType wrap_id)
943 wrap_id = dataConWrapId con
946 | isNaughtyRecordSelector id -> failWithTc (naughtyRecordSel id)
947 | otherwise -> return (HsVar id, idType id)
948 -- A global cannot possibly be ill-staged
949 -- nor does it need the 'lifting' treatment
951 ATcId { tct_id = id, tct_type = ty, tct_co = mb_co, tct_level = lvl }
952 -> do { thLocalId orig id ty lvl
954 Nothing -> return (HsVar id, ty) -- Wobbly, or no free vars
955 Just co -> return (mkHsCoerce co (HsVar id), ty) }
957 other -> failWithTc (ppr other <+> ptext SLIT("used where a value identifer was expected"))
960 #ifndef GHCI /* GHCI and TH is off */
961 --------------------------------------
962 -- thLocalId : Check for cross-stage lifting
963 thLocalId orig id id_ty th_bind_lvl
966 #else /* GHCI and TH is on */
967 thLocalId orig id id_ty th_bind_lvl
968 = do { use_stage <- getStage -- TH case
970 Brack use_lvl ps_var lie_var | use_lvl > th_bind_lvl
971 -> thBrackId orig id ps_var lie_var
972 other -> checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage
975 thLocalId orig id_name id th_bind_lvl (Brack use_lvl ps_var lie_var)
976 | use_lvl > th_bind_lvl
978 thLocalId orig id_name id th_bind_lvl use_stage
979 = do { checkWellStaged
982 --------------------------------------
983 thBrackId orig id ps_var lie_var
984 | isExternalName id_name
985 = -- Top-level identifiers in this module,
986 -- (which have External Names)
987 -- are just like the imported case:
988 -- no need for the 'lifting' treatment
989 -- E.g. this is fine:
992 -- But we do need to put f into the keep-alive
993 -- set, because after desugaring the code will
994 -- only mention f's *name*, not f itself.
995 do { keepAliveTc id_name; return id }
998 = -- Nested identifiers, such as 'x' in
999 -- E.g. \x -> [| h x |]
1000 -- We must behave as if the reference to x was
1002 -- We use 'x' itself as the splice proxy, used by
1003 -- the desugarer to stitch it all back together.
1004 -- If 'x' occurs many times we may get many identical
1005 -- bindings of the same splice proxy, but that doesn't
1006 -- matter, although it's a mite untidy.
1007 do { let id_ty = idType id
1008 ; checkTc (isTauTy id_ty) (polySpliceErr id)
1009 -- If x is polymorphic, its occurrence sites might
1010 -- have different instantiations, so we can't use plain
1011 -- 'x' as the splice proxy name. I don't know how to
1012 -- solve this, and it's probably unimportant, so I'm
1013 -- just going to flag an error for now
1015 ; id_ty' <- zapToMonotype id_ty
1016 -- The id_ty might have an OpenTypeKind, but we
1017 -- can't instantiate the Lift class at that kind,
1018 -- so we zap it to a LiftedTypeKind monotype
1019 -- C.f. the call in TcPat.newLitInst
1021 ; setLIEVar lie_var $ do
1022 { lift <- newMethodFromName orig id_ty' DsMeta.liftName
1023 -- Put the 'lift' constraint into the right LIE
1025 -- Update the pending splices
1026 ; ps <- readMutVar ps_var
1027 ; writeMutVar ps_var ((id_name, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps)
1036 %************************************************************************
1038 \subsection{Record bindings}
1040 %************************************************************************
1042 Game plan for record bindings
1043 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1044 1. Find the TyCon for the bindings, from the first field label.
1046 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1048 For each binding field = value
1050 3. Instantiate the field type (from the field label) using the type
1053 4 Type check the value using tcArg, passing the field type as
1054 the expected argument type.
1056 This extends OK when the field types are universally quantified.
1062 -> [TcType] -- Expected type for each field
1063 -> HsRecordBinds Name
1064 -> TcM (HsRecordBinds TcId)
1066 tcRecordBinds data_con arg_tys rbinds
1067 = do { mb_binds <- mappM do_bind rbinds
1068 ; return (catMaybes mb_binds) }
1070 flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1071 do_bind (L loc field_lbl, rhs)
1072 | Just field_ty <- assocMaybe flds_w_tys field_lbl
1073 = addErrCtxt (fieldCtxt field_lbl) $
1074 do { rhs' <- tcPolyExprNC rhs field_ty
1075 ; sel_id <- tcLookupField field_lbl
1076 ; ASSERT( isRecordSelector sel_id )
1077 return (Just (L loc sel_id, rhs')) }
1079 = do { addErrTc (badFieldCon data_con field_lbl)
1082 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1083 checkMissingFields data_con rbinds
1084 | null field_labels -- Not declared as a record;
1085 -- But C{} is still valid if no strict fields
1086 = if any isMarkedStrict field_strs then
1087 -- Illegal if any arg is strict
1088 addErrTc (missingStrictFields data_con [])
1092 | otherwise -- A record
1093 = checkM (null missing_s_fields)
1094 (addErrTc (missingStrictFields data_con missing_s_fields)) `thenM_`
1096 doptM Opt_WarnMissingFields `thenM` \ warn ->
1097 checkM (not (warn && notNull missing_ns_fields))
1098 (warnTc True (missingFields data_con missing_ns_fields))
1102 = [ fl | (fl, str) <- field_info,
1104 not (fl `elem` field_names_used)
1107 = [ fl | (fl, str) <- field_info,
1108 not (isMarkedStrict str),
1109 not (fl `elem` field_names_used)
1112 field_names_used = recBindFields rbinds
1113 field_labels = dataConFieldLabels data_con
1115 field_info = zipEqual "missingFields"
1119 field_strs = dataConStrictMarks data_con
1122 %************************************************************************
1124 \subsection{Errors and contexts}
1126 %************************************************************************
1128 Boring and alphabetical:
1131 = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1134 = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1136 fieldCtxt field_name
1137 = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1139 funAppCtxt fun arg arg_no
1140 = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"),
1141 quotes (ppr fun) <> text ", namely"])
1142 4 (quotes (ppr arg))
1145 = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1148 = vcat [ptext SLIT("Record update for the non-Haskell-98 data type") <+> quotes (ppr tycon)
1149 <+> ptext SLIT("is not (yet) supported"),
1150 ptext SLIT("Use pattern-matching instead")]
1152 = hang (ptext SLIT("No constructor has all these fields:"))
1153 4 (pprQuotedList (recBindFields rbinds))
1155 naughtyRecordSel sel_id
1156 = ptext SLIT("Cannot use record selector") <+> quotes (ppr sel_id) <+>
1157 ptext SLIT("as a function due to escaped type variables") $$
1158 ptext SLIT("Probably fix: use pattern-matching syntax instead")
1161 = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1163 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1164 missingStrictFields con fields
1167 rest | null fields = empty -- Happens for non-record constructors
1168 -- with strict fields
1169 | otherwise = colon <+> pprWithCommas ppr fields
1171 header = ptext SLIT("Constructor") <+> quotes (ppr con) <+>
1172 ptext SLIT("does not have the required strict field(s)")
1174 missingFields :: DataCon -> [FieldLabel] -> SDoc
1175 missingFields con fields
1176 = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:")
1177 <+> pprWithCommas ppr fields
1180 = ptext SLIT("In the call") <+> parens (ppr (foldl mkHsApp fun args))
1183 polySpliceErr :: Id -> SDoc
1185 = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)