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, tcMonoExpr, tcInferRho, tcSyntaxOp ) where
17 #include "HsVersions.h"
19 #ifdef GHCI /* Only if bootstrapped */
20 import {-# SOURCE #-} TcSplice( tcSpliceExpr, tcBracket )
21 import qualified DsMeta
38 import TcIface ( checkWiredInTyCon )
64 %************************************************************************
66 \subsection{Main wrappers}
68 %************************************************************************
71 tcPolyExpr, tcPolyExprNC
72 :: LHsExpr Name -- Expession to type check
73 -> BoxySigmaType -- Expected type (could be a polytpye)
74 -> TcM (LHsExpr TcId) -- Generalised expr with expected type
76 -- tcPolyExpr is a convenient place (frequent but not too frequent) place
77 -- to add context information.
78 -- The NC version does not do so, usually because the caller wants
81 tcPolyExpr expr res_ty
82 = addErrCtxt (exprCtxt (unLoc expr)) $
83 (do {traceTc (text "tcPolyExpr") ; tcPolyExprNC expr res_ty })
85 tcPolyExprNC expr res_ty
87 = do { traceTc (text "tcPolyExprNC" <+> ppr res_ty)
88 ; (gen_fn, expr') <- tcGen res_ty emptyVarSet (\_ -> tcPolyExprNC expr)
89 -- Note the recursive call to tcPolyExpr, because the
90 -- type may have multiple layers of for-alls
91 -- E.g. forall a. Eq a => forall b. Ord b => ....
92 ; return (mkLHsWrap gen_fn expr') }
95 = tcMonoExpr expr res_ty
98 tcPolyExprs :: [LHsExpr Name] -> [TcType] -> TcM [LHsExpr TcId]
99 tcPolyExprs [] [] = return []
100 tcPolyExprs (expr:exprs) (ty:tys)
101 = do { expr' <- tcPolyExpr expr ty
102 ; exprs' <- tcPolyExprs exprs tys
103 ; return (expr':exprs') }
104 tcPolyExprs exprs tys = pprPanic "tcPolyExprs" (ppr exprs $$ ppr tys)
107 tcMonoExpr :: LHsExpr Name -- Expression to type check
108 -> BoxyRhoType -- Expected type (could be a type variable)
109 -- Definitely no foralls at the top
110 -- Can contain boxes, which will be filled in
111 -> TcM (LHsExpr TcId)
113 tcMonoExpr (L loc expr) res_ty
114 = ASSERT( not (isSigmaTy res_ty) )
116 do { expr' <- tcExpr expr res_ty
117 ; return (L loc expr') }
120 tcInferRho :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
121 tcInferRho expr = tcInfer (tcMonoExpr expr)
125 %************************************************************************
127 tcExpr: the main expression typechecker
129 %************************************************************************
132 tcExpr :: HsExpr Name -> BoxyRhoType -> TcM (HsExpr TcId)
133 tcExpr (HsVar name) res_ty = tcId (OccurrenceOf name) name res_ty
135 tcExpr (HsLit lit) res_ty = do { let lit_ty = hsLitType lit
136 ; coi <- boxyUnify lit_ty res_ty
137 ; return $ mkHsWrapCoI coi (HsLit lit)
140 tcExpr (HsPar expr) res_ty = do { expr' <- tcMonoExpr expr res_ty
141 ; return (HsPar expr') }
143 tcExpr (HsSCC lbl expr) res_ty = do { expr' <- tcMonoExpr expr res_ty
144 ; return (HsSCC lbl expr') }
145 tcExpr (HsTickPragma info expr) res_ty
146 = do { expr' <- tcMonoExpr expr res_ty
147 ; return (HsTickPragma info expr') }
149 tcExpr (HsCoreAnn lbl expr) res_ty -- hdaume: core annotation
150 = do { expr' <- tcMonoExpr expr res_ty
151 ; return (HsCoreAnn lbl expr') }
153 tcExpr (HsOverLit lit) res_ty
154 = do { lit' <- tcOverloadedLit (LiteralOrigin lit) lit res_ty
155 ; return (HsOverLit lit') }
157 tcExpr (NegApp expr neg_expr) res_ty
158 = do { neg_expr' <- tcSyntaxOp NegateOrigin neg_expr
159 (mkFunTy res_ty res_ty)
160 ; expr' <- tcMonoExpr expr res_ty
161 ; return (NegApp expr' neg_expr') }
163 tcExpr (HsIPVar ip) res_ty
164 = do { let origin = IPOccOrigin ip
165 -- Implicit parameters must have a *tau-type* not a
166 -- type scheme. We enforce this by creating a fresh
167 -- type variable as its type. (Because res_ty may not
169 ; ip_ty <- newFlexiTyVarTy argTypeKind -- argTypeKind: it can't be an unboxed tuple
170 ; co_fn <- tcSubExp origin ip_ty res_ty
171 ; (ip', inst) <- newIPDict origin ip ip_ty
173 ; return (mkHsWrap co_fn (HsIPVar ip')) }
175 tcExpr (HsApp e1 e2) res_ty
178 go :: LHsExpr Name -> [LHsExpr Name] -> TcM (HsExpr TcId)
179 go (L _ (HsApp e1 e2)) args = go e1 (e2:args)
180 go lfun@(L loc fun) args
181 = do { (fun', args') <- -- addErrCtxt (callCtxt lfun args) $
182 tcApp fun (length args) (tcArgs lfun args) res_ty
183 ; traceTc (text "tcExpr args': " <+> ppr args')
184 ; return (unLoc (foldl mkHsApp (L loc fun') args')) }
186 tcExpr (HsLam match) res_ty
187 = do { (co_fn, match') <- tcMatchLambda match res_ty
188 ; return (mkHsWrap co_fn (HsLam match')) }
190 tcExpr in_expr@(ExprWithTySig expr sig_ty) res_ty
191 = do { sig_tc_ty <- tcHsSigType ExprSigCtxt sig_ty
193 -- Remember to extend the lexical type-variable environment
194 ; (gen_fn, expr') <- tcGen sig_tc_ty emptyVarSet (\ skol_tvs res_ty ->
195 tcExtendTyVarEnv2 (hsExplicitTvs sig_ty `zip` mkTyVarTys skol_tvs) $
196 tcPolyExprNC expr res_ty)
198 ; co_fn <- tcSubExp ExprSigOrigin sig_tc_ty res_ty
199 ; return (mkHsWrap co_fn (ExprWithTySigOut (mkLHsWrap gen_fn expr') sig_ty)) }
201 tcExpr (HsType ty) res_ty
202 = failWithTc (text "Can't handle type argument:" <+> ppr ty)
203 -- This is the syntax for type applications that I was planning
204 -- but there are difficulties (e.g. what order for type args)
205 -- so it's not enabled yet.
206 -- Can't eliminate it altogether from the parser, because the
207 -- same parser parses *patterns*.
211 %************************************************************************
213 Infix operators and sections
215 %************************************************************************
218 tcExpr in_expr@(OpApp arg1 lop@(L loc op) fix arg2) res_ty
219 = do { (op', [arg1', arg2']) <- tcApp op 2 (tcArgs lop [arg1,arg2]) res_ty
220 ; return (OpApp arg1' (L loc op') fix arg2') }
222 -- Left sections, equivalent to
229 -- We treat it as similar to the latter, so we don't
230 -- actually require the function to take two arguments
231 -- at all. For example, (x `not`) means (not x);
232 -- you get postfix operators! Not really Haskell 98
233 -- I suppose, but it's less work and kind of useful.
235 tcExpr in_expr@(SectionL arg1 lop@(L loc op)) res_ty
236 = do { (op', [arg1']) <- tcApp op 1 (tcArgs lop [arg1]) res_ty
237 ; return (SectionL arg1' (L loc op')) }
239 -- Right sections, equivalent to \ x -> x `op` expr, or
242 tcExpr in_expr@(SectionR lop@(L loc op) arg2) res_ty
243 = do { (co_fn, (op', arg2')) <- subFunTys doc 1 res_ty $ \ [arg1_ty'] res_ty' ->
244 tcApp op 2 (tc_args arg1_ty') res_ty'
245 ; return (mkHsWrap co_fn (SectionR (L loc op') arg2')) }
247 doc = ptext (sLit "The section") <+> quotes (ppr in_expr)
248 <+> ptext (sLit "takes one argument")
249 tc_args arg1_ty' qtvs qtys [arg1_ty, arg2_ty]
250 = do { boxyUnify arg1_ty' (substTyWith qtvs qtys arg1_ty)
251 ; arg2' <- tcArg lop 2 arg2 qtvs qtys arg2_ty
252 ; qtys' <- mapM refineBox qtys -- c.f. tcArgs
253 ; return (qtys', arg2') }
254 tc_args arg1_ty' _ _ _ = panic "tcExpr SectionR"
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,
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, coi) <- boxySplitListTy res_ty
295 ; exprs' <- mapM (tc_elt elt_ty) exprs
296 ; return $ mkHsWrapCoI coi (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, coi) <- boxySplitPArrTy res_ty
302 ; exprs' <- mapM (tc_elt elt_ty) exprs
303 ; when (null exprs) (zapToMonotype elt_ty >> return ())
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 $ mkHsWrapCoI coi (ExplicitPArr elt_ty exprs') }
310 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
312 -- For tuples, take care to preserve rigidity
313 -- E.g. case (x,y) of ....
314 -- The scrutinee should have a rigid type if x,y do
315 -- The general scheme is the same as in tcIdApp
316 tcExpr (ExplicitTuple exprs boxity) res_ty
317 = do { let kind = case boxity of { Boxed -> liftedTypeKind
318 ; Unboxed -> argTypeKind }
319 ; tvs <- newBoxyTyVars [kind | e <- exprs]
320 ; let tup_tc = tupleTyCon boxity (length exprs)
321 tup_res_ty = mkTyConApp tup_tc (mkTyVarTys tvs)
322 ; checkWiredInTyCon tup_tc -- Ensure instances are available
323 ; arg_tys <- preSubType tvs (mkVarSet tvs) tup_res_ty res_ty
324 ; exprs' <- tcPolyExprs exprs arg_tys
325 ; arg_tys' <- mapM refineBox arg_tys
326 ; co_fn <- tcSubExp TupleOrigin (mkTyConApp tup_tc arg_tys') res_ty
327 ; return (mkHsWrap co_fn (ExplicitTuple exprs' boxity)) }
329 tcExpr (HsProc pat cmd) res_ty
330 = do { (pat', cmd', coi) <- tcProc pat cmd res_ty
331 ; return $ mkHsWrapCoI coi (HsProc pat' cmd') }
333 tcExpr e@(HsArrApp _ _ _ _ _) _
334 = failWithTc (vcat [ptext (sLit "The arrow command"), nest 2 (ppr e),
335 ptext (sLit "was found where an expression was expected")])
337 tcExpr e@(HsArrForm _ _ _) _
338 = failWithTc (vcat [ptext (sLit "The arrow command"), nest 2 (ppr e),
339 ptext (sLit "was found where an expression was expected")])
342 %************************************************************************
344 Record construction and update
346 %************************************************************************
349 tcExpr expr@(RecordCon (L loc con_name) _ rbinds) res_ty
350 = do { data_con <- tcLookupDataCon con_name
352 -- Check for missing fields
353 ; checkMissingFields data_con rbinds
355 ; let arity = dataConSourceArity data_con
356 check_fields qtvs qtys arg_tys
357 = do { let arg_tys' = substTys (zipOpenTvSubst qtvs qtys) arg_tys
358 ; rbinds' <- tcRecordBinds data_con arg_tys' rbinds
359 ; qtys' <- mapM refineBoxToTau qtys
360 ; return (qtys', rbinds') }
361 -- The refineBoxToTau ensures that all the boxes in arg_tys are indeed
362 -- filled, which is the invariant expected by tcIdApp
363 -- How could this not be the case? Consider a record construction
364 -- that does not mention all the fields.
366 ; (con_expr, rbinds') <- tcIdApp con_name arity check_fields res_ty
368 ; return (RecordCon (L loc (dataConWrapId data_con)) con_expr rbinds') }
370 -- The main complication with RecordUpd is that we need to explicitly
371 -- handle the *non-updated* fields. Consider:
373 -- data T a b = MkT1 { fa :: a, fb :: b }
374 -- | MkT2 { fa :: a, fc :: Int -> Int }
375 -- | MkT3 { fd :: a }
377 -- upd :: T a b -> c -> T a c
378 -- upd t x = t { fb = x}
380 -- The type signature on upd is correct (i.e. the result should not be (T a b))
381 -- because upd should be equivalent to:
383 -- upd t x = case t of
384 -- MkT1 p q -> MkT1 p x
385 -- MkT2 a b -> MkT2 p b
386 -- MkT3 d -> error ...
388 -- So we need to give a completely fresh type to the result record,
389 -- and then constrain it by the fields that are *not* updated ("p" above).
391 -- Note that because MkT3 doesn't contain all the fields being updated,
392 -- its RHS is simply an error, so it doesn't impose any type constraints
394 -- All this is done in STEP 4 below.
398 -- For record update we require that every constructor involved in the
399 -- update (i.e. that has all the specified fields) is "vanilla". I
400 -- don't know how to do the update otherwise.
403 tcExpr expr@(RecordUpd record_expr rbinds _ _ _) res_ty = do
405 -- Check that the field names are really field names
407 field_names = hsRecFields rbinds
409 MASSERT( notNull field_names )
410 sel_ids <- mapM tcLookupField field_names
411 -- The renamer has already checked that they
414 bad_guys = [ setSrcSpan loc $ addErrTc (notSelector field_name)
415 | (fld, sel_id) <- rec_flds rbinds `zip` sel_ids,
416 not (isRecordSelector sel_id), -- Excludes class ops
417 let L loc field_name = hsRecFieldId fld
420 unless (null bad_guys) (sequence bad_guys >> failM)
423 -- Figure out the tycon and data cons from the first field name
425 -- It's OK to use the non-tc splitters here (for a selector)
427 (tycon, _) = recordSelectorFieldLabel sel_id -- We've failed already if
428 data_cons = tyConDataCons tycon -- it's not a field label
429 -- NB: for a data type family, the tycon is the instance tycon
431 relevant_cons = filter is_relevant data_cons
432 is_relevant con = all (`elem` dataConFieldLabels con) field_names
435 -- Check that at least one constructor has all the named fields
436 -- i.e. has an empty set of bad fields returned by badFields
437 checkTc (not (null relevant_cons))
438 (badFieldsUpd rbinds)
440 -- Check that all relevant data cons are vanilla. Doing record updates on
441 -- GADTs and/or existentials is more than my tiny brain can cope with today
442 checkTc (all isVanillaDataCon relevant_cons)
443 (nonVanillaUpd tycon)
446 -- Use the un-updated fields to find a vector of booleans saying
447 -- which type arguments must be the same in updatee and result.
449 -- WARNING: this code assumes that all data_cons in a common tycon
450 -- have FieldLabels abstracted over the same tyvars.
452 -- A constructor is only relevant to this process if
453 -- it contains *all* the fields that are being updated
454 con1 = ASSERT( not (null relevant_cons) ) head relevant_cons -- A representative constructor
455 (con1_tyvars, theta, con1_arg_tys, con1_res_ty) = dataConSig con1
456 con1_flds = dataConFieldLabels con1
457 common_tyvars = exactTyVarsOfTypes [ty | (fld,ty) <- con1_flds `zip` con1_arg_tys
458 , not (fld `elem` field_names) ]
460 is_common_tv tv = tv `elemVarSet` common_tyvars
462 mk_inst_ty tv result_inst_ty
463 | is_common_tv tv = return result_inst_ty -- Same as result type
464 | otherwise = newFlexiTyVarTy (tyVarKind tv) -- Fresh type, of correct kind
466 MASSERT( null theta ) -- Vanilla datacon
467 (_, result_inst_tys, result_inst_env) <- tcInstTyVars con1_tyvars
468 scrut_inst_tys <- zipWithM mk_inst_ty con1_tyvars result_inst_tys
470 -- STEP 3: Typecheck the update bindings.
471 -- Do this after checking for bad fields in case
472 -- there's a field that doesn't match the constructor.
474 result_ty = substTy result_inst_env con1_res_ty
475 con1_arg_tys' = map (substTy result_inst_env) con1_arg_tys
476 origin = RecordUpdOrigin
478 co_fn <- tcSubExp origin result_ty res_ty
479 rbinds' <- tcRecordBinds con1 con1_arg_tys' rbinds
481 -- STEP 5: Typecheck the expression to be updated
483 scrut_inst_env = zipTopTvSubst con1_tyvars scrut_inst_tys
484 scrut_ty = substTy scrut_inst_env con1_res_ty
485 -- This is one place where the isVanilla check is important
486 -- So that inst_tys matches the con1_tyvars
488 record_expr' <- tcMonoExpr record_expr scrut_ty
490 -- STEP 6: Figure out the LIE we need.
491 -- We have to generate some dictionaries for the data type context,
492 -- since we are going to do pattern matching over the data cons.
494 -- What dictionaries do we need? The dataConStupidTheta tells us.
496 theta' = substTheta scrut_inst_env (dataConStupidTheta con1)
498 instStupidTheta origin theta'
500 -- Step 7: make a cast for the scrutinee, in the case that it's from a type family
501 let scrut_co | Just co_con <- tyConFamilyCoercion_maybe tycon
502 = WpCast $ mkTyConApp co_con scrut_inst_tys
507 return (mkHsWrap co_fn (RecordUpd (mkLHsWrap scrut_co record_expr') rbinds'
508 relevant_cons scrut_inst_tys result_inst_tys))
512 %************************************************************************
514 Arithmetic sequences e.g. [a,b..]
515 and their parallel-array counterparts e.g. [: a,b.. :]
518 %************************************************************************
521 tcExpr (ArithSeq _ seq@(From expr)) res_ty
522 = do { (elt_ty, coi) <- boxySplitListTy res_ty
523 ; expr' <- tcPolyExpr expr elt_ty
524 ; enum_from <- newMethodFromName (ArithSeqOrigin seq)
526 ; return $ mkHsWrapCoI coi (ArithSeq (HsVar enum_from) (From expr')) }
528 tcExpr in_expr@(ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
529 = do { (elt_ty, coi) <- boxySplitListTy res_ty
530 ; expr1' <- tcPolyExpr expr1 elt_ty
531 ; expr2' <- tcPolyExpr expr2 elt_ty
532 ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq)
533 elt_ty enumFromThenName
534 ; return $ mkHsWrapCoI coi
535 (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2')) }
537 tcExpr in_expr@(ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
538 = do { (elt_ty, coi) <- boxySplitListTy res_ty
539 ; expr1' <- tcPolyExpr expr1 elt_ty
540 ; expr2' <- tcPolyExpr expr2 elt_ty
541 ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq)
542 elt_ty enumFromToName
543 ; return $ mkHsWrapCoI coi
544 (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
546 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
547 = do { (elt_ty, coi) <- boxySplitListTy res_ty
548 ; expr1' <- tcPolyExpr expr1 elt_ty
549 ; expr2' <- tcPolyExpr expr2 elt_ty
550 ; expr3' <- tcPolyExpr expr3 elt_ty
551 ; eft <- newMethodFromName (ArithSeqOrigin seq)
552 elt_ty enumFromThenToName
553 ; return $ mkHsWrapCoI coi
554 (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
556 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
557 = do { (elt_ty, coi) <- boxySplitPArrTy res_ty
558 ; expr1' <- tcPolyExpr expr1 elt_ty
559 ; expr2' <- tcPolyExpr expr2 elt_ty
560 ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq)
561 elt_ty enumFromToPName
562 ; return $ mkHsWrapCoI coi
563 (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
565 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
566 = do { (elt_ty, coi) <- boxySplitPArrTy res_ty
567 ; expr1' <- tcPolyExpr expr1 elt_ty
568 ; expr2' <- tcPolyExpr expr2 elt_ty
569 ; expr3' <- tcPolyExpr expr3 elt_ty
570 ; eft <- newMethodFromName (PArrSeqOrigin seq)
571 elt_ty enumFromThenToPName
572 ; return $ mkHsWrapCoI coi
573 (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
575 tcExpr (PArrSeq _ _) _
576 = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
577 -- the parser shouldn't have generated it and the renamer shouldn't have
582 %************************************************************************
586 %************************************************************************
589 #ifdef GHCI /* Only if bootstrapped */
590 -- Rename excludes these cases otherwise
591 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
592 tcExpr (HsBracket brack) res_ty = do { e <- tcBracket brack res_ty
594 tcExpr e@(HsQuasiQuoteE _) res_ty =
595 pprPanic "Should never see HsQuasiQuoteE in type checker" (ppr e)
600 %************************************************************************
604 %************************************************************************
607 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
611 %************************************************************************
615 %************************************************************************
618 ---------------------------
619 tcApp :: HsExpr Name -- Function
620 -> Arity -- Number of args reqd
621 -> ArgChecker results
622 -> BoxyRhoType -- Result type
623 -> TcM (HsExpr TcId, results)
625 -- (tcFun fun n_args arg_checker res_ty)
626 -- The argument type checker, arg_checker, will be passed exactly n_args types
628 tcApp (HsVar fun_name) n_args arg_checker res_ty
629 = tcIdApp fun_name n_args arg_checker res_ty
631 tcApp fun n_args arg_checker res_ty -- The vanilla case (rula APP)
632 = do { arg_boxes <- newBoxyTyVars (replicate n_args argTypeKind)
633 ; fun' <- tcExpr fun (mkFunTys (mkTyVarTys arg_boxes) res_ty)
634 ; arg_tys' <- mapM readFilledBox arg_boxes
635 ; (_, args') <- arg_checker [] [] arg_tys' -- Yuk
636 ; return (fun', args') }
638 ---------------------------
639 tcIdApp :: Name -- Function
640 -> Arity -- Number of args reqd
641 -> ArgChecker results -- The arg-checker guarantees to fill all boxes in the arg types
642 -> BoxyRhoType -- Result type
643 -> TcM (HsExpr TcId, results)
645 -- Call (f e1 ... en) :: res_ty
646 -- Type f :: forall a b c. theta => fa_1 -> ... -> fa_k -> fres
647 -- (where k <= n; fres has the rest)
648 -- NB: if k < n then the function doesn't have enough args, and
649 -- presumably fres is a type variable that we are going to
650 -- instantiate with a function type
652 -- Then fres <= bx_(k+1) -> ... -> bx_n -> res_ty
654 tcIdApp fun_name n_args arg_checker res_ty
655 = do { let orig = OccurrenceOf fun_name
656 ; (fun, fun_ty) <- lookupFun orig fun_name
658 -- Split up the function type
659 ; let (tv_theta_prs, rho) = tcMultiSplitSigmaTy fun_ty
660 (fun_arg_tys, fun_res_ty) = tcSplitFunTysN rho n_args
662 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
663 arg_qtvs = exactTyVarsOfTypes fun_arg_tys
664 res_qtvs = exactTyVarsOfType fun_res_ty
665 -- NB: exactTyVarsOfType. See Note [Silly type synonyms in smart-app]
666 tau_qtvs = arg_qtvs `unionVarSet` res_qtvs
667 k = length fun_arg_tys -- k <= n_args
668 n_missing_args = n_args - k -- Always >= 0
670 -- Match the result type of the function with the
671 -- result type of the context, to get an inital substitution
672 ; extra_arg_boxes <- newBoxyTyVars (replicate n_missing_args argTypeKind)
673 ; let extra_arg_tys' = mkTyVarTys extra_arg_boxes
674 res_ty' = mkFunTys extra_arg_tys' res_ty
675 ; qtys' <- preSubType qtvs tau_qtvs fun_res_ty res_ty'
677 -- Typecheck the arguments!
678 -- Doing so will fill arg_qtvs and extra_arg_tys'
679 ; (qtys'', args') <- arg_checker qtvs qtys' (fun_arg_tys ++ extra_arg_tys')
681 -- Strip boxes from the qtvs that have been filled in by the arg checking
682 ; extra_arg_tys'' <- mapM readFilledBox extra_arg_boxes
684 -- Result subsumption
685 -- This fills in res_qtvs
686 ; let res_subst = zipOpenTvSubst qtvs qtys''
687 fun_res_ty'' = substTy res_subst fun_res_ty
688 res_ty'' = mkFunTys extra_arg_tys'' res_ty
689 ; co_fn <- tcSubExp orig fun_res_ty'' res_ty''
691 -- And pack up the results
692 -- By applying the coercion just to the *function* we can make
693 -- tcFun work nicely for OpApp and Sections too
694 ; fun' <- instFun orig fun res_subst tv_theta_prs
695 ; co_fn' <- wrapFunResCoercion (substTys res_subst fun_arg_tys) co_fn
696 ; traceTc (text "tcIdApp: " <+> ppr (mkHsWrap co_fn' fun') <+> ppr tv_theta_prs <+> ppr co_fn' <+> ppr fun')
697 ; return (mkHsWrap co_fn' fun', args') }
700 Note [Silly type synonyms in smart-app]
701 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
702 When we call sripBoxyType, all of the boxes should be filled
703 in. But we need to be careful about type synonyms:
707 In the call (f x) we'll typecheck x, expecting it to have type
708 (T box). Usually that would fill in the box, but in this case not;
709 because 'a' is discarded by the silly type synonym T. So we must
710 use exactTyVarsOfType to figure out which type variables are free
711 in the argument type.
714 -- tcId is a specialisation of tcIdApp when there are no arguments
715 -- tcId f ty = do { (res, _) <- tcIdApp f [] (\[] -> return ()) ty
720 -> BoxyRhoType -- Result type
722 tcId orig fun_name res_ty
723 = do { traceTc (text "tcId" <+> ppr fun_name <+> ppr res_ty)
724 ; (fun, fun_ty) <- lookupFun orig fun_name
726 -- Split up the function type
727 ; let (tv_theta_prs, fun_tau) = tcMultiSplitSigmaTy fun_ty
728 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
729 tau_qtvs = exactTyVarsOfType fun_tau -- Mentioned in the tau part
730 ; qtv_tys <- preSubType qtvs tau_qtvs fun_tau res_ty
732 -- Do the subsumption check wrt the result type
733 ; let res_subst = zipTopTvSubst qtvs qtv_tys
734 fun_tau' = substTy res_subst fun_tau
736 ; co_fn <- tcSubExp orig fun_tau' res_ty
738 -- And pack up the results
739 ; fun' <- instFun orig fun res_subst tv_theta_prs
740 ; traceTc (text "tcId yields" <+> ppr (mkHsWrap co_fn fun'))
741 ; return (mkHsWrap 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 ---------------------------
774 instFun :: InstOrigin
776 -> TvSubst -- The instantiating substitution
777 -> [([TyVar], ThetaType)] -- Stuff to instantiate
780 instFun orig fun subst []
781 = return fun -- Common short cut
783 instFun orig fun subst tv_theta_prs
784 = do { let ty_theta_prs' = map subst_pr tv_theta_prs
785 ; traceTc (text "instFun" <+> ppr ty_theta_prs')
786 -- Make two ad-hoc checks
787 ; doStupidChecks fun ty_theta_prs'
789 -- Now do normal instantiation
790 ; method_sharing <- doptM Opt_MethodSharing
791 ; result <- go method_sharing True fun ty_theta_prs'
792 ; traceTc (text "instFun result" <+> ppr result)
796 subst_pr (tvs, theta)
797 = (substTyVars subst tvs, substTheta subst theta)
799 go _ _ fun [] = do {traceTc (text "go _ _ fun [] returns" <+> ppr fun) ; return fun }
801 go method_sharing True (HsVar fun_id) ((tys,theta) : prs)
802 | want_method_inst method_sharing theta
803 = do { traceTc (text "go (HsVar fun_id) ((tys,theta) : prs) | want_method_inst theta")
804 ; meth_id <- newMethodWithGivenTy orig fun_id tys
805 ; go method_sharing False (HsVar meth_id) prs }
806 -- Go round with 'False' to prevent further use
807 -- of newMethod: see Note [Multiple instantiation]
809 go method_sharing _ fun ((tys, theta) : prs)
810 = do { co_fn <- instCall orig tys theta
811 ; traceTc (text "go yields co_fn" <+> ppr co_fn)
812 ; go method_sharing False (HsWrap co_fn fun) prs }
814 -- See Note [No method sharing]
815 want_method_inst method_sharing theta = not (null theta) -- Overloaded
819 Note [Multiple instantiation]
820 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
821 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
822 For example, consider
823 f :: forall a. Eq a => forall b. Ord b => a -> b
824 At a call to f, at say [Int, Bool], it's tempting to translate the call to
828 f_m1 :: forall b. Ord b => Int -> b
832 f_m2 = f_m1 Bool dOrdBool
834 But notice that f_m2 has f_m1 as its meth_id. Now the danger is that if we do
835 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
837 But it's entirely possible that f_m2 will continue to float out, because it
838 mentions no type variables. Result, f_m1 isn't in scope.
840 Here's a concrete example that does this (test tc200):
843 f :: Eq b => b -> a -> Int
844 baz :: Eq a => Int -> a -> Int
849 Current solution: only do the "method sharing" thing for the first type/dict
850 application, not for the iterated ones. A horribly subtle point.
852 Note [No method sharing]
853 ~~~~~~~~~~~~~~~~~~~~~~~~
854 The -fno-method-sharing flag controls what happens so far as the LIE
855 is concerned. The default case is that for an overloaded function we
856 generate a "method" Id, and add the Method Inst to the LIE. So you get
859 f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
860 If you specify -fno-method-sharing, the dictionary application
861 isn't shared, so we get
863 f = /\a (d:Num a) (x:a) -> (+) a d x x
864 This gets a bit less sharing, but
865 a) it's better for RULEs involving overloaded functions
866 b) perhaps fewer separated lambdas
870 tcArgs implements a left-to-right order, which goes beyond what is described in the
871 impredicative type inference paper. In particular, it allows
873 where runST :: (forall s. ST s a) -> a
874 When typechecking the application of ($)::(a->b) -> a -> b, we first check that
875 runST has type (a->b), thereby filling in a=forall s. ST s a. Then we un-box this type
876 before checking foo. The left-to-right order really helps here.
879 tcArgs :: LHsExpr Name -- The function (for error messages)
880 -> [LHsExpr Name] -- Actual args
881 -> ArgChecker [LHsExpr TcId]
883 type ArgChecker results
884 = [TyVar] -> [TcSigmaType] -- Current instantiation
885 -> [TcSigmaType] -- Expected arg types (**before** applying the instantiation)
886 -> TcM ([TcSigmaType], results) -- Resulting instaniation and args
888 tcArgs fun args qtvs qtys arg_tys
889 = go 1 qtys args arg_tys
891 go n qtys [] [] = return (qtys, [])
892 go n qtys (arg:args) (arg_ty:arg_tys)
893 = do { arg' <- tcArg fun n arg qtvs qtys arg_ty
894 ; qtys' <- mapM refineBox qtys -- Exploit new info
895 ; (qtys'', args') <- go (n+1) qtys' args arg_tys
896 ; return (qtys'', arg':args') }
897 go n qtys args arg_tys = panic "tcArgs"
899 tcArg :: LHsExpr Name -- The function
900 -> Int -- and arg number (for error messages)
902 -> [TyVar] -> [TcSigmaType] -- Instantiate the arg type like this
904 -> TcM (LHsExpr TcId) -- Resulting argument
905 tcArg fun arg_no arg qtvs qtys ty
906 = addErrCtxt (funAppCtxt fun arg arg_no) $
907 tcPolyExprNC arg (substTyWith qtvs qtys ty)
913 Nasty check to ensure that tagToEnum# is applied to a type that is an
914 enumeration TyCon. Unification may refine the type later, but this
915 check won't see that, alas. It's crude but it works.
917 Here's are two cases that should fail
919 f = tagToEnum# 0 -- Can't do tagToEnum# at a type variable
922 g = tagToEnum# 0 -- Int is not an enumeration
926 doStupidChecks :: HsExpr TcId
927 -> [([TcType], ThetaType)]
929 -- Check two tiresome and ad-hoc cases
930 -- (a) the "stupid theta" for a data con; add the constraints
931 -- from the "stupid theta" of a data constructor (sigh)
932 -- (b) deal with the tagToEnum# problem: see Note [tagToEnum#]
934 doStupidChecks (HsVar fun_id) ((tys,_):_)
935 | Just con <- isDataConId_maybe fun_id -- (a)
936 = addDataConStupidTheta con tys
938 | fun_id `hasKey` tagToEnumKey -- (b)
939 = do { tys' <- zonkTcTypes tys
940 ; checkTc (ok tys') (tagToEnumError tys')
944 ok (ty:tys) = case tcSplitTyConApp_maybe ty of
945 Just (tc,_) -> isEnumerationTyCon tc
948 doStupidChecks fun tv_theta_prs
949 = return () -- The common case
953 = hang (ptext (sLit "Bad call to tagToEnum#") <+> at_type)
954 2 (vcat [ptext (sLit "Specify the type by giving a type signature"),
955 ptext (sLit "e.g. (tagToEnum# x) :: Bool")])
957 at_type | null tys = empty -- Probably never happens
958 | otherwise = ptext (sLit "at type") <+> ppr (head tys)
961 %************************************************************************
963 \subsection{@tcId@ typechecks an identifier occurrence}
965 %************************************************************************
968 lookupFun :: InstOrigin -> Name -> TcM (HsExpr TcId, TcType)
969 lookupFun orig id_name
970 = do { thing <- tcLookup id_name
972 AGlobal (ADataCon con) -> return (HsVar wrap_id, idType wrap_id)
974 wrap_id = dataConWrapId con
977 | isNaughtyRecordSelector id -> failWithTc (naughtyRecordSel id)
978 | otherwise -> return (HsVar id, idType id)
979 -- A global cannot possibly be ill-staged
980 -- nor does it need the 'lifting' treatment
982 ATcId { tct_id = id, tct_type = ty, tct_co = mb_co, tct_level = lvl }
983 -> do { thLocalId orig id ty lvl
985 Unrefineable -> return (HsVar id, ty)
986 Rigid co -> return (mkHsWrap co (HsVar id), ty)
987 Wobbly -> traceTc (text "lookupFun" <+> ppr id) >> return (HsVar id, ty) -- Wobbly, or no free vars
988 WobblyInvisible -> failWithTc (ppr id_name <+> ptext (sLit " not in scope because it has a wobbly type (solution: add a type annotation)"))
991 other -> failWithTc (ppr other <+> ptext (sLit "used where a value identifer was expected"))
994 #ifndef GHCI /* GHCI and TH is off */
995 --------------------------------------
996 -- thLocalId : Check for cross-stage lifting
997 thLocalId orig id id_ty th_bind_lvl
1000 #else /* GHCI and TH is on */
1001 thLocalId orig id id_ty th_bind_lvl
1002 = do { use_stage <- getStage -- TH case
1004 Brack use_lvl ps_var lie_var | use_lvl > th_bind_lvl
1005 -> thBrackId orig id ps_var lie_var
1006 other -> do { checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage
1010 --------------------------------------
1011 thBrackId orig id ps_var lie_var
1013 = -- Top-level identifiers in this module,
1014 -- (which have External Names)
1015 -- are just like the imported case:
1016 -- no need for the 'lifting' treatment
1017 -- E.g. this is fine:
1020 -- But we do need to put f into the keep-alive
1021 -- set, because after desugaring the code will
1022 -- only mention f's *name*, not f itself.
1023 do { keepAliveTc id; return id }
1026 = -- Nested identifiers, such as 'x' in
1027 -- E.g. \x -> [| h x |]
1028 -- We must behave as if the reference to x was
1030 -- We use 'x' itself as the splice proxy, used by
1031 -- the desugarer to stitch it all back together.
1032 -- If 'x' occurs many times we may get many identical
1033 -- bindings of the same splice proxy, but that doesn't
1034 -- matter, although it's a mite untidy.
1035 do { let id_ty = idType id
1036 ; checkTc (isTauTy id_ty) (polySpliceErr id)
1037 -- If x is polymorphic, its occurrence sites might
1038 -- have different instantiations, so we can't use plain
1039 -- 'x' as the splice proxy name. I don't know how to
1040 -- solve this, and it's probably unimportant, so I'm
1041 -- just going to flag an error for now
1043 ; id_ty' <- zapToMonotype id_ty
1044 -- The id_ty might have an OpenTypeKind, but we
1045 -- can't instantiate the Lift class at that kind,
1046 -- so we zap it to a LiftedTypeKind monotype
1047 -- C.f. the call in TcPat.newLitInst
1049 ; setLIEVar lie_var $ do
1050 { lift <- newMethodFromName orig id_ty' DsMeta.liftName
1051 -- Put the 'lift' constraint into the right LIE
1053 -- Update the pending splices
1054 ; ps <- readMutVar ps_var
1055 ; writeMutVar ps_var ((idName id, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps)
1062 %************************************************************************
1064 \subsection{Record bindings}
1066 %************************************************************************
1068 Game plan for record bindings
1069 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1070 1. Find the TyCon for the bindings, from the first field label.
1072 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1074 For each binding field = value
1076 3. Instantiate the field type (from the field label) using the type
1079 4 Type check the value using tcArg, passing the field type as
1080 the expected argument type.
1082 This extends OK when the field types are universally quantified.
1088 -> [TcType] -- Expected type for each field
1089 -> HsRecordBinds Name
1090 -> TcM (HsRecordBinds TcId)
1092 tcRecordBinds data_con arg_tys (HsRecFields rbinds dd)
1093 = do { mb_binds <- mapM do_bind rbinds
1094 ; return (HsRecFields (catMaybes mb_binds) dd) }
1096 flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1097 do_bind fld@(HsRecField { hsRecFieldId = L loc field_lbl, hsRecFieldArg = rhs })
1098 | Just field_ty <- assocMaybe flds_w_tys field_lbl
1099 = addErrCtxt (fieldCtxt field_lbl) $
1100 do { rhs' <- tcPolyExprNC rhs field_ty
1101 ; sel_id <- tcLookupField field_lbl
1102 ; ASSERT( isRecordSelector sel_id )
1103 return (Just (fld { hsRecFieldId = L loc sel_id, hsRecFieldArg = rhs' })) }
1105 = do { addErrTc (badFieldCon data_con field_lbl)
1108 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1109 checkMissingFields data_con rbinds
1110 | null field_labels -- Not declared as a record;
1111 -- But C{} is still valid if no strict fields
1112 = if any isMarkedStrict field_strs then
1113 -- Illegal if any arg is strict
1114 addErrTc (missingStrictFields data_con [])
1118 | otherwise = do -- A record
1119 unless (null missing_s_fields)
1120 (addErrTc (missingStrictFields data_con missing_s_fields))
1122 warn <- doptM Opt_WarnMissingFields
1123 unless (not (warn && notNull missing_ns_fields))
1124 (warnTc True (missingFields data_con missing_ns_fields))
1128 = [ fl | (fl, str) <- field_info,
1130 not (fl `elem` field_names_used)
1133 = [ fl | (fl, str) <- field_info,
1134 not (isMarkedStrict str),
1135 not (fl `elem` field_names_used)
1138 field_names_used = hsRecFields rbinds
1139 field_labels = dataConFieldLabels data_con
1141 field_info = zipEqual "missingFields"
1145 field_strs = dataConStrictMarks data_con
1148 %************************************************************************
1150 \subsection{Errors and contexts}
1152 %************************************************************************
1154 Boring and alphabetical:
1157 = hang (ptext (sLit "In the scrutinee of a case expression:")) 4 (ppr expr)
1160 = hang (ptext (sLit "In the expression:")) 4 (ppr expr)
1162 fieldCtxt field_name
1163 = ptext (sLit "In the") <+> quotes (ppr field_name) <+> ptext (sLit "field of a record")
1165 funAppCtxt fun arg arg_no
1166 = hang (hsep [ ptext (sLit "In the"), speakNth arg_no, ptext (sLit "argument of"),
1167 quotes (ppr fun) <> text ", namely"])
1168 4 (quotes (ppr arg))
1171 = hang (ptext (sLit "In the predicate expression:")) 4 (ppr expr)
1174 = vcat [ptext (sLit "Record update for the non-Haskell-98 data type")
1175 <+> quotes (pprSourceTyCon tycon)
1176 <+> ptext (sLit "is not (yet) supported"),
1177 ptext (sLit "Use pattern-matching instead")]
1179 = hang (ptext (sLit "No constructor has all these fields:"))
1180 4 (pprQuotedList (hsRecFields rbinds))
1182 naughtyRecordSel sel_id
1183 = ptext (sLit "Cannot use record selector") <+> quotes (ppr sel_id) <+>
1184 ptext (sLit "as a function due to escaped type variables") $$
1185 ptext (sLit "Probably fix: use pattern-matching syntax instead")
1188 = hsep [quotes (ppr field), ptext (sLit "is not a record selector")]
1190 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1191 missingStrictFields con fields
1194 rest | null fields = empty -- Happens for non-record constructors
1195 -- with strict fields
1196 | otherwise = colon <+> pprWithCommas ppr fields
1198 header = ptext (sLit "Constructor") <+> quotes (ppr con) <+>
1199 ptext (sLit "does not have the required strict field(s)")
1201 missingFields :: DataCon -> [FieldLabel] -> SDoc
1202 missingFields con fields
1203 = ptext (sLit "Fields of") <+> quotes (ppr con) <+> ptext (sLit "not initialised:")
1204 <+> pprWithCommas ppr fields
1206 -- callCtxt fun args = ptext (sLit "In the call") <+> parens (ppr (foldl mkHsApp fun args))
1209 polySpliceErr :: Id -> SDoc
1211 = ptext (sLit "Can't splice the polymorphic local variable") <+> quotes (ppr id)