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 { tvs <- newBoxyTyVars [argTypeKind | e <- exprs]
318 ; let tup_tc = tupleTyCon boxity (length exprs)
319 tup_res_ty = mkTyConApp tup_tc (mkTyVarTys tvs)
320 ; checkWiredInTyCon tup_tc -- Ensure instances are available
321 ; arg_tys <- preSubType tvs (mkVarSet tvs) tup_res_ty res_ty
322 ; exprs' <- tcPolyExprs exprs arg_tys
323 ; arg_tys' <- mapM refineBox arg_tys
324 ; co_fn <- tcSubExp TupleOrigin (mkTyConApp tup_tc arg_tys') res_ty
325 ; return (mkHsWrap co_fn (ExplicitTuple exprs' boxity)) }
327 tcExpr (HsProc pat cmd) res_ty
328 = do { (pat', cmd', coi) <- tcProc pat cmd res_ty
329 ; return $ mkHsWrapCoI coi (HsProc pat' cmd') }
331 tcExpr e@(HsArrApp _ _ _ _ _) _
332 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
333 ptext SLIT("was found where an expression was expected")])
335 tcExpr e@(HsArrForm _ _ _) _
336 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
337 ptext SLIT("was found where an expression was expected")])
340 %************************************************************************
342 Record construction and update
344 %************************************************************************
347 tcExpr expr@(RecordCon (L loc con_name) _ rbinds) res_ty
348 = do { data_con <- tcLookupDataCon con_name
350 -- Check for missing fields
351 ; checkMissingFields data_con rbinds
353 ; let arity = dataConSourceArity data_con
354 check_fields qtvs qtys arg_tys
355 = do { let arg_tys' = substTys (zipOpenTvSubst qtvs qtys) arg_tys
356 ; rbinds' <- tcRecordBinds data_con arg_tys' rbinds
357 ; qtys' <- mapM refineBoxToTau qtys
358 ; return (qtys', rbinds') }
359 -- The refineBoxToTau ensures that all the boxes in arg_tys are indeed
360 -- filled, which is the invariant expected by tcIdApp
361 -- How could this not be the case? Consider a record construction
362 -- that does not mention all the fields.
364 ; (con_expr, rbinds') <- tcIdApp con_name arity check_fields res_ty
366 ; return (RecordCon (L loc (dataConWrapId data_con)) con_expr rbinds') }
368 -- The main complication with RecordUpd is that we need to explicitly
369 -- handle the *non-updated* fields. Consider:
371 -- data T a b = MkT1 { fa :: a, fb :: b }
372 -- | MkT2 { fa :: a, fc :: Int -> Int }
373 -- | MkT3 { fd :: a }
375 -- upd :: T a b -> c -> T a c
376 -- upd t x = t { fb = x}
378 -- The type signature on upd is correct (i.e. the result should not be (T a b))
379 -- because upd should be equivalent to:
381 -- upd t x = case t of
382 -- MkT1 p q -> MkT1 p x
383 -- MkT2 a b -> MkT2 p b
384 -- MkT3 d -> error ...
386 -- So we need to give a completely fresh type to the result record,
387 -- and then constrain it by the fields that are *not* updated ("p" above).
389 -- Note that because MkT3 doesn't contain all the fields being updated,
390 -- its RHS is simply an error, so it doesn't impose any type constraints
392 -- All this is done in STEP 4 below.
396 -- For record update we require that every constructor involved in the
397 -- update (i.e. that has all the specified fields) is "vanilla". I
398 -- don't know how to do the update otherwise.
401 tcExpr expr@(RecordUpd record_expr rbinds _ _ _) res_ty = do
403 -- Check that the field names are really field names
405 field_names = hsRecFields rbinds
407 MASSERT( notNull field_names )
408 sel_ids <- mapM tcLookupField field_names
409 -- The renamer has already checked that they
412 bad_guys = [ setSrcSpan loc $ addErrTc (notSelector field_name)
413 | (fld, sel_id) <- rec_flds rbinds `zip` sel_ids,
414 not (isRecordSelector sel_id), -- Excludes class ops
415 let L loc field_name = hsRecFieldId fld
418 unless (null bad_guys) (sequence bad_guys >> failM)
421 -- Figure out the tycon and data cons from the first field name
423 -- It's OK to use the non-tc splitters here (for a selector)
425 (tycon, _) = recordSelectorFieldLabel sel_id -- We've failed already if
426 data_cons = tyConDataCons tycon -- it's not a field label
427 -- NB: for a data type family, the tycon is the instance tycon
429 relevant_cons = filter is_relevant data_cons
430 is_relevant con = all (`elem` dataConFieldLabels con) field_names
433 -- Check that at least one constructor has all the named fields
434 -- i.e. has an empty set of bad fields returned by badFields
435 checkTc (not (null relevant_cons))
436 (badFieldsUpd rbinds)
438 -- Check that all relevant data cons are vanilla. Doing record updates on
439 -- GADTs and/or existentials is more than my tiny brain can cope with today
440 checkTc (all isVanillaDataCon relevant_cons)
441 (nonVanillaUpd tycon)
444 -- Use the un-updated fields to find a vector of booleans saying
445 -- which type arguments must be the same in updatee and result.
447 -- WARNING: this code assumes that all data_cons in a common tycon
448 -- have FieldLabels abstracted over the same tyvars.
450 -- A constructor is only relevant to this process if
451 -- it contains *all* the fields that are being updated
452 con1 = ASSERT( not (null relevant_cons) ) head relevant_cons -- A representative constructor
453 (con1_tyvars, theta, con1_arg_tys, con1_res_ty) = dataConSig con1
454 con1_flds = dataConFieldLabels con1
455 common_tyvars = exactTyVarsOfTypes [ty | (fld,ty) <- con1_flds `zip` con1_arg_tys
456 , not (fld `elem` field_names) ]
458 is_common_tv tv = tv `elemVarSet` common_tyvars
460 mk_inst_ty tv result_inst_ty
461 | is_common_tv tv = return result_inst_ty -- Same as result type
462 | otherwise = newFlexiTyVarTy (tyVarKind tv) -- Fresh type, of correct kind
464 MASSERT( null theta ) -- Vanilla datacon
465 (_, result_inst_tys, result_inst_env) <- tcInstTyVars con1_tyvars
466 scrut_inst_tys <- zipWithM mk_inst_ty con1_tyvars result_inst_tys
468 -- STEP 3: Typecheck the update bindings.
469 -- Do this after checking for bad fields in case
470 -- there's a field that doesn't match the constructor.
472 result_ty = substTy result_inst_env con1_res_ty
473 con1_arg_tys' = map (substTy result_inst_env) con1_arg_tys
474 origin = RecordUpdOrigin
476 co_fn <- tcSubExp origin result_ty res_ty
477 rbinds' <- tcRecordBinds con1 con1_arg_tys' rbinds
479 -- STEP 5: Typecheck the expression to be updated
481 scrut_inst_env = zipTopTvSubst con1_tyvars scrut_inst_tys
482 scrut_ty = substTy scrut_inst_env con1_res_ty
483 -- This is one place where the isVanilla check is important
484 -- So that inst_tys matches the con1_tyvars
486 record_expr' <- tcMonoExpr record_expr scrut_ty
488 -- STEP 6: Figure out the LIE we need.
489 -- We have to generate some dictionaries for the data type context,
490 -- since we are going to do pattern matching over the data cons.
492 -- What dictionaries do we need? The dataConStupidTheta tells us.
494 theta' = substTheta scrut_inst_env (dataConStupidTheta con1)
496 instStupidTheta origin theta'
498 -- Step 7: make a cast for the scrutinee, in the case that it's from a type family
499 let scrut_co | Just co_con <- tyConFamilyCoercion_maybe tycon
500 = WpCast $ mkTyConApp co_con scrut_inst_tys
505 return (mkHsWrap co_fn (RecordUpd (mkLHsWrap scrut_co record_expr') rbinds'
506 relevant_cons scrut_inst_tys result_inst_tys))
510 %************************************************************************
512 Arithmetic sequences e.g. [a,b..]
513 and their parallel-array counterparts e.g. [: a,b.. :]
516 %************************************************************************
519 tcExpr (ArithSeq _ seq@(From expr)) res_ty
520 = do { (elt_ty, coi) <- boxySplitListTy res_ty
521 ; expr' <- tcPolyExpr expr elt_ty
522 ; enum_from <- newMethodFromName (ArithSeqOrigin seq)
524 ; return $ mkHsWrapCoI coi (ArithSeq (HsVar enum_from) (From expr')) }
526 tcExpr in_expr@(ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
527 = do { (elt_ty, coi) <- boxySplitListTy res_ty
528 ; expr1' <- tcPolyExpr expr1 elt_ty
529 ; expr2' <- tcPolyExpr expr2 elt_ty
530 ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq)
531 elt_ty enumFromThenName
532 ; return $ mkHsWrapCoI coi
533 (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2')) }
535 tcExpr in_expr@(ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
536 = do { (elt_ty, coi) <- boxySplitListTy res_ty
537 ; expr1' <- tcPolyExpr expr1 elt_ty
538 ; expr2' <- tcPolyExpr expr2 elt_ty
539 ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq)
540 elt_ty enumFromToName
541 ; return $ mkHsWrapCoI coi
542 (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
544 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
545 = do { (elt_ty, coi) <- boxySplitListTy res_ty
546 ; expr1' <- tcPolyExpr expr1 elt_ty
547 ; expr2' <- tcPolyExpr expr2 elt_ty
548 ; expr3' <- tcPolyExpr expr3 elt_ty
549 ; eft <- newMethodFromName (ArithSeqOrigin seq)
550 elt_ty enumFromThenToName
551 ; return $ mkHsWrapCoI coi
552 (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
554 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
555 = do { (elt_ty, coi) <- boxySplitPArrTy res_ty
556 ; expr1' <- tcPolyExpr expr1 elt_ty
557 ; expr2' <- tcPolyExpr expr2 elt_ty
558 ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq)
559 elt_ty enumFromToPName
560 ; return $ mkHsWrapCoI coi
561 (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
563 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
564 = do { (elt_ty, coi) <- boxySplitPArrTy res_ty
565 ; expr1' <- tcPolyExpr expr1 elt_ty
566 ; expr2' <- tcPolyExpr expr2 elt_ty
567 ; expr3' <- tcPolyExpr expr3 elt_ty
568 ; eft <- newMethodFromName (PArrSeqOrigin seq)
569 elt_ty enumFromThenToPName
570 ; return $ mkHsWrapCoI coi
571 (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
573 tcExpr (PArrSeq _ _) _
574 = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
575 -- the parser shouldn't have generated it and the renamer shouldn't have
580 %************************************************************************
584 %************************************************************************
587 #ifdef GHCI /* Only if bootstrapped */
588 -- Rename excludes these cases otherwise
589 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
590 tcExpr (HsBracket brack) res_ty = do { e <- tcBracket brack res_ty
592 tcExpr e@(HsQuasiQuoteE _) res_ty =
593 pprPanic "Should never see HsQuasiQuoteE in type checker" (ppr e)
598 %************************************************************************
602 %************************************************************************
605 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
609 %************************************************************************
613 %************************************************************************
616 ---------------------------
617 tcApp :: HsExpr Name -- Function
618 -> Arity -- Number of args reqd
619 -> ArgChecker results
620 -> BoxyRhoType -- Result type
621 -> TcM (HsExpr TcId, results)
623 -- (tcFun fun n_args arg_checker res_ty)
624 -- The argument type checker, arg_checker, will be passed exactly n_args types
626 tcApp (HsVar fun_name) n_args arg_checker res_ty
627 = tcIdApp fun_name n_args arg_checker res_ty
629 tcApp fun n_args arg_checker res_ty -- The vanilla case (rula APP)
630 = do { arg_boxes <- newBoxyTyVars (replicate n_args argTypeKind)
631 ; fun' <- tcExpr fun (mkFunTys (mkTyVarTys arg_boxes) res_ty)
632 ; arg_tys' <- mapM readFilledBox arg_boxes
633 ; (_, args') <- arg_checker [] [] arg_tys' -- Yuk
634 ; return (fun', args') }
636 ---------------------------
637 tcIdApp :: Name -- Function
638 -> Arity -- Number of args reqd
639 -> ArgChecker results -- The arg-checker guarantees to fill all boxes in the arg types
640 -> BoxyRhoType -- Result type
641 -> TcM (HsExpr TcId, results)
643 -- Call (f e1 ... en) :: res_ty
644 -- Type f :: forall a b c. theta => fa_1 -> ... -> fa_k -> fres
645 -- (where k <= n; fres has the rest)
646 -- NB: if k < n then the function doesn't have enough args, and
647 -- presumably fres is a type variable that we are going to
648 -- instantiate with a function type
650 -- Then fres <= bx_(k+1) -> ... -> bx_n -> res_ty
652 tcIdApp fun_name n_args arg_checker res_ty
653 = do { let orig = OccurrenceOf fun_name
654 ; (fun, fun_ty) <- lookupFun orig fun_name
656 -- Split up the function type
657 ; let (tv_theta_prs, rho) = tcMultiSplitSigmaTy fun_ty
658 (fun_arg_tys, fun_res_ty) = tcSplitFunTysN rho n_args
660 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
661 arg_qtvs = exactTyVarsOfTypes fun_arg_tys
662 res_qtvs = exactTyVarsOfType fun_res_ty
663 -- NB: exactTyVarsOfType. See Note [Silly type synonyms in smart-app]
664 tau_qtvs = arg_qtvs `unionVarSet` res_qtvs
665 k = length fun_arg_tys -- k <= n_args
666 n_missing_args = n_args - k -- Always >= 0
668 -- Match the result type of the function with the
669 -- result type of the context, to get an inital substitution
670 ; extra_arg_boxes <- newBoxyTyVars (replicate n_missing_args argTypeKind)
671 ; let extra_arg_tys' = mkTyVarTys extra_arg_boxes
672 res_ty' = mkFunTys extra_arg_tys' res_ty
673 ; qtys' <- preSubType qtvs tau_qtvs fun_res_ty res_ty'
675 -- Typecheck the arguments!
676 -- Doing so will fill arg_qtvs and extra_arg_tys'
677 ; (qtys'', args') <- arg_checker qtvs qtys' (fun_arg_tys ++ extra_arg_tys')
679 -- Strip boxes from the qtvs that have been filled in by the arg checking
680 ; extra_arg_tys'' <- mapM readFilledBox extra_arg_boxes
682 -- Result subsumption
683 -- This fills in res_qtvs
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 <- tcSubExp orig 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 orig fun res_subst tv_theta_prs
693 ; co_fn' <- wrapFunResCoercion (substTys res_subst fun_arg_tys) co_fn
694 ; traceTc (text "tcIdApp: " <+> ppr (mkHsWrap co_fn' fun') <+> ppr tv_theta_prs <+> ppr co_fn' <+> ppr fun')
695 ; return (mkHsWrap co_fn' fun', args') }
698 Note [Silly type synonyms in smart-app]
699 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
700 When we call sripBoxyType, all of the boxes should be filled
701 in. But we need to be careful about type synonyms:
705 In the call (f x) we'll typecheck x, expecting it to have type
706 (T box). Usually that would fill in the box, but in this case not;
707 because 'a' is discarded by the silly type synonym T. So we must
708 use exactTyVarsOfType to figure out which type variables are free
709 in the argument type.
712 -- tcId is a specialisation of tcIdApp when there are no arguments
713 -- tcId f ty = do { (res, _) <- tcIdApp f [] (\[] -> return ()) ty
718 -> BoxyRhoType -- Result type
720 tcId orig fun_name res_ty
721 = do { traceTc (text "tcId" <+> ppr fun_name <+> ppr res_ty)
722 ; (fun, fun_ty) <- lookupFun orig fun_name
724 -- Split up the function type
725 ; let (tv_theta_prs, fun_tau) = tcMultiSplitSigmaTy fun_ty
726 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
727 tau_qtvs = exactTyVarsOfType fun_tau -- Mentioned in the tau part
728 ; qtv_tys <- preSubType qtvs tau_qtvs fun_tau res_ty
730 -- Do the subsumption check wrt the result type
731 ; let res_subst = zipTopTvSubst qtvs qtv_tys
732 fun_tau' = substTy res_subst fun_tau
734 ; co_fn <- tcSubExp orig fun_tau' res_ty
736 -- And pack up the results
737 ; fun' <- instFun orig fun res_subst tv_theta_prs
738 ; traceTc (text "tcId yields" <+> ppr (mkHsWrap co_fn fun'))
739 ; return (mkHsWrap co_fn fun') }
741 -- Note [Push result type in]
743 -- Unify with expected result before (was: after) type-checking the args
744 -- so that the info from res_ty (was: args) percolates to args (was actual_res_ty).
745 -- This is when we might detect a too-few args situation.
746 -- (One can think of cases when the opposite order would give
747 -- a better error message.)
748 -- [March 2003: I'm experimenting with putting this first. Here's an
749 -- example where it actually makes a real difference
750 -- class C t a b | t a -> b
751 -- instance C Char a Bool
753 -- data P t a = forall b. (C t a b) => MkP b
754 -- data Q t = MkQ (forall a. P t a)
757 -- f1 = MkQ (MkP True)
758 -- f2 = MkQ (MkP True :: forall a. P Char a)
760 -- With the change, f1 will type-check, because the 'Char' info from
761 -- the signature is propagated into MkQ's argument. With the check
762 -- in the other order, the extra signature in f2 is reqd.]
764 ---------------------------
765 tcSyntaxOp :: InstOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
766 -- Typecheck a syntax operator, checking that it has the specified type
767 -- The operator is always a variable at this stage (i.e. renamer output)
768 tcSyntaxOp orig (HsVar op) ty = tcId orig op ty
769 tcSyntaxOp orig other ty = pprPanic "tcSyntaxOp" (ppr other)
771 ---------------------------
772 instFun :: InstOrigin
774 -> TvSubst -- The instantiating substitution
775 -> [([TyVar], ThetaType)] -- Stuff to instantiate
778 instFun orig fun subst []
779 = return fun -- Common short cut
781 instFun orig fun subst tv_theta_prs
782 = do { let ty_theta_prs' = map subst_pr tv_theta_prs
783 ; traceTc (text "instFun" <+> ppr ty_theta_prs')
784 -- Make two ad-hoc checks
785 ; doStupidChecks fun ty_theta_prs'
787 -- Now do normal instantiation
788 ; result <- go True fun ty_theta_prs'
789 ; traceTc (text "instFun result" <+> ppr result)
793 subst_pr (tvs, theta)
794 = (substTyVars subst tvs, substTheta subst theta)
796 go _ fun [] = do {traceTc (text "go _ fun [] returns" <+> ppr fun) ; return fun }
798 go True (HsVar fun_id) ((tys,theta) : prs)
799 | want_method_inst theta
800 = do { traceTc (text "go (HsVar fun_id) ((tys,theta) : prs) | want_method_inst theta")
801 ; meth_id <- newMethodWithGivenTy orig fun_id tys
802 ; go False (HsVar meth_id) prs }
803 -- Go round with 'False' to prevent further use
804 -- of newMethod: see Note [Multiple instantiation]
806 go _ fun ((tys, theta) : prs)
807 = do { co_fn <- instCall orig tys theta
808 ; traceTc (text "go yields co_fn" <+> ppr co_fn)
809 ; go False (HsWrap co_fn fun) prs }
811 -- See Note [No method sharing]
812 want_method_inst theta = not (null theta) -- Overloaded
813 && not opt_NoMethodSharing
816 Note [Multiple instantiation]
817 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
818 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
819 For example, consider
820 f :: forall a. Eq a => forall b. Ord b => a -> b
821 At a call to f, at say [Int, Bool], it's tempting to translate the call to
825 f_m1 :: forall b. Ord b => Int -> b
829 f_m2 = f_m1 Bool dOrdBool
831 But notice that f_m2 has f_m1 as its meth_id. Now the danger is that if we do
832 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
834 But it's entirely possible that f_m2 will continue to float out, because it
835 mentions no type variables. Result, f_m1 isn't in scope.
837 Here's a concrete example that does this (test tc200):
840 f :: Eq b => b -> a -> Int
841 baz :: Eq a => Int -> a -> Int
846 Current solution: only do the "method sharing" thing for the first type/dict
847 application, not for the iterated ones. A horribly subtle point.
849 Note [No method sharing]
850 ~~~~~~~~~~~~~~~~~~~~~~~~
851 The -fno-method-sharing flag controls what happens so far as the LIE
852 is concerned. The default case is that for an overloaded function we
853 generate a "method" Id, and add the Method Inst to the LIE. So you get
856 f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
857 If you specify -fno-method-sharing, the dictionary application
858 isn't shared, so we get
860 f = /\a (d:Num a) (x:a) -> (+) a d x x
861 This gets a bit less sharing, but
862 a) it's better for RULEs involving overloaded functions
863 b) perhaps fewer separated lambdas
867 tcArgs implements a left-to-right order, which goes beyond what is described in the
868 impredicative type inference paper. In particular, it allows
870 where runST :: (forall s. ST s a) -> a
871 When typechecking the application of ($)::(a->b) -> a -> b, we first check that
872 runST has type (a->b), thereby filling in a=forall s. ST s a. Then we un-box this type
873 before checking foo. The left-to-right order really helps here.
876 tcArgs :: LHsExpr Name -- The function (for error messages)
877 -> [LHsExpr Name] -- Actual args
878 -> ArgChecker [LHsExpr TcId]
880 type ArgChecker results
881 = [TyVar] -> [TcSigmaType] -- Current instantiation
882 -> [TcSigmaType] -- Expected arg types (**before** applying the instantiation)
883 -> TcM ([TcSigmaType], results) -- Resulting instaniation and args
885 tcArgs fun args qtvs qtys arg_tys
886 = go 1 qtys args arg_tys
888 go n qtys [] [] = return (qtys, [])
889 go n qtys (arg:args) (arg_ty:arg_tys)
890 = do { arg' <- tcArg fun n arg qtvs qtys arg_ty
891 ; qtys' <- mapM refineBox qtys -- Exploit new info
892 ; (qtys'', args') <- go (n+1) qtys' args arg_tys
893 ; return (qtys'', arg':args') }
894 go n qtys args arg_tys = panic "tcArgs"
896 tcArg :: LHsExpr Name -- The function
897 -> Int -- and arg number (for error messages)
899 -> [TyVar] -> [TcSigmaType] -- Instantiate the arg type like this
901 -> TcM (LHsExpr TcId) -- Resulting argument
902 tcArg fun arg_no arg qtvs qtys ty
903 = addErrCtxt (funAppCtxt fun arg arg_no) $
904 tcPolyExprNC arg (substTyWith qtvs qtys ty)
910 Nasty check to ensure that tagToEnum# is applied to a type that is an
911 enumeration TyCon. Unification may refine the type later, but this
912 check won't see that, alas. It's crude but it works.
914 Here's are two cases that should fail
916 f = tagToEnum# 0 -- Can't do tagToEnum# at a type variable
919 g = tagToEnum# 0 -- Int is not an enumeration
923 doStupidChecks :: HsExpr TcId
924 -> [([TcType], ThetaType)]
926 -- Check two tiresome and ad-hoc cases
927 -- (a) the "stupid theta" for a data con; add the constraints
928 -- from the "stupid theta" of a data constructor (sigh)
929 -- (b) deal with the tagToEnum# problem: see Note [tagToEnum#]
931 doStupidChecks (HsVar fun_id) ((tys,_):_)
932 | Just con <- isDataConId_maybe fun_id -- (a)
933 = addDataConStupidTheta con tys
935 | fun_id `hasKey` tagToEnumKey -- (b)
936 = do { tys' <- zonkTcTypes tys
937 ; checkTc (ok tys') (tagToEnumError tys')
941 ok (ty:tys) = case tcSplitTyConApp_maybe ty of
942 Just (tc,_) -> isEnumerationTyCon tc
945 doStupidChecks fun tv_theta_prs
946 = return () -- The common case
950 = hang (ptext SLIT("Bad call to tagToEnum#") <+> at_type)
951 2 (vcat [ptext SLIT("Specify the type by giving a type signature"),
952 ptext SLIT("e.g. (tagToEnum# x) :: Bool")])
954 at_type | null tys = empty -- Probably never happens
955 | otherwise = ptext SLIT("at type") <+> ppr (head tys)
958 %************************************************************************
960 \subsection{@tcId@ typechecks an identifier occurrence}
962 %************************************************************************
965 lookupFun :: InstOrigin -> Name -> TcM (HsExpr TcId, TcType)
966 lookupFun orig id_name
967 = do { thing <- tcLookup id_name
969 AGlobal (ADataCon con) -> return (HsVar wrap_id, idType wrap_id)
971 wrap_id = dataConWrapId con
974 | isNaughtyRecordSelector id -> failWithTc (naughtyRecordSel id)
975 | otherwise -> return (HsVar id, idType id)
976 -- A global cannot possibly be ill-staged
977 -- nor does it need the 'lifting' treatment
979 ATcId { tct_id = id, tct_type = ty, tct_co = mb_co, tct_level = lvl }
980 -> do { thLocalId orig id ty lvl
982 Unrefineable -> return (HsVar id, ty)
983 Rigid co -> return (mkHsWrap co (HsVar id), ty)
984 Wobbly -> traceTc (text "lookupFun" <+> ppr id) >> return (HsVar id, ty) -- Wobbly, or no free vars
985 WobblyInvisible -> failWithTc (ppr id_name <+> ptext SLIT(" not in scope because it has a wobbly type (solution: add a type annotation)"))
988 other -> failWithTc (ppr other <+> ptext SLIT("used where a value identifer was expected"))
991 #ifndef GHCI /* GHCI and TH is off */
992 --------------------------------------
993 -- thLocalId : Check for cross-stage lifting
994 thLocalId orig id id_ty th_bind_lvl
997 #else /* GHCI and TH is on */
998 thLocalId orig id id_ty th_bind_lvl
999 = do { use_stage <- getStage -- TH case
1001 Brack use_lvl ps_var lie_var | use_lvl > th_bind_lvl
1002 -> thBrackId orig id ps_var lie_var
1003 other -> do { checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage
1007 --------------------------------------
1008 thBrackId orig id ps_var lie_var
1010 = -- Top-level identifiers in this module,
1011 -- (which have External Names)
1012 -- are just like the imported case:
1013 -- no need for the 'lifting' treatment
1014 -- E.g. this is fine:
1017 -- But we do need to put f into the keep-alive
1018 -- set, because after desugaring the code will
1019 -- only mention f's *name*, not f itself.
1020 do { keepAliveTc id; return id }
1023 = -- Nested identifiers, such as 'x' in
1024 -- E.g. \x -> [| h x |]
1025 -- We must behave as if the reference to x was
1027 -- We use 'x' itself as the splice proxy, used by
1028 -- the desugarer to stitch it all back together.
1029 -- If 'x' occurs many times we may get many identical
1030 -- bindings of the same splice proxy, but that doesn't
1031 -- matter, although it's a mite untidy.
1032 do { let id_ty = idType id
1033 ; checkTc (isTauTy id_ty) (polySpliceErr id)
1034 -- If x is polymorphic, its occurrence sites might
1035 -- have different instantiations, so we can't use plain
1036 -- 'x' as the splice proxy name. I don't know how to
1037 -- solve this, and it's probably unimportant, so I'm
1038 -- just going to flag an error for now
1040 ; id_ty' <- zapToMonotype id_ty
1041 -- The id_ty might have an OpenTypeKind, but we
1042 -- can't instantiate the Lift class at that kind,
1043 -- so we zap it to a LiftedTypeKind monotype
1044 -- C.f. the call in TcPat.newLitInst
1046 ; setLIEVar lie_var $ do
1047 { lift <- newMethodFromName orig id_ty' DsMeta.liftName
1048 -- Put the 'lift' constraint into the right LIE
1050 -- Update the pending splices
1051 ; ps <- readMutVar ps_var
1052 ; writeMutVar ps_var ((idName id, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps)
1059 %************************************************************************
1061 \subsection{Record bindings}
1063 %************************************************************************
1065 Game plan for record bindings
1066 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1067 1. Find the TyCon for the bindings, from the first field label.
1069 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1071 For each binding field = value
1073 3. Instantiate the field type (from the field label) using the type
1076 4 Type check the value using tcArg, passing the field type as
1077 the expected argument type.
1079 This extends OK when the field types are universally quantified.
1085 -> [TcType] -- Expected type for each field
1086 -> HsRecordBinds Name
1087 -> TcM (HsRecordBinds TcId)
1089 tcRecordBinds data_con arg_tys (HsRecFields rbinds dd)
1090 = do { mb_binds <- mapM do_bind rbinds
1091 ; return (HsRecFields (catMaybes mb_binds) dd) }
1093 flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1094 do_bind fld@(HsRecField { hsRecFieldId = L loc field_lbl, hsRecFieldArg = rhs })
1095 | Just field_ty <- assocMaybe flds_w_tys field_lbl
1096 = addErrCtxt (fieldCtxt field_lbl) $
1097 do { rhs' <- tcPolyExprNC rhs field_ty
1098 ; sel_id <- tcLookupField field_lbl
1099 ; ASSERT( isRecordSelector sel_id )
1100 return (Just (fld { hsRecFieldId = L loc sel_id, hsRecFieldArg = rhs' })) }
1102 = do { addErrTc (badFieldCon data_con field_lbl)
1105 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1106 checkMissingFields data_con rbinds
1107 | null field_labels -- Not declared as a record;
1108 -- But C{} is still valid if no strict fields
1109 = if any isMarkedStrict field_strs then
1110 -- Illegal if any arg is strict
1111 addErrTc (missingStrictFields data_con [])
1115 | otherwise = do -- A record
1116 unless (null missing_s_fields)
1117 (addErrTc (missingStrictFields data_con missing_s_fields))
1119 warn <- doptM Opt_WarnMissingFields
1120 unless (not (warn && notNull missing_ns_fields))
1121 (warnTc True (missingFields data_con missing_ns_fields))
1125 = [ fl | (fl, str) <- field_info,
1127 not (fl `elem` field_names_used)
1130 = [ fl | (fl, str) <- field_info,
1131 not (isMarkedStrict str),
1132 not (fl `elem` field_names_used)
1135 field_names_used = hsRecFields rbinds
1136 field_labels = dataConFieldLabels data_con
1138 field_info = zipEqual "missingFields"
1142 field_strs = dataConStrictMarks data_con
1145 %************************************************************************
1147 \subsection{Errors and contexts}
1149 %************************************************************************
1151 Boring and alphabetical:
1154 = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1157 = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1159 fieldCtxt field_name
1160 = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1162 funAppCtxt fun arg arg_no
1163 = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"),
1164 quotes (ppr fun) <> text ", namely"])
1165 4 (quotes (ppr arg))
1168 = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1171 = vcat [ptext SLIT("Record update for the non-Haskell-98 data type")
1172 <+> quotes (pprSourceTyCon tycon)
1173 <+> ptext SLIT("is not (yet) supported"),
1174 ptext SLIT("Use pattern-matching instead")]
1176 = hang (ptext SLIT("No constructor has all these fields:"))
1177 4 (pprQuotedList (hsRecFields rbinds))
1179 naughtyRecordSel sel_id
1180 = ptext SLIT("Cannot use record selector") <+> quotes (ppr sel_id) <+>
1181 ptext SLIT("as a function due to escaped type variables") $$
1182 ptext SLIT("Probably fix: use pattern-matching syntax instead")
1185 = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1187 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1188 missingStrictFields con fields
1191 rest | null fields = empty -- Happens for non-record constructors
1192 -- with strict fields
1193 | otherwise = colon <+> pprWithCommas ppr fields
1195 header = ptext SLIT("Constructor") <+> quotes (ppr con) <+>
1196 ptext SLIT("does not have the required strict field(s)")
1198 missingFields :: DataCon -> [FieldLabel] -> SDoc
1199 missingFields con fields
1200 = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:")
1201 <+> pprWithCommas ppr fields
1203 -- callCtxt fun args = ptext SLIT("In the call") <+> parens (ppr (foldl mkHsApp fun args))
1206 polySpliceErr :: Id -> SDoc
1208 = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)