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,
25 mkHsCoerce, mkHsApp, mkHsDictApp, mkHsTyApp )
26 import TcHsSyn ( hsLitType )
28 import TcUnify ( tcInfer, tcSubExp, tcGen, boxyUnify, subFunTys, zapToMonotype, stripBoxyType,
29 boxySplitListTy, boxySplitTyConApp, wrapFunResCoercion, boxySubMatchType, unBox )
30 import BasicTypes ( Arity, isMarkedStrict )
31 import Inst ( newMethodFromName, newIPDict, instToId,
32 newDicts, newMethodWithGivenTy, tcInstStupidTheta )
33 import TcBinds ( tcLocalBinds )
34 import TcEnv ( tcLookup, tcLookupId,
35 tcLookupDataCon, tcLookupGlobalId
37 import TcArrows ( tcProc )
38 import TcMatches ( tcMatchesCase, tcMatchLambda, tcDoStmts, TcMatchCtxt(..) )
39 import TcHsType ( tcHsSigType, UserTypeCtxt(..) )
40 import TcPat ( tcOverloadedLit, badFieldCon )
41 import TcMType ( tcInstTyVars, newFlexiTyVarTy, newBoxyTyVars, readFilledBox,
42 tcInstBoxyTyVar, tcInstTyVar, zonkTcType )
43 import TcType ( TcType, TcSigmaType, TcRhoType,
44 BoxySigmaType, BoxyRhoType, ThetaType,
45 tcSplitFunTys, mkTyVarTys, mkFunTys,
46 tcMultiSplitSigmaTy, tcSplitFunTysN,
47 isSigmaTy, mkFunTy, mkTyConApp, isLinearPred,
48 exactTyVarsOfType, exactTyVarsOfTypes, mkTyVarTy,
50 zipTopTvSubst, zipOpenTvSubst, substTys, substTyVar, lookupTyVar
52 import Kind ( argTypeKind )
54 import Id ( idType, idName, recordSelectorFieldLabel, isRecordSelector,
55 isNaughtyRecordSelector, isDataConId_maybe )
56 import DataCon ( DataCon, dataConFieldLabels, dataConStrictMarks, dataConSourceArity,
57 dataConWrapId, isVanillaDataCon, dataConTyVars, dataConOrigArgTys )
59 import TyCon ( FieldLabel, tyConStupidTheta, tyConDataCons )
60 import Type ( substTheta, substTy )
61 import Var ( TyVar, tyVarKind )
62 import VarSet ( emptyVarSet, elemVarSet, unionVarSet )
63 import TysWiredIn ( boolTy, parrTyCon, tupleTyCon )
64 import PrelNames ( enumFromName, enumFromThenName,
65 enumFromToName, enumFromThenToName,
66 enumFromToPName, enumFromThenToPName, negateName
69 import StaticFlags ( opt_NoMethodSharing )
70 import HscTypes ( TyThing(..) )
71 import SrcLoc ( Located(..), unLoc, noLoc, getLoc )
73 import ListSetOps ( assocMaybe )
74 import Maybes ( catMaybes )
79 import TyCon ( tyConArity )
83 %************************************************************************
85 \subsection{Main wrappers}
87 %************************************************************************
90 tcPolyExpr, tcPolyExprNC
91 :: LHsExpr Name -- Expession to type check
92 -> BoxySigmaType -- Expected type (could be a polytpye)
93 -> TcM (LHsExpr TcId) -- Generalised expr with expected type
95 -- tcPolyExpr is a convenient place (frequent but not too frequent) place
96 -- to add context information.
97 -- The NC version does not do so, usually because the caller wants
100 tcPolyExpr expr res_ty
101 = addErrCtxt (exprCtxt (unLoc expr)) $
102 tcPolyExprNC expr res_ty
104 tcPolyExprNC expr res_ty
106 = do { (gen_fn, expr') <- tcGen res_ty emptyVarSet (tcPolyExprNC expr)
107 -- Note the recursive call to tcPolyExpr, because the
108 -- type may have multiple layers of for-alls
109 ; return (L (getLoc expr') (mkHsCoerce gen_fn (unLoc expr'))) }
112 = tcMonoExpr expr res_ty
115 tcPolyExprs :: [LHsExpr Name] -> [TcType] -> TcM [LHsExpr TcId]
116 tcPolyExprs [] [] = returnM []
117 tcPolyExprs (expr:exprs) (ty:tys)
118 = do { expr' <- tcPolyExpr expr ty
119 ; exprs' <- tcPolyExprs exprs tys
120 ; returnM (expr':exprs') }
121 tcPolyExprs exprs tys = pprPanic "tcPolyExprs" (ppr exprs $$ ppr tys)
124 tcMonoExpr :: LHsExpr Name -- Expression to type check
125 -> BoxyRhoType -- Expected type (could be a type variable)
126 -- Definitely no foralls at the top
127 -- Can contain boxes, which will be filled in
128 -> TcM (LHsExpr TcId)
130 tcMonoExpr (L loc expr) res_ty
131 = ASSERT( not (isSigmaTy res_ty) )
133 do { expr' <- tcExpr expr res_ty
134 ; return (L loc expr') }
137 tcInferRho :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
138 tcInferRho expr = tcInfer (tcMonoExpr expr)
143 %************************************************************************
145 tcExpr: the main expression typechecker
147 %************************************************************************
150 tcExpr :: HsExpr Name -> BoxyRhoType -> TcM (HsExpr TcId)
151 tcExpr (HsVar name) res_ty = tcId (OccurrenceOf name) name res_ty
153 tcExpr (HsLit lit) res_ty = do { boxyUnify (hsLitType lit) res_ty
154 ; return (HsLit lit) }
156 tcExpr (HsPar expr) res_ty = do { expr' <- tcMonoExpr expr res_ty
157 ; return (HsPar expr') }
159 tcExpr (HsSCC lbl expr) res_ty = do { expr' <- tcMonoExpr expr res_ty
160 ; returnM (HsSCC lbl expr') }
162 tcExpr (HsCoreAnn lbl expr) res_ty -- hdaume: core annotation
163 = do { expr' <- tcMonoExpr expr res_ty
164 ; return (HsCoreAnn lbl expr') }
166 tcExpr (HsOverLit lit) res_ty
167 = do { lit' <- tcOverloadedLit (LiteralOrigin lit) lit res_ty
168 ; return (HsOverLit lit') }
170 tcExpr (NegApp expr neg_expr) res_ty
171 = do { neg_expr' <- tcSyntaxOp (OccurrenceOf negateName) neg_expr
172 (mkFunTy res_ty res_ty)
173 ; expr' <- tcMonoExpr expr res_ty
174 ; return (NegApp expr' neg_expr') }
176 tcExpr (HsIPVar ip) res_ty
177 = do { -- Implicit parameters must have a *tau-type* not a
178 -- type scheme. We enforce this by creating a fresh
179 -- type variable as its type. (Because res_ty may not
181 ip_ty <- newFlexiTyVarTy argTypeKind -- argTypeKind: it can't be an unboxed tuple
182 ; co_fn <- tcSubExp ip_ty res_ty
183 ; (ip', inst) <- newIPDict (IPOccOrigin ip) ip ip_ty
185 ; return (mkHsCoerce co_fn (HsIPVar ip')) }
187 tcExpr (HsApp e1 e2) res_ty
190 go :: LHsExpr Name -> [LHsExpr Name] -> TcM (HsExpr TcId)
191 go (L _ (HsApp e1 e2)) args = go e1 (e2:args)
192 go lfun@(L loc fun) args
193 = do { (fun', args') <- addErrCtxt (callCtxt lfun args) $
194 tcApp fun (length args) (tcArgs lfun args) res_ty
195 ; return (unLoc (foldl mkHsApp (L loc fun') args')) }
197 tcExpr (HsLam match) res_ty
198 = do { (co_fn, match') <- tcMatchLambda match res_ty
199 ; return (mkHsCoerce co_fn (HsLam match')) }
201 tcExpr in_expr@(ExprWithTySig expr sig_ty) res_ty
202 = do { sig_tc_ty <- tcHsSigType ExprSigCtxt sig_ty
203 ; expr' <- tcPolyExpr expr sig_tc_ty
204 ; co_fn <- tcSubExp sig_tc_ty res_ty
205 ; return (mkHsCoerce co_fn (ExprWithTySigOut expr' sig_ty)) }
207 tcExpr (HsType ty) res_ty
208 = failWithTc (text "Can't handle type argument:" <+> ppr ty)
209 -- This is the syntax for type applications that I was planning
210 -- but there are difficulties (e.g. what order for type args)
211 -- so it's not enabled yet.
212 -- Can't eliminate it altogether from the parser, because the
213 -- same parser parses *patterns*.
217 %************************************************************************
219 Infix operators and sections
221 %************************************************************************
224 tcExpr in_expr@(OpApp arg1 lop@(L loc op) fix arg2) res_ty
225 = do { (op', [arg1', arg2']) <- tcApp op 2 (tcArgs lop [arg1,arg2]) res_ty
226 ; return (OpApp arg1' (L loc op') fix arg2') }
228 -- Left sections, equivalent to
235 -- We treat it as similar to the latter, so we don't
236 -- actually require the function to take two arguments
237 -- at all. For example, (x `not`) means (not x);
238 -- you get postfix operators! Not really Haskell 98
239 -- I suppose, but it's less work and kind of useful.
241 tcExpr in_expr@(SectionL arg1 lop@(L loc op)) res_ty
242 = do { (op', [arg1']) <- tcApp op 1 (tcArgs lop [arg1]) res_ty
243 ; return (SectionL arg1' (L loc op')) }
245 -- Right sections, equivalent to \ x -> x `op` expr, or
248 tcExpr in_expr@(SectionR lop@(L loc op) arg2) res_ty
249 = do { (co_fn, (op', arg2')) <- subFunTys doc 1 res_ty $ \ [arg1_ty'] res_ty' ->
250 tcApp op 2 (tc_args arg1_ty') res_ty'
251 ; return (mkHsCoerce co_fn (SectionR (L loc op') arg2')) }
253 doc = ptext SLIT("The section") <+> quotes (ppr in_expr)
254 <+> ptext SLIT("takes one argument")
255 tc_args arg1_ty' [arg1_ty, arg2_ty]
256 = do { boxyUnify arg1_ty' arg1_ty
257 ; tcArg lop (arg2, arg2_ty, 2) }
261 tcExpr (HsLet binds expr) res_ty
262 = do { (binds', expr') <- tcLocalBinds binds $
263 tcMonoExpr expr res_ty
264 ; return (HsLet binds' expr') }
266 tcExpr (HsCase scrut matches) exp_ty
267 = do { -- We used to typecheck the case alternatives first.
268 -- The case patterns tend to give good type info to use
269 -- when typechecking the scrutinee. For example
272 -- will report that map is applied to too few arguments
274 -- But now, in the GADT world, we need to typecheck the scrutinee
275 -- first, to get type info that may be refined in the case alternatives
276 (scrut', scrut_ty) <- addErrCtxt (caseScrutCtxt scrut)
279 ; traceTc (text "HsCase" <+> ppr scrut_ty)
280 ; matches' <- tcMatchesCase match_ctxt scrut_ty matches exp_ty
281 ; return (HsCase scrut' matches') }
283 match_ctxt = MC { mc_what = CaseAlt,
284 mc_body = tcPolyExpr }
286 tcExpr (HsIf pred b1 b2) res_ty
287 = do { pred' <- addErrCtxt (predCtxt pred) $
288 tcMonoExpr pred boolTy
289 ; b1' <- tcMonoExpr b1 res_ty
290 ; b2' <- tcMonoExpr b2 res_ty
291 ; return (HsIf pred' b1' b2') }
293 tcExpr (HsDo do_or_lc stmts body _) res_ty
294 = tcDoStmts do_or_lc stmts body res_ty
296 tcExpr in_expr@(ExplicitList _ exprs) res_ty -- Non-empty list
297 = do { elt_ty <- boxySplitListTy res_ty
298 ; exprs' <- mappM (tc_elt elt_ty) exprs
299 ; return (ExplicitList elt_ty exprs') }
301 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
303 tcExpr in_expr@(ExplicitPArr _ exprs) res_ty -- maybe empty
304 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
305 ; exprs' <- mappM (tc_elt elt_ty) exprs
306 ; ifM (null exprs) (zapToMonotype elt_ty)
307 -- If there are no expressions in the comprehension
308 -- we must still fill in the box
309 -- (Not needed for [] and () becuase they happen
310 -- to parse as data constructors.)
311 ; return (ExplicitPArr elt_ty exprs') }
313 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
315 tcExpr (ExplicitTuple exprs boxity) res_ty
316 = do { arg_tys <- boxySplitTyConApp (tupleTyCon boxity (length exprs)) res_ty
317 ; exprs' <- tcPolyExprs exprs arg_tys
318 ; return (ExplicitTuple exprs' boxity) }
320 tcExpr (HsProc pat cmd) res_ty
321 = do { (pat', cmd') <- tcProc pat cmd res_ty
322 ; return (HsProc pat' cmd') }
324 tcExpr e@(HsArrApp _ _ _ _ _) _
325 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
326 ptext SLIT("was found where an expression was expected")])
328 tcExpr e@(HsArrForm _ _ _) _
329 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
330 ptext SLIT("was found where an expression was expected")])
333 %************************************************************************
335 Record construction and update
337 %************************************************************************
340 tcExpr expr@(RecordCon (L loc con_name) _ rbinds) res_ty
341 = do { data_con <- tcLookupDataCon con_name
343 -- Check for missing fields
344 ; checkMissingFields data_con rbinds
346 ; let arity = dataConSourceArity data_con
348 = do { rbinds' <- tcRecordBinds data_con arg_tys rbinds
351 -- The unBox ensures that all the boxes in arg_tys are indeed
352 -- filled, which is the invariant expected by tcIdApp
354 ; (con_expr, rbinds') <- tcIdApp con_name arity check_fields res_ty
356 ; returnM (RecordCon (L loc (dataConWrapId data_con)) con_expr rbinds') }
358 -- The main complication with RecordUpd is that we need to explicitly
359 -- handle the *non-updated* fields. Consider:
361 -- data T a b = MkT1 { fa :: a, fb :: b }
362 -- | MkT2 { fa :: a, fc :: Int -> Int }
363 -- | MkT3 { fd :: a }
365 -- upd :: T a b -> c -> T a c
366 -- upd t x = t { fb = x}
368 -- The type signature on upd is correct (i.e. the result should not be (T a b))
369 -- because upd should be equivalent to:
371 -- upd t x = case t of
372 -- MkT1 p q -> MkT1 p x
373 -- MkT2 a b -> MkT2 p b
374 -- MkT3 d -> error ...
376 -- So we need to give a completely fresh type to the result record,
377 -- and then constrain it by the fields that are *not* updated ("p" above).
379 -- Note that because MkT3 doesn't contain all the fields being updated,
380 -- its RHS is simply an error, so it doesn't impose any type constraints
382 -- All this is done in STEP 4 below.
386 -- For record update we require that every constructor involved in the
387 -- update (i.e. that has all the specified fields) is "vanilla". I
388 -- don't know how to do the update otherwise.
391 tcExpr expr@(RecordUpd record_expr rbinds _ _) res_ty
393 -- Check that the field names are really field names
394 ASSERT( notNull rbinds )
396 field_names = map fst rbinds
398 mappM (tcLookupGlobalId.unLoc) field_names `thenM` \ sel_ids ->
399 -- The renamer has already checked that they
402 bad_guys = [ setSrcSpan loc $ addErrTc (notSelector field_name)
403 | (L loc field_name, sel_id) <- field_names `zip` sel_ids,
404 not (isRecordSelector sel_id) -- Excludes class ops
407 checkM (null bad_guys) (sequenceM bad_guys `thenM_` failM) `thenM_`
410 -- Figure out the tycon and data cons from the first field name
412 -- It's OK to use the non-tc splitters here (for a selector)
413 upd_field_lbls = recBindFields rbinds
415 (tycon, _) = recordSelectorFieldLabel sel_id -- We've failed already if
416 data_cons = tyConDataCons tycon -- it's not a field label
417 relevant_cons = filter is_relevant data_cons
418 is_relevant con = all (`elem` dataConFieldLabels con) upd_field_lbls
422 -- Check that at least one constructor has all the named fields
423 -- i.e. has an empty set of bad fields returned by badFields
424 checkTc (not (null relevant_cons))
425 (badFieldsUpd rbinds) `thenM_`
427 -- Check that all relevant data cons are vanilla. Doing record updates on
428 -- GADTs and/or existentials is more than my tiny brain can cope with today
429 checkTc (all isVanillaDataCon relevant_cons)
430 (nonVanillaUpd tycon) `thenM_`
433 -- Use the un-updated fields to find a vector of booleans saying
434 -- which type arguments must be the same in updatee and result.
436 -- WARNING: this code assumes that all data_cons in a common tycon
437 -- have FieldLabels abstracted over the same tyvars.
439 -- A constructor is only relevant to this process if
440 -- it contains *all* the fields that are being updated
441 con1 = head relevant_cons -- A representative constructor
442 con1_tyvars = dataConTyVars con1
443 con1_flds = dataConFieldLabels con1
444 con1_arg_tys = dataConOrigArgTys con1
445 common_tyvars = exactTyVarsOfTypes [ty | (fld,ty) <- con1_flds `zip` con1_arg_tys
446 , not (fld `elem` upd_field_lbls) ]
448 is_common_tv tv = tv `elemVarSet` common_tyvars
450 mk_inst_ty tv result_inst_ty
451 | is_common_tv tv = returnM result_inst_ty -- Same as result type
452 | otherwise = newFlexiTyVarTy (tyVarKind tv) -- Fresh type, of correct kind
454 tcInstTyVars con1_tyvars `thenM` \ (_, result_inst_tys, inst_env) ->
455 zipWithM mk_inst_ty con1_tyvars result_inst_tys `thenM` \ inst_tys ->
458 -- Typecheck the update bindings.
459 -- (Do this after checking for bad fields in case there's a field that
460 -- doesn't match the constructor.)
462 result_record_ty = mkTyConApp tycon result_inst_tys
463 con1_arg_tys' = map (substTy inst_env) con1_arg_tys
465 tcSubExp result_record_ty res_ty `thenM` \ co_fn ->
466 tcRecordBinds con1 con1_arg_tys' rbinds `thenM` \ rbinds' ->
469 -- Typecheck the expression to be updated
471 record_ty = ASSERT( length inst_tys == tyConArity tycon )
472 mkTyConApp tycon inst_tys
473 -- This is one place where the isVanilla check is important
474 -- So that inst_tys matches the tycon
476 tcMonoExpr record_expr record_ty `thenM` \ record_expr' ->
479 -- Figure out the LIE we need. We have to generate some
480 -- dictionaries for the data type context, since we are going to
481 -- do pattern matching over the data cons.
483 -- What dictionaries do we need?
484 -- We just take the context of the first data constructor
485 -- This isn't right, but I just can't bear to union up all the relevant ones
487 theta' = substTheta inst_env (tyConStupidTheta tycon)
489 newDicts RecordUpdOrigin theta' `thenM` \ dicts ->
490 extendLIEs dicts `thenM_`
493 returnM (mkHsCoerce co_fn (RecordUpd record_expr' rbinds' record_ty result_record_ty))
497 %************************************************************************
499 Arithmetic sequences e.g. [a,b..]
500 and their parallel-array counterparts e.g. [: a,b.. :]
503 %************************************************************************
506 tcExpr (ArithSeq _ seq@(From expr)) res_ty
507 = do { elt_ty <- boxySplitListTy res_ty
508 ; expr' <- tcPolyExpr expr elt_ty
509 ; enum_from <- newMethodFromName (ArithSeqOrigin seq)
511 ; return (ArithSeq (HsVar enum_from) (From expr')) }
513 tcExpr in_expr@(ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
514 = do { elt_ty <- boxySplitListTy res_ty
515 ; expr1' <- tcPolyExpr expr1 elt_ty
516 ; expr2' <- tcPolyExpr expr2 elt_ty
517 ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq)
518 elt_ty enumFromThenName
519 ; return (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2')) }
522 tcExpr in_expr@(ArithSeq _ seq@(FromTo 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_to <- newMethodFromName (ArithSeqOrigin seq)
527 elt_ty enumFromToName
528 ; return (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
530 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
531 = do { elt_ty <- boxySplitListTy res_ty
532 ; expr1' <- tcPolyExpr expr1 elt_ty
533 ; expr2' <- tcPolyExpr expr2 elt_ty
534 ; expr3' <- tcPolyExpr expr3 elt_ty
535 ; eft <- newMethodFromName (ArithSeqOrigin seq)
536 elt_ty enumFromThenToName
537 ; return (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
539 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
540 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
541 ; expr1' <- tcPolyExpr expr1 elt_ty
542 ; expr2' <- tcPolyExpr expr2 elt_ty
543 ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq)
544 elt_ty enumFromToPName
545 ; return (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
547 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
548 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
549 ; expr1' <- tcPolyExpr expr1 elt_ty
550 ; expr2' <- tcPolyExpr expr2 elt_ty
551 ; expr3' <- tcPolyExpr expr3 elt_ty
552 ; eft <- newMethodFromName (PArrSeqOrigin seq)
553 elt_ty enumFromThenToPName
554 ; return (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
556 tcExpr (PArrSeq _ _) _
557 = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
558 -- the parser shouldn't have generated it and the renamer shouldn't have
563 %************************************************************************
567 %************************************************************************
570 #ifdef GHCI /* Only if bootstrapped */
571 -- Rename excludes these cases otherwise
572 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
573 tcExpr (HsBracket brack) res_ty = do { e <- tcBracket brack res_ty
579 %************************************************************************
583 %************************************************************************
586 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
590 %************************************************************************
594 %************************************************************************
597 ---------------------------
598 tcApp :: HsExpr Name -- Function
599 -> Arity -- Number of args reqd
600 -> ([BoxySigmaType] -> TcM arg_results) -- Argument type-checker
601 -> BoxyRhoType -- Result type
602 -> TcM (HsExpr TcId, arg_results)
604 -- (tcFun fun n_args arg_checker res_ty)
605 -- The argument type checker, arg_checker, will be passed exactly n_args types
607 tcApp (HsVar fun_name) n_args arg_checker res_ty
608 = tcIdApp fun_name n_args arg_checker res_ty
610 tcApp fun n_args arg_checker res_ty -- The vanilla case (rula APP)
611 = do { arg_boxes <- newBoxyTyVars (replicate n_args argTypeKind)
612 ; fun' <- tcExpr fun (mkFunTys (mkTyVarTys arg_boxes) res_ty)
613 ; arg_tys' <- mapM readFilledBox arg_boxes
614 ; args' <- arg_checker arg_tys'
615 ; return (fun', args') }
617 ---------------------------
618 tcIdApp :: Name -- Function
619 -> Arity -- Number of args reqd
620 -> ([BoxySigmaType] -> TcM arg_results) -- Argument type-checker
621 -- The arg-checker guarantees to fill all boxes in the arg types
622 -> BoxyRhoType -- Result type
623 -> TcM (HsExpr TcId, arg_results)
625 -- Call (f e1 ... en) :: res_ty
626 -- Type f :: forall a b c. theta => fa_1 -> ... -> fa_k -> fres
627 -- (where k <= n; fres has the rest)
628 -- NB: if k < n then the function doesn't have enough args, and
629 -- presumably fres is a type variable that we are going to
630 -- instantiate with a function type
632 -- Then fres <= bx_(k+1) -> ... -> bx_n -> res_ty
634 tcIdApp fun_name n_args arg_checker res_ty
635 = do { fun_id <- lookupFun (OccurrenceOf fun_name) fun_name
637 -- Split up the function type
638 ; let (tv_theta_prs, rho) = tcMultiSplitSigmaTy (idType fun_id)
639 (fun_arg_tys, fun_res_ty) = tcSplitFunTysN rho n_args
641 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
642 arg_qtvs = exactTyVarsOfTypes fun_arg_tys
643 res_qtvs = exactTyVarsOfType fun_res_ty
644 -- NB: exactTyVarsOfType. See Note [Silly type synonyms in smart-app]
645 tau_qtvs = arg_qtvs `unionVarSet` res_qtvs
646 k = length fun_arg_tys -- k <= n_args
647 n_missing_args = n_args - k -- Always >= 0
649 -- Match the result type of the function with the
650 -- result type of the context, to get an inital substitution
651 ; extra_arg_boxes <- newBoxyTyVars (replicate n_missing_args argTypeKind)
652 ; let extra_arg_tys' = mkTyVarTys extra_arg_boxes
653 res_ty' = mkFunTys extra_arg_tys' res_ty
654 subst = boxySubMatchType arg_qtvs fun_res_ty res_ty'
655 -- Only bind arg_qtvs, since only they will be
656 -- *definitely* be filled in by arg_checker
657 -- E.g. error :: forall a. String -> a
658 -- (error "foo") :: bx5
659 -- Don't make subst [a |-> bx5]
660 -- because then the result subsumption becomes
662 -- and the unifer doesn't expect the
663 -- same box on both sides
664 inst_qtv tv | Just boxy_ty <- lookupTyVar subst tv = return boxy_ty
665 | tv `elemVarSet` tau_qtvs = do { tv' <- tcInstBoxyTyVar tv
666 ; return (mkTyVarTy tv') }
667 | otherwise = do { tv' <- tcInstTyVar tv
668 ; return (mkTyVarTy tv') }
669 -- The 'otherwise' case handles type variables that are
670 -- mentioned only in the constraints, not in argument or
671 -- result types. We'll make them tau-types
673 ; qtys' <- mapM inst_qtv qtvs
674 ; let arg_subst = zipOpenTvSubst qtvs qtys'
675 fun_arg_tys' = substTys arg_subst fun_arg_tys
677 -- Typecheck the arguments!
678 -- Doing so will fill arg_qtvs and extra_arg_tys'
679 ; args' <- arg_checker (fun_arg_tys' ++ extra_arg_tys')
681 ; let strip qtv qty' | qtv `elemVarSet` arg_qtvs = stripBoxyType qty'
682 | otherwise = return qty'
683 ; qtys'' <- zipWithM strip qtvs qtys'
684 ; extra_arg_tys'' <- mapM readFilledBox extra_arg_boxes
686 -- Result subsumption
687 ; let res_subst = zipOpenTvSubst qtvs qtys''
688 fun_res_ty'' = substTy res_subst fun_res_ty
689 res_ty'' = mkFunTys extra_arg_tys'' res_ty
690 ; co_fn <- addErrCtxtM (checkFunResCtxt fun_name res_ty fun_res_ty'') $
691 tcSubExp fun_res_ty'' res_ty''
693 -- And pack up the results
694 -- By applying the coercion just to the *function* we can make
695 -- tcFun work nicely for OpApp and Sections too
696 ; fun' <- instFun fun_id qtvs qtys'' tv_theta_prs
697 ; co_fn' <- wrapFunResCoercion fun_arg_tys' co_fn
698 ; return (mkHsCoerce co_fn' fun', args') }
701 Note [Silly type synonyms in smart-app]
702 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
703 When we call sripBoxyType, all of the boxes should be filled
704 in. But we need to be careful about type synonyms:
708 In the call (f x) we'll typecheck x, expecting it to have type
709 (T box). Usually that would fill in the box, but in this case not;
710 because 'a' is discarded by the silly type synonym T. So we must
711 use exactTyVarsOfType to figure out which type variables are free
712 in the argument type.
715 -- tcId is a specialisation of tcIdApp when there are no arguments
716 -- tcId f ty = do { (res, _) <- tcIdApp f [] (\[] -> return ()) ty
721 -> BoxyRhoType -- Result type
723 tcId orig fun_name res_ty
724 = do { traceTc (text "tcId" <+> ppr fun_name <+> ppr res_ty)
725 ; fun_id <- lookupFun orig fun_name
727 -- Split up the function type
728 ; let (tv_theta_prs, fun_tau) = tcMultiSplitSigmaTy (idType fun_id)
729 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
730 tau_qtvs = exactTyVarsOfType fun_tau -- Mentiond in the tau part
731 inst_qtv tv | tv `elemVarSet` tau_qtvs = do { tv' <- tcInstBoxyTyVar tv
732 ; return (mkTyVarTy tv') }
733 | otherwise = do { tv' <- tcInstTyVar tv
734 ; return (mkTyVarTy tv') }
736 -- Do the subsumption check wrt the result type
737 ; qtv_tys <- mapM inst_qtv qtvs
738 ; let res_subst = zipTopTvSubst qtvs qtv_tys
739 fun_tau' = substTy res_subst fun_tau
741 ; co_fn <- addErrCtxtM (checkFunResCtxt fun_name res_ty fun_tau') $
742 tcSubExp fun_tau' res_ty
744 -- And pack up the results
745 ; fun' <- instFun fun_id qtvs qtv_tys tv_theta_prs
746 ; return (mkHsCoerce co_fn fun') }
748 -- Note [Push result type in]
750 -- Unify with expected result before (was: after) type-checking the args
751 -- so that the info from res_ty (was: args) percolates to args (was actual_res_ty).
752 -- This is when we might detect a too-few args situation.
753 -- (One can think of cases when the opposite order would give
754 -- a better error message.)
755 -- [March 2003: I'm experimenting with putting this first. Here's an
756 -- example where it actually makes a real difference
757 -- class C t a b | t a -> b
758 -- instance C Char a Bool
760 -- data P t a = forall b. (C t a b) => MkP b
761 -- data Q t = MkQ (forall a. P t a)
764 -- f1 = MkQ (MkP True)
765 -- f2 = MkQ (MkP True :: forall a. P Char a)
767 -- With the change, f1 will type-check, because the 'Char' info from
768 -- the signature is propagated into MkQ's argument. With the check
769 -- in the other order, the extra signature in f2 is reqd.]
771 ---------------------------
772 tcSyntaxOp :: InstOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
773 -- Typecheck a syntax operator, checking that it has the specified type
774 -- The operator is always a variable at this stage (i.e. renamer output)
775 tcSyntaxOp orig (HsVar op) ty = tcId orig op ty
776 tcSyntaxOp orig other ty = pprPanic "tcSyntaxOp" (ppr other)
778 ---------------------------
780 -> [TyVar] -> [TcType] -- Quantified type variables and
781 -- their instantiating types
782 -> [([TyVar], ThetaType)] -- Stuff to instantiate
784 instFun fun_id qtvs qtv_tys []
785 = return (HsVar fun_id) -- Common short cut
787 instFun fun_id qtvs qtv_tys tv_theta_prs
788 = do { let subst = zipOpenTvSubst qtvs qtv_tys
789 ty_theta_prs' = map subst_pr tv_theta_prs
790 subst_pr (tvs, theta) = (map (substTyVar subst) tvs,
791 substTheta subst theta)
793 -- The ty_theta_prs' is always non-empty
794 ((tys1',theta1') : further_prs') = ty_theta_prs'
796 -- First, chuck in the constraints from
797 -- the "stupid theta" of a data constructor (sigh)
798 ; case isDataConId_maybe fun_id of
799 Just con -> tcInstStupidTheta con tys1'
802 ; if want_method_inst theta1'
803 then do { meth_id <- newMethodWithGivenTy orig fun_id tys1'
804 -- See Note [Multiple instantiation]
805 ; go (HsVar meth_id) further_prs' }
806 else go (HsVar fun_id) ty_theta_prs'
809 orig = OccurrenceOf (idName fun_id)
811 go fun [] = return fun
813 go fun ((tys, theta) : prs)
814 = do { dicts <- newDicts orig theta
816 ; let the_app = unLoc $ mkHsDictApp (mkHsTyApp (noLoc fun) tys)
820 -- Hack Alert (want_method_inst)!
821 -- See Note [No method sharing]
822 -- If f :: (%x :: T) => Int -> Int
823 -- Then if we have two separate calls, (f 3, f 4), we cannot
824 -- make a method constraint that then gets shared, thus:
825 -- let m = f %x in (m 3, m 4)
826 -- because that loses the linearity of the constraint.
827 -- The simplest thing to do is never to construct a method constraint
828 -- in the first place that has a linear implicit parameter in it.
829 want_method_inst theta = not (null theta) -- Overloaded
830 && not (any isLinearPred theta) -- Not linear
831 && not opt_NoMethodSharing
832 -- See Note [No method sharing] below
835 Note [Multiple instantiation]
836 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
837 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
838 For example, consider
839 f :: forall a. Eq a => forall b. Ord b => a -> b
840 At a call to f, at say [Int, Bool], it's tempting to translate the call to
844 f_m1 :: forall b. Ord b => Int -> b
848 f_m2 = f_m1 Bool dOrdBool
850 But notice that f_m2 has f_m1 as its meth_id. Now the danger is that if we do
851 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
853 But it's entirely possible that f_m2 will continue to float out, because it
854 mentions no type variables. Result, f_m1 isn't in scope.
856 Here's a concrete example that does this (test tc200):
859 f :: Eq b => b -> a -> Int
860 baz :: Eq a => Int -> a -> Int
865 Current solution: only do the "method sharing" thing for the first type/dict
866 application, not for the iterated ones. A horribly subtle point.
868 Note [No method sharing]
869 ~~~~~~~~~~~~~~~~~~~~~~~~
870 The -fno-method-sharing flag controls what happens so far as the LIE
871 is concerned. The default case is that for an overloaded function we
872 generate a "method" Id, and add the Method Inst to the LIE. So you get
875 f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
876 If you specify -fno-method-sharing, the dictionary application
877 isn't shared, so we get
879 f = /\a (d:Num a) (x:a) -> (+) a d x x
880 This gets a bit less sharing, but
881 a) it's better for RULEs involving overloaded functions
882 b) perhaps fewer separated lambdas
885 tcArgs :: LHsExpr Name -- The function (for error messages)
886 -> [LHsExpr Name] -> [TcSigmaType] -- Actual arguments and expected arg types
887 -> TcM [LHsExpr TcId] -- Resulting args
889 tcArgs fun args expected_arg_tys
890 = mapM (tcArg fun) (zip3 args expected_arg_tys [1..])
892 tcArg :: LHsExpr Name -- The function (for error messages)
893 -> (LHsExpr Name, BoxySigmaType, Int) -- Actual argument and expected arg type
894 -> TcM (LHsExpr TcId) -- Resulting argument
895 tcArg fun (arg, ty, arg_no) = addErrCtxt (funAppCtxt fun arg arg_no) $
900 -- If an error happens we try to figure out whether the
901 -- function has been given too many or too few arguments,
903 checkFunResCtxt fun expected_res_ty actual_res_ty tidy_env
904 = zonkTcType expected_res_ty `thenM` \ exp_ty' ->
905 zonkTcType actual_res_ty `thenM` \ act_ty' ->
907 (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
908 (env2, act_ty'') = tidyOpenType env1 act_ty'
909 (exp_args, _) = tcSplitFunTys exp_ty''
910 (act_args, _) = tcSplitFunTys act_ty''
912 len_act_args = length act_args
913 len_exp_args = length exp_args
915 message | len_exp_args < len_act_args = wrongArgsCtxt "too few" fun
916 | len_exp_args > len_act_args = wrongArgsCtxt "too many" fun
919 returnM (env2, message)
923 %************************************************************************
925 \subsection{@tcId@ typchecks an identifier occurrence}
927 %************************************************************************
930 lookupFun :: InstOrigin -> Name -> TcM TcId
931 lookupFun orig id_name
932 = do { thing <- tcLookup id_name
934 AGlobal (ADataCon con) -> return (dataConWrapId con)
937 | isNaughtyRecordSelector id -> failWithTc (naughtyRecordSel id)
938 | otherwise -> return id
939 -- A global cannot possibly be ill-staged
940 -- nor does it need the 'lifting' treatment
943 ATcId id th_level _ -> return id -- Non-TH case
945 ATcId id th_level _ -> do { use_stage <- getStage -- TH case
946 ; thLocalId orig id_name id th_level use_stage }
949 other -> failWithTc (ppr other <+> ptext SLIT("used where a value identifer was expected"))
952 #ifdef GHCI /* GHCI and TH is on */
953 --------------------------------------
954 -- thLocalId : Check for cross-stage lifting
955 thLocalId orig id_name id th_bind_lvl (Brack use_lvl ps_var lie_var)
956 | use_lvl > th_bind_lvl
957 = thBrackId orig id_name id ps_var lie_var
958 thLocalId orig id_name id th_bind_lvl use_stage
959 = do { checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage
962 --------------------------------------
963 thBrackId orig id_name id ps_var lie_var
964 | isExternalName id_name
965 = -- Top-level identifiers in this module,
966 -- (which have External Names)
967 -- are just like the imported case:
968 -- no need for the 'lifting' treatment
969 -- E.g. this is fine:
972 -- But we do need to put f into the keep-alive
973 -- set, because after desugaring the code will
974 -- only mention f's *name*, not f itself.
975 do { keepAliveTc id_name; return id }
978 = -- Nested identifiers, such as 'x' in
979 -- E.g. \x -> [| h x |]
980 -- We must behave as if the reference to x was
982 -- We use 'x' itself as the splice proxy, used by
983 -- the desugarer to stitch it all back together.
984 -- If 'x' occurs many times we may get many identical
985 -- bindings of the same splice proxy, but that doesn't
986 -- matter, although it's a mite untidy.
987 do { let id_ty = idType id
988 ; checkTc (isTauTy id_ty) (polySpliceErr id)
989 -- If x is polymorphic, its occurrence sites might
990 -- have different instantiations, so we can't use plain
991 -- 'x' as the splice proxy name. I don't know how to
992 -- solve this, and it's probably unimportant, so I'm
993 -- just going to flag an error for now
995 ; setLIEVar lie_var $ do
996 { lift <- newMethodFromName orig id_ty DsMeta.liftName
997 -- Put the 'lift' constraint into the right LIE
999 -- Update the pending splices
1000 ; ps <- readMutVar ps_var
1001 ; writeMutVar ps_var ((id_name, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps)
1007 Note [Multiple instantiation]
1008 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1009 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
1010 For example, consider
1011 f :: forall a. Eq a => forall b. Ord b => a -> b
1012 At a call to f, at say [Int, Bool], it's tempting to translate the call to
1016 f_m1 :: forall b. Ord b => Int -> b
1020 f_m2 = f_m1 Bool dOrdBool
1022 But notice that f_m2 has f_m1 as its meth_id. Now the danger is that if we do
1023 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
1025 But it's entirely possible that f_m2 will continue to float out, because it
1026 mentions no type variables. Result, f_m1 isn't in scope.
1028 Here's a concrete example that does this (test tc200):
1031 f :: Eq b => b -> a -> Int
1032 baz :: Eq a => Int -> a -> Int
1034 instance C Int where
1037 Current solution: only do the "method sharing" thing for the first type/dict
1038 application, not for the iterated ones. A horribly subtle point.
1041 %************************************************************************
1043 \subsection{Record bindings}
1045 %************************************************************************
1047 Game plan for record bindings
1048 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1049 1. Find the TyCon for the bindings, from the first field label.
1051 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1053 For each binding field = value
1055 3. Instantiate the field type (from the field label) using the type
1058 4 Type check the value using tcArg, passing the field type as
1059 the expected argument type.
1061 This extends OK when the field types are universally quantified.
1067 -> [TcType] -- Expected type for each field
1068 -> HsRecordBinds Name
1069 -> TcM (HsRecordBinds TcId)
1071 tcRecordBinds data_con arg_tys rbinds
1072 = do { mb_binds <- mappM do_bind rbinds
1073 ; return (catMaybes mb_binds) }
1075 flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1076 do_bind (L loc field_lbl, rhs)
1077 | Just field_ty <- assocMaybe flds_w_tys field_lbl
1078 = addErrCtxt (fieldCtxt field_lbl) $
1079 do { rhs' <- tcPolyExprNC rhs field_ty
1080 ; sel_id <- tcLookupId field_lbl
1081 ; ASSERT( isRecordSelector sel_id )
1082 return (Just (L loc sel_id, rhs')) }
1084 = do { addErrTc (badFieldCon data_con field_lbl)
1087 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1088 checkMissingFields data_con rbinds
1089 | null field_labels -- Not declared as a record;
1090 -- But C{} is still valid if no strict fields
1091 = if any isMarkedStrict field_strs then
1092 -- Illegal if any arg is strict
1093 addErrTc (missingStrictFields data_con [])
1097 | otherwise -- A record
1098 = checkM (null missing_s_fields)
1099 (addErrTc (missingStrictFields data_con missing_s_fields)) `thenM_`
1101 doptM Opt_WarnMissingFields `thenM` \ warn ->
1102 checkM (not (warn && notNull missing_ns_fields))
1103 (warnTc True (missingFields data_con missing_ns_fields))
1107 = [ fl | (fl, str) <- field_info,
1109 not (fl `elem` field_names_used)
1112 = [ fl | (fl, str) <- field_info,
1113 not (isMarkedStrict str),
1114 not (fl `elem` field_names_used)
1117 field_names_used = recBindFields rbinds
1118 field_labels = dataConFieldLabels data_con
1120 field_info = zipEqual "missingFields"
1124 field_strs = dataConStrictMarks data_con
1127 %************************************************************************
1129 \subsection{Errors and contexts}
1131 %************************************************************************
1133 Boring and alphabetical:
1136 = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1139 = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1141 fieldCtxt field_name
1142 = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1144 funAppCtxt fun arg arg_no
1145 = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"),
1146 quotes (ppr fun) <> text ", namely"])
1147 4 (quotes (ppr arg))
1150 = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1153 = vcat [ptext SLIT("Record update for the non-Haskell-98 data type") <+> quotes (ppr tycon)
1154 <+> ptext SLIT("is not (yet) supported"),
1155 ptext SLIT("Use pattern-matching instead")]
1157 = hang (ptext SLIT("No constructor has all these fields:"))
1158 4 (pprQuotedList (recBindFields rbinds))
1160 naughtyRecordSel sel_id
1161 = ptext SLIT("Cannot use record selector") <+> quotes (ppr sel_id) <+>
1162 ptext SLIT("as a function due to escaped type variables") $$
1163 ptext SLIT("Probably fix: use pattern-matching syntax instead")
1166 = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1168 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1169 missingStrictFields con fields
1172 rest | null fields = empty -- Happens for non-record constructors
1173 -- with strict fields
1174 | otherwise = colon <+> pprWithCommas ppr fields
1176 header = ptext SLIT("Constructor") <+> quotes (ppr con) <+>
1177 ptext SLIT("does not have the required strict field(s)")
1179 missingFields :: DataCon -> [FieldLabel] -> SDoc
1180 missingFields con fields
1181 = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:")
1182 <+> pprWithCommas ppr fields
1185 = ptext SLIT("In the call") <+> parens (ppr (foldl mkHsApp fun args))
1187 wrongArgsCtxt too_many_or_few fun
1188 = ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1189 <+> ptext SLIT("is applied to") <+> text too_many_or_few
1190 <+> ptext SLIT("arguments")
1193 polySpliceErr :: Id -> SDoc
1195 = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)