2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 \section[TcExpr]{Typecheck an expression}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
15 module TcExpr ( tcPolyExpr, tcPolyExprNC,
16 tcMonoExpr, tcInferRho, tcSyntaxOp ) where
18 #include "HsVersions.h"
20 #ifdef GHCI /* Only if bootstrapped */
21 import {-# SOURCE #-} TcSplice( tcSpliceExpr, tcBracket )
22 import qualified DsMeta
39 import TcIface ( checkWiredInTyCon )
63 %************************************************************************
65 \subsection{Main wrappers}
67 %************************************************************************
70 tcPolyExpr, tcPolyExprNC
71 :: LHsExpr Name -- Expession to type check
72 -> BoxySigmaType -- Expected type (could be a polytpye)
73 -> TcM (LHsExpr TcId) -- Generalised expr with expected type
75 -- tcPolyExpr is a convenient place (frequent but not too frequent) place
76 -- to add context information.
77 -- The NC version does not do so, usually because the caller wants
80 tcPolyExpr expr res_ty
81 = addErrCtxt (exprCtxt (unLoc expr)) $
82 (do {traceTc (text "tcPolyExpr") ; tcPolyExprNC expr res_ty })
84 tcPolyExprNC expr res_ty
86 = do { traceTc (text "tcPolyExprNC" <+> ppr res_ty)
87 ; (gen_fn, expr') <- tcGen res_ty emptyVarSet (\_ -> tcPolyExprNC expr)
88 -- Note the recursive call to tcPolyExpr, because the
89 -- type may have multiple layers of for-alls
90 -- E.g. forall a. Eq a => forall b. Ord b => ....
91 ; return (mkLHsWrap gen_fn expr') }
94 = tcMonoExpr expr res_ty
97 tcPolyExprs :: [LHsExpr Name] -> [TcType] -> TcM [LHsExpr TcId]
98 tcPolyExprs [] [] = returnM []
99 tcPolyExprs (expr:exprs) (ty:tys)
100 = do { expr' <- tcPolyExpr expr ty
101 ; exprs' <- tcPolyExprs exprs tys
102 ; returnM (expr':exprs') }
103 tcPolyExprs exprs tys = pprPanic "tcPolyExprs" (ppr exprs $$ ppr tys)
106 tcMonoExpr :: LHsExpr Name -- Expression to type check
107 -> BoxyRhoType -- Expected type (could be a type variable)
108 -- Definitely no foralls at the top
109 -- Can contain boxes, which will be filled in
110 -> TcM (LHsExpr TcId)
112 tcMonoExpr (L loc expr) res_ty
113 = ASSERT( not (isSigmaTy res_ty) )
115 do { expr' <- tcExpr expr res_ty
116 ; return (L loc expr') }
119 tcInferRho :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
120 tcInferRho expr = tcInfer (tcMonoExpr expr)
124 %************************************************************************
126 tcExpr: the main expression typechecker
128 %************************************************************************
131 tcExpr :: HsExpr Name -> BoxyRhoType -> TcM (HsExpr TcId)
132 tcExpr (HsVar name) res_ty = tcId (OccurrenceOf name) name res_ty
134 tcExpr (HsLit lit) res_ty = do { let lit_ty = hsLitType lit
135 ; coi <- boxyUnify lit_ty res_ty
136 ; return $ wrapExprCoI (HsLit lit) coi
139 tcExpr (HsPar expr) res_ty = do { expr' <- tcMonoExpr expr res_ty
140 ; return (HsPar expr') }
142 tcExpr (HsSCC lbl expr) res_ty = do { expr' <- tcMonoExpr expr res_ty
143 ; returnM (HsSCC lbl expr') }
144 tcExpr (HsTickPragma info expr) res_ty
145 = do { expr' <- tcMonoExpr expr res_ty
146 ; returnM (HsTickPragma info expr') }
148 tcExpr (HsCoreAnn lbl expr) res_ty -- hdaume: core annotation
149 = do { expr' <- tcMonoExpr expr res_ty
150 ; return (HsCoreAnn lbl expr') }
152 tcExpr (HsOverLit lit) res_ty
153 = do { lit' <- tcOverloadedLit (LiteralOrigin lit) lit res_ty
154 ; return (HsOverLit lit') }
156 tcExpr (NegApp expr neg_expr) res_ty
157 = do { neg_expr' <- tcSyntaxOp (OccurrenceOf negateName) neg_expr
158 (mkFunTy res_ty res_ty)
159 ; expr' <- tcMonoExpr expr res_ty
160 ; return (NegApp expr' neg_expr') }
162 tcExpr (HsIPVar ip) res_ty
163 = do { -- Implicit parameters must have a *tau-type* not a
164 -- type scheme. We enforce this by creating a fresh
165 -- type variable as its type. (Because res_ty may not
167 ip_ty <- newFlexiTyVarTy argTypeKind -- argTypeKind: it can't be an unboxed tuple
168 ; co_fn <- tcSubExp ip_ty res_ty
169 ; (ip', inst) <- newIPDict (IPOccOrigin ip) ip ip_ty
171 ; return (mkHsWrap co_fn (HsIPVar ip')) }
173 tcExpr (HsApp e1 e2) res_ty
176 go :: LHsExpr Name -> [LHsExpr Name] -> TcM (HsExpr TcId)
177 go (L _ (HsApp e1 e2)) args = go e1 (e2:args)
178 go lfun@(L loc fun) args
179 = do { (fun', args') <- -- addErrCtxt (callCtxt lfun args) $
180 tcApp fun (length args) (tcArgs lfun args) res_ty
181 ; traceTc (text "tcExpr args': " <+> ppr args')
182 ; return (unLoc (foldl mkHsApp (L loc fun') args')) }
184 tcExpr (HsLam match) res_ty
185 = do { (co_fn, match') <- tcMatchLambda match res_ty
186 ; return (mkHsWrap co_fn (HsLam match')) }
188 tcExpr in_expr@(ExprWithTySig expr sig_ty) res_ty
189 = do { sig_tc_ty <- tcHsSigType ExprSigCtxt sig_ty
191 -- Remember to extend the lexical type-variable environment
192 ; (gen_fn, expr') <- tcGen sig_tc_ty emptyVarSet (\ skol_tvs res_ty ->
193 tcExtendTyVarEnv2 (hsExplicitTvs sig_ty `zip` mkTyVarTys skol_tvs) $
194 tcPolyExprNC expr res_ty)
196 ; co_fn <- tcSubExp sig_tc_ty res_ty
197 ; return (mkHsWrap co_fn (ExprWithTySigOut (mkLHsWrap gen_fn expr') sig_ty)) }
199 tcExpr (HsType ty) res_ty
200 = failWithTc (text "Can't handle type argument:" <+> ppr ty)
201 -- This is the syntax for type applications that I was planning
202 -- but there are difficulties (e.g. what order for type args)
203 -- so it's not enabled yet.
204 -- Can't eliminate it altogether from the parser, because the
205 -- same parser parses *patterns*.
209 %************************************************************************
211 Infix operators and sections
213 %************************************************************************
216 tcExpr in_expr@(OpApp arg1 lop@(L loc op) fix arg2) res_ty
217 = do { (op', [arg1', arg2']) <- tcApp op 2 (tcArgs lop [arg1,arg2]) res_ty
218 ; return (OpApp arg1' (L loc op') fix arg2') }
220 -- Left sections, equivalent to
227 -- We treat it as similar to the latter, so we don't
228 -- actually require the function to take two arguments
229 -- at all. For example, (x `not`) means (not x);
230 -- you get postfix operators! Not really Haskell 98
231 -- I suppose, but it's less work and kind of useful.
233 tcExpr in_expr@(SectionL arg1 lop@(L loc op)) res_ty
234 = do { (op', [arg1']) <- tcApp op 1 (tcArgs lop [arg1]) res_ty
235 ; return (SectionL arg1' (L loc op')) }
237 -- Right sections, equivalent to \ x -> x `op` expr, or
240 tcExpr in_expr@(SectionR lop@(L loc op) arg2) res_ty
241 = do { (co_fn, (op', arg2')) <- subFunTys doc 1 res_ty $ \ [arg1_ty'] res_ty' ->
242 tcApp op 2 (tc_args arg1_ty') res_ty'
243 ; return (mkHsWrap co_fn (SectionR (L loc op') arg2')) }
245 doc = ptext SLIT("The section") <+> quotes (ppr in_expr)
246 <+> ptext SLIT("takes one argument")
247 tc_args arg1_ty' qtvs qtys [arg1_ty, arg2_ty]
248 = do { boxyUnify arg1_ty' (substTyWith qtvs qtys arg1_ty)
249 ; arg2' <- tcArg lop 2 arg2 qtvs qtys arg2_ty
250 ; qtys' <- mapM refineBox qtys -- c.f. tcArgs
251 ; return (qtys', arg2') }
252 tc_args arg1_ty' _ _ _ = panic "tcExpr SectionR"
256 tcExpr (HsLet binds expr) res_ty
257 = do { (binds', expr') <- tcLocalBinds binds $
258 tcMonoExpr expr res_ty
259 ; return (HsLet binds' expr') }
261 tcExpr (HsCase scrut matches) exp_ty
262 = do { -- We used to typecheck the case alternatives first.
263 -- The case patterns tend to give good type info to use
264 -- when typechecking the scrutinee. For example
267 -- will report that map is applied to too few arguments
269 -- But now, in the GADT world, we need to typecheck the scrutinee
270 -- first, to get type info that may be refined in the case alternatives
271 (scrut', scrut_ty) <- addErrCtxt (caseScrutCtxt scrut)
274 ; traceTc (text "HsCase" <+> ppr scrut_ty)
275 ; matches' <- tcMatchesCase match_ctxt scrut_ty matches exp_ty
276 ; return (HsCase scrut' matches') }
278 match_ctxt = MC { mc_what = CaseAlt,
281 tcExpr (HsIf pred b1 b2) res_ty
282 = do { pred' <- addErrCtxt (predCtxt pred) $
283 tcMonoExpr pred boolTy
284 ; b1' <- tcMonoExpr b1 res_ty
285 ; b2' <- tcMonoExpr b2 res_ty
286 ; return (HsIf pred' b1' b2') }
288 tcExpr (HsDo do_or_lc stmts body _) res_ty
289 = tcDoStmts do_or_lc stmts body res_ty
291 tcExpr in_expr@(ExplicitList _ exprs) res_ty -- Non-empty list
292 = do { elt_ty <- boxySplitListTy res_ty
293 ; exprs' <- mappM (tc_elt elt_ty) exprs
294 ; return (ExplicitList elt_ty exprs') }
296 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
297 {- TODO: Version from Tom's original patch. Unfortunately, we cannot do it this
298 way, but need to teach boxy splitters about match deferral and coercions.
299 = do { elt_tv <- newBoxyTyVar argTypeKind
300 ; let elt_ty = TyVarTy elt_tv
301 ; coi <- boxyUnify (mkTyConApp listTyCon [elt_ty]) res_ty
302 -- ; elt_ty <- boxySplitListTy res_ty
303 ; exprs' <- mappM (tc_elt elt_ty) exprs
304 ; return $ wrapExprCoI (ExplicitList elt_ty exprs') coi }
305 -- ; return (ExplicitList elt_ty exprs') }
307 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
310 tcExpr in_expr@(ExplicitPArr _ exprs) res_ty -- maybe empty
311 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
312 ; exprs' <- mappM (tc_elt elt_ty) exprs
313 ; ifM (null exprs) (zapToMonotype elt_ty)
314 -- If there are no expressions in the comprehension
315 -- we must still fill in the box
316 -- (Not needed for [] and () becuase they happen
317 -- to parse as data constructors.)
318 ; return (ExplicitPArr elt_ty exprs') }
320 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
322 -- For tuples, take care to preserve rigidity
323 -- E.g. case (x,y) of ....
324 -- The scrutinee should have a rigid type if x,y do
325 -- The general scheme is the same as in tcIdApp
326 tcExpr (ExplicitTuple exprs boxity) res_ty
327 = do { tvs <- newBoxyTyVars [argTypeKind | e <- exprs]
328 ; let tup_tc = tupleTyCon boxity (length exprs)
329 tup_res_ty = mkTyConApp tup_tc (mkTyVarTys tvs)
330 ; checkWiredInTyCon tup_tc -- Ensure instances are available
331 ; arg_tys <- preSubType tvs (mkVarSet tvs) tup_res_ty res_ty
332 ; exprs' <- tcPolyExprs exprs arg_tys
333 ; arg_tys' <- mapM refineBox arg_tys
334 ; co_fn <- tcFunResTy (tyConName tup_tc) (mkTyConApp tup_tc arg_tys') res_ty
335 ; return (mkHsWrap co_fn (ExplicitTuple exprs' boxity)) }
337 tcExpr (HsProc pat cmd) res_ty
338 = do { (pat', cmd') <- tcProc pat cmd res_ty
339 ; return (HsProc pat' cmd') }
341 tcExpr e@(HsArrApp _ _ _ _ _) _
342 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
343 ptext SLIT("was found where an expression was expected")])
345 tcExpr e@(HsArrForm _ _ _) _
346 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
347 ptext SLIT("was found where an expression was expected")])
350 %************************************************************************
352 Record construction and update
354 %************************************************************************
357 tcExpr expr@(RecordCon (L loc con_name) _ rbinds) res_ty
358 = do { data_con <- tcLookupDataCon con_name
360 -- Check for missing fields
361 ; checkMissingFields data_con rbinds
363 ; let arity = dataConSourceArity data_con
364 check_fields qtvs qtys arg_tys
365 = do { let arg_tys' = substTys (zipOpenTvSubst qtvs qtys) arg_tys
366 ; rbinds' <- tcRecordBinds data_con arg_tys' rbinds
367 ; qtys' <- mapM refineBoxToTau qtys
368 ; return (qtys', rbinds') }
369 -- The refineBoxToTau ensures that all the boxes in arg_tys are indeed
370 -- filled, which is the invariant expected by tcIdApp
371 -- How could this not be the case? Consider a record construction
372 -- that does not mention all the fields.
374 ; (con_expr, rbinds') <- tcIdApp con_name arity check_fields res_ty
376 ; returnM (RecordCon (L loc (dataConWrapId data_con)) con_expr rbinds') }
378 -- The main complication with RecordUpd is that we need to explicitly
379 -- handle the *non-updated* fields. Consider:
381 -- data T a b = MkT1 { fa :: a, fb :: b }
382 -- | MkT2 { fa :: a, fc :: Int -> Int }
383 -- | MkT3 { fd :: a }
385 -- upd :: T a b -> c -> T a c
386 -- upd t x = t { fb = x}
388 -- The type signature on upd is correct (i.e. the result should not be (T a b))
389 -- because upd should be equivalent to:
391 -- upd t x = case t of
392 -- MkT1 p q -> MkT1 p x
393 -- MkT2 a b -> MkT2 p b
394 -- MkT3 d -> error ...
396 -- So we need to give a completely fresh type to the result record,
397 -- and then constrain it by the fields that are *not* updated ("p" above).
399 -- Note that because MkT3 doesn't contain all the fields being updated,
400 -- its RHS is simply an error, so it doesn't impose any type constraints
402 -- All this is done in STEP 4 below.
406 -- For record update we require that every constructor involved in the
407 -- update (i.e. that has all the specified fields) is "vanilla". I
408 -- don't know how to do the update otherwise.
411 tcExpr expr@(RecordUpd record_expr rbinds _ _ _) res_ty
413 -- Check that the field names are really field names
415 field_names = hsRecFields rbinds
417 ASSERT( notNull field_names )
418 mappM tcLookupField field_names `thenM` \ sel_ids ->
419 -- The renamer has already checked that they
422 bad_guys = [ setSrcSpan loc $ addErrTc (notSelector field_name)
423 | (fld, sel_id) <- rec_flds rbinds `zip` sel_ids,
424 not (isRecordSelector sel_id), -- Excludes class ops
425 let L loc field_name = hsRecFieldId fld
428 checkM (null bad_guys) (sequenceM bad_guys `thenM_` failM) `thenM_`
431 -- Figure out the tycon and data cons from the first field name
433 -- It's OK to use the non-tc splitters here (for a selector)
435 (tycon, _) = recordSelectorFieldLabel sel_id -- We've failed already if
436 data_cons = tyConDataCons tycon -- it's not a field label
437 -- NB: for a data type family, the tycon is the instance tycon
439 relevant_cons = filter is_relevant data_cons
440 is_relevant con = all (`elem` dataConFieldLabels con) field_names
444 -- Check that at least one constructor has all the named fields
445 -- i.e. has an empty set of bad fields returned by badFields
446 checkTc (not (null relevant_cons))
447 (badFieldsUpd rbinds) `thenM_`
449 -- Check that all relevant data cons are vanilla. Doing record updates on
450 -- GADTs and/or existentials is more than my tiny brain can cope with today
451 checkTc (all isVanillaDataCon relevant_cons)
452 (nonVanillaUpd tycon) `thenM_`
455 -- Use the un-updated fields to find a vector of booleans saying
456 -- which type arguments must be the same in updatee and result.
458 -- WARNING: this code assumes that all data_cons in a common tycon
459 -- have FieldLabels abstracted over the same tyvars.
461 -- A constructor is only relevant to this process if
462 -- it contains *all* the fields that are being updated
463 con1 = ASSERT( not (null relevant_cons) ) head relevant_cons -- A representative constructor
464 (con1_tyvars, theta, con1_arg_tys, con1_res_ty) = dataConSig con1
465 con1_flds = dataConFieldLabels con1
466 common_tyvars = exactTyVarsOfTypes [ty | (fld,ty) <- con1_flds `zip` con1_arg_tys
467 , not (fld `elem` field_names) ]
469 is_common_tv tv = tv `elemVarSet` common_tyvars
471 mk_inst_ty tv result_inst_ty
472 | is_common_tv tv = returnM result_inst_ty -- Same as result type
473 | otherwise = newFlexiTyVarTy (tyVarKind tv) -- Fresh type, of correct kind
475 ASSERT( null theta ) -- Vanilla datacon
476 tcInstTyVars con1_tyvars `thenM` \ (_, result_inst_tys, result_inst_env) ->
477 zipWithM mk_inst_ty con1_tyvars result_inst_tys `thenM` \ scrut_inst_tys ->
479 -- STEP 3: Typecheck the update bindings.
480 -- Do this after checking for bad fields in case
481 -- there's a field that doesn't match the constructor.
483 result_ty = substTy result_inst_env con1_res_ty
484 con1_arg_tys' = map (substTy result_inst_env) con1_arg_tys
486 tcSubExp result_ty res_ty `thenM` \ co_fn ->
487 tcRecordBinds con1 con1_arg_tys' rbinds `thenM` \ rbinds' ->
489 -- STEP 5: Typecheck the expression to be updated
491 scrut_inst_env = zipTopTvSubst con1_tyvars scrut_inst_tys
492 scrut_ty = substTy scrut_inst_env con1_res_ty
493 -- This is one place where the isVanilla check is important
494 -- So that inst_tys matches the con1_tyvars
496 tcMonoExpr record_expr scrut_ty `thenM` \ record_expr' ->
498 -- STEP 6: Figure out the LIE we need.
499 -- We have to generate some dictionaries for the data type context,
500 -- since we are going to do pattern matching over the data cons.
502 -- What dictionaries do we need? The dataConStupidTheta tells us.
504 theta' = substTheta scrut_inst_env (dataConStupidTheta con1)
506 instStupidTheta RecordUpdOrigin theta' `thenM_`
508 -- Step 7: make a cast for the scrutinee, in the case that it's from a type family
509 let scrut_co | Just co_con <- tyConFamilyCoercion_maybe tycon
510 = WpCo $ mkTyConApp co_con scrut_inst_tys
515 returnM (mkHsWrap co_fn (RecordUpd (mkLHsWrap scrut_co record_expr') rbinds'
516 relevant_cons scrut_inst_tys result_inst_tys))
520 %************************************************************************
522 Arithmetic sequences e.g. [a,b..]
523 and their parallel-array counterparts e.g. [: a,b.. :]
526 %************************************************************************
529 tcExpr (ArithSeq _ seq@(From expr)) res_ty
530 = do { elt_ty <- boxySplitListTy res_ty
531 ; expr' <- tcPolyExpr expr elt_ty
532 ; enum_from <- newMethodFromName (ArithSeqOrigin seq)
534 ; return (ArithSeq (HsVar enum_from) (From expr')) }
536 tcExpr in_expr@(ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
537 = do { elt_ty <- boxySplitListTy res_ty
538 ; expr1' <- tcPolyExpr expr1 elt_ty
539 ; expr2' <- tcPolyExpr expr2 elt_ty
540 ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq)
541 elt_ty enumFromThenName
542 ; return (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2')) }
545 tcExpr in_expr@(ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
546 = do { elt_ty <- boxySplitListTy res_ty
547 ; expr1' <- tcPolyExpr expr1 elt_ty
548 ; expr2' <- tcPolyExpr expr2 elt_ty
549 ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq)
550 elt_ty enumFromToName
551 ; return (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
553 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
554 = do { elt_ty <- boxySplitListTy res_ty
555 ; expr1' <- tcPolyExpr expr1 elt_ty
556 ; expr2' <- tcPolyExpr expr2 elt_ty
557 ; expr3' <- tcPolyExpr expr3 elt_ty
558 ; eft <- newMethodFromName (ArithSeqOrigin seq)
559 elt_ty enumFromThenToName
560 ; return (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
562 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
563 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
564 ; expr1' <- tcPolyExpr expr1 elt_ty
565 ; expr2' <- tcPolyExpr expr2 elt_ty
566 ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq)
567 elt_ty enumFromToPName
568 ; return (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
570 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
571 = do { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
572 ; expr1' <- tcPolyExpr expr1 elt_ty
573 ; expr2' <- tcPolyExpr expr2 elt_ty
574 ; expr3' <- tcPolyExpr expr3 elt_ty
575 ; eft <- newMethodFromName (PArrSeqOrigin seq)
576 elt_ty enumFromThenToPName
577 ; return (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
579 tcExpr (PArrSeq _ _) _
580 = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
581 -- the parser shouldn't have generated it and the renamer shouldn't have
586 %************************************************************************
590 %************************************************************************
593 #ifdef GHCI /* Only if bootstrapped */
594 -- Rename excludes these cases otherwise
595 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
596 tcExpr (HsBracket brack) res_ty = do { e <- tcBracket brack res_ty
602 %************************************************************************
606 %************************************************************************
609 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
613 %************************************************************************
617 %************************************************************************
620 ---------------------------
621 tcApp :: HsExpr Name -- Function
622 -> Arity -- Number of args reqd
623 -> ArgChecker results
624 -> BoxyRhoType -- Result type
625 -> TcM (HsExpr TcId, results)
627 -- (tcFun fun n_args arg_checker res_ty)
628 -- The argument type checker, arg_checker, will be passed exactly n_args types
630 tcApp (HsVar fun_name) n_args arg_checker res_ty
631 = tcIdApp fun_name n_args arg_checker res_ty
633 tcApp fun n_args arg_checker res_ty -- The vanilla case (rula APP)
634 = do { arg_boxes <- newBoxyTyVars (replicate n_args argTypeKind)
635 ; fun' <- tcExpr fun (mkFunTys (mkTyVarTys arg_boxes) res_ty)
636 ; arg_tys' <- mapM readFilledBox arg_boxes
637 ; (_, args') <- arg_checker [] [] arg_tys' -- Yuk
638 ; return (fun', args') }
640 ---------------------------
641 tcIdApp :: Name -- Function
642 -> Arity -- Number of args reqd
643 -> ArgChecker results -- The arg-checker guarantees to fill all boxes in the arg types
644 -> BoxyRhoType -- Result type
645 -> TcM (HsExpr TcId, results)
647 -- Call (f e1 ... en) :: res_ty
648 -- Type f :: forall a b c. theta => fa_1 -> ... -> fa_k -> fres
649 -- (where k <= n; fres has the rest)
650 -- NB: if k < n then the function doesn't have enough args, and
651 -- presumably fres is a type variable that we are going to
652 -- instantiate with a function type
654 -- Then fres <= bx_(k+1) -> ... -> bx_n -> res_ty
656 tcIdApp fun_name n_args arg_checker res_ty
657 = do { let orig = OccurrenceOf fun_name
658 ; (fun, fun_ty) <- lookupFun orig fun_name
660 -- Split up the function type
661 ; let (tv_theta_prs, rho) = tcMultiSplitSigmaTy fun_ty
662 (fun_arg_tys, fun_res_ty) = tcSplitFunTysN rho n_args
664 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
665 arg_qtvs = exactTyVarsOfTypes fun_arg_tys
666 res_qtvs = exactTyVarsOfType fun_res_ty
667 -- NB: exactTyVarsOfType. See Note [Silly type synonyms in smart-app]
668 tau_qtvs = arg_qtvs `unionVarSet` res_qtvs
669 k = length fun_arg_tys -- k <= n_args
670 n_missing_args = n_args - k -- Always >= 0
672 -- Match the result type of the function with the
673 -- result type of the context, to get an inital substitution
674 ; extra_arg_boxes <- newBoxyTyVars (replicate n_missing_args argTypeKind)
675 ; let extra_arg_tys' = mkTyVarTys extra_arg_boxes
676 res_ty' = mkFunTys extra_arg_tys' res_ty
677 ; qtys' <- preSubType qtvs tau_qtvs fun_res_ty res_ty'
679 -- Typecheck the arguments!
680 -- Doing so will fill arg_qtvs and extra_arg_tys'
681 ; (qtys'', args') <- arg_checker qtvs qtys' (fun_arg_tys ++ extra_arg_tys')
683 -- Strip boxes from the qtvs that have been filled in by the arg checking
684 ; extra_arg_tys'' <- mapM readFilledBox extra_arg_boxes
686 -- Result subsumption
687 -- This fills in res_qtvs
688 ; let res_subst = zipOpenTvSubst qtvs qtys''
689 fun_res_ty'' = substTy res_subst fun_res_ty
690 res_ty'' = mkFunTys extra_arg_tys'' res_ty
691 ; co_fn <- tcFunResTy fun_name 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 orig fun res_subst tv_theta_prs
697 ; co_fn' <- wrapFunResCoercion (substTys res_subst fun_arg_tys) co_fn
698 ; traceTc (text "tcIdApp: " <+> ppr (mkHsWrap co_fn' fun') <+> ppr tv_theta_prs <+> ppr co_fn' <+> ppr fun')
699 ; return (mkHsWrap co_fn' fun', args') }
702 Note [Silly type synonyms in smart-app]
703 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
704 When we call sripBoxyType, all of the boxes should be filled
705 in. But we need to be careful about type synonyms:
709 In the call (f x) we'll typecheck x, expecting it to have type
710 (T box). Usually that would fill in the box, but in this case not;
711 because 'a' is discarded by the silly type synonym T. So we must
712 use exactTyVarsOfType to figure out which type variables are free
713 in the argument type.
716 -- tcId is a specialisation of tcIdApp when there are no arguments
717 -- tcId f ty = do { (res, _) <- tcIdApp f [] (\[] -> return ()) ty
722 -> BoxyRhoType -- Result type
724 tcId orig fun_name res_ty
725 = do { traceTc (text "tcId" <+> ppr fun_name <+> ppr res_ty)
726 ; (fun, fun_ty) <- lookupFun orig fun_name
728 -- Split up the function type
729 ; let (tv_theta_prs, fun_tau) = tcMultiSplitSigmaTy fun_ty
730 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
731 tau_qtvs = exactTyVarsOfType fun_tau -- Mentioned in the tau part
732 ; qtv_tys <- preSubType qtvs tau_qtvs fun_tau res_ty
734 -- Do the subsumption check wrt the result type
735 ; let res_subst = zipTopTvSubst qtvs qtv_tys
736 fun_tau' = substTy res_subst fun_tau
738 ; co_fn <- tcFunResTy fun_name fun_tau' res_ty
740 -- And pack up the results
741 ; fun' <- instFun orig fun res_subst tv_theta_prs
742 ; traceTc (text "tcId yields" <+> ppr (mkHsWrap co_fn fun'))
743 ; return (mkHsWrap co_fn fun') }
745 -- Note [Push result type in]
747 -- Unify with expected result before (was: after) type-checking the args
748 -- so that the info from res_ty (was: args) percolates to args (was actual_res_ty).
749 -- This is when we might detect a too-few args situation.
750 -- (One can think of cases when the opposite order would give
751 -- a better error message.)
752 -- [March 2003: I'm experimenting with putting this first. Here's an
753 -- example where it actually makes a real difference
754 -- class C t a b | t a -> b
755 -- instance C Char a Bool
757 -- data P t a = forall b. (C t a b) => MkP b
758 -- data Q t = MkQ (forall a. P t a)
761 -- f1 = MkQ (MkP True)
762 -- f2 = MkQ (MkP True :: forall a. P Char a)
764 -- With the change, f1 will type-check, because the 'Char' info from
765 -- the signature is propagated into MkQ's argument. With the check
766 -- in the other order, the extra signature in f2 is reqd.]
768 ---------------------------
769 tcSyntaxOp :: InstOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
770 -- Typecheck a syntax operator, checking that it has the specified type
771 -- The operator is always a variable at this stage (i.e. renamer output)
772 tcSyntaxOp orig (HsVar op) ty = tcId orig op ty
773 tcSyntaxOp orig other ty = pprPanic "tcSyntaxOp" (ppr other)
775 ---------------------------
776 instFun :: InstOrigin
778 -> TvSubst -- The instantiating substitution
779 -> [([TyVar], ThetaType)] -- Stuff to instantiate
782 instFun orig fun subst []
783 = return fun -- Common short cut
785 instFun orig fun subst tv_theta_prs
786 = do { let ty_theta_prs' = map subst_pr tv_theta_prs
787 ; traceTc (text "instFun" <+> ppr ty_theta_prs')
788 -- Make two ad-hoc checks
789 ; doStupidChecks fun ty_theta_prs'
791 -- Now do normal instantiation
792 ; result <- go True fun ty_theta_prs'
793 ; traceTc (text "instFun result" <+> ppr result)
797 subst_pr (tvs, theta)
798 = (substTyVars subst tvs, substTheta subst theta)
800 go _ fun [] = do {traceTc (text "go _ fun [] returns" <+> ppr fun) ; return fun }
802 go True (HsVar fun_id) ((tys,theta) : prs)
803 | want_method_inst theta
804 = do { traceTc (text "go (HsVar fun_id) ((tys,theta) : prs) | want_method_inst theta")
805 ; meth_id <- newMethodWithGivenTy orig fun_id tys
806 ; go False (HsVar meth_id) prs }
807 -- Go round with 'False' to prevent further use
808 -- of newMethod: see Note [Multiple instantiation]
810 go _ fun ((tys, theta) : prs)
811 = do { co_fn <- instCall orig tys theta
812 ; traceTc (text "go yields co_fn" <+> ppr co_fn)
813 ; go False (HsWrap co_fn fun) prs }
815 -- See Note [No method sharing]
816 want_method_inst theta = not (null theta) -- Overloaded
817 && not opt_NoMethodSharing
820 Note [Multiple instantiation]
821 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
822 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
823 For example, consider
824 f :: forall a. Eq a => forall b. Ord b => a -> b
825 At a call to f, at say [Int, Bool], it's tempting to translate the call to
829 f_m1 :: forall b. Ord b => Int -> b
833 f_m2 = f_m1 Bool dOrdBool
835 But notice that f_m2 has f_m1 as its meth_id. Now the danger is that if we do
836 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
838 But it's entirely possible that f_m2 will continue to float out, because it
839 mentions no type variables. Result, f_m1 isn't in scope.
841 Here's a concrete example that does this (test tc200):
844 f :: Eq b => b -> a -> Int
845 baz :: Eq a => Int -> a -> Int
850 Current solution: only do the "method sharing" thing for the first type/dict
851 application, not for the iterated ones. A horribly subtle point.
853 Note [No method sharing]
854 ~~~~~~~~~~~~~~~~~~~~~~~~
855 The -fno-method-sharing flag controls what happens so far as the LIE
856 is concerned. The default case is that for an overloaded function we
857 generate a "method" Id, and add the Method Inst to the LIE. So you get
860 f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
861 If you specify -fno-method-sharing, the dictionary application
862 isn't shared, so we get
864 f = /\a (d:Num a) (x:a) -> (+) a d x x
865 This gets a bit less sharing, but
866 a) it's better for RULEs involving overloaded functions
867 b) perhaps fewer separated lambdas
871 tcArgs implements a left-to-right order, which goes beyond what is described in the
872 impredicative type inference paper. In particular, it allows
874 where runST :: (forall s. ST s a) -> a
875 When typechecking the application of ($)::(a->b) -> a -> b, we first check that
876 runST has type (a->b), thereby filling in a=forall s. ST s a. Then we un-box this type
877 before checking foo. The left-to-right order really helps here.
880 tcArgs :: LHsExpr Name -- The function (for error messages)
881 -> [LHsExpr Name] -- Actual args
882 -> ArgChecker [LHsExpr TcId]
884 type ArgChecker results
885 = [TyVar] -> [TcSigmaType] -- Current instantiation
886 -> [TcSigmaType] -- Expected arg types (**before** applying the instantiation)
887 -> TcM ([TcSigmaType], results) -- Resulting instaniation and args
889 tcArgs fun args qtvs qtys arg_tys
890 = go 1 qtys args arg_tys
892 go n qtys [] [] = return (qtys, [])
893 go n qtys (arg:args) (arg_ty:arg_tys)
894 = do { arg' <- tcArg fun n arg qtvs qtys arg_ty
895 ; qtys' <- mapM refineBox qtys -- Exploit new info
896 ; (qtys'', args') <- go (n+1) qtys' args arg_tys
897 ; return (qtys'', arg':args') }
898 go n qtys args arg_tys = panic "tcArgs"
900 tcArg :: LHsExpr Name -- The function
901 -> Int -- and arg number (for error messages)
903 -> [TyVar] -> [TcSigmaType] -- Instantiate the arg type like this
905 -> TcM (LHsExpr TcId) -- Resulting argument
906 tcArg fun arg_no arg qtvs qtys ty
907 = addErrCtxt (funAppCtxt fun arg arg_no) $
908 tcPolyExprNC arg (substTyWith qtvs qtys ty)
914 Nasty check to ensure that tagToEnum# is applied to a type that is an
915 enumeration TyCon. Unification may refine the type later, but this
916 check won't see that, alas. It's crude but it works.
918 Here's are two cases that should fail
920 f = tagToEnum# 0 -- Can't do tagToEnum# at a type variable
923 g = tagToEnum# 0 -- Int is not an enumeration
927 doStupidChecks :: HsExpr TcId
928 -> [([TcType], ThetaType)]
930 -- Check two tiresome and ad-hoc cases
931 -- (a) the "stupid theta" for a data con; add the constraints
932 -- from the "stupid theta" of a data constructor (sigh)
933 -- (b) deal with the tagToEnum# problem: see Note [tagToEnum#]
935 doStupidChecks (HsVar fun_id) ((tys,_):_)
936 | Just con <- isDataConId_maybe fun_id -- (a)
937 = addDataConStupidTheta con tys
939 | fun_id `hasKey` tagToEnumKey -- (b)
940 = do { tys' <- zonkTcTypes tys
941 ; checkTc (ok tys') (tagToEnumError tys')
945 ok (ty:tys) = case tcSplitTyConApp_maybe ty of
946 Just (tc,_) -> isEnumerationTyCon tc
949 doStupidChecks fun tv_theta_prs
950 = return () -- The common case
954 = hang (ptext SLIT("Bad call to tagToEnum#") <+> at_type)
955 2 (vcat [ptext SLIT("Specify the type by giving a type signature"),
956 ptext SLIT("e.g. (tagToEnum# x) :: Bool")])
958 at_type | null tys = empty -- Probably never happens
959 | otherwise = ptext SLIT("at type") <+> ppr (head tys)
962 %************************************************************************
964 \subsection{@tcId@ typechecks an identifier occurrence}
966 %************************************************************************
969 lookupFun :: InstOrigin -> Name -> TcM (HsExpr TcId, TcType)
970 lookupFun orig id_name
971 = do { thing <- tcLookup id_name
973 AGlobal (ADataCon con) -> return (HsVar wrap_id, idType wrap_id)
975 wrap_id = dataConWrapId con
978 | isNaughtyRecordSelector id -> failWithTc (naughtyRecordSel id)
979 | otherwise -> return (HsVar id, idType id)
980 -- A global cannot possibly be ill-staged
981 -- nor does it need the 'lifting' treatment
983 ATcId { tct_id = id, tct_type = ty, tct_co = mb_co, tct_level = lvl }
984 -> do { thLocalId orig id ty lvl
986 Unrefineable -> return (HsVar id, ty)
987 Rigid co -> return (mkHsWrap co (HsVar id), ty)
988 Wobbly -> traceTc (text "lookupFun" <+> ppr id) >> return (HsVar id, ty) -- Wobbly, or no free vars
989 WobblyInvisible -> failWithTc (ppr id_name <+> ptext SLIT(" not in scope because it has a wobbly type (solution: add a type annotation)"))
992 other -> failWithTc (ppr other <+> ptext SLIT("used where a value identifer was expected"))
995 #ifndef GHCI /* GHCI and TH is off */
996 --------------------------------------
997 -- thLocalId : Check for cross-stage lifting
998 thLocalId orig id id_ty th_bind_lvl
1001 #else /* GHCI and TH is on */
1002 thLocalId orig id id_ty th_bind_lvl
1003 = do { use_stage <- getStage -- TH case
1005 Brack use_lvl ps_var lie_var | use_lvl > th_bind_lvl
1006 -> thBrackId orig id ps_var lie_var
1007 other -> do { checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage
1011 --------------------------------------
1012 thBrackId orig id ps_var lie_var
1013 | isExternalName id_name
1014 = -- Top-level identifiers in this module,
1015 -- (which have External Names)
1016 -- are just like the imported case:
1017 -- no need for the 'lifting' treatment
1018 -- E.g. this is fine:
1021 -- But we do need to put f into the keep-alive
1022 -- set, because after desugaring the code will
1023 -- only mention f's *name*, not f itself.
1024 do { keepAliveTc id_name; return id }
1027 = -- Nested identifiers, such as 'x' in
1028 -- E.g. \x -> [| h x |]
1029 -- We must behave as if the reference to x was
1031 -- We use 'x' itself as the splice proxy, used by
1032 -- the desugarer to stitch it all back together.
1033 -- If 'x' occurs many times we may get many identical
1034 -- bindings of the same splice proxy, but that doesn't
1035 -- matter, although it's a mite untidy.
1036 do { let id_ty = idType id
1037 ; checkTc (isTauTy id_ty) (polySpliceErr id)
1038 -- If x is polymorphic, its occurrence sites might
1039 -- have different instantiations, so we can't use plain
1040 -- 'x' as the splice proxy name. I don't know how to
1041 -- solve this, and it's probably unimportant, so I'm
1042 -- just going to flag an error for now
1044 ; id_ty' <- zapToMonotype id_ty
1045 -- The id_ty might have an OpenTypeKind, but we
1046 -- can't instantiate the Lift class at that kind,
1047 -- so we zap it to a LiftedTypeKind monotype
1048 -- C.f. the call in TcPat.newLitInst
1050 ; setLIEVar lie_var $ do
1051 { lift <- newMethodFromName orig id_ty' DsMeta.liftName
1052 -- Put the 'lift' constraint into the right LIE
1054 -- Update the pending splices
1055 ; ps <- readMutVar ps_var
1056 ; writeMutVar ps_var ((id_name, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps)
1065 %************************************************************************
1067 \subsection{Record bindings}
1069 %************************************************************************
1071 Game plan for record bindings
1072 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1073 1. Find the TyCon for the bindings, from the first field label.
1075 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1077 For each binding field = value
1079 3. Instantiate the field type (from the field label) using the type
1082 4 Type check the value using tcArg, passing the field type as
1083 the expected argument type.
1085 This extends OK when the field types are universally quantified.
1091 -> [TcType] -- Expected type for each field
1092 -> HsRecordBinds Name
1093 -> TcM (HsRecordBinds TcId)
1095 tcRecordBinds data_con arg_tys (HsRecFields rbinds dd)
1096 = do { mb_binds <- mappM do_bind rbinds
1097 ; return (HsRecFields (catMaybes mb_binds) dd) }
1099 flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1100 do_bind fld@(HsRecField { hsRecFieldId = L loc field_lbl, hsRecFieldArg = rhs })
1101 | Just field_ty <- assocMaybe flds_w_tys field_lbl
1102 = addErrCtxt (fieldCtxt field_lbl) $
1103 do { rhs' <- tcPolyExprNC rhs field_ty
1104 ; sel_id <- tcLookupField field_lbl
1105 ; ASSERT( isRecordSelector sel_id )
1106 return (Just (fld { hsRecFieldId = L loc sel_id, hsRecFieldArg = rhs' })) }
1108 = do { addErrTc (badFieldCon data_con field_lbl)
1111 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1112 checkMissingFields data_con rbinds
1113 | null field_labels -- Not declared as a record;
1114 -- But C{} is still valid if no strict fields
1115 = if any isMarkedStrict field_strs then
1116 -- Illegal if any arg is strict
1117 addErrTc (missingStrictFields data_con [])
1121 | otherwise -- A record
1122 = checkM (null missing_s_fields)
1123 (addErrTc (missingStrictFields data_con missing_s_fields)) `thenM_`
1125 doptM Opt_WarnMissingFields `thenM` \ warn ->
1126 checkM (not (warn && notNull missing_ns_fields))
1127 (warnTc True (missingFields data_con missing_ns_fields))
1131 = [ fl | (fl, str) <- field_info,
1133 not (fl `elem` field_names_used)
1136 = [ fl | (fl, str) <- field_info,
1137 not (isMarkedStrict str),
1138 not (fl `elem` field_names_used)
1141 field_names_used = hsRecFields rbinds
1142 field_labels = dataConFieldLabels data_con
1144 field_info = zipEqual "missingFields"
1148 field_strs = dataConStrictMarks data_con
1151 %************************************************************************
1153 \subsection{Errors and contexts}
1155 %************************************************************************
1157 Boring and alphabetical:
1160 = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1163 = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1165 fieldCtxt field_name
1166 = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1168 funAppCtxt fun arg arg_no
1169 = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"),
1170 quotes (ppr fun) <> text ", namely"])
1171 4 (quotes (ppr arg))
1174 = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1177 = vcat [ptext SLIT("Record update for the non-Haskell-98 data type")
1178 <+> quotes (pprSourceTyCon tycon)
1179 <+> ptext SLIT("is not (yet) supported"),
1180 ptext SLIT("Use pattern-matching instead")]
1182 = hang (ptext SLIT("No constructor has all these fields:"))
1183 4 (pprQuotedList (hsRecFields rbinds))
1185 naughtyRecordSel sel_id
1186 = ptext SLIT("Cannot use record selector") <+> quotes (ppr sel_id) <+>
1187 ptext SLIT("as a function due to escaped type variables") $$
1188 ptext SLIT("Probably fix: use pattern-matching syntax instead")
1191 = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1193 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1194 missingStrictFields con fields
1197 rest | null fields = empty -- Happens for non-record constructors
1198 -- with strict fields
1199 | otherwise = colon <+> pprWithCommas ppr fields
1201 header = ptext SLIT("Constructor") <+> quotes (ppr con) <+>
1202 ptext SLIT("does not have the required strict field(s)")
1204 missingFields :: DataCon -> [FieldLabel] -> SDoc
1205 missingFields con fields
1206 = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:")
1207 <+> pprWithCommas ppr fields
1209 -- callCtxt fun args = ptext SLIT("In the call") <+> parens (ppr (foldl mkHsApp fun args))
1212 polySpliceErr :: Id -> SDoc
1214 = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)
1219 wrapExprCoI :: HsExpr a -> CoercionI -> HsExpr a
1220 wrapExprCoI expr IdCo = expr
1221 wrapExprCoI expr (ACo co) = mkHsWrap (WpCo co) expr