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, tcInferRhoNC, 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 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 Nothing $ \ _ res_ty ->
89 tcPolyExprNC expr res_ty
90 -- Note the recursive call to tcPolyExpr, because the
91 -- type may have multiple layers of for-alls
92 -- E.g. forall a. Eq a => forall b. Ord b => ....
93 ; return (mkLHsWrap gen_fn expr') }
96 = tcMonoExprNC expr res_ty
99 tcPolyExprs :: [LHsExpr Name] -> [TcType] -> TcM [LHsExpr TcId]
100 tcPolyExprs [] [] = return []
101 tcPolyExprs (expr:exprs) (ty:tys)
102 = do { expr' <- tcPolyExpr expr ty
103 ; exprs' <- tcPolyExprs exprs tys
104 ; return (expr':exprs') }
105 tcPolyExprs exprs tys = pprPanic "tcPolyExprs" (ppr exprs $$ ppr tys)
108 tcMonoExpr, tcMonoExprNC
109 :: LHsExpr Name -- Expression to type check
110 -> BoxyRhoType -- Expected type (could be a type variable)
111 -- Definitely no foralls at the top
112 -- Can contain boxes, which will be filled in
113 -> TcM (LHsExpr TcId)
115 tcMonoExpr expr res_ty
116 = addErrCtxt (exprCtxt expr) $
117 tcMonoExprNC expr res_ty
119 tcMonoExprNC (L loc expr) res_ty
120 = ASSERT( not (isSigmaTy res_ty) )
122 do { expr' <- tcExpr expr res_ty
123 ; return (L loc expr') }
126 tcInferRho, tcInferRhoNC :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
127 tcInferRho expr = tcInfer (tcMonoExpr expr)
128 tcInferRhoNC expr = tcInfer (tcMonoExprNC expr)
132 %************************************************************************
134 tcExpr: the main expression typechecker
136 %************************************************************************
139 tcExpr :: HsExpr Name -> BoxyRhoType -> TcM (HsExpr TcId)
140 tcExpr e res_ty | debugIsOn && isSigmaTy res_ty -- Sanity check
141 = pprPanic "tcExpr: sigma" (ppr res_ty $$ ppr e)
143 tcExpr (HsVar name) res_ty = tcId (OccurrenceOf name) name res_ty
145 tcExpr (HsLit lit) res_ty = do { let lit_ty = hsLitType lit
146 ; coi <- boxyUnify lit_ty res_ty
147 ; return $ mkHsWrapCoI coi (HsLit lit)
150 tcExpr (HsPar expr) res_ty = do { expr' <- tcMonoExprNC expr res_ty
151 ; return (HsPar expr') }
153 tcExpr (HsSCC lbl expr) res_ty = do { expr' <- tcMonoExpr expr res_ty
154 ; return (HsSCC lbl expr') }
155 tcExpr (HsTickPragma info expr) res_ty
156 = do { expr' <- tcMonoExpr expr res_ty
157 ; return (HsTickPragma info expr') }
159 tcExpr (HsCoreAnn lbl expr) res_ty -- hdaume: core annotation
160 = do { expr' <- tcMonoExpr expr res_ty
161 ; return (HsCoreAnn lbl expr') }
163 tcExpr (HsOverLit lit) res_ty
164 = do { lit' <- tcOverloadedLit (LiteralOrigin lit) lit res_ty
165 ; return (HsOverLit lit') }
167 tcExpr (NegApp expr neg_expr) res_ty
168 = do { neg_expr' <- tcSyntaxOp NegateOrigin neg_expr
169 (mkFunTy res_ty res_ty)
170 ; expr' <- tcMonoExpr expr res_ty
171 ; return (NegApp expr' neg_expr') }
173 tcExpr (HsIPVar ip) res_ty
174 = do { let origin = IPOccOrigin ip
175 -- Implicit parameters must have a *tau-type* not a
176 -- type scheme. We enforce this by creating a fresh
177 -- type variable as its type. (Because res_ty may not
179 ; ip_ty <- newFlexiTyVarTy argTypeKind -- argTypeKind: it can't be an unboxed tuple
180 ; co_fn <- tcSubExp origin ip_ty res_ty
181 ; (ip', inst) <- newIPDict origin ip ip_ty
183 ; return (mkHsWrap co_fn (HsIPVar ip')) }
185 tcExpr (HsApp e1 e2) res_ty
188 go :: LHsExpr Name -> [LHsExpr Name] -> TcM (HsExpr TcId)
189 go (L _ (HsApp e1 e2)) args = go e1 (e2:args)
190 go lfun@(L loc fun) args
191 = do { (fun', args') <- -- addErrCtxt (callCtxt lfun args) $
192 tcApp fun (length args) (tcArgs lfun args) res_ty
193 ; traceTc (text "tcExpr args': " <+> ppr args')
194 ; return (unLoc (foldl mkHsApp (L loc fun') args')) }
196 tcExpr (HsLam match) res_ty
197 = do { (co_fn, match') <- tcMatchLambda match res_ty
198 ; return (mkHsWrap co_fn (HsLam match')) }
200 tcExpr in_expr@(ExprWithTySig expr sig_ty) res_ty
201 = do { sig_tc_ty <- tcHsSigType ExprSigCtxt sig_ty
203 -- Remember to extend the lexical type-variable environment
204 ; (gen_fn, expr') <- tcGen sig_tc_ty emptyVarSet (Just ExprSigCtxt) $ \ skol_tvs res_ty ->
205 tcExtendTyVarEnv2 (hsExplicitTvs sig_ty `zip` mkTyVarTys skol_tvs) $
206 -- See Note [More instantiated than scoped] in TcBinds
207 tcMonoExprNC expr res_ty
209 ; co_fn <- tcSubExp ExprSigOrigin sig_tc_ty res_ty
210 ; return (mkHsWrap co_fn (ExprWithTySigOut (mkLHsWrap gen_fn expr') sig_ty)) }
212 tcExpr (HsType ty) res_ty
213 = failWithTc (text "Can't handle type argument:" <+> ppr ty)
214 -- This is the syntax for type applications that I was planning
215 -- but there are difficulties (e.g. what order for type args)
216 -- so it's not enabled yet.
217 -- Can't eliminate it altogether from the parser, because the
218 -- same parser parses *patterns*.
222 %************************************************************************
224 Infix operators and sections
226 %************************************************************************
229 tcExpr in_expr@(OpApp arg1 lop@(L loc op) fix arg2) res_ty
230 = do { (op', [arg1', arg2']) <- tcApp op 2 (tcArgs lop [arg1,arg2]) res_ty
231 ; return (OpApp arg1' (L loc op') fix arg2') }
233 -- Left sections, equivalent to
237 -- or, if PostfixOperators is enabled, just
240 -- With PostfixOperators we don't
241 -- actually require the function to take two arguments
242 -- at all. For example, (x `not`) means (not x);
243 -- you get postfix operators! Not Haskell 98,
244 -- but it's less work and kind of useful.
246 tcExpr in_expr@(SectionL arg1 lop@(L loc op)) res_ty
247 = do dflags <- getDOpts
248 if dopt Opt_PostfixOperators dflags
249 then do (op', [arg1']) <- tcApp op 1 (tcArgs lop [arg1]) res_ty
250 return (SectionL arg1' (L loc op'))
251 else do (co_fn, (op', arg1'))
252 <- subFunTys doc 1 res_ty Nothing
253 $ \ [arg2_ty'] res_ty' ->
254 tcApp op 2 (tc_args arg2_ty') res_ty'
255 return (mkHsWrap co_fn (SectionL arg1' (L loc op')))
257 doc = ptext (sLit "The section") <+> quotes (ppr in_expr)
258 <+> ptext (sLit "takes one argument")
259 tc_args arg2_ty' qtvs qtys [arg1_ty, arg2_ty]
260 = do { boxyUnify arg2_ty' (substTyWith qtvs qtys arg2_ty)
261 ; arg1' <- tcArg lop 2 arg1 qtvs qtys arg1_ty
262 ; qtys' <- mapM refineBox qtys -- c.f. tcArgs
263 ; return (qtys', arg1') }
264 tc_args _ _ _ _ = panic "tcExpr SectionL"
266 -- Right sections, equivalent to \ x -> x `op` expr, or
269 tcExpr in_expr@(SectionR lop@(L loc op) arg2) res_ty
270 = do { (co_fn, (op', arg2')) <- subFunTys doc 1 res_ty Nothing $ \ [arg1_ty'] res_ty' ->
271 tcApp op 2 (tc_args arg1_ty') res_ty'
272 ; return (mkHsWrap co_fn (SectionR (L loc op') arg2')) }
274 doc = ptext (sLit "The section") <+> quotes (ppr in_expr)
275 <+> ptext (sLit "takes one argument")
276 tc_args arg1_ty' qtvs qtys [arg1_ty, arg2_ty]
277 = do { boxyUnify arg1_ty' (substTyWith qtvs qtys arg1_ty)
278 ; arg2' <- tcArg lop 2 arg2 qtvs qtys arg2_ty
279 ; qtys' <- mapM refineBox qtys -- c.f. tcArgs
280 ; return (qtys', arg2') }
281 tc_args arg1_ty' _ _ _ = panic "tcExpr SectionR"
285 tcExpr (HsLet binds expr) res_ty
286 = do { (binds', expr') <- tcLocalBinds binds $
287 tcMonoExpr expr res_ty
288 ; return (HsLet binds' expr') }
290 tcExpr (HsCase scrut matches) exp_ty
291 = do { -- We used to typecheck the case alternatives first.
292 -- The case patterns tend to give good type info to use
293 -- when typechecking the scrutinee. For example
296 -- will report that map is applied to too few arguments
298 -- But now, in the GADT world, we need to typecheck the scrutinee
299 -- first, to get type info that may be refined in the case alternatives
300 (scrut', scrut_ty) <- tcInferRho scrut
302 ; traceTc (text "HsCase" <+> ppr scrut_ty)
303 ; matches' <- tcMatchesCase match_ctxt scrut_ty matches exp_ty
304 ; return (HsCase scrut' matches') }
306 match_ctxt = MC { mc_what = CaseAlt,
309 tcExpr (HsIf pred b1 b2) res_ty
310 = do { pred' <- tcMonoExpr pred boolTy
311 ; b1' <- tcMonoExpr b1 res_ty
312 ; b2' <- tcMonoExpr b2 res_ty
313 ; return (HsIf pred' b1' b2') }
315 tcExpr (HsDo do_or_lc stmts body _) res_ty
316 = tcDoStmts do_or_lc stmts body res_ty
318 tcExpr in_expr@(ExplicitList _ exprs) res_ty
319 = do { (elt_ty, coi) <- boxySplitListTy res_ty
320 ; exprs' <- mapM (tc_elt elt_ty) exprs
321 ; when (null exprs) (zapToMonotype elt_ty >> return ())
322 -- If there are no expressions in the comprehension
323 -- we must still fill in the box
325 -- The GHC front end never generates an empty ExplicitList
326 -- (instead it generates the [] data constructor) but
327 -- Template Haskell might. We could fix the bit of
328 -- TH that generates ExplicitList, but it seems less
329 -- fragile to just handle the case here.
330 ; return $ mkHsWrapCoI coi (ExplicitList elt_ty exprs') }
332 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
334 tcExpr in_expr@(ExplicitPArr _ exprs) res_ty -- maybe empty
335 = do { (elt_ty, coi) <- boxySplitPArrTy res_ty
336 ; exprs' <- mapM (tc_elt elt_ty) exprs
337 ; when (null exprs) (zapToMonotype elt_ty >> return ())
338 -- If there are no expressions in the comprehension
339 -- we must still fill in the box
340 -- (Not needed for [] and () becuase they happen
341 -- to parse as data constructors.)
342 ; return $ mkHsWrapCoI coi (ExplicitPArr elt_ty exprs') }
344 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
346 -- For tuples, take care to preserve rigidity
347 -- E.g. case (x,y) of ....
348 -- The scrutinee should have a rigid type if x,y do
349 -- The general scheme is the same as in tcIdApp
350 tcExpr (ExplicitTuple exprs boxity) res_ty
351 = do { let kind = case boxity of { Boxed -> liftedTypeKind
352 ; Unboxed -> argTypeKind }
353 ; tvs <- newBoxyTyVars [kind | e <- exprs]
354 ; let tup_tc = tupleTyCon boxity (length exprs)
355 tup_res_ty = mkTyConApp tup_tc (mkTyVarTys tvs)
356 ; checkWiredInTyCon tup_tc -- Ensure instances are available
357 ; arg_tys <- preSubType tvs (mkVarSet tvs) tup_res_ty res_ty
358 ; exprs' <- tcPolyExprs exprs arg_tys
359 ; arg_tys' <- mapM refineBox arg_tys
360 ; co_fn <- tcSubExp TupleOrigin (mkTyConApp tup_tc arg_tys') res_ty
361 ; return (mkHsWrap co_fn (ExplicitTuple exprs' boxity)) }
363 tcExpr (HsProc pat cmd) res_ty
364 = do { (pat', cmd', coi) <- tcProc pat cmd res_ty
365 ; return $ mkHsWrapCoI coi (HsProc pat' cmd') }
367 tcExpr e@(HsArrApp _ _ _ _ _) _
368 = failWithTc (vcat [ptext (sLit "The arrow command"), nest 2 (ppr e),
369 ptext (sLit "was found where an expression was expected")])
371 tcExpr e@(HsArrForm _ _ _) _
372 = failWithTc (vcat [ptext (sLit "The arrow command"), nest 2 (ppr e),
373 ptext (sLit "was found where an expression was expected")])
376 %************************************************************************
378 Record construction and update
380 %************************************************************************
383 tcExpr expr@(RecordCon (L loc con_name) _ rbinds) res_ty
384 = do { data_con <- tcLookupDataCon con_name
386 -- Check for missing fields
387 ; checkMissingFields data_con rbinds
389 ; let arity = dataConSourceArity data_con
390 check_fields qtvs qtys arg_tys
391 = do { let arg_tys' = substTys (zipOpenTvSubst qtvs qtys) arg_tys
392 ; rbinds' <- tcRecordBinds data_con arg_tys' rbinds
393 ; qtys' <- mapM refineBoxToTau qtys
394 ; return (qtys', rbinds') }
395 -- The refineBoxToTau ensures that all the boxes in arg_tys are indeed
396 -- filled, which is the invariant expected by tcIdApp
397 -- How could this not be the case? Consider a record construction
398 -- that does not mention all the fields.
400 ; (con_expr, rbinds') <- tcIdApp con_name arity check_fields res_ty
402 ; return (RecordCon (L loc (dataConWrapId data_con)) con_expr rbinds') }
404 -- The main complication with RecordUpd is that we need to explicitly
405 -- handle the *non-updated* fields. Consider:
407 -- data T a b = MkT1 { fa :: a, fb :: b }
408 -- | MkT2 { fa :: a, fc :: Int -> Int }
409 -- | MkT3 { fd :: a }
411 -- upd :: T a b -> c -> T a c
412 -- upd t x = t { fb = x}
414 -- The type signature on upd is correct (i.e. the result should not be (T a b))
415 -- because upd should be equivalent to:
417 -- upd t x = case t of
418 -- MkT1 p q -> MkT1 p x
419 -- MkT2 a b -> MkT2 p b
420 -- MkT3 d -> error ...
422 -- So we need to give a completely fresh type to the result record,
423 -- and then constrain it by the fields that are *not* updated ("p" above).
425 -- Note that because MkT3 doesn't contain all the fields being updated,
426 -- its RHS is simply an error, so it doesn't impose any type constraints
428 -- All this is done in STEP 4 below.
432 -- For record update we require that every constructor involved in the
433 -- update (i.e. that has all the specified fields) is "vanilla". I
434 -- don't know how to do the update otherwise.
437 tcExpr expr@(RecordUpd record_expr rbinds _ _ _) res_ty = do
439 -- Check that the field names are really field names
441 field_names = hsRecFields rbinds
443 MASSERT( notNull field_names )
444 sel_ids <- mapM tcLookupField field_names
445 -- The renamer has already checked that they
448 bad_guys = [ setSrcSpan loc $ addErrTc (notSelector field_name)
449 | (fld, sel_id) <- rec_flds rbinds `zip` sel_ids,
450 not (isRecordSelector sel_id), -- Excludes class ops
451 let L loc field_name = hsRecFieldId fld
454 unless (null bad_guys) (sequence bad_guys >> failM)
457 -- Figure out the tycon and data cons from the first field name
459 -- It's OK to use the non-tc splitters here (for a selector)
461 (tycon, _) = recordSelectorFieldLabel sel_id -- We've failed already if
462 data_cons = tyConDataCons tycon -- it's not a field label
463 -- NB: for a data type family, the tycon is the instance tycon
465 relevant_cons = filter is_relevant data_cons
466 is_relevant con = all (`elem` dataConFieldLabels con) field_names
469 -- Check that at least one constructor has all the named fields
470 -- i.e. has an empty set of bad fields returned by badFields
471 checkTc (not (null relevant_cons))
472 (badFieldsUpd rbinds)
474 -- Check that all relevant data cons are vanilla. Doing record updates on
475 -- GADTs and/or existentials is more than my tiny brain can cope with today
476 checkTc (all isVanillaDataCon relevant_cons)
477 (nonVanillaUpd tycon)
480 -- Use the un-updated fields to find a vector of booleans saying
481 -- which type arguments must be the same in updatee and result.
483 -- WARNING: this code assumes that all data_cons in a common tycon
484 -- have FieldLabels abstracted over the same tyvars.
486 -- A constructor is only relevant to this process if
487 -- it contains *all* the fields that are being updated
488 con1 = ASSERT( not (null relevant_cons) ) head relevant_cons -- A representative constructor
489 (con1_tyvars, theta, con1_arg_tys, con1_res_ty) = dataConSig con1
490 con1_flds = dataConFieldLabels con1
491 common_tyvars = exactTyVarsOfTypes [ty | (fld,ty) <- con1_flds `zip` con1_arg_tys
492 , not (fld `elem` field_names) ]
494 is_common_tv tv = tv `elemVarSet` common_tyvars
496 mk_inst_ty tv result_inst_ty
497 | is_common_tv tv = return result_inst_ty -- Same as result type
498 | otherwise = newFlexiTyVarTy (tyVarKind tv) -- Fresh type, of correct kind
500 MASSERT( null theta ) -- Vanilla datacon
501 (_, result_inst_tys, result_inst_env) <- tcInstTyVars con1_tyvars
502 scrut_inst_tys <- zipWithM mk_inst_ty con1_tyvars result_inst_tys
504 -- STEP 3: Typecheck the update bindings.
505 -- Do this after checking for bad fields in case
506 -- there's a field that doesn't match the constructor.
508 result_ty = substTy result_inst_env con1_res_ty
509 con1_arg_tys' = map (substTy result_inst_env) con1_arg_tys
510 origin = RecordUpdOrigin
512 co_fn <- tcSubExp origin result_ty res_ty
513 rbinds' <- tcRecordBinds con1 con1_arg_tys' rbinds
515 -- STEP 5: Typecheck the expression to be updated
517 scrut_inst_env = zipTopTvSubst con1_tyvars scrut_inst_tys
518 scrut_ty = substTy scrut_inst_env con1_res_ty
519 -- This is one place where the isVanilla check is important
520 -- So that inst_tys matches the con1_tyvars
522 record_expr' <- tcMonoExpr record_expr scrut_ty
524 -- STEP 6: Figure out the LIE we need.
525 -- We have to generate some dictionaries for the data type context,
526 -- since we are going to do pattern matching over the data cons.
528 -- What dictionaries do we need? The dataConStupidTheta tells us.
530 theta' = substTheta scrut_inst_env (dataConStupidTheta con1)
532 instStupidTheta origin theta'
534 -- Step 7: make a cast for the scrutinee, in the case that it's from a type family
535 let scrut_co | Just co_con <- tyConFamilyCoercion_maybe tycon
536 = WpCast $ mkTyConApp co_con scrut_inst_tys
541 return (mkHsWrap co_fn (RecordUpd (mkLHsWrap scrut_co record_expr') rbinds'
542 relevant_cons scrut_inst_tys result_inst_tys))
546 %************************************************************************
548 Arithmetic sequences e.g. [a,b..]
549 and their parallel-array counterparts e.g. [: a,b.. :]
552 %************************************************************************
555 tcExpr (ArithSeq _ seq@(From expr)) res_ty
556 = do { (elt_ty, coi) <- boxySplitListTy res_ty
557 ; expr' <- tcPolyExpr expr elt_ty
558 ; enum_from <- newMethodFromName (ArithSeqOrigin seq)
560 ; return $ mkHsWrapCoI coi (ArithSeq (HsVar enum_from) (From expr')) }
562 tcExpr in_expr@(ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
563 = do { (elt_ty, coi) <- boxySplitListTy res_ty
564 ; expr1' <- tcPolyExpr expr1 elt_ty
565 ; expr2' <- tcPolyExpr expr2 elt_ty
566 ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq)
567 elt_ty enumFromThenName
568 ; return $ mkHsWrapCoI coi
569 (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2')) }
571 tcExpr in_expr@(ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
572 = do { (elt_ty, coi) <- boxySplitListTy res_ty
573 ; expr1' <- tcPolyExpr expr1 elt_ty
574 ; expr2' <- tcPolyExpr expr2 elt_ty
575 ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq)
576 elt_ty enumFromToName
577 ; return $ mkHsWrapCoI coi
578 (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
580 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
581 = do { (elt_ty, coi) <- boxySplitListTy res_ty
582 ; expr1' <- tcPolyExpr expr1 elt_ty
583 ; expr2' <- tcPolyExpr expr2 elt_ty
584 ; expr3' <- tcPolyExpr expr3 elt_ty
585 ; eft <- newMethodFromName (ArithSeqOrigin seq)
586 elt_ty enumFromThenToName
587 ; return $ mkHsWrapCoI coi
588 (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
590 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
591 = do { (elt_ty, coi) <- boxySplitPArrTy res_ty
592 ; expr1' <- tcPolyExpr expr1 elt_ty
593 ; expr2' <- tcPolyExpr expr2 elt_ty
594 ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq)
595 elt_ty enumFromToPName
596 ; return $ mkHsWrapCoI coi
597 (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
599 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
600 = do { (elt_ty, coi) <- boxySplitPArrTy res_ty
601 ; expr1' <- tcPolyExpr expr1 elt_ty
602 ; expr2' <- tcPolyExpr expr2 elt_ty
603 ; expr3' <- tcPolyExpr expr3 elt_ty
604 ; eft <- newMethodFromName (PArrSeqOrigin seq)
605 elt_ty enumFromThenToPName
606 ; return $ mkHsWrapCoI coi
607 (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
609 tcExpr (PArrSeq _ _) _
610 = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
611 -- the parser shouldn't have generated it and the renamer shouldn't have
616 %************************************************************************
620 %************************************************************************
623 #ifdef GHCI /* Only if bootstrapped */
624 -- Rename excludes these cases otherwise
625 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
626 tcExpr (HsBracket brack) res_ty = do { e <- tcBracket brack res_ty
628 tcExpr e@(HsQuasiQuoteE _) res_ty =
629 pprPanic "Should never see HsQuasiQuoteE in type checker" (ppr e)
634 %************************************************************************
638 %************************************************************************
641 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
645 %************************************************************************
649 %************************************************************************
652 ---------------------------
653 tcApp :: HsExpr Name -- Function
654 -> Arity -- Number of args reqd
655 -> ArgChecker results
656 -> BoxyRhoType -- Result type
657 -> TcM (HsExpr TcId, results)
659 -- (tcFun fun n_args arg_checker res_ty)
660 -- The argument type checker, arg_checker, will be passed exactly n_args types
662 tcApp (HsVar fun_name) n_args arg_checker res_ty
663 = tcIdApp fun_name n_args arg_checker res_ty
665 tcApp fun n_args arg_checker res_ty -- The vanilla case (rula APP)
666 = do { arg_boxes <- newBoxyTyVars (replicate n_args argTypeKind)
667 ; fun' <- tcExpr fun (mkFunTys (mkTyVarTys arg_boxes) res_ty)
668 ; arg_tys' <- mapM readFilledBox arg_boxes
669 ; (_, args') <- arg_checker [] [] arg_tys' -- Yuk
670 ; return (fun', args') }
672 ---------------------------
673 tcIdApp :: Name -- Function
674 -> Arity -- Number of args reqd
675 -> ArgChecker results -- The arg-checker guarantees to fill all boxes in the arg types
676 -> BoxyRhoType -- Result type
677 -> TcM (HsExpr TcId, results)
679 -- Call (f e1 ... en) :: res_ty
680 -- Type f :: forall a b c. theta => fa_1 -> ... -> fa_k -> fres
681 -- (where k <= n; fres has the rest)
682 -- NB: if k < n then the function doesn't have enough args, and
683 -- presumably fres is a type variable that we are going to
684 -- instantiate with a function type
686 -- Then fres <= bx_(k+1) -> ... -> bx_n -> res_ty
688 tcIdApp fun_name n_args arg_checker res_ty
689 = do { let orig = OccurrenceOf fun_name
690 ; (fun, fun_ty) <- lookupFun orig fun_name
692 -- Split up the function type
693 ; let (tv_theta_prs, rho) = tcMultiSplitSigmaTy fun_ty
694 (fun_arg_tys, fun_res_ty) = tcSplitFunTysN rho n_args
696 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
697 arg_qtvs = exactTyVarsOfTypes fun_arg_tys
698 res_qtvs = exactTyVarsOfType fun_res_ty
699 -- NB: exactTyVarsOfType. See Note [Silly type synonyms in smart-app]
700 tau_qtvs = arg_qtvs `unionVarSet` res_qtvs
701 k = length fun_arg_tys -- k <= n_args
702 n_missing_args = n_args - k -- Always >= 0
704 -- Match the result type of the function with the
705 -- result type of the context, to get an inital substitution
706 ; extra_arg_boxes <- newBoxyTyVars (replicate n_missing_args argTypeKind)
707 ; let extra_arg_tys' = mkTyVarTys extra_arg_boxes
708 res_ty' = mkFunTys extra_arg_tys' res_ty
709 ; qtys' <- preSubType qtvs tau_qtvs fun_res_ty res_ty'
711 -- Typecheck the arguments!
712 -- Doing so will fill arg_qtvs and extra_arg_tys'
713 ; (qtys'', args') <- arg_checker qtvs qtys' (fun_arg_tys ++ extra_arg_tys')
715 -- Strip boxes from the qtvs that have been filled in by the arg checking
716 ; extra_arg_tys'' <- mapM readFilledBox extra_arg_boxes
718 -- Result subsumption
719 -- This fills in res_qtvs
720 ; let res_subst = zipOpenTvSubst qtvs qtys''
721 fun_res_ty'' = substTy res_subst fun_res_ty
722 res_ty'' = mkFunTys extra_arg_tys'' res_ty
723 ; co_fn <- tcSubExp orig fun_res_ty'' res_ty''
725 -- And pack up the results
726 -- By applying the coercion just to the *function* we can make
727 -- tcFun work nicely for OpApp and Sections too
728 ; fun' <- instFun orig fun res_subst tv_theta_prs
729 ; co_fn' <- wrapFunResCoercion (substTys res_subst fun_arg_tys) co_fn
730 ; traceTc (text "tcIdApp: " <+> ppr (mkHsWrap co_fn' fun') <+> ppr tv_theta_prs <+> ppr co_fn' <+> ppr fun')
731 ; return (mkHsWrap co_fn' fun', args') }
734 Note [Silly type synonyms in smart-app]
735 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
736 When we call sripBoxyType, all of the boxes should be filled
737 in. But we need to be careful about type synonyms:
741 In the call (f x) we'll typecheck x, expecting it to have type
742 (T box). Usually that would fill in the box, but in this case not;
743 because 'a' is discarded by the silly type synonym T. So we must
744 use exactTyVarsOfType to figure out which type variables are free
745 in the argument type.
748 -- tcId is a specialisation of tcIdApp when there are no arguments
749 -- tcId f ty = do { (res, _) <- tcIdApp f [] (\[] -> return ()) ty
754 -> BoxyRhoType -- Result type
756 tcId orig fun_name res_ty
757 = do { traceTc (text "tcId" <+> ppr fun_name <+> ppr res_ty)
758 ; (fun, fun_ty) <- lookupFun orig fun_name
760 -- Split up the function type
761 ; let (tv_theta_prs, fun_tau) = tcMultiSplitSigmaTy fun_ty
762 qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
763 tau_qtvs = exactTyVarsOfType fun_tau -- Mentioned in the tau part
764 ; qtv_tys <- preSubType qtvs tau_qtvs fun_tau res_ty
766 -- Do the subsumption check wrt the result type
767 ; let res_subst = zipTopTvSubst qtvs qtv_tys
768 fun_tau' = substTy res_subst fun_tau
770 ; co_fn <- tcSubExp orig fun_tau' res_ty
772 -- And pack up the results
773 ; fun' <- instFun orig fun res_subst tv_theta_prs
774 ; traceTc (text "tcId yields" <+> ppr (mkHsWrap co_fn fun'))
775 ; return (mkHsWrap co_fn fun') }
777 -- Note [Push result type in]
779 -- Unify with expected result before (was: after) type-checking the args
780 -- so that the info from res_ty (was: args) percolates to args (was actual_res_ty).
781 -- This is when we might detect a too-few args situation.
782 -- (One can think of cases when the opposite order would give
783 -- a better error message.)
784 -- [March 2003: I'm experimenting with putting this first. Here's an
785 -- example where it actually makes a real difference
786 -- class C t a b | t a -> b
787 -- instance C Char a Bool
789 -- data P t a = forall b. (C t a b) => MkP b
790 -- data Q t = MkQ (forall a. P t a)
793 -- f1 = MkQ (MkP True)
794 -- f2 = MkQ (MkP True :: forall a. P Char a)
796 -- With the change, f1 will type-check, because the 'Char' info from
797 -- the signature is propagated into MkQ's argument. With the check
798 -- in the other order, the extra signature in f2 is reqd.]
800 ---------------------------
801 tcSyntaxOp :: InstOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
802 -- Typecheck a syntax operator, checking that it has the specified type
803 -- The operator is always a variable at this stage (i.e. renamer output)
804 tcSyntaxOp orig (HsVar op) ty = tcId orig op ty
805 tcSyntaxOp orig other ty = pprPanic "tcSyntaxOp" (ppr other)
807 ---------------------------
808 instFun :: InstOrigin
810 -> TvSubst -- The instantiating substitution
811 -> [([TyVar], ThetaType)] -- Stuff to instantiate
814 instFun orig fun subst []
815 = return fun -- Common short cut
817 instFun orig fun subst tv_theta_prs
818 = do { let ty_theta_prs' = map subst_pr tv_theta_prs
819 ; traceTc (text "instFun" <+> ppr ty_theta_prs')
820 -- Make two ad-hoc checks
821 ; doStupidChecks fun ty_theta_prs'
823 -- Now do normal instantiation
824 ; method_sharing <- doptM Opt_MethodSharing
825 ; result <- go method_sharing True fun ty_theta_prs'
826 ; traceTc (text "instFun result" <+> ppr result)
830 subst_pr (tvs, theta)
831 = (substTyVars subst tvs, substTheta subst theta)
833 go _ _ fun [] = do {traceTc (text "go _ _ fun [] returns" <+> ppr fun) ; return fun }
835 go method_sharing True (HsVar fun_id) ((tys,theta) : prs)
836 | want_method_inst method_sharing theta
837 = do { traceTc (text "go (HsVar fun_id) ((tys,theta) : prs) | want_method_inst theta")
838 ; meth_id <- newMethodWithGivenTy orig fun_id tys
839 ; go method_sharing False (HsVar meth_id) prs }
840 -- Go round with 'False' to prevent further use
841 -- of newMethod: see Note [Multiple instantiation]
843 go method_sharing _ fun ((tys, theta) : prs)
844 = do { co_fn <- instCall orig tys theta
845 ; traceTc (text "go yields co_fn" <+> ppr co_fn)
846 ; go method_sharing False (HsWrap co_fn fun) prs }
848 -- See Note [No method sharing]
849 want_method_inst method_sharing theta = not (null theta) -- Overloaded
853 Note [Multiple instantiation]
854 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
855 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
856 For example, consider
857 f :: forall a. Eq a => forall b. Ord b => a -> b
858 At a call to f, at say [Int, Bool], it's tempting to translate the call to
862 f_m1 :: forall b. Ord b => Int -> b
866 f_m2 = f_m1 Bool dOrdBool
868 But notice that f_m2 has f_m1 as its meth_id. Now the danger is that if we do
869 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
871 But it's entirely possible that f_m2 will continue to float out, because it
872 mentions no type variables. Result, f_m1 isn't in scope.
874 Here's a concrete example that does this (test tc200):
877 f :: Eq b => b -> a -> Int
878 baz :: Eq a => Int -> a -> Int
883 Current solution: only do the "method sharing" thing for the first type/dict
884 application, not for the iterated ones. A horribly subtle point.
886 Note [No method sharing]
887 ~~~~~~~~~~~~~~~~~~~~~~~~
888 The -fno-method-sharing flag controls what happens so far as the LIE
889 is concerned. The default case is that for an overloaded function we
890 generate a "method" Id, and add the Method Inst to the LIE. So you get
893 f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
894 If you specify -fno-method-sharing, the dictionary application
895 isn't shared, so we get
897 f = /\a (d:Num a) (x:a) -> (+) a d x x
898 This gets a bit less sharing, but
899 a) it's better for RULEs involving overloaded functions
900 b) perhaps fewer separated lambdas
904 tcArgs implements a left-to-right order, which goes beyond what is described in the
905 impredicative type inference paper. In particular, it allows
907 where runST :: (forall s. ST s a) -> a
908 When typechecking the application of ($)::(a->b) -> a -> b, we first check that
909 runST has type (a->b), thereby filling in a=forall s. ST s a. Then we un-box this type
910 before checking foo. The left-to-right order really helps here.
913 tcArgs :: LHsExpr Name -- The function (for error messages)
914 -> [LHsExpr Name] -- Actual args
915 -> ArgChecker [LHsExpr TcId]
917 type ArgChecker results
918 = [TyVar] -> [TcSigmaType] -- Current instantiation
919 -> [TcSigmaType] -- Expected arg types (**before** applying the instantiation)
920 -> TcM ([TcSigmaType], results) -- Resulting instaniation and args
922 tcArgs fun args qtvs qtys arg_tys
923 = go 1 qtys args arg_tys
925 go n qtys [] [] = return (qtys, [])
926 go n qtys (arg:args) (arg_ty:arg_tys)
927 = do { arg' <- tcArg fun n arg qtvs qtys arg_ty
928 ; qtys' <- mapM refineBox qtys -- Exploit new info
929 ; (qtys'', args') <- go (n+1) qtys' args arg_tys
930 ; return (qtys'', arg':args') }
931 go n qtys args arg_tys = panic "tcArgs"
933 tcArg :: LHsExpr Name -- The function
934 -> Int -- and arg number (for error messages)
936 -> [TyVar] -> [TcSigmaType] -- Instantiate the arg type like this
938 -> TcM (LHsExpr TcId) -- Resulting argument
939 tcArg fun arg_no arg qtvs qtys ty
940 = addErrCtxt (funAppCtxt fun arg arg_no) $
941 tcPolyExprNC arg (substTyWith qtvs qtys ty)
947 Nasty check to ensure that tagToEnum# is applied to a type that is an
948 enumeration TyCon. Unification may refine the type later, but this
949 check won't see that, alas. It's crude but it works.
951 Here's are two cases that should fail
953 f = tagToEnum# 0 -- Can't do tagToEnum# at a type variable
956 g = tagToEnum# 0 -- Int is not an enumeration
960 doStupidChecks :: HsExpr TcId
961 -> [([TcType], ThetaType)]
963 -- Check two tiresome and ad-hoc cases
964 -- (a) the "stupid theta" for a data con; add the constraints
965 -- from the "stupid theta" of a data constructor (sigh)
966 -- (b) deal with the tagToEnum# problem: see Note [tagToEnum#]
968 doStupidChecks (HsVar fun_id) ((tys,_):_)
969 | Just con <- isDataConId_maybe fun_id -- (a)
970 = addDataConStupidTheta con tys
972 | fun_id `hasKey` tagToEnumKey -- (b)
973 = do { tys' <- zonkTcTypes tys
974 ; checkTc (ok tys') (tagToEnumError tys')
978 ok (ty:tys) = case tcSplitTyConApp_maybe ty of
979 Just (tc,_) -> isEnumerationTyCon tc
982 doStupidChecks fun tv_theta_prs
983 = return () -- The common case
987 = hang (ptext (sLit "Bad call to tagToEnum#") <+> at_type)
988 2 (vcat [ptext (sLit "Specify the type by giving a type signature"),
989 ptext (sLit "e.g. (tagToEnum# x) :: Bool")])
991 at_type | null tys = empty -- Probably never happens
992 | otherwise = ptext (sLit "at type") <+> ppr (head tys)
995 %************************************************************************
997 \subsection{@tcId@ typechecks an identifier occurrence}
999 %************************************************************************
1002 lookupFun :: InstOrigin -> Name -> TcM (HsExpr TcId, TcType)
1003 lookupFun orig id_name
1004 = do { thing <- tcLookup id_name
1006 AGlobal (ADataCon con) -> return (HsVar wrap_id, idType wrap_id)
1008 wrap_id = dataConWrapId con
1011 | isNaughtyRecordSelector id -> failWithTc (naughtyRecordSel id)
1012 | otherwise -> return (HsVar id, idType id)
1013 -- A global cannot possibly be ill-staged
1014 -- nor does it need the 'lifting' treatment
1016 ATcId { tct_id = id, tct_type = ty, tct_co = mb_co, tct_level = lvl }
1017 -> do { thLocalId orig id ty lvl
1019 Unrefineable -> return (HsVar id, ty)
1020 Rigid co -> return (mkHsWrap co (HsVar id), ty)
1021 Wobbly -> traceTc (text "lookupFun" <+> ppr id) >> return (HsVar id, ty) -- Wobbly, or no free vars
1022 WobblyInvisible -> failWithTc (ppr id_name <+> ptext (sLit " not in scope because it has a wobbly type (solution: add a type annotation)"))
1025 other -> failWithTc (ppr other <+> ptext (sLit "used where a value identifer was expected"))
1028 #ifndef GHCI /* GHCI and TH is off */
1029 --------------------------------------
1030 -- thLocalId : Check for cross-stage lifting
1031 thLocalId orig id id_ty th_bind_lvl
1034 #else /* GHCI and TH is on */
1035 thLocalId orig id id_ty th_bind_lvl
1036 = do { use_stage <- getStage -- TH case
1038 Brack use_lvl ps_var lie_var | use_lvl > th_bind_lvl
1039 -> thBrackId orig id ps_var lie_var
1040 other -> do { checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage
1044 --------------------------------------
1045 thBrackId orig id ps_var lie_var
1047 = -- Top-level identifiers in this module,
1048 -- (which have External Names)
1049 -- are just like the imported case:
1050 -- no need for the 'lifting' treatment
1051 -- E.g. this is fine:
1054 -- But we do need to put f into the keep-alive
1055 -- set, because after desugaring the code will
1056 -- only mention f's *name*, not f itself.
1057 do { keepAliveTc id; return id }
1060 = -- Nested identifiers, such as 'x' in
1061 -- E.g. \x -> [| h x |]
1062 -- We must behave as if the reference to x was
1064 -- We use 'x' itself as the splice proxy, used by
1065 -- the desugarer to stitch it all back together.
1066 -- If 'x' occurs many times we may get many identical
1067 -- bindings of the same splice proxy, but that doesn't
1068 -- matter, although it's a mite untidy.
1069 do { let id_ty = idType id
1070 ; checkTc (isTauTy id_ty) (polySpliceErr id)
1071 -- If x is polymorphic, its occurrence sites might
1072 -- have different instantiations, so we can't use plain
1073 -- 'x' as the splice proxy name. I don't know how to
1074 -- solve this, and it's probably unimportant, so I'm
1075 -- just going to flag an error for now
1077 ; id_ty' <- zapToMonotype id_ty
1078 -- The id_ty might have an OpenTypeKind, but we
1079 -- can't instantiate the Lift class at that kind,
1080 -- so we zap it to a LiftedTypeKind monotype
1081 -- C.f. the call in TcPat.newLitInst
1083 ; setLIEVar lie_var $ do
1084 { lift <- newMethodFromName orig id_ty' DsMeta.liftName
1085 -- Put the 'lift' constraint into the right LIE
1087 -- Update the pending splices
1088 ; ps <- readMutVar ps_var
1089 ; writeMutVar ps_var ((idName id, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps)
1096 %************************************************************************
1098 \subsection{Record bindings}
1100 %************************************************************************
1102 Game plan for record bindings
1103 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1104 1. Find the TyCon for the bindings, from the first field label.
1106 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1108 For each binding field = value
1110 3. Instantiate the field type (from the field label) using the type
1113 4 Type check the value using tcArg, passing the field type as
1114 the expected argument type.
1116 This extends OK when the field types are universally quantified.
1122 -> [TcType] -- Expected type for each field
1123 -> HsRecordBinds Name
1124 -> TcM (HsRecordBinds TcId)
1126 tcRecordBinds data_con arg_tys (HsRecFields rbinds dd)
1127 = do { mb_binds <- mapM do_bind rbinds
1128 ; return (HsRecFields (catMaybes mb_binds) dd) }
1130 flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1131 do_bind fld@(HsRecField { hsRecFieldId = L loc field_lbl, hsRecFieldArg = rhs })
1132 | Just field_ty <- assocMaybe flds_w_tys field_lbl
1133 = addErrCtxt (fieldCtxt field_lbl) $
1134 do { rhs' <- tcPolyExprNC rhs field_ty
1135 ; sel_id <- tcLookupField field_lbl
1136 ; ASSERT( isRecordSelector sel_id )
1137 return (Just (fld { hsRecFieldId = L loc sel_id, hsRecFieldArg = rhs' })) }
1139 = do { addErrTc (badFieldCon data_con field_lbl)
1142 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1143 checkMissingFields data_con rbinds
1144 | null field_labels -- Not declared as a record;
1145 -- But C{} is still valid if no strict fields
1146 = if any isMarkedStrict field_strs then
1147 -- Illegal if any arg is strict
1148 addErrTc (missingStrictFields data_con [])
1152 | otherwise = do -- A record
1153 unless (null missing_s_fields)
1154 (addErrTc (missingStrictFields data_con missing_s_fields))
1156 warn <- doptM Opt_WarnMissingFields
1157 unless (not (warn && notNull missing_ns_fields))
1158 (warnTc True (missingFields data_con missing_ns_fields))
1162 = [ fl | (fl, str) <- field_info,
1164 not (fl `elem` field_names_used)
1167 = [ fl | (fl, str) <- field_info,
1168 not (isMarkedStrict str),
1169 not (fl `elem` field_names_used)
1172 field_names_used = hsRecFields rbinds
1173 field_labels = dataConFieldLabels data_con
1175 field_info = zipEqual "missingFields"
1179 field_strs = dataConStrictMarks data_con
1182 %************************************************************************
1184 \subsection{Errors and contexts}
1186 %************************************************************************
1188 Boring and alphabetical:
1191 = hang (ptext (sLit "In the expression:")) 4 (ppr expr)
1193 fieldCtxt field_name
1194 = ptext (sLit "In the") <+> quotes (ppr field_name) <+> ptext (sLit "field of a record")
1196 funAppCtxt fun arg arg_no
1197 = hang (hsep [ ptext (sLit "In the"), speakNth arg_no, ptext (sLit "argument of"),
1198 quotes (ppr fun) <> text ", namely"])
1199 4 (quotes (ppr arg))
1202 = vcat [ptext (sLit "Record update for the non-Haskell-98 data type")
1203 <+> quotes (pprSourceTyCon tycon)
1204 <+> ptext (sLit "is not (yet) supported"),
1205 ptext (sLit "Use pattern-matching instead")]
1207 = hang (ptext (sLit "No constructor has all these fields:"))
1208 4 (pprQuotedList (hsRecFields rbinds))
1210 naughtyRecordSel sel_id
1211 = ptext (sLit "Cannot use record selector") <+> quotes (ppr sel_id) <+>
1212 ptext (sLit "as a function due to escaped type variables") $$
1213 ptext (sLit "Probably fix: use pattern-matching syntax instead")
1216 = hsep [quotes (ppr field), ptext (sLit "is not a record selector")]
1218 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1219 missingStrictFields con fields
1222 rest | null fields = empty -- Happens for non-record constructors
1223 -- with strict fields
1224 | otherwise = colon <+> pprWithCommas ppr fields
1226 header = ptext (sLit "Constructor") <+> quotes (ppr con) <+>
1227 ptext (sLit "does not have the required strict field(s)")
1229 missingFields :: DataCon -> [FieldLabel] -> SDoc
1230 missingFields con fields
1231 = ptext (sLit "Fields of") <+> quotes (ppr con) <+> ptext (sLit "not initialised:")
1232 <+> pprWithCommas ppr fields
1234 -- callCtxt fun args = ptext (sLit "In the call") <+> parens (ppr (foldl mkHsApp fun args))
1237 polySpliceErr :: Id -> SDoc
1239 = ptext (sLit "Can't splice the polymorphic local variable") <+> quotes (ppr id)