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, boxySubMatchType,
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,
41 tcInstBoxyTyVar, tcInstTyVar )
42 import TcType ( TcType, TcSigmaType, TcRhoType,
43 BoxySigmaType, BoxyRhoType, ThetaType,
44 mkTyVarTys, mkFunTys, tcMultiSplitSigmaTy, tcSplitFunTysN,
45 isSigmaTy, mkFunTy, mkTyConApp, isLinearPred,
46 exactTyVarsOfType, exactTyVarsOfTypes, mkTyVarTy,
47 zipTopTvSubst, zipOpenTvSubst, substTys, substTyVar, lookupTyVar
49 import Kind ( argTypeKind )
51 import Id ( idType, idName, recordSelectorFieldLabel, isRecordSelector,
52 isNaughtyRecordSelector, isDataConId_maybe )
53 import DataCon ( DataCon, dataConFieldLabels, dataConStrictMarks, dataConSourceArity,
54 dataConWrapId, isVanillaDataCon, dataConTyVars, dataConOrigArgTys )
56 import TyCon ( FieldLabel, tyConStupidTheta, tyConDataCons )
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 StaticFlags ( opt_NoMethodSharing )
67 import HscTypes ( TyThing(..) )
68 import SrcLoc ( Located(..), unLoc, noLoc, getLoc )
70 import ListSetOps ( assocMaybe )
71 import Maybes ( catMaybes )
76 import TyCon ( tyConArity )
80 %************************************************************************
82 \subsection{Main wrappers}
84 %************************************************************************
87 tcPolyExpr, tcPolyExprNC
88 :: LHsExpr Name -- Expession to type check
89 -> BoxySigmaType -- Expected type (could be a polytpye)
90 -> TcM (LHsExpr TcId) -- Generalised expr with expected type
92 -- tcPolyExpr is a convenient place (frequent but not too frequent) place
93 -- to add context information.
94 -- The NC version does not do so, usually because the caller wants
97 tcPolyExpr expr res_ty
98 = addErrCtxt (exprCtxt (unLoc expr)) $
99 tcPolyExprNC expr res_ty
101 tcPolyExprNC expr res_ty
103 = do { (gen_fn, expr') <- tcGen res_ty emptyVarSet (tcPolyExprNC expr)
104 -- Note the recursive call to tcPolyExpr, because the
105 -- type may have multiple layers of for-alls
106 ; return (L (getLoc expr') (mkHsCoerce gen_fn (unLoc expr'))) }
109 = tcMonoExpr expr res_ty
112 tcPolyExprs :: [LHsExpr Name] -> [TcType] -> TcM [LHsExpr TcId]
113 tcPolyExprs [] [] = returnM []
114 tcPolyExprs (expr:exprs) (ty:tys)
115 = do { expr' <- tcPolyExpr expr ty
116 ; exprs' <- tcPolyExprs exprs tys
117 ; returnM (expr':exprs') }
118 tcPolyExprs exprs tys = pprPanic "tcPolyExprs" (ppr exprs $$ ppr tys)
121 tcMonoExpr :: LHsExpr Name -- Expression to type check
122 -> BoxyRhoType -- Expected type (could be a type variable)
123 -- Definitely no foralls at the top
124 -- Can contain boxes, which will be filled in
125 -> TcM (LHsExpr TcId)
127 tcMonoExpr (L loc expr) res_ty
128 = ASSERT( not (isSigmaTy res_ty) )
130 do { expr' <- tcExpr expr res_ty
131 ; return (L loc expr') }
134 tcInferRho :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
135 tcInferRho expr = tcInfer (tcMonoExpr expr)
140 %************************************************************************
142 tcExpr: the main expression typechecker
144 %************************************************************************
147 tcExpr :: HsExpr Name -> BoxyRhoType -> TcM (HsExpr TcId)
148 tcExpr (HsVar name) res_ty = tcId (OccurrenceOf name) name res_ty
150 tcExpr (HsLit lit) res_ty = do { boxyUnify (hsLitType lit) res_ty
151 ; return (HsLit lit) }
153 tcExpr (HsPar expr) res_ty = do { expr' <- tcMonoExpr expr res_ty
154 ; return (HsPar expr') }
156 tcExpr (HsSCC lbl expr) res_ty = do { expr' <- tcMonoExpr expr res_ty
157 ; returnM (HsSCC lbl expr') }
159 tcExpr (HsCoreAnn lbl expr) res_ty -- hdaume: core annotation
160 = do { expr' <- tcMonoExpr expr res_ty
161 ; return (HsCoreAnn lbl expr') }
163 tcExpr (HsOverLit lit) res_ty
164 = do { lit' <- tcOverloadedLit (LiteralOrigin lit) lit res_ty
165 ; return (HsOverLit lit') }
167 tcExpr (NegApp expr neg_expr) res_ty
168 = do { neg_expr' <- tcSyntaxOp (OccurrenceOf negateName) neg_expr
169 (mkFunTy res_ty res_ty)
170 ; expr' <- tcMonoExpr expr res_ty
171 ; return (NegApp expr' neg_expr') }
173 tcExpr (HsIPVar ip) res_ty
174 = do { -- Implicit parameters must have a *tau-type* not a
175 -- type scheme. We enforce this by creating a fresh
176 -- type variable as its type. (Because res_ty may not
178 ip_ty <- newFlexiTyVarTy argTypeKind -- argTypeKind: it can't be an unboxed tuple
179 ; co_fn <- tcSubExp ip_ty res_ty
180 ; (ip', inst) <- newIPDict (IPOccOrigin ip) ip ip_ty
182 ; return (mkHsCoerce co_fn (HsIPVar ip')) }
184 tcExpr (HsApp e1 e2) res_ty
187 go :: LHsExpr Name -> [LHsExpr Name] -> TcM (HsExpr TcId)
188 go (L _ (HsApp e1 e2)) args = go e1 (e2:args)
189 go lfun@(L loc fun) args
190 = do { (fun', args') <- addErrCtxt (callCtxt lfun args) $
191 tcApp fun (length args) (tcArgs lfun args) res_ty
192 ; return (unLoc (foldl mkHsApp (L loc fun') args')) }
194 tcExpr (HsLam match) res_ty
195 = do { (co_fn, match') <- tcMatchLambda match res_ty
196 ; return (mkHsCoerce co_fn (HsLam match')) }
198 tcExpr in_expr@(ExprWithTySig expr sig_ty) res_ty
199 = do { sig_tc_ty <- tcHsSigType ExprSigCtxt sig_ty
200 ; expr' <- tcPolyExpr expr sig_tc_ty
201 ; co_fn <- tcSubExp sig_tc_ty res_ty
202 ; return (mkHsCoerce co_fn (ExprWithTySigOut expr' sig_ty)) }
204 tcExpr (HsType ty) res_ty
205 = failWithTc (text "Can't handle type argument:" <+> ppr ty)
206 -- This is the syntax for type applications that I was planning
207 -- but there are difficulties (e.g. what order for type args)
208 -- so it's not enabled yet.
209 -- Can't eliminate it altogether from the parser, because the
210 -- same parser parses *patterns*.
214 %************************************************************************
216 Infix operators and sections
218 %************************************************************************
221 tcExpr in_expr@(OpApp arg1 lop@(L loc op) fix arg2) res_ty
222 = do { (op', [arg1', arg2']) <- tcApp op 2 (tcArgs lop [arg1,arg2]) res_ty
223 ; return (OpApp arg1' (L loc op') fix arg2') }
225 -- Left sections, equivalent to
232 -- We treat it as similar to the latter, so we don't
233 -- actually require the function to take two arguments
234 -- at all. For example, (x `not`) means (not x);
235 -- you get postfix operators! Not really Haskell 98
236 -- I suppose, but it's less work and kind of useful.
238 tcExpr in_expr@(SectionL arg1 lop@(L loc op)) res_ty
239 = do { (op', [arg1']) <- tcApp op 1 (tcArgs lop [arg1]) res_ty
240 ; return (SectionL arg1' (L loc op')) }
242 -- Right sections, equivalent to \ x -> x `op` expr, or
245 tcExpr in_expr@(SectionR lop@(L loc op) arg2) res_ty
246 = do { (co_fn, (op', arg2')) <- subFunTys doc 1 res_ty $ \ [arg1_ty'] res_ty' ->
247 tcApp op 2 (tc_args arg1_ty') res_ty'
248 ; return (mkHsCoerce co_fn (SectionR (L loc op') arg2')) }
250 doc = ptext SLIT("The section") <+> quotes (ppr in_expr)
251 <+> ptext SLIT("takes one argument")
252 tc_args arg1_ty' [arg1_ty, arg2_ty]
253 = do { boxyUnify arg1_ty' arg1_ty
254 ; tcArg lop (arg2, arg2_ty, 2) }
258 tcExpr (HsLet binds expr) res_ty
259 = do { (binds', expr') <- tcLocalBinds binds $
260 tcMonoExpr expr res_ty
261 ; return (HsLet binds' expr') }
263 tcExpr (HsCase scrut matches) exp_ty
264 = do { -- We used to typecheck the case alternatives first.
265 -- The case patterns tend to give good type info to use
266 -- when typechecking the scrutinee. For example
269 -- will report that map is applied to too few arguments
271 -- But now, in the GADT world, we need to typecheck the scrutinee
272 -- first, to get type info that may be refined in the case alternatives
273 (scrut', scrut_ty) <- addErrCtxt (caseScrutCtxt scrut)
276 ; traceTc (text "HsCase" <+> ppr scrut_ty)
277 ; matches' <- tcMatchesCase match_ctxt scrut_ty matches exp_ty
278 ; return (HsCase scrut' matches') }
280 match_ctxt = MC { mc_what = CaseAlt,
281 mc_body = tcPolyExpr }
283 tcExpr (HsIf pred b1 b2) res_ty
284 = do { pred' <- addErrCtxt (predCtxt pred) $
285 tcMonoExpr pred boolTy
286 ; b1' <- tcMonoExpr b1 res_ty
287 ; b2' <- tcMonoExpr b2 res_ty
288 ; return (HsIf pred' b1' b2') }
290 tcExpr (HsDo do_or_lc stmts body _) res_ty
291 = tcDoStmts do_or_lc stmts body res_ty
293 tcExpr in_expr@(ExplicitList _ exprs) res_ty -- Non-empty list
294 = do { elt_ty <- boxySplitListTy res_ty
295 ; exprs' <- mappM (tc_elt elt_ty) exprs
296 ; return (ExplicitList elt_ty exprs') }
298 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
300 tcExpr in_expr@(ExplicitPArr _ exprs) res_ty -- maybe empty
301 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
302 ; exprs' <- mappM (tc_elt elt_ty) exprs
303 ; ifM (null exprs) (zapToMonotype elt_ty)
304 -- If there are no expressions in the comprehension
305 -- we must still fill in the box
306 -- (Not needed for [] and () becuase they happen
307 -- to parse as data constructors.)
308 ; return (ExplicitPArr elt_ty exprs') }
310 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
312 tcExpr (ExplicitTuple exprs boxity) res_ty
313 = do { arg_tys <- boxySplitTyConApp (tupleTyCon boxity (length exprs)) res_ty
314 ; exprs' <- tcPolyExprs exprs arg_tys
315 ; return (ExplicitTuple exprs' boxity) }
317 tcExpr (HsProc pat cmd) res_ty
318 = do { (pat', cmd') <- tcProc pat cmd res_ty
319 ; return (HsProc pat' cmd') }
321 tcExpr e@(HsArrApp _ _ _ _ _) _
322 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
323 ptext SLIT("was found where an expression was expected")])
325 tcExpr e@(HsArrForm _ _ _) _
326 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
327 ptext SLIT("was found where an expression was expected")])
330 %************************************************************************
332 Record construction and update
334 %************************************************************************
337 tcExpr expr@(RecordCon (L loc con_name) _ rbinds) res_ty
338 = do { data_con <- tcLookupDataCon con_name
340 -- Check for missing fields
341 ; checkMissingFields data_con rbinds
343 ; let arity = dataConSourceArity data_con
345 = do { rbinds' <- tcRecordBinds data_con arg_tys rbinds
348 -- The unBox ensures that all the boxes in arg_tys are indeed
349 -- filled, which is the invariant expected by tcIdApp
351 ; (con_expr, rbinds') <- tcIdApp con_name arity check_fields res_ty
353 ; returnM (RecordCon (L loc (dataConWrapId data_con)) con_expr rbinds') }
355 -- The main complication with RecordUpd is that we need to explicitly
356 -- handle the *non-updated* fields. Consider:
358 -- data T a b = MkT1 { fa :: a, fb :: b }
359 -- | MkT2 { fa :: a, fc :: Int -> Int }
360 -- | MkT3 { fd :: a }
362 -- upd :: T a b -> c -> T a c
363 -- upd t x = t { fb = x}
365 -- The type signature on upd is correct (i.e. the result should not be (T a b))
366 -- because upd should be equivalent to:
368 -- upd t x = case t of
369 -- MkT1 p q -> MkT1 p x
370 -- MkT2 a b -> MkT2 p b
371 -- MkT3 d -> error ...
373 -- So we need to give a completely fresh type to the result record,
374 -- and then constrain it by the fields that are *not* updated ("p" above).
376 -- Note that because MkT3 doesn't contain all the fields being updated,
377 -- its RHS is simply an error, so it doesn't impose any type constraints
379 -- All this is done in STEP 4 below.
383 -- For record update we require that every constructor involved in the
384 -- update (i.e. that has all the specified fields) is "vanilla". I
385 -- don't know how to do the update otherwise.
388 tcExpr expr@(RecordUpd record_expr rbinds _ _) res_ty
390 -- Check that the field names are really field names
391 ASSERT( notNull rbinds )
393 field_names = map fst rbinds
395 mappM (tcLookupField . unLoc) field_names `thenM` \ sel_ids ->
396 -- The renamer has already checked that they
399 bad_guys = [ setSrcSpan loc $ addErrTc (notSelector field_name)
400 | (L loc field_name, sel_id) <- field_names `zip` sel_ids,
401 not (isRecordSelector sel_id) -- Excludes class ops
404 checkM (null bad_guys) (sequenceM bad_guys `thenM_` failM) `thenM_`
407 -- Figure out the tycon and data cons from the first field name
409 -- It's OK to use the non-tc splitters here (for a selector)
410 upd_field_lbls = recBindFields rbinds
412 (tycon, _) = recordSelectorFieldLabel sel_id -- We've failed already if
413 data_cons = tyConDataCons tycon -- it's not a field label
414 relevant_cons = filter is_relevant data_cons
415 is_relevant con = all (`elem` dataConFieldLabels con) upd_field_lbls
419 -- Check that at least one constructor has all the named fields
420 -- i.e. has an empty set of bad fields returned by badFields
421 checkTc (not (null relevant_cons))
422 (badFieldsUpd rbinds) `thenM_`
424 -- Check that all relevant data cons are vanilla. Doing record updates on
425 -- GADTs and/or existentials is more than my tiny brain can cope with today
426 checkTc (all isVanillaDataCon relevant_cons)
427 (nonVanillaUpd tycon) `thenM_`
430 -- Use the un-updated fields to find a vector of booleans saying
431 -- which type arguments must be the same in updatee and result.
433 -- WARNING: this code assumes that all data_cons in a common tycon
434 -- have FieldLabels abstracted over the same tyvars.
436 -- A constructor is only relevant to this process if
437 -- it contains *all* the fields that are being updated
438 con1 = head relevant_cons -- A representative constructor
439 con1_tyvars = dataConTyVars con1
440 con1_flds = dataConFieldLabels con1
441 con1_arg_tys = dataConOrigArgTys con1
442 common_tyvars = exactTyVarsOfTypes [ty | (fld,ty) <- con1_flds `zip` con1_arg_tys
443 , not (fld `elem` upd_field_lbls) ]
445 is_common_tv tv = tv `elemVarSet` common_tyvars
447 mk_inst_ty tv result_inst_ty
448 | is_common_tv tv = returnM result_inst_ty -- Same as result type
449 | otherwise = newFlexiTyVarTy (tyVarKind tv) -- Fresh type, of correct kind
451 tcInstTyVars con1_tyvars `thenM` \ (_, result_inst_tys, inst_env) ->
452 zipWithM mk_inst_ty con1_tyvars result_inst_tys `thenM` \ inst_tys ->
455 -- Typecheck the update bindings.
456 -- (Do this after checking for bad fields in case there's a field that
457 -- doesn't match the constructor.)
459 result_record_ty = mkTyConApp tycon result_inst_tys
460 con1_arg_tys' = map (substTy inst_env) con1_arg_tys
462 tcSubExp result_record_ty res_ty `thenM` \ co_fn ->
463 tcRecordBinds con1 con1_arg_tys' rbinds `thenM` \ rbinds' ->
466 -- Typecheck the expression to be updated
468 record_ty = ASSERT( length inst_tys == tyConArity tycon )
469 mkTyConApp tycon inst_tys
470 -- This is one place where the isVanilla check is important
471 -- So that inst_tys matches the tycon
473 tcMonoExpr record_expr record_ty `thenM` \ record_expr' ->
476 -- Figure out the LIE we need. We have to generate some
477 -- dictionaries for the data type context, since we are going to
478 -- do pattern matching over the data cons.
480 -- What dictionaries do we need?
481 -- We just take the context of the first data constructor
482 -- This isn't right, but I just can't bear to union up all the relevant ones
484 theta' = substTheta inst_env (tyConStupidTheta tycon)
486 newDicts RecordUpdOrigin theta' `thenM` \ dicts ->
487 extendLIEs dicts `thenM_`
490 returnM (mkHsCoerce co_fn (RecordUpd record_expr' rbinds' record_ty result_record_ty))
494 %************************************************************************
496 Arithmetic sequences e.g. [a,b..]
497 and their parallel-array counterparts e.g. [: a,b.. :]
500 %************************************************************************
503 tcExpr (ArithSeq _ seq@(From expr)) res_ty
504 = do { elt_ty <- boxySplitListTy res_ty
505 ; expr' <- tcPolyExpr expr elt_ty
506 ; enum_from <- newMethodFromName (ArithSeqOrigin seq)
508 ; return (ArithSeq (HsVar enum_from) (From expr')) }
510 tcExpr in_expr@(ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
511 = do { elt_ty <- boxySplitListTy res_ty
512 ; expr1' <- tcPolyExpr expr1 elt_ty
513 ; expr2' <- tcPolyExpr expr2 elt_ty
514 ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq)
515 elt_ty enumFromThenName
516 ; return (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2')) }
519 tcExpr in_expr@(ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
520 = do { elt_ty <- boxySplitListTy res_ty
521 ; expr1' <- tcPolyExpr expr1 elt_ty
522 ; expr2' <- tcPolyExpr expr2 elt_ty
523 ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq)
524 elt_ty enumFromToName
525 ; return (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
527 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
528 = do { elt_ty <- boxySplitListTy res_ty
529 ; expr1' <- tcPolyExpr expr1 elt_ty
530 ; expr2' <- tcPolyExpr expr2 elt_ty
531 ; expr3' <- tcPolyExpr expr3 elt_ty
532 ; eft <- newMethodFromName (ArithSeqOrigin seq)
533 elt_ty enumFromThenToName
534 ; return (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
536 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
537 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
538 ; expr1' <- tcPolyExpr expr1 elt_ty
539 ; expr2' <- tcPolyExpr expr2 elt_ty
540 ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq)
541 elt_ty enumFromToPName
542 ; return (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
544 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
545 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
546 ; expr1' <- tcPolyExpr expr1 elt_ty
547 ; expr2' <- tcPolyExpr expr2 elt_ty
548 ; expr3' <- tcPolyExpr expr3 elt_ty
549 ; eft <- newMethodFromName (PArrSeqOrigin seq)
550 elt_ty enumFromThenToPName
551 ; return (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
553 tcExpr (PArrSeq _ _) _
554 = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
555 -- the parser shouldn't have generated it and the renamer shouldn't have
560 %************************************************************************
564 %************************************************************************
567 #ifdef GHCI /* Only if bootstrapped */
568 -- Rename excludes these cases otherwise
569 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
570 tcExpr (HsBracket brack) res_ty = do { e <- tcBracket brack res_ty
576 %************************************************************************
580 %************************************************************************
583 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
587 %************************************************************************
591 %************************************************************************
594 ---------------------------
595 tcApp :: HsExpr Name -- Function
596 -> Arity -- Number of args reqd
597 -> ([BoxySigmaType] -> TcM arg_results) -- Argument type-checker
598 -> BoxyRhoType -- Result type
599 -> TcM (HsExpr TcId, arg_results)
601 -- (tcFun fun n_args arg_checker res_ty)
602 -- The argument type checker, arg_checker, will be passed exactly n_args types
604 tcApp (HsVar fun_name) n_args arg_checker res_ty
605 = tcIdApp fun_name n_args arg_checker res_ty
607 tcApp fun n_args arg_checker res_ty -- The vanilla case (rula APP)
608 = do { arg_boxes <- newBoxyTyVars (replicate n_args argTypeKind)
609 ; fun' <- tcExpr fun (mkFunTys (mkTyVarTys arg_boxes) res_ty)
610 ; arg_tys' <- mapM readFilledBox arg_boxes
611 ; args' <- arg_checker arg_tys'
612 ; return (fun', args') }
614 ---------------------------
615 tcIdApp :: Name -- Function
616 -> Arity -- Number of args reqd
617 -> ([BoxySigmaType] -> TcM arg_results) -- Argument type-checker
618 -- The arg-checker guarantees to fill all boxes in the arg types
619 -> BoxyRhoType -- Result type
620 -> TcM (HsExpr TcId, arg_results)
622 -- Call (f e1 ... en) :: res_ty
623 -- Type f :: forall a b c. theta => fa_1 -> ... -> fa_k -> fres
624 -- (where k <= n; fres has the rest)
625 -- NB: if k < n then the function doesn't have enough args, and
626 -- presumably fres is a type variable that we are going to
627 -- instantiate with a function type
629 -- Then fres <= bx_(k+1) -> ... -> bx_n -> res_ty
631 tcIdApp fun_name n_args arg_checker res_ty
632 = do { fun_id <- lookupFun (OccurrenceOf fun_name) fun_name
634 -- Split up the function type
635 ; let (tv_theta_prs, rho) = tcMultiSplitSigmaTy (idType fun_id)
636 (fun_arg_tys, fun_res_ty) = tcSplitFunTysN rho n_args
638 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
639 arg_qtvs = exactTyVarsOfTypes fun_arg_tys
640 res_qtvs = exactTyVarsOfType fun_res_ty
641 -- NB: exactTyVarsOfType. See Note [Silly type synonyms in smart-app]
642 tau_qtvs = arg_qtvs `unionVarSet` res_qtvs
643 k = length fun_arg_tys -- k <= n_args
644 n_missing_args = n_args - k -- Always >= 0
646 -- Match the result type of the function with the
647 -- result type of the context, to get an inital substitution
648 ; extra_arg_boxes <- newBoxyTyVars (replicate n_missing_args argTypeKind)
649 ; let extra_arg_tys' = mkTyVarTys extra_arg_boxes
650 res_ty' = mkFunTys extra_arg_tys' res_ty
651 subst = boxySubMatchType arg_qtvs fun_res_ty res_ty'
652 -- Only bind arg_qtvs, since only they will be
653 -- *definitely* be filled in by arg_checker
654 -- E.g. error :: forall a. String -> a
655 -- (error "foo") :: bx5
656 -- Don't make subst [a |-> bx5]
657 -- because then the result subsumption becomes
659 -- and the unifer doesn't expect the
660 -- same box on both sides
661 inst_qtv tv | Just boxy_ty <- lookupTyVar subst tv = return boxy_ty
662 | tv `elemVarSet` tau_qtvs = do { tv' <- tcInstBoxyTyVar tv
663 ; return (mkTyVarTy tv') }
664 | otherwise = do { tv' <- tcInstTyVar tv
665 ; return (mkTyVarTy tv') }
666 -- The 'otherwise' case handles type variables that are
667 -- mentioned only in the constraints, not in argument or
668 -- result types. We'll make them tau-types
670 ; qtys' <- mapM inst_qtv qtvs
671 ; let arg_subst = zipOpenTvSubst qtvs qtys'
672 fun_arg_tys' = substTys arg_subst fun_arg_tys
674 -- Typecheck the arguments!
675 -- Doing so will fill arg_qtvs and extra_arg_tys'
676 ; args' <- arg_checker (fun_arg_tys' ++ extra_arg_tys')
678 ; let strip qtv qty' | qtv `elemVarSet` arg_qtvs = stripBoxyType qty'
679 | otherwise = return qty'
680 ; qtys'' <- zipWithM strip qtvs qtys'
681 ; extra_arg_tys'' <- mapM readFilledBox extra_arg_boxes
683 -- Result subsumption
684 ; let res_subst = zipOpenTvSubst qtvs qtys''
685 fun_res_ty'' = substTy res_subst fun_res_ty
686 res_ty'' = mkFunTys extra_arg_tys'' res_ty
687 ; co_fn <- tcFunResTy fun_name fun_res_ty'' res_ty''
689 -- And pack up the results
690 -- By applying the coercion just to the *function* we can make
691 -- tcFun work nicely for OpApp and Sections too
692 ; fun' <- instFun fun_id qtvs qtys'' tv_theta_prs
693 ; co_fn' <- wrapFunResCoercion fun_arg_tys' co_fn
694 ; return (mkHsCoerce co_fn' fun', args') }
697 Note [Silly type synonyms in smart-app]
698 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
699 When we call sripBoxyType, all of the boxes should be filled
700 in. But we need to be careful about type synonyms:
704 In the call (f x) we'll typecheck x, expecting it to have type
705 (T box). Usually that would fill in the box, but in this case not;
706 because 'a' is discarded by the silly type synonym T. So we must
707 use exactTyVarsOfType to figure out which type variables are free
708 in the argument type.
711 -- tcId is a specialisation of tcIdApp when there are no arguments
712 -- tcId f ty = do { (res, _) <- tcIdApp f [] (\[] -> return ()) ty
717 -> BoxyRhoType -- Result type
719 tcId orig fun_name res_ty
720 = do { traceTc (text "tcId" <+> ppr fun_name <+> ppr res_ty)
721 ; fun_id <- lookupFun orig fun_name
723 -- Split up the function type
724 ; let (tv_theta_prs, fun_tau) = tcMultiSplitSigmaTy (idType fun_id)
725 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
726 tau_qtvs = exactTyVarsOfType fun_tau -- Mentiond in the tau part
727 inst_qtv tv | tv `elemVarSet` tau_qtvs = do { tv' <- tcInstBoxyTyVar tv
728 ; return (mkTyVarTy tv') }
729 | otherwise = do { tv' <- tcInstTyVar tv
730 ; return (mkTyVarTy tv') }
732 -- Do the subsumption check wrt the result type
733 ; qtv_tys <- mapM inst_qtv qtvs
734 ; let res_subst = zipTopTvSubst qtvs qtv_tys
735 fun_tau' = substTy res_subst fun_tau
737 ; co_fn <- tcFunResTy fun_name fun_tau' res_ty
739 -- And pack up the results
740 ; fun' <- instFun fun_id qtvs qtv_tys tv_theta_prs
741 ; return (mkHsCoerce co_fn fun') }
743 -- Note [Push result type in]
745 -- Unify with expected result before (was: after) type-checking the args
746 -- so that the info from res_ty (was: args) percolates to args (was actual_res_ty).
747 -- This is when we might detect a too-few args situation.
748 -- (One can think of cases when the opposite order would give
749 -- a better error message.)
750 -- [March 2003: I'm experimenting with putting this first. Here's an
751 -- example where it actually makes a real difference
752 -- class C t a b | t a -> b
753 -- instance C Char a Bool
755 -- data P t a = forall b. (C t a b) => MkP b
756 -- data Q t = MkQ (forall a. P t a)
759 -- f1 = MkQ (MkP True)
760 -- f2 = MkQ (MkP True :: forall a. P Char a)
762 -- With the change, f1 will type-check, because the 'Char' info from
763 -- the signature is propagated into MkQ's argument. With the check
764 -- in the other order, the extra signature in f2 is reqd.]
766 ---------------------------
767 tcSyntaxOp :: InstOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
768 -- Typecheck a syntax operator, checking that it has the specified type
769 -- The operator is always a variable at this stage (i.e. renamer output)
770 tcSyntaxOp orig (HsVar op) ty = tcId orig op ty
771 tcSyntaxOp orig other ty = pprPanic "tcSyntaxOp" (ppr other)
773 ---------------------------
775 -> [TyVar] -> [TcType] -- Quantified type variables and
776 -- their instantiating types
777 -> [([TyVar], ThetaType)] -- Stuff to instantiate
779 instFun fun_id qtvs qtv_tys []
780 = return (HsVar fun_id) -- Common short cut
782 instFun fun_id qtvs qtv_tys tv_theta_prs
783 = do { let subst = zipOpenTvSubst qtvs qtv_tys
784 ty_theta_prs' = map subst_pr tv_theta_prs
785 subst_pr (tvs, theta) = (map (substTyVar subst) tvs,
786 substTheta subst theta)
788 -- The ty_theta_prs' is always non-empty
789 ((tys1',theta1') : further_prs') = ty_theta_prs'
791 -- First, chuck in the constraints from
792 -- the "stupid theta" of a data constructor (sigh)
793 ; case isDataConId_maybe fun_id of
794 Just con -> tcInstStupidTheta con tys1'
797 ; if want_method_inst theta1'
798 then do { meth_id <- newMethodWithGivenTy orig fun_id tys1'
799 -- See Note [Multiple instantiation]
800 ; go (HsVar meth_id) further_prs' }
801 else go (HsVar fun_id) ty_theta_prs'
804 orig = OccurrenceOf (idName fun_id)
806 go fun [] = return fun
808 go fun ((tys, theta) : prs)
809 = do { dicts <- newDicts orig theta
811 ; let the_app = unLoc $ mkHsDictApp (mkHsTyApp (noLoc fun) tys)
815 -- Hack Alert (want_method_inst)!
816 -- See Note [No method sharing]
817 -- If f :: (%x :: T) => Int -> Int
818 -- Then if we have two separate calls, (f 3, f 4), we cannot
819 -- make a method constraint that then gets shared, thus:
820 -- let m = f %x in (m 3, m 4)
821 -- because that loses the linearity of the constraint.
822 -- The simplest thing to do is never to construct a method constraint
823 -- in the first place that has a linear implicit parameter in it.
824 want_method_inst theta = not (null theta) -- Overloaded
825 && not (any isLinearPred theta) -- Not linear
826 && not opt_NoMethodSharing
827 -- See Note [No method sharing] below
830 Note [Multiple instantiation]
831 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
832 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
833 For example, consider
834 f :: forall a. Eq a => forall b. Ord b => a -> b
835 At a call to f, at say [Int, Bool], it's tempting to translate the call to
839 f_m1 :: forall b. Ord b => Int -> b
843 f_m2 = f_m1 Bool dOrdBool
845 But notice that f_m2 has f_m1 as its meth_id. Now the danger is that if we do
846 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
848 But it's entirely possible that f_m2 will continue to float out, because it
849 mentions no type variables. Result, f_m1 isn't in scope.
851 Here's a concrete example that does this (test tc200):
854 f :: Eq b => b -> a -> Int
855 baz :: Eq a => Int -> a -> Int
860 Current solution: only do the "method sharing" thing for the first type/dict
861 application, not for the iterated ones. A horribly subtle point.
863 Note [No method sharing]
864 ~~~~~~~~~~~~~~~~~~~~~~~~
865 The -fno-method-sharing flag controls what happens so far as the LIE
866 is concerned. The default case is that for an overloaded function we
867 generate a "method" Id, and add the Method Inst to the LIE. So you get
870 f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
871 If you specify -fno-method-sharing, the dictionary application
872 isn't shared, so we get
874 f = /\a (d:Num a) (x:a) -> (+) a d x x
875 This gets a bit less sharing, but
876 a) it's better for RULEs involving overloaded functions
877 b) perhaps fewer separated lambdas
880 tcArgs :: LHsExpr Name -- The function (for error messages)
881 -> [LHsExpr Name] -> [TcSigmaType] -- Actual arguments and expected arg types
882 -> TcM [LHsExpr TcId] -- Resulting args
884 tcArgs fun args expected_arg_tys
885 = mapM (tcArg fun) (zip3 args expected_arg_tys [1..])
887 tcArg :: LHsExpr Name -- The function (for error messages)
888 -> (LHsExpr Name, BoxySigmaType, Int) -- Actual argument and expected arg type
889 -> TcM (LHsExpr TcId) -- Resulting argument
890 tcArg fun (arg, ty, arg_no) = addErrCtxt (funAppCtxt fun arg arg_no) $
895 %************************************************************************
897 \subsection{@tcId@ typchecks an identifier occurrence}
899 %************************************************************************
902 lookupFun :: InstOrigin -> Name -> TcM TcId
903 lookupFun orig id_name
904 = do { thing <- tcLookup id_name
906 AGlobal (ADataCon con) -> return (dataConWrapId con)
909 | isNaughtyRecordSelector id -> failWithTc (naughtyRecordSel id)
910 | otherwise -> return id
911 -- A global cannot possibly be ill-staged
912 -- nor does it need the 'lifting' treatment
915 ATcId id th_level _ -> return id -- Non-TH case
917 ATcId id th_level _ -> do { use_stage <- getStage -- TH case
918 ; thLocalId orig id_name id th_level use_stage }
921 other -> failWithTc (ppr other <+> ptext SLIT("used where a value identifer was expected"))
924 #ifdef GHCI /* GHCI and TH is on */
925 --------------------------------------
926 -- thLocalId : Check for cross-stage lifting
927 thLocalId orig id_name id th_bind_lvl (Brack use_lvl ps_var lie_var)
928 | use_lvl > th_bind_lvl
929 = thBrackId orig id_name id ps_var lie_var
930 thLocalId orig id_name id th_bind_lvl use_stage
931 = do { checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage
934 --------------------------------------
935 thBrackId orig id_name id ps_var lie_var
936 | isExternalName id_name
937 = -- Top-level identifiers in this module,
938 -- (which have External Names)
939 -- are just like the imported case:
940 -- no need for the 'lifting' treatment
941 -- E.g. this is fine:
944 -- But we do need to put f into the keep-alive
945 -- set, because after desugaring the code will
946 -- only mention f's *name*, not f itself.
947 do { keepAliveTc id_name; return id }
950 = -- Nested identifiers, such as 'x' in
951 -- E.g. \x -> [| h x |]
952 -- We must behave as if the reference to x was
954 -- We use 'x' itself as the splice proxy, used by
955 -- the desugarer to stitch it all back together.
956 -- If 'x' occurs many times we may get many identical
957 -- bindings of the same splice proxy, but that doesn't
958 -- matter, although it's a mite untidy.
959 do { let id_ty = idType id
960 ; checkTc (isTauTy id_ty) (polySpliceErr id)
961 -- If x is polymorphic, its occurrence sites might
962 -- have different instantiations, so we can't use plain
963 -- 'x' as the splice proxy name. I don't know how to
964 -- solve this, and it's probably unimportant, so I'm
965 -- just going to flag an error for now
967 ; id_ty' <- zapToMonotype id_ty
968 -- The id_ty might have an OpenTypeKind, but we
969 -- can't instantiate the Lift class at that kind,
970 -- so we zap it to a LiftedTypeKind monotype
971 -- C.f. the call in TcPat.newLitInst
973 ; setLIEVar lie_var $ do
974 { lift <- newMethodFromName orig id_ty' DsMeta.liftName
975 -- Put the 'lift' constraint into the right LIE
977 -- Update the pending splices
978 ; ps <- readMutVar ps_var
979 ; writeMutVar ps_var ((id_name, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps)
986 %************************************************************************
988 \subsection{Record bindings}
990 %************************************************************************
992 Game plan for record bindings
993 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
994 1. Find the TyCon for the bindings, from the first field label.
996 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
998 For each binding field = value
1000 3. Instantiate the field type (from the field label) using the type
1003 4 Type check the value using tcArg, passing the field type as
1004 the expected argument type.
1006 This extends OK when the field types are universally quantified.
1012 -> [TcType] -- Expected type for each field
1013 -> HsRecordBinds Name
1014 -> TcM (HsRecordBinds TcId)
1016 tcRecordBinds data_con arg_tys rbinds
1017 = do { mb_binds <- mappM do_bind rbinds
1018 ; return (catMaybes mb_binds) }
1020 flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1021 do_bind (L loc field_lbl, rhs)
1022 | Just field_ty <- assocMaybe flds_w_tys field_lbl
1023 = addErrCtxt (fieldCtxt field_lbl) $
1024 do { rhs' <- tcPolyExprNC rhs field_ty
1025 ; sel_id <- tcLookupId field_lbl
1026 ; ASSERT( isRecordSelector sel_id )
1027 return (Just (L loc sel_id, rhs')) }
1029 = do { addErrTc (badFieldCon data_con field_lbl)
1032 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1033 checkMissingFields data_con rbinds
1034 | null field_labels -- Not declared as a record;
1035 -- But C{} is still valid if no strict fields
1036 = if any isMarkedStrict field_strs then
1037 -- Illegal if any arg is strict
1038 addErrTc (missingStrictFields data_con [])
1042 | otherwise -- A record
1043 = checkM (null missing_s_fields)
1044 (addErrTc (missingStrictFields data_con missing_s_fields)) `thenM_`
1046 doptM Opt_WarnMissingFields `thenM` \ warn ->
1047 checkM (not (warn && notNull missing_ns_fields))
1048 (warnTc True (missingFields data_con missing_ns_fields))
1052 = [ fl | (fl, str) <- field_info,
1054 not (fl `elem` field_names_used)
1057 = [ fl | (fl, str) <- field_info,
1058 not (isMarkedStrict str),
1059 not (fl `elem` field_names_used)
1062 field_names_used = recBindFields rbinds
1063 field_labels = dataConFieldLabels data_con
1065 field_info = zipEqual "missingFields"
1069 field_strs = dataConStrictMarks data_con
1072 %************************************************************************
1074 \subsection{Errors and contexts}
1076 %************************************************************************
1078 Boring and alphabetical:
1081 = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1084 = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1086 fieldCtxt field_name
1087 = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1089 funAppCtxt fun arg arg_no
1090 = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"),
1091 quotes (ppr fun) <> text ", namely"])
1092 4 (quotes (ppr arg))
1095 = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1098 = vcat [ptext SLIT("Record update for the non-Haskell-98 data type") <+> quotes (ppr tycon)
1099 <+> ptext SLIT("is not (yet) supported"),
1100 ptext SLIT("Use pattern-matching instead")]
1102 = hang (ptext SLIT("No constructor has all these fields:"))
1103 4 (pprQuotedList (recBindFields rbinds))
1105 naughtyRecordSel sel_id
1106 = ptext SLIT("Cannot use record selector") <+> quotes (ppr sel_id) <+>
1107 ptext SLIT("as a function due to escaped type variables") $$
1108 ptext SLIT("Probably fix: use pattern-matching syntax instead")
1111 = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1113 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1114 missingStrictFields con fields
1117 rest | null fields = empty -- Happens for non-record constructors
1118 -- with strict fields
1119 | otherwise = colon <+> pprWithCommas ppr fields
1121 header = ptext SLIT("Constructor") <+> quotes (ppr con) <+>
1122 ptext SLIT("does not have the required strict field(s)")
1124 missingFields :: DataCon -> [FieldLabel] -> SDoc
1125 missingFields con fields
1126 = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:")
1127 <+> pprWithCommas ppr fields
1130 = ptext SLIT("In the call") <+> parens (ppr (foldl mkHsApp fun args))
1133 polySpliceErr :: Id -> SDoc
1135 = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)