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, tcFunResTy, tcGen, boxyUnify, subFunTys, zapToMonotype, stripBoxyType,
29 boxySplitListTy, boxySplitTyConApp, wrapFunResCoercion, preSubType,
31 import BasicTypes ( Arity, isMarkedStrict )
32 import Inst ( newMethodFromName, newIPDict, instToId,
33 newDicts, newMethodWithGivenTy, tcInstStupidTheta )
34 import TcBinds ( tcLocalBinds )
35 import TcEnv ( tcLookup, tcLookupId, tcLookupDataCon, tcLookupField )
36 import TcArrows ( tcProc )
37 import TcMatches ( tcMatchesCase, tcMatchLambda, tcDoStmts, TcMatchCtxt(..) )
38 import TcHsType ( tcHsSigType, UserTypeCtxt(..) )
39 import TcPat ( tcOverloadedLit, badFieldCon )
40 import TcMType ( tcInstTyVars, newFlexiTyVarTy, newBoxyTyVars, readFilledBox, zonkTcTypes )
41 import TcType ( TcType, TcSigmaType, TcRhoType,
42 BoxySigmaType, BoxyRhoType, ThetaType,
44 tcMultiSplitSigmaTy, tcSplitFunTysN, tcSplitTyConApp_maybe,
45 isSigmaTy, mkFunTy, mkTyConApp, isLinearPred,
46 exactTyVarsOfType, exactTyVarsOfTypes,
47 zipTopTvSubst, zipOpenTvSubst, substTys, substTyVar
49 import Kind ( argTypeKind )
51 import Id ( Id, idType, idName, recordSelectorFieldLabel,
52 isRecordSelector, isNaughtyRecordSelector, isDataConId_maybe )
53 import DataCon ( DataCon, dataConFieldLabels, dataConStrictMarks, dataConSourceArity,
54 dataConWrapId, isVanillaDataCon, dataConTyVars, dataConOrigArgTys )
56 import TyCon ( FieldLabel, tyConStupidTheta, tyConDataCons, isEnumerationTyCon )
57 import Type ( substTheta, substTy )
58 import Var ( TyVar, tyVarKind )
59 import VarSet ( emptyVarSet, elemVarSet, unionVarSet )
60 import TysWiredIn ( boolTy, parrTyCon, tupleTyCon )
61 import PrelNames ( enumFromName, enumFromThenName,
62 enumFromToName, enumFromThenToName,
63 enumFromToPName, enumFromThenToPName, negateName,
66 import PrimOp ( tagToEnumKey )
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) }
258 tc_args arg1_ty' other = panic "tcExpr SectionR"
262 tcExpr (HsLet binds expr) res_ty
263 = do { (binds', expr') <- tcLocalBinds binds $
264 tcMonoExpr expr res_ty
265 ; return (HsLet binds' expr') }
267 tcExpr (HsCase scrut matches) exp_ty
268 = do { -- We used to typecheck the case alternatives first.
269 -- The case patterns tend to give good type info to use
270 -- when typechecking the scrutinee. For example
273 -- will report that map is applied to too few arguments
275 -- But now, in the GADT world, we need to typecheck the scrutinee
276 -- first, to get type info that may be refined in the case alternatives
277 (scrut', scrut_ty) <- addErrCtxt (caseScrutCtxt scrut)
280 ; traceTc (text "HsCase" <+> ppr scrut_ty)
281 ; matches' <- tcMatchesCase match_ctxt scrut_ty matches exp_ty
282 ; return (HsCase scrut' matches') }
284 match_ctxt = MC { mc_what = CaseAlt,
285 mc_body = tcPolyExpr }
287 tcExpr (HsIf pred b1 b2) res_ty
288 = do { pred' <- addErrCtxt (predCtxt pred) $
289 tcMonoExpr pred boolTy
290 ; b1' <- tcMonoExpr b1 res_ty
291 ; b2' <- tcMonoExpr b2 res_ty
292 ; return (HsIf pred' b1' b2') }
294 tcExpr (HsDo do_or_lc stmts body _) res_ty
295 = tcDoStmts do_or_lc stmts body res_ty
297 tcExpr in_expr@(ExplicitList _ exprs) res_ty -- Non-empty list
298 = do { elt_ty <- boxySplitListTy res_ty
299 ; exprs' <- mappM (tc_elt elt_ty) exprs
300 ; return (ExplicitList elt_ty exprs') }
302 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
304 tcExpr in_expr@(ExplicitPArr _ exprs) res_ty -- maybe empty
305 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
306 ; exprs' <- mappM (tc_elt elt_ty) exprs
307 ; ifM (null exprs) (zapToMonotype elt_ty)
308 -- If there are no expressions in the comprehension
309 -- we must still fill in the box
310 -- (Not needed for [] and () becuase they happen
311 -- to parse as data constructors.)
312 ; return (ExplicitPArr elt_ty exprs') }
314 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
316 tcExpr (ExplicitTuple exprs boxity) res_ty
317 = do { arg_tys <- boxySplitTyConApp (tupleTyCon boxity (length exprs)) res_ty
318 ; exprs' <- tcPolyExprs exprs arg_tys
319 ; return (ExplicitTuple exprs' boxity) }
321 tcExpr (HsProc pat cmd) res_ty
322 = do { (pat', cmd') <- tcProc pat cmd res_ty
323 ; return (HsProc pat' cmd') }
325 tcExpr e@(HsArrApp _ _ _ _ _) _
326 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
327 ptext SLIT("was found where an expression was expected")])
329 tcExpr e@(HsArrForm _ _ _) _
330 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
331 ptext SLIT("was found where an expression was expected")])
334 %************************************************************************
336 Record construction and update
338 %************************************************************************
341 tcExpr expr@(RecordCon (L loc con_name) _ rbinds) res_ty
342 = do { data_con <- tcLookupDataCon con_name
344 -- Check for missing fields
345 ; checkMissingFields data_con rbinds
347 ; let arity = dataConSourceArity data_con
349 = do { rbinds' <- tcRecordBinds data_con arg_tys rbinds
352 -- The unBox ensures that all the boxes in arg_tys are indeed
353 -- filled, which is the invariant expected by tcIdApp
355 ; (con_expr, rbinds') <- tcIdApp con_name arity check_fields res_ty
357 ; returnM (RecordCon (L loc (dataConWrapId data_con)) con_expr rbinds') }
359 -- The main complication with RecordUpd is that we need to explicitly
360 -- handle the *non-updated* fields. Consider:
362 -- data T a b = MkT1 { fa :: a, fb :: b }
363 -- | MkT2 { fa :: a, fc :: Int -> Int }
364 -- | MkT3 { fd :: a }
366 -- upd :: T a b -> c -> T a c
367 -- upd t x = t { fb = x}
369 -- The type signature on upd is correct (i.e. the result should not be (T a b))
370 -- because upd should be equivalent to:
372 -- upd t x = case t of
373 -- MkT1 p q -> MkT1 p x
374 -- MkT2 a b -> MkT2 p b
375 -- MkT3 d -> error ...
377 -- So we need to give a completely fresh type to the result record,
378 -- and then constrain it by the fields that are *not* updated ("p" above).
380 -- Note that because MkT3 doesn't contain all the fields being updated,
381 -- its RHS is simply an error, so it doesn't impose any type constraints
383 -- All this is done in STEP 4 below.
387 -- For record update we require that every constructor involved in the
388 -- update (i.e. that has all the specified fields) is "vanilla". I
389 -- don't know how to do the update otherwise.
392 tcExpr expr@(RecordUpd record_expr rbinds _ _) res_ty
394 -- Check that the field names are really field names
395 ASSERT( notNull rbinds )
397 field_names = map fst rbinds
399 mappM (tcLookupField . unLoc) field_names `thenM` \ sel_ids ->
400 -- The renamer has already checked that they
403 bad_guys = [ setSrcSpan loc $ addErrTc (notSelector field_name)
404 | (L loc field_name, sel_id) <- field_names `zip` sel_ids,
405 not (isRecordSelector sel_id) -- Excludes class ops
408 checkM (null bad_guys) (sequenceM bad_guys `thenM_` failM) `thenM_`
411 -- Figure out the tycon and data cons from the first field name
413 -- It's OK to use the non-tc splitters here (for a selector)
414 upd_field_lbls = recBindFields rbinds
416 (tycon, _) = recordSelectorFieldLabel sel_id -- We've failed already if
417 data_cons = tyConDataCons tycon -- it's not a field label
418 relevant_cons = filter is_relevant data_cons
419 is_relevant con = all (`elem` dataConFieldLabels con) upd_field_lbls
423 -- Check that at least one constructor has all the named fields
424 -- i.e. has an empty set of bad fields returned by badFields
425 checkTc (not (null relevant_cons))
426 (badFieldsUpd rbinds) `thenM_`
428 -- Check that all relevant data cons are vanilla. Doing record updates on
429 -- GADTs and/or existentials is more than my tiny brain can cope with today
430 checkTc (all isVanillaDataCon relevant_cons)
431 (nonVanillaUpd tycon) `thenM_`
434 -- Use the un-updated fields to find a vector of booleans saying
435 -- which type arguments must be the same in updatee and result.
437 -- WARNING: this code assumes that all data_cons in a common tycon
438 -- have FieldLabels abstracted over the same tyvars.
440 -- A constructor is only relevant to this process if
441 -- it contains *all* the fields that are being updated
442 con1 = head relevant_cons -- A representative constructor
443 con1_tyvars = dataConTyVars con1
444 con1_flds = dataConFieldLabels con1
445 con1_arg_tys = dataConOrigArgTys con1
446 common_tyvars = exactTyVarsOfTypes [ty | (fld,ty) <- con1_flds `zip` con1_arg_tys
447 , not (fld `elem` upd_field_lbls) ]
449 is_common_tv tv = tv `elemVarSet` common_tyvars
451 mk_inst_ty tv result_inst_ty
452 | is_common_tv tv = returnM result_inst_ty -- Same as result type
453 | otherwise = newFlexiTyVarTy (tyVarKind tv) -- Fresh type, of correct kind
455 tcInstTyVars con1_tyvars `thenM` \ (_, result_inst_tys, inst_env) ->
456 zipWithM mk_inst_ty con1_tyvars result_inst_tys `thenM` \ inst_tys ->
459 -- Typecheck the update bindings.
460 -- (Do this after checking for bad fields in case there's a field that
461 -- doesn't match the constructor.)
463 result_record_ty = mkTyConApp tycon result_inst_tys
464 con1_arg_tys' = map (substTy inst_env) con1_arg_tys
466 tcSubExp result_record_ty res_ty `thenM` \ co_fn ->
467 tcRecordBinds con1 con1_arg_tys' rbinds `thenM` \ rbinds' ->
470 -- Typecheck the expression to be updated
472 record_ty = ASSERT( length inst_tys == tyConArity tycon )
473 mkTyConApp tycon inst_tys
474 -- This is one place where the isVanilla check is important
475 -- So that inst_tys matches the tycon
477 tcMonoExpr record_expr record_ty `thenM` \ record_expr' ->
480 -- Figure out the LIE we need. We have to generate some
481 -- dictionaries for the data type context, since we are going to
482 -- do pattern matching over the data cons.
484 -- What dictionaries do we need?
485 -- We just take the context of the first data constructor
486 -- This isn't right, but I just can't bear to union up all the relevant ones
488 theta' = substTheta inst_env (tyConStupidTheta tycon)
490 newDicts RecordUpdOrigin theta' `thenM` \ dicts ->
491 extendLIEs dicts `thenM_`
494 returnM (mkHsCoerce co_fn (RecordUpd record_expr' rbinds' record_ty result_record_ty))
498 %************************************************************************
500 Arithmetic sequences e.g. [a,b..]
501 and their parallel-array counterparts e.g. [: a,b.. :]
504 %************************************************************************
507 tcExpr (ArithSeq _ seq@(From expr)) res_ty
508 = do { elt_ty <- boxySplitListTy res_ty
509 ; expr' <- tcPolyExpr expr elt_ty
510 ; enum_from <- newMethodFromName (ArithSeqOrigin seq)
512 ; return (ArithSeq (HsVar enum_from) (From expr')) }
514 tcExpr in_expr@(ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
515 = do { elt_ty <- boxySplitListTy res_ty
516 ; expr1' <- tcPolyExpr expr1 elt_ty
517 ; expr2' <- tcPolyExpr expr2 elt_ty
518 ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq)
519 elt_ty enumFromThenName
520 ; return (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2')) }
523 tcExpr in_expr@(ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
524 = do { elt_ty <- boxySplitListTy res_ty
525 ; expr1' <- tcPolyExpr expr1 elt_ty
526 ; expr2' <- tcPolyExpr expr2 elt_ty
527 ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq)
528 elt_ty enumFromToName
529 ; return (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
531 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
532 = do { elt_ty <- boxySplitListTy res_ty
533 ; expr1' <- tcPolyExpr expr1 elt_ty
534 ; expr2' <- tcPolyExpr expr2 elt_ty
535 ; expr3' <- tcPolyExpr expr3 elt_ty
536 ; eft <- newMethodFromName (ArithSeqOrigin seq)
537 elt_ty enumFromThenToName
538 ; return (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
540 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
541 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
542 ; expr1' <- tcPolyExpr expr1 elt_ty
543 ; expr2' <- tcPolyExpr expr2 elt_ty
544 ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq)
545 elt_ty enumFromToPName
546 ; return (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
548 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
549 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
550 ; expr1' <- tcPolyExpr expr1 elt_ty
551 ; expr2' <- tcPolyExpr expr2 elt_ty
552 ; expr3' <- tcPolyExpr expr3 elt_ty
553 ; eft <- newMethodFromName (PArrSeqOrigin seq)
554 elt_ty enumFromThenToPName
555 ; return (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
557 tcExpr (PArrSeq _ _) _
558 = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
559 -- the parser shouldn't have generated it and the renamer shouldn't have
564 %************************************************************************
568 %************************************************************************
571 #ifdef GHCI /* Only if bootstrapped */
572 -- Rename excludes these cases otherwise
573 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
574 tcExpr (HsBracket brack) res_ty = do { e <- tcBracket brack res_ty
580 %************************************************************************
584 %************************************************************************
587 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
591 %************************************************************************
595 %************************************************************************
598 ---------------------------
599 tcApp :: HsExpr Name -- Function
600 -> Arity -- Number of args reqd
601 -> ([BoxySigmaType] -> TcM arg_results) -- Argument type-checker
602 -> BoxyRhoType -- Result type
603 -> TcM (HsExpr TcId, arg_results)
605 -- (tcFun fun n_args arg_checker res_ty)
606 -- The argument type checker, arg_checker, will be passed exactly n_args types
608 tcApp (HsVar fun_name) n_args arg_checker res_ty
609 = tcIdApp fun_name n_args arg_checker res_ty
611 tcApp fun n_args arg_checker res_ty -- The vanilla case (rula APP)
612 = do { arg_boxes <- newBoxyTyVars (replicate n_args argTypeKind)
613 ; fun' <- tcExpr fun (mkFunTys (mkTyVarTys arg_boxes) res_ty)
614 ; arg_tys' <- mapM readFilledBox arg_boxes
615 ; args' <- arg_checker arg_tys'
616 ; return (fun', args') }
618 ---------------------------
619 tcIdApp :: Name -- Function
620 -> Arity -- Number of args reqd
621 -> ([BoxySigmaType] -> TcM arg_results) -- Argument type-checker
622 -- The arg-checker guarantees to fill all boxes in the arg types
623 -> BoxyRhoType -- Result type
624 -> TcM (HsExpr TcId, arg_results)
626 -- Call (f e1 ... en) :: res_ty
627 -- Type f :: forall a b c. theta => fa_1 -> ... -> fa_k -> fres
628 -- (where k <= n; fres has the rest)
629 -- NB: if k < n then the function doesn't have enough args, and
630 -- presumably fres is a type variable that we are going to
631 -- instantiate with a function type
633 -- Then fres <= bx_(k+1) -> ... -> bx_n -> res_ty
635 tcIdApp fun_name n_args arg_checker res_ty
636 = do { fun_id <- lookupFun (OccurrenceOf fun_name) fun_name
638 -- Split up the function type
639 ; let (tv_theta_prs, rho) = tcMultiSplitSigmaTy (idType fun_id)
640 (fun_arg_tys, fun_res_ty) = tcSplitFunTysN rho n_args
642 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
643 arg_qtvs = exactTyVarsOfTypes fun_arg_tys
644 res_qtvs = exactTyVarsOfType fun_res_ty
645 -- NB: exactTyVarsOfType. See Note [Silly type synonyms in smart-app]
646 tau_qtvs = arg_qtvs `unionVarSet` res_qtvs
647 k = length fun_arg_tys -- k <= n_args
648 n_missing_args = n_args - k -- Always >= 0
650 -- Match the result type of the function with the
651 -- result type of the context, to get an inital substitution
652 ; extra_arg_boxes <- newBoxyTyVars (replicate n_missing_args argTypeKind)
653 ; let extra_arg_tys' = mkTyVarTys extra_arg_boxes
654 res_ty' = mkFunTys extra_arg_tys' res_ty
655 ; qtys' <- preSubType qtvs tau_qtvs fun_res_ty res_ty'
656 ; let arg_subst = zipOpenTvSubst qtvs qtys'
657 fun_arg_tys' = substTys arg_subst fun_arg_tys
659 -- Typecheck the arguments!
660 -- Doing so will fill arg_qtvs and extra_arg_tys'
661 ; args' <- arg_checker (fun_arg_tys' ++ extra_arg_tys')
663 -- Strip boxes from the qtvs that have been filled in by the arg checking
664 -- AND any variables that are mentioned in neither arg nor result
665 -- the latter are mentioned only in constraints; stripBoxyType will
666 -- fill them with a monotype
667 ; let strip qtv qty' | qtv `elemVarSet` arg_qtvs = stripBoxyType qty'
668 | otherwise = return qty'
669 ; qtys'' <- zipWithM strip qtvs qtys'
670 ; extra_arg_tys'' <- mapM readFilledBox extra_arg_boxes
672 -- Result subsumption
673 ; let res_subst = zipOpenTvSubst qtvs qtys''
674 fun_res_ty'' = substTy res_subst fun_res_ty
675 res_ty'' = mkFunTys extra_arg_tys'' res_ty
676 ; co_fn <- tcFunResTy fun_name fun_res_ty'' res_ty''
678 -- And pack up the results
679 -- By applying the coercion just to the *function* we can make
680 -- tcFun work nicely for OpApp and Sections too
681 ; fun' <- instFun fun_id qtvs qtys'' tv_theta_prs
682 ; co_fn' <- wrapFunResCoercion fun_arg_tys' co_fn
683 ; return (mkHsCoerce co_fn' fun', args') }
686 Note [Silly type synonyms in smart-app]
687 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
688 When we call sripBoxyType, all of the boxes should be filled
689 in. But we need to be careful about type synonyms:
693 In the call (f x) we'll typecheck x, expecting it to have type
694 (T box). Usually that would fill in the box, but in this case not;
695 because 'a' is discarded by the silly type synonym T. So we must
696 use exactTyVarsOfType to figure out which type variables are free
697 in the argument type.
700 -- tcId is a specialisation of tcIdApp when there are no arguments
701 -- tcId f ty = do { (res, _) <- tcIdApp f [] (\[] -> return ()) ty
706 -> BoxyRhoType -- Result type
708 tcId orig fun_name res_ty
709 = do { traceTc (text "tcId" <+> ppr fun_name <+> ppr res_ty)
710 ; fun_id <- lookupFun orig fun_name
712 -- Split up the function type
713 ; let (tv_theta_prs, fun_tau) = tcMultiSplitSigmaTy (idType fun_id)
714 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
715 tau_qtvs = exactTyVarsOfType fun_tau -- Mentioned in the tau part
716 ; qtv_tys <- preSubType qtvs tau_qtvs fun_tau res_ty
718 -- Do the subsumption check wrt the result type
719 ; let res_subst = zipTopTvSubst qtvs qtv_tys
720 fun_tau' = substTy res_subst fun_tau
722 ; co_fn <- tcFunResTy fun_name fun_tau' res_ty
724 -- And pack up the results
725 ; fun' <- instFun fun_id qtvs qtv_tys tv_theta_prs
726 ; return (mkHsCoerce co_fn fun') }
728 -- Note [Push result type in]
730 -- Unify with expected result before (was: after) type-checking the args
731 -- so that the info from res_ty (was: args) percolates to args (was actual_res_ty).
732 -- This is when we might detect a too-few args situation.
733 -- (One can think of cases when the opposite order would give
734 -- a better error message.)
735 -- [March 2003: I'm experimenting with putting this first. Here's an
736 -- example where it actually makes a real difference
737 -- class C t a b | t a -> b
738 -- instance C Char a Bool
740 -- data P t a = forall b. (C t a b) => MkP b
741 -- data Q t = MkQ (forall a. P t a)
744 -- f1 = MkQ (MkP True)
745 -- f2 = MkQ (MkP True :: forall a. P Char a)
747 -- With the change, f1 will type-check, because the 'Char' info from
748 -- the signature is propagated into MkQ's argument. With the check
749 -- in the other order, the extra signature in f2 is reqd.]
751 ---------------------------
752 tcSyntaxOp :: InstOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
753 -- Typecheck a syntax operator, checking that it has the specified type
754 -- The operator is always a variable at this stage (i.e. renamer output)
755 tcSyntaxOp orig (HsVar op) ty = tcId orig op ty
756 tcSyntaxOp orig other ty = pprPanic "tcSyntaxOp" (ppr other)
758 ---------------------------
760 -> [TyVar] -> [TcType] -- Quantified type variables and
761 -- their instantiating types
762 -> [([TyVar], ThetaType)] -- Stuff to instantiate
764 instFun fun_id qtvs qtv_tys []
765 = return (HsVar fun_id) -- Common short cut
767 instFun fun_id qtvs qtv_tys tv_theta_prs
768 = do { -- Horrid check for tagToEnum; see Note [tagToEnum#]
769 checkBadTagToEnumCall fun_id qtv_tys
771 ; let subst = zipOpenTvSubst qtvs qtv_tys
772 ty_theta_prs' = map subst_pr tv_theta_prs
773 subst_pr (tvs, theta) = (map (substTyVar subst) tvs,
774 substTheta subst theta)
776 -- The ty_theta_prs' is always non-empty
777 ((tys1',theta1') : further_prs') = ty_theta_prs'
779 -- First, chuck in the constraints from
780 -- the "stupid theta" of a data constructor (sigh)
781 ; case isDataConId_maybe fun_id of
782 Just con -> tcInstStupidTheta con tys1'
785 ; if want_method_inst theta1'
786 then do { meth_id <- newMethodWithGivenTy orig fun_id tys1'
787 -- See Note [Multiple instantiation]
788 ; go (HsVar meth_id) further_prs' }
789 else go (HsVar fun_id) ty_theta_prs'
792 orig = OccurrenceOf (idName fun_id)
794 go fun [] = return fun
796 go fun ((tys, theta) : prs)
797 = do { dicts <- newDicts orig theta
799 ; let the_app = unLoc $ mkHsDictApp (mkHsTyApp (noLoc fun) tys)
803 -- Hack Alert (want_method_inst)!
804 -- See Note [No method sharing]
805 -- If f :: (%x :: T) => Int -> Int
806 -- Then if we have two separate calls, (f 3, f 4), we cannot
807 -- make a method constraint that then gets shared, thus:
808 -- let m = f %x in (m 3, m 4)
809 -- because that loses the linearity of the constraint.
810 -- The simplest thing to do is never to construct a method constraint
811 -- in the first place that has a linear implicit parameter in it.
812 want_method_inst theta = not (null theta) -- Overloaded
813 && not (any isLinearPred theta) -- Not linear
814 && not opt_NoMethodSharing
815 -- See Note [No method sharing] below
818 Note [Multiple instantiation]
819 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
820 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
821 For example, consider
822 f :: forall a. Eq a => forall b. Ord b => a -> b
823 At a call to f, at say [Int, Bool], it's tempting to translate the call to
827 f_m1 :: forall b. Ord b => Int -> b
831 f_m2 = f_m1 Bool dOrdBool
833 But notice that f_m2 has f_m1 as its meth_id. Now the danger is that if we do
834 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
836 But it's entirely possible that f_m2 will continue to float out, because it
837 mentions no type variables. Result, f_m1 isn't in scope.
839 Here's a concrete example that does this (test tc200):
842 f :: Eq b => b -> a -> Int
843 baz :: Eq a => Int -> a -> Int
848 Current solution: only do the "method sharing" thing for the first type/dict
849 application, not for the iterated ones. A horribly subtle point.
851 Note [No method sharing]
852 ~~~~~~~~~~~~~~~~~~~~~~~~
853 The -fno-method-sharing flag controls what happens so far as the LIE
854 is concerned. The default case is that for an overloaded function we
855 generate a "method" Id, and add the Method Inst to the LIE. So you get
858 f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
859 If you specify -fno-method-sharing, the dictionary application
860 isn't shared, so we get
862 f = /\a (d:Num a) (x:a) -> (+) a d x x
863 This gets a bit less sharing, but
864 a) it's better for RULEs involving overloaded functions
865 b) perhaps fewer separated lambdas
868 tcArgs :: LHsExpr Name -- The function (for error messages)
869 -> [LHsExpr Name] -> [TcSigmaType] -- Actual arguments and expected arg types
870 -> TcM [LHsExpr TcId] -- Resulting args
872 tcArgs fun args expected_arg_tys
873 = mapM (tcArg fun) (zip3 args expected_arg_tys [1..])
875 tcArg :: LHsExpr Name -- The function (for error messages)
876 -> (LHsExpr Name, BoxySigmaType, Int) -- Actual argument and expected arg type
877 -> TcM (LHsExpr TcId) -- Resulting argument
878 tcArg fun (arg, ty, arg_no) = addErrCtxt (funAppCtxt fun arg arg_no) $
885 Nasty check to ensure that tagToEnum# is applied to a type that is an
886 enumeration TyCon. Unification may refine the type later, but this
887 check won't see that, alas. It's crude but it works.
889 Here's are two cases that should fail
891 f = tagToEnum# 0 -- Can't do tagToEnum# at a type variable
894 g = tagToEnum# 0 -- Int is not an enumeration
898 checkBadTagToEnumCall :: Id -> [TcType] -> TcM ()
899 checkBadTagToEnumCall fun_id tys
900 | fun_id `hasKey` tagToEnumKey
901 = do { tys' <- zonkTcTypes tys
902 ; checkTc (ok tys') (tagToEnumError tys')
904 | otherwise -- Vastly common case
908 ok (ty:tys) = case tcSplitTyConApp_maybe ty of
909 Just (tc,_) -> isEnumerationTyCon tc
913 = hang (ptext SLIT("Bad call to tagToEnum#") <+> at_type)
914 2 (vcat [ptext SLIT("Specify the type by giving a type signature"),
915 ptext SLIT("e.g. (tagToEnum# x) :: Bool")])
917 at_type | null tys = empty -- Probably never happens
918 | otherwise = ptext SLIT("at type") <+> ppr (head tys)
921 %************************************************************************
923 \subsection{@tcId@ typchecks an identifier occurrence}
925 %************************************************************************
928 lookupFun :: InstOrigin -> Name -> TcM TcId
929 lookupFun orig id_name
930 = do { thing <- tcLookup id_name
932 AGlobal (ADataCon con) -> return (dataConWrapId con)
935 | isNaughtyRecordSelector id -> failWithTc (naughtyRecordSel id)
936 | otherwise -> return id
937 -- A global cannot possibly be ill-staged
938 -- nor does it need the 'lifting' treatment
941 ATcId id th_level _ -> return id -- Non-TH case
943 ATcId id th_level _ -> do { use_stage <- getStage -- TH case
944 ; thLocalId orig id_name id th_level use_stage }
947 other -> failWithTc (ppr other <+> ptext SLIT("used where a value identifer was expected"))
950 #ifdef GHCI /* GHCI and TH is on */
951 --------------------------------------
952 -- thLocalId : Check for cross-stage lifting
953 thLocalId orig id_name id th_bind_lvl (Brack use_lvl ps_var lie_var)
954 | use_lvl > th_bind_lvl
955 = thBrackId orig id_name id ps_var lie_var
956 thLocalId orig id_name id th_bind_lvl use_stage
957 = do { checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage
960 --------------------------------------
961 thBrackId orig id_name id ps_var lie_var
962 | isExternalName id_name
963 = -- Top-level identifiers in this module,
964 -- (which have External Names)
965 -- are just like the imported case:
966 -- no need for the 'lifting' treatment
967 -- E.g. this is fine:
970 -- But we do need to put f into the keep-alive
971 -- set, because after desugaring the code will
972 -- only mention f's *name*, not f itself.
973 do { keepAliveTc id_name; return id }
976 = -- Nested identifiers, such as 'x' in
977 -- E.g. \x -> [| h x |]
978 -- We must behave as if the reference to x was
980 -- We use 'x' itself as the splice proxy, used by
981 -- the desugarer to stitch it all back together.
982 -- If 'x' occurs many times we may get many identical
983 -- bindings of the same splice proxy, but that doesn't
984 -- matter, although it's a mite untidy.
985 do { let id_ty = idType id
986 ; checkTc (isTauTy id_ty) (polySpliceErr id)
987 -- If x is polymorphic, its occurrence sites might
988 -- have different instantiations, so we can't use plain
989 -- 'x' as the splice proxy name. I don't know how to
990 -- solve this, and it's probably unimportant, so I'm
991 -- just going to flag an error for now
993 ; id_ty' <- zapToMonotype id_ty
994 -- The id_ty might have an OpenTypeKind, but we
995 -- can't instantiate the Lift class at that kind,
996 -- so we zap it to a LiftedTypeKind monotype
997 -- C.f. the call in TcPat.newLitInst
999 ; setLIEVar lie_var $ do
1000 { lift <- newMethodFromName orig id_ty' DsMeta.liftName
1001 -- Put the 'lift' constraint into the right LIE
1003 -- Update the pending splices
1004 ; ps <- readMutVar ps_var
1005 ; writeMutVar ps_var ((id_name, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps)
1012 %************************************************************************
1014 \subsection{Record bindings}
1016 %************************************************************************
1018 Game plan for record bindings
1019 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1020 1. Find the TyCon for the bindings, from the first field label.
1022 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1024 For each binding field = value
1026 3. Instantiate the field type (from the field label) using the type
1029 4 Type check the value using tcArg, passing the field type as
1030 the expected argument type.
1032 This extends OK when the field types are universally quantified.
1038 -> [TcType] -- Expected type for each field
1039 -> HsRecordBinds Name
1040 -> TcM (HsRecordBinds TcId)
1042 tcRecordBinds data_con arg_tys rbinds
1043 = do { mb_binds <- mappM do_bind rbinds
1044 ; return (catMaybes mb_binds) }
1046 flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1047 do_bind (L loc field_lbl, rhs)
1048 | Just field_ty <- assocMaybe flds_w_tys field_lbl
1049 = addErrCtxt (fieldCtxt field_lbl) $
1050 do { rhs' <- tcPolyExprNC rhs field_ty
1051 ; sel_id <- tcLookupId field_lbl
1052 ; ASSERT( isRecordSelector sel_id )
1053 return (Just (L loc sel_id, rhs')) }
1055 = do { addErrTc (badFieldCon data_con field_lbl)
1058 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1059 checkMissingFields data_con rbinds
1060 | null field_labels -- Not declared as a record;
1061 -- But C{} is still valid if no strict fields
1062 = if any isMarkedStrict field_strs then
1063 -- Illegal if any arg is strict
1064 addErrTc (missingStrictFields data_con [])
1068 | otherwise -- A record
1069 = checkM (null missing_s_fields)
1070 (addErrTc (missingStrictFields data_con missing_s_fields)) `thenM_`
1072 doptM Opt_WarnMissingFields `thenM` \ warn ->
1073 checkM (not (warn && notNull missing_ns_fields))
1074 (warnTc True (missingFields data_con missing_ns_fields))
1078 = [ fl | (fl, str) <- field_info,
1080 not (fl `elem` field_names_used)
1083 = [ fl | (fl, str) <- field_info,
1084 not (isMarkedStrict str),
1085 not (fl `elem` field_names_used)
1088 field_names_used = recBindFields rbinds
1089 field_labels = dataConFieldLabels data_con
1091 field_info = zipEqual "missingFields"
1095 field_strs = dataConStrictMarks data_con
1098 %************************************************************************
1100 \subsection{Errors and contexts}
1102 %************************************************************************
1104 Boring and alphabetical:
1107 = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1110 = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1112 fieldCtxt field_name
1113 = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1115 funAppCtxt fun arg arg_no
1116 = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"),
1117 quotes (ppr fun) <> text ", namely"])
1118 4 (quotes (ppr arg))
1121 = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1124 = vcat [ptext SLIT("Record update for the non-Haskell-98 data type") <+> quotes (ppr tycon)
1125 <+> ptext SLIT("is not (yet) supported"),
1126 ptext SLIT("Use pattern-matching instead")]
1128 = hang (ptext SLIT("No constructor has all these fields:"))
1129 4 (pprQuotedList (recBindFields rbinds))
1131 naughtyRecordSel sel_id
1132 = ptext SLIT("Cannot use record selector") <+> quotes (ppr sel_id) <+>
1133 ptext SLIT("as a function due to escaped type variables") $$
1134 ptext SLIT("Probably fix: use pattern-matching syntax instead")
1137 = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1139 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1140 missingStrictFields con fields
1143 rest | null fields = empty -- Happens for non-record constructors
1144 -- with strict fields
1145 | otherwise = colon <+> pprWithCommas ppr fields
1147 header = ptext SLIT("Constructor") <+> quotes (ppr con) <+>
1148 ptext SLIT("does not have the required strict field(s)")
1150 missingFields :: DataCon -> [FieldLabel] -> SDoc
1151 missingFields con fields
1152 = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:")
1153 <+> pprWithCommas ppr fields
1156 = ptext SLIT("In the call") <+> parens (ppr (foldl mkHsApp fun args))
1159 polySpliceErr :: Id -> SDoc
1161 = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)