2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcExpr]{Typecheck an expression}
7 module TcExpr ( tcCheckSigma, tcCheckRho, tcInferRho,
8 tcMonoExpr, tcExpr, tcSyntaxOp
11 #include "HsVersions.h"
13 #ifdef GHCI /* Only if bootstrapped */
14 import {-# SOURCE #-} TcSplice( tcSpliceExpr, tcBracket )
15 import HsSyn ( nlHsVar )
17 import Name ( isExternalName )
18 import TcType ( isTauTy )
19 import TcEnv ( checkWellStaged )
20 import HsSyn ( nlHsApp )
21 import qualified DsMeta
24 import HsSyn ( HsExpr(..), LHsExpr, HsLit(..), ArithSeqInfo(..), recBindFields,
25 HsMatchContext(..), HsRecordBinds, mkHsApp )
26 import TcHsSyn ( hsLitType, (<$>) )
28 import TcUnify ( Expected(..), tcInfer, zapExpectedType, zapExpectedTo,
29 tcSubExp, tcGen, tcSub,
30 unifyFunTys, zapToListTy, zapToTyConApp )
31 import BasicTypes ( isMarkedStrict )
32 import Inst ( tcOverloadedLit, newMethodFromName, newIPDict,
33 newDicts, newMethodWithGivenTy, tcInstStupidTheta, tcInstCall )
34 import TcBinds ( tcLocalBinds )
35 import TcEnv ( tcLookup, tcLookupId,
36 tcLookupDataCon, tcLookupGlobalId
38 import TcArrows ( tcProc )
39 import TcMatches ( tcMatchesCase, tcMatchLambda, tcDoStmts, tcThingWithSig, TcMatchCtxt(..) )
40 import TcHsType ( tcHsSigType, UserTypeCtxt(..) )
41 import TcPat ( badFieldCon, refineTyVars )
42 import TcMType ( tcInstTyVars, tcInstType, newTyFlexiVarTy, zonkTcType )
43 import TcType ( TcTyVar, TcType, TcSigmaType, TcRhoType,
44 tcSplitFunTys, mkTyVarTys,
45 isSigmaTy, mkFunTy, mkTyConApp, tyVarsOfTypes, isLinearPred,
46 tcSplitSigmaTy, tidyOpenType
48 import Kind ( openTypeKind, liftedTypeKind, argTypeKind )
50 import Id ( idType, recordSelectorFieldLabel, isRecordSelector, isNaughtyRecordSelector )
51 import DataCon ( DataCon, dataConFieldLabels, dataConStrictMarks,
52 dataConWrapId, isVanillaDataCon, dataConTyVars, dataConOrigArgTys )
54 import TyCon ( TyCon, FieldLabel, tyConStupidTheta, tyConArity, tyConDataCons )
55 import Type ( substTheta, substTy )
56 import Var ( tyVarKind )
57 import VarSet ( emptyVarSet, elemVarSet )
58 import TysWiredIn ( boolTy, parrTyCon, tupleTyCon )
59 import PrelNames ( enumFromName, enumFromThenName,
60 enumFromToName, enumFromThenToName,
61 enumFromToPName, enumFromThenToPName, negateName
64 import StaticFlags ( opt_NoMethodSharing )
65 import HscTypes ( TyThing(..) )
66 import SrcLoc ( Located(..), unLoc, getLoc )
68 import ListSetOps ( assocMaybe )
69 import Maybes ( catMaybes )
74 %************************************************************************
76 \subsection{Main wrappers}
78 %************************************************************************
81 -- tcCheckSigma does type *checking*; it's passed the expected type of the result
82 tcCheckSigma :: LHsExpr Name -- Expession to type check
83 -> TcSigmaType -- Expected type (could be a polytpye)
84 -> TcM (LHsExpr TcId) -- Generalised expr with expected type
86 tcCheckSigma expr expected_ty
87 = -- traceTc (text "tcExpr" <+> (ppr expected_ty $$ ppr expr)) `thenM_`
88 tc_expr' expr expected_ty
90 tc_expr' expr sigma_ty
92 = tcGen sigma_ty emptyVarSet (
93 \ rho_ty -> tcCheckRho expr rho_ty
94 ) `thenM` \ (gen_fn, expr') ->
95 returnM (L (getLoc expr') (gen_fn <$> unLoc expr'))
97 tc_expr' expr rho_ty -- Monomorphic case
98 = tcCheckRho expr rho_ty
101 Typecheck expression which in most cases will be an Id.
102 The expression can return a higher-ranked type, such as
103 (forall a. a->a) -> Int
104 so we must create a hole to pass in as the expected tyvar.
107 tcCheckRho :: LHsExpr Name -> TcRhoType -> TcM (LHsExpr TcId)
108 tcCheckRho expr rho_ty = tcMonoExpr expr (Check rho_ty)
110 tcInferRho :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
111 tcInferRho (L loc (HsVar name)) = setSrcSpan loc $ do
112 { (e,_,ty) <- tcId (OccurrenceOf name) name
113 ; return (L loc e, ty) }
114 tcInferRho expr = tcInfer (tcMonoExpr expr)
116 tcSyntaxOp :: InstOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
117 -- Typecheck a syntax operator, checking that it has the specified type
118 -- The operator is always a variable at this stage (i.e. renamer output)
119 tcSyntaxOp orig (HsVar op) ty = do { (expr', _, id_ty) <- tcId orig op
120 ; co_fn <- tcSub ty id_ty
121 ; returnM (co_fn <$> expr') }
122 tcSyntaxOp orig other ty = pprPanic "tcSyntaxOp" (ppr other)
127 %************************************************************************
129 \subsection{The TAUT rules for variables}TcExpr
131 %************************************************************************
134 tcMonoExpr :: LHsExpr Name -- Expession to type check
135 -> Expected TcRhoType -- Expected type (could be a type variable)
136 -- Definitely no foralls at the top
138 -> TcM (LHsExpr TcId)
140 tcMonoExpr (L loc expr) res_ty
141 = setSrcSpan loc (do { expr' <- tcExpr expr res_ty
142 ; return (L loc expr') })
144 tcExpr :: HsExpr Name -> Expected TcRhoType -> TcM (HsExpr TcId)
145 tcExpr (HsVar name) res_ty
146 = do { (expr', _, id_ty) <- tcId (OccurrenceOf name) name
147 ; co_fn <- tcSubExp res_ty id_ty
148 ; returnM (co_fn <$> expr') }
150 tcExpr (HsIPVar ip) res_ty
151 = -- Implicit parameters must have a *tau-type* not a
152 -- type scheme. We enforce this by creating a fresh
153 -- type variable as its type. (Because res_ty may not
155 newTyFlexiVarTy argTypeKind `thenM` \ ip_ty ->
156 -- argTypeKind: it can't be an unboxed tuple
157 newIPDict (IPOccOrigin ip) ip ip_ty `thenM` \ (ip', inst) ->
158 extendLIE inst `thenM_`
159 tcSubExp res_ty ip_ty `thenM` \ co_fn ->
160 returnM (co_fn <$> HsIPVar ip')
164 %************************************************************************
166 \subsection{Expressions type signatures}
168 %************************************************************************
171 tcExpr in_expr@(ExprWithTySig expr poly_ty) res_ty
172 = addErrCtxt (exprCtxt in_expr) $
173 tcHsSigType ExprSigCtxt poly_ty `thenM` \ sig_tc_ty ->
174 tcThingWithSig sig_tc_ty (tcCheckRho expr) res_ty `thenM` \ (co_fn, expr') ->
175 returnM (co_fn <$> ExprWithTySigOut expr' poly_ty)
177 tcExpr (HsType ty) res_ty
178 = failWithTc (text "Can't handle type argument:" <+> ppr ty)
179 -- This is the syntax for type applications that I was planning
180 -- but there are difficulties (e.g. what order for type args)
181 -- so it's not enabled yet.
182 -- Can't eliminate it altogether from the parser, because the
183 -- same parser parses *patterns*.
187 %************************************************************************
189 \subsection{Other expression forms}
191 %************************************************************************
194 tcExpr (HsPar expr) res_ty = tcMonoExpr expr res_ty `thenM` \ expr' ->
195 returnM (HsPar expr')
196 tcExpr (HsSCC lbl expr) res_ty = tcMonoExpr expr res_ty `thenM` \ expr' ->
197 returnM (HsSCC lbl expr')
198 tcExpr (HsCoreAnn lbl expr) res_ty = tcMonoExpr expr res_ty `thenM` \ expr' -> -- hdaume: core annotation
199 returnM (HsCoreAnn lbl expr')
201 tcExpr (HsLit lit) res_ty = tcLit lit res_ty
203 tcExpr (HsOverLit lit) res_ty
204 = zapExpectedType res_ty liftedTypeKind `thenM` \ res_ty' ->
205 -- Overloaded literals must have liftedTypeKind, because
206 -- we're instantiating an overloaded function here,
207 -- whereas res_ty might be openTypeKind. This was a bug in 6.2.2
208 tcOverloadedLit (LiteralOrigin lit) lit res_ty' `thenM` \ lit' ->
209 returnM (HsOverLit lit')
211 tcExpr (NegApp expr neg_expr) res_ty
212 = do { res_ty' <- zapExpectedType res_ty liftedTypeKind
213 ; neg_expr' <- tcSyntaxOp (OccurrenceOf negateName) neg_expr
214 (mkFunTy res_ty' res_ty')
215 ; expr' <- tcCheckRho expr res_ty'
216 ; return (NegApp expr' neg_expr') }
218 tcExpr (HsLam match) res_ty
219 = tcMatchLambda match res_ty `thenM` \ match' ->
220 returnM (HsLam match')
222 tcExpr (HsApp e1 e2) res_ty
223 = tcApp e1 [e2] res_ty
226 Note that the operators in sections are expected to be binary, and
227 a type error will occur if they aren't.
230 -- Left sections, equivalent to
237 tcExpr in_expr@(SectionL arg1 op) res_ty
238 = tcInferRho op `thenM` \ (op', op_ty) ->
239 unifyInfixTy op in_expr op_ty `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
240 tcArg op (arg1, arg1_ty, 1) `thenM` \ arg1' ->
241 addErrCtxt (exprCtxt in_expr) $
242 tcSubExp res_ty (mkFunTy arg2_ty op_res_ty) `thenM` \ co_fn ->
243 returnM (co_fn <$> SectionL arg1' op')
245 -- Right sections, equivalent to \ x -> x op expr, or
248 tcExpr in_expr@(SectionR op arg2) res_ty
249 = tcInferRho op `thenM` \ (op', op_ty) ->
250 unifyInfixTy op in_expr op_ty `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
251 tcArg op (arg2, arg2_ty, 2) `thenM` \ arg2' ->
252 addErrCtxt (exprCtxt in_expr) $
253 tcSubExp res_ty (mkFunTy arg1_ty op_res_ty) `thenM` \ co_fn ->
254 returnM (co_fn <$> SectionR op' arg2')
256 -- equivalent to (op e1) e2:
258 tcExpr in_expr@(OpApp arg1 op fix arg2) res_ty
259 = tcInferRho op `thenM` \ (op', op_ty) ->
260 unifyInfixTy op in_expr op_ty `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
261 tcArg op (arg1, arg1_ty, 1) `thenM` \ arg1' ->
262 tcArg op (arg2, arg2_ty, 2) `thenM` \ arg2' ->
263 addErrCtxt (exprCtxt in_expr) $
264 tcSubExp res_ty op_res_ty `thenM` \ co_fn ->
265 returnM (co_fn <$> OpApp arg1' op' fix arg2')
269 tcExpr (HsLet binds expr) res_ty
270 = do { (binds', expr') <- tcLocalBinds binds $
271 tcMonoExpr expr res_ty
272 ; return (HsLet binds' expr') }
274 tcExpr in_expr@(HsCase scrut matches) exp_ty
275 = -- We used to typecheck the case alternatives first.
276 -- The case patterns tend to give good type info to use
277 -- when typechecking the scrutinee. For example
280 -- will report that map is applied to too few arguments
282 -- But now, in the GADT world, we need to typecheck the scrutinee
283 -- first, to get type info that may be refined in the case alternatives
284 addErrCtxt (caseScrutCtxt scrut)
285 (tcInferRho scrut) `thenM` \ (scrut', scrut_ty) ->
287 addErrCtxt (caseCtxt in_expr) $
288 tcMatchesCase match_ctxt scrut_ty matches exp_ty `thenM` \ matches' ->
289 returnM (HsCase scrut' matches')
291 match_ctxt = MC { mc_what = CaseAlt,
292 mc_body = tcMonoExpr }
294 tcExpr (HsIf pred b1 b2) res_ty
295 = addErrCtxt (predCtxt pred)
296 (tcCheckRho pred boolTy) `thenM` \ pred' ->
298 zapExpectedType res_ty openTypeKind `thenM` \ res_ty' ->
299 -- C.f. the call to zapToType in TcMatches.tcMatches
301 tcCheckRho b1 res_ty' `thenM` \ b1' ->
302 tcCheckRho b2 res_ty' `thenM` \ b2' ->
303 returnM (HsIf pred' b1' b2')
305 tcExpr (HsDo do_or_lc stmts body _) res_ty
306 = tcDoStmts do_or_lc stmts body res_ty
308 tcExpr in_expr@(ExplicitList _ exprs) res_ty -- Non-empty list
309 = zapToListTy res_ty `thenM` \ elt_ty ->
310 mappM (tc_elt elt_ty) exprs `thenM` \ exprs' ->
311 returnM (ExplicitList elt_ty exprs')
314 = addErrCtxt (listCtxt expr) $
315 tcCheckRho expr elt_ty
317 tcExpr in_expr@(ExplicitPArr _ exprs) res_ty -- maybe empty
318 = do { [elt_ty] <- zapToTyConApp parrTyCon res_ty
319 ; exprs' <- mappM (tc_elt elt_ty) exprs
320 ; return (ExplicitPArr elt_ty exprs') }
323 = addErrCtxt (parrCtxt expr) (tcCheckRho expr elt_ty)
325 tcExpr (ExplicitTuple exprs boxity) res_ty
326 = do { arg_tys <- zapToTyConApp (tupleTyCon boxity (length exprs)) res_ty
327 ; exprs' <- tcCheckRhos exprs arg_tys
328 ; return (ExplicitTuple exprs' boxity) }
330 tcExpr (HsProc pat cmd) res_ty
331 = tcProc pat cmd res_ty `thenM` \ (pat', cmd') ->
332 returnM (HsProc pat' cmd')
334 tcExpr e@(HsArrApp _ _ _ _ _) _
335 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
336 ptext SLIT("was found where an expression was expected")])
338 tcExpr e@(HsArrForm _ _ _) _
339 = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e),
340 ptext SLIT("was found where an expression was expected")])
343 %************************************************************************
345 Record construction and update
347 %************************************************************************
350 tcExpr expr@(RecordCon (L loc con_name) _ rbinds) res_ty
351 = addErrCtxt (recordConCtxt expr) $
352 do { (con_expr, _, con_tau) <- setSrcSpan loc $
353 tcId (OccurrenceOf con_name) con_name
354 ; data_con <- tcLookupDataCon con_name
356 ; let (arg_tys, record_ty) = tcSplitFunTys con_tau
357 flds_w_tys = zipEqual "tcExpr RecordCon" (dataConFieldLabels data_con) arg_tys
359 -- Make the result type line up
360 ; zapExpectedTo res_ty record_ty
362 -- Typecheck the record bindings
363 ; rbinds' <- tcRecordBinds data_con flds_w_tys rbinds
365 -- Check for missing fields
366 ; checkMissingFields data_con rbinds
368 ; returnM (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.
396 tcExpr expr@(RecordUpd record_expr rbinds _ _) res_ty
397 = addErrCtxt (recordUpdCtxt expr) $
400 -- Check that the field names are really field names
401 ASSERT( notNull rbinds )
403 field_names = map fst rbinds
405 mappM (tcLookupGlobalId.unLoc) field_names `thenM` \ sel_ids ->
406 -- The renamer has already checked that they
409 bad_guys = [ setSrcSpan loc $ addErrTc (notSelector field_name)
410 | (L loc field_name, sel_id) <- field_names `zip` sel_ids,
411 not (isRecordSelector sel_id) -- Excludes class ops
414 checkM (null bad_guys) (sequenceM bad_guys `thenM_` failM) `thenM_`
417 -- Figure out the tycon and data cons from the first field name
419 -- It's OK to use the non-tc splitters here (for a selector)
421 (tycon, _) = recordSelectorFieldLabel sel_id -- We've failed already if
422 data_cons = tyConDataCons tycon -- it's not a field label
425 -- Check that all data cons are vanilla. Doing record updates on GADTs
426 -- and/or existentials is more than my tiny brain can cope with today
427 -- [I think we might be able to manage if none of the selectors is naughty,
428 -- but that's for another day.]
429 checkTc (all isVanillaDataCon data_cons)
430 (nonVanillaUpd tycon) `thenM_`
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 (any (null . badFields rbinds) data_cons)
436 (badFieldsUpd rbinds) `thenM_`
439 -- Use the un-updated fields to find a vector of booleans saying
440 -- which type arguments must be the same in updatee and result.
442 -- WARNING: this code assumes that all data_cons in a common tycon
443 -- have FieldLabels abstracted over the same tyvars.
445 upd_field_lbls = recBindFields rbinds
447 -- A constructor is only relevant to this process if
448 -- it contains *all* the fields that are being updated
449 relevant_cons = filter is_relevant data_cons
450 is_relevant con = all (`elem` dataConFieldLabels con) upd_field_lbls
451 con1 = head relevant_cons -- A representative constructor
452 con1_tyvars = dataConTyVars con1
453 con1_fld_tys = dataConFieldLabels con1 `zip` dataConOrigArgTys con1
454 common_tyvars = tyVarsOfTypes [ty | (fld,ty) <- con1_fld_tys
455 , not (fld `elem` upd_field_lbls) ]
457 is_common_tv tv = tv `elemVarSet` common_tyvars
459 mk_inst_ty tv result_inst_ty
460 | is_common_tv tv = returnM result_inst_ty -- Same as result type
461 | otherwise = newTyFlexiVarTy (tyVarKind tv) -- Fresh type, of correct kind
463 tcInstTyVars con1_tyvars `thenM` \ (_, result_inst_tys, inst_env) ->
464 zipWithM mk_inst_ty con1_tyvars result_inst_tys `thenM` \ inst_tys ->
467 -- Typecheck the update bindings.
468 -- (Do this after checking for bad fields in case there's a field that
469 -- doesn't match the constructor.)
471 result_record_ty = mkTyConApp tycon result_inst_tys
472 inst_fld_tys = [(fld, substTy inst_env ty) | (fld, ty) <- con1_fld_tys]
474 zapExpectedTo res_ty result_record_ty `thenM_`
475 tcRecordBinds con1 inst_fld_tys rbinds `thenM` \ rbinds' ->
478 -- Typecheck the expression to be updated
480 record_ty = ASSERT( length inst_tys == tyConArity tycon )
481 mkTyConApp tycon inst_tys
482 -- This is one place where the isVanilla check is important
483 -- So that inst_tys matches the tycon
485 tcCheckRho record_expr record_ty `thenM` \ record_expr' ->
488 -- Figure out the LIE we need. We have to generate some
489 -- dictionaries for the data type context, since we are going to
490 -- do pattern matching over the data cons.
492 -- What dictionaries do we need?
493 -- We just take the context of the first data constructor
494 -- This isn't right, but I just can't bear to union up all the relevant ones
496 theta' = substTheta inst_env (tyConStupidTheta tycon)
498 newDicts RecordUpdOrigin theta' `thenM` \ dicts ->
499 extendLIEs dicts `thenM_`
502 returnM (RecordUpd record_expr' rbinds' record_ty result_record_ty)
506 %************************************************************************
508 Arithmetic sequences e.g. [a,b..]
509 and their parallel-array counterparts e.g. [: a,b.. :]
512 %************************************************************************
515 tcExpr (ArithSeq _ seq@(From expr)) res_ty
516 = zapToListTy res_ty `thenM` \ elt_ty ->
517 tcCheckRho expr elt_ty `thenM` \ expr' ->
519 newMethodFromName (ArithSeqOrigin seq)
520 elt_ty enumFromName `thenM` \ enum_from ->
522 returnM (ArithSeq (HsVar enum_from) (From expr'))
524 tcExpr in_expr@(ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
525 = addErrCtxt (arithSeqCtxt in_expr) $
526 zapToListTy res_ty `thenM` \ elt_ty ->
527 tcCheckRho expr1 elt_ty `thenM` \ expr1' ->
528 tcCheckRho expr2 elt_ty `thenM` \ expr2' ->
529 newMethodFromName (ArithSeqOrigin seq)
530 elt_ty enumFromThenName `thenM` \ enum_from_then ->
532 returnM (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2'))
535 tcExpr in_expr@(ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
536 = addErrCtxt (arithSeqCtxt in_expr) $
537 zapToListTy res_ty `thenM` \ elt_ty ->
538 tcCheckRho expr1 elt_ty `thenM` \ expr1' ->
539 tcCheckRho expr2 elt_ty `thenM` \ expr2' ->
540 newMethodFromName (ArithSeqOrigin seq)
541 elt_ty enumFromToName `thenM` \ enum_from_to ->
543 returnM (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2'))
545 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
546 = addErrCtxt (arithSeqCtxt in_expr) $
547 zapToListTy res_ty `thenM` \ elt_ty ->
548 tcCheckRho expr1 elt_ty `thenM` \ expr1' ->
549 tcCheckRho expr2 elt_ty `thenM` \ expr2' ->
550 tcCheckRho expr3 elt_ty `thenM` \ expr3' ->
551 newMethodFromName (ArithSeqOrigin seq)
552 elt_ty enumFromThenToName `thenM` \ eft ->
554 returnM (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3'))
556 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
557 = addErrCtxt (parrSeqCtxt in_expr) $
558 zapToTyConApp parrTyCon res_ty `thenM` \ [elt_ty] ->
559 tcCheckRho expr1 elt_ty `thenM` \ expr1' ->
560 tcCheckRho expr2 elt_ty `thenM` \ expr2' ->
561 newMethodFromName (PArrSeqOrigin seq)
562 elt_ty enumFromToPName `thenM` \ enum_from_to ->
564 returnM (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2'))
566 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
567 = addErrCtxt (parrSeqCtxt in_expr) $
568 zapToTyConApp parrTyCon res_ty `thenM` \ [elt_ty] ->
569 tcCheckRho expr1 elt_ty `thenM` \ expr1' ->
570 tcCheckRho expr2 elt_ty `thenM` \ expr2' ->
571 tcCheckRho expr3 elt_ty `thenM` \ expr3' ->
572 newMethodFromName (PArrSeqOrigin seq)
573 elt_ty enumFromThenToPName `thenM` \ eft ->
575 returnM (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3'))
577 tcExpr (PArrSeq _ _) _
578 = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
579 -- the parser shouldn't have generated it and the renamer shouldn't have
584 %************************************************************************
588 %************************************************************************
591 #ifdef GHCI /* Only if bootstrapped */
592 -- Rename excludes these cases otherwise
593 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
594 tcExpr (HsBracket brack) res_ty = do { e <- tcBracket brack res_ty
600 %************************************************************************
604 %************************************************************************
607 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
611 %************************************************************************
613 \subsection{@tcApp@ typchecks an application}
615 %************************************************************************
619 tcApp :: LHsExpr Name -> [LHsExpr Name] -- Function and args
620 -> Expected TcRhoType -- Expected result type of application
621 -> TcM (HsExpr TcId) -- Translated fun and args
623 tcApp (L _ (HsApp e1 e2)) args res_ty
624 = tcApp e1 (e2:args) res_ty -- Accumulate the arguments
626 tcApp fun args res_ty
627 = do { let n_args = length args
628 ; (fun', fun_tvs, fun_tau) <- tcFun fun -- Type-check the function
630 -- Extract its argument types
631 ; (expected_arg_tys, actual_res_ty)
632 <- do { traceTc (text "tcApp" <+> (ppr fun $$ ppr fun_tau))
633 ; let msg = sep [ptext SLIT("The function") <+> quotes (ppr fun),
634 ptext SLIT("is applied to")
635 <+> speakN n_args <+> ptext SLIT("arguments")]
636 ; unifyFunTys msg n_args fun_tau }
639 Check _ -> do -- Connect to result type first
640 -- See Note [Push result type in]
641 { co_fn <- tcResult fun args res_ty actual_res_ty
642 ; the_app' <- tcArgs fun fun' args expected_arg_tys
643 ; traceTc (text "tcApp: check" <+> vcat [ppr fun <+> ppr args,
644 ppr the_app', ppr actual_res_ty])
645 ; returnM (co_fn <$> the_app') }
647 Infer _ -> do -- Type check args first, then
648 -- refine result type, then do tcResult
649 { the_app' <- tcArgs fun fun' args expected_arg_tys
650 ; subst <- refineTyVars fun_tvs
651 ; let actual_res_ty' = substTy subst actual_res_ty
652 ; co_fn <- tcResult fun args res_ty actual_res_ty'
653 ; traceTc (text "tcApp: infer" <+> vcat [ppr fun <+> ppr args, ppr the_app',
654 ppr actual_res_ty, ppr actual_res_ty'])
655 ; returnM (co_fn <$> the_app') }
658 -- Note [Push result type in]
660 -- Unify with expected result before (was: after) type-checking the args
661 -- so that the info from res_ty (was: args) percolates to args (was actual_res_ty).
662 -- This is when we might detect a too-few args situation.
663 -- (One can think of cases when the opposite order would give
664 -- a better error message.)
665 -- [March 2003: I'm experimenting with putting this first. Here's an
666 -- example where it actually makes a real difference
667 -- class C t a b | t a -> b
668 -- instance C Char a Bool
670 -- data P t a = forall b. (C t a b) => MkP b
671 -- data Q t = MkQ (forall a. P t a)
674 -- f1 = MkQ (MkP True)
675 -- f2 = MkQ (MkP True :: forall a. P Char a)
677 -- With the change, f1 will type-check, because the 'Char' info from
678 -- the signature is propagated into MkQ's argument. With the check
679 -- in the other order, the extra signature in f2 is reqd.]
682 tcFun :: LHsExpr Name -> TcM (LHsExpr TcId, [TcTyVar], TcRhoType)
683 -- Instantiate the function, returning the type variables used
684 -- If the function isn't simple, infer its type, and return no
686 tcFun (L loc (HsVar f)) = setSrcSpan loc $ do
687 { (fun', tvs, fun_tau) <- tcId (OccurrenceOf f) f
688 ; return (L loc fun', tvs, fun_tau) }
689 tcFun fun = do { (fun', fun_tau) <- tcInfer (tcMonoExpr fun)
690 ; return (fun', [], fun_tau) }
693 tcArgs :: LHsExpr Name -- The function (for error messages)
694 -> LHsExpr TcId -- The function (to build into result)
695 -> [LHsExpr Name] -> [TcSigmaType] -- Actual arguments and expected arg types
696 -> TcM (HsExpr TcId) -- Resulting application
698 tcArgs fun fun' args expected_arg_tys
699 = do { args' <- mappM (tcArg fun) (zip3 args expected_arg_tys [1..])
700 ; return (unLoc (foldl mkHsApp fun' args')) }
702 tcArg :: LHsExpr Name -- The function (for error messages)
703 -> (LHsExpr Name, TcSigmaType, Int) -- Actual argument and expected arg type
704 -> TcM (LHsExpr TcId) -- Resulting argument
705 tcArg fun (arg, ty, arg_no) = addErrCtxt (funAppCtxt fun arg arg_no)
706 (tcCheckSigma arg ty)
709 tcResult fun args res_ty actual_res_ty
710 = addErrCtxtM (checkArgsCtxt fun args res_ty actual_res_ty)
711 (tcSubExp res_ty actual_res_ty)
714 -- If an error happens we try to figure out whether the
715 -- function has been given too many or too few arguments,
717 -- The ~(Check...) is because in the Infer case the tcSubExp
718 -- definitely won't fail, so we can be certain we're in the Check branch
719 checkArgsCtxt fun args (Infer _) actual_res_ty tidy_env
720 = return (tidy_env, ptext SLIT("Urk infer"))
722 checkArgsCtxt fun args (Check expected_res_ty) actual_res_ty tidy_env
723 = zonkTcType expected_res_ty `thenM` \ exp_ty' ->
724 zonkTcType actual_res_ty `thenM` \ act_ty' ->
726 (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
727 (env2, act_ty'') = tidyOpenType env1 act_ty'
728 (exp_args, _) = tcSplitFunTys exp_ty''
729 (act_args, _) = tcSplitFunTys act_ty''
731 len_act_args = length act_args
732 len_exp_args = length exp_args
734 message | len_exp_args < len_act_args = wrongArgsCtxt "too few" fun args
735 | len_exp_args > len_act_args = wrongArgsCtxt "too many" fun args
736 | otherwise = appCtxt fun args
738 returnM (env2, message)
741 unifyInfixTy :: LHsExpr Name -> HsExpr Name -> TcType
742 -> TcM ([TcType], TcType)
743 -- This wrapper just prepares the error message for unifyFunTys
744 unifyInfixTy op expr op_ty
745 = unifyFunTys msg 2 op_ty
747 msg = sep [herald <+> quotes (ppr expr),
748 ptext SLIT("requires") <+> quotes (ppr op)
749 <+> ptext SLIT("to take two arguments")]
750 herald = case expr of
751 OpApp _ _ _ _ -> ptext SLIT("The infix expression")
752 other -> ptext SLIT("The operator section")
756 %************************************************************************
758 \subsection{@tcId@ typchecks an identifier occurrence}
760 %************************************************************************
762 tcId instantiates an occurrence of an Id.
763 The instantiate_it loop runs round instantiating the Id.
764 It has to be a loop because we are now prepared to entertain
766 f:: forall a. Eq a => forall b. Baz b => tau
767 We want to instantiate this to
768 f2::tau {f2 = f1 b (Baz b), f1 = f a (Eq a)}
770 The -fno-method-sharing flag controls what happens so far as the LIE
771 is concerned. The default case is that for an overloaded function we
772 generate a "method" Id, and add the Method Inst to the LIE. So you get
775 f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
776 If you specify -fno-method-sharing, the dictionary application
777 isn't shared, so we get
779 f = /\a (d:Num a) (x:a) -> (+) a d x x
780 This gets a bit less sharing, but
781 a) it's better for RULEs involving overloaded functions
782 b) perhaps fewer separated lambdas
785 tcId :: InstOrigin -> Name -> TcM (HsExpr TcId, [TcTyVar], TcRhoType)
786 -- Return the type variables at which the function
787 -- is instantiated, as well as the translated variable and its type
789 tcId orig id_name -- Look up the Id and instantiate its type
790 = tcLookup id_name `thenM` \ thing ->
792 AGlobal (ADataCon con) -- Similar, but instantiate the stupid theta too
793 -> do { (expr, tvs, tau) <- instantiate (dataConWrapId con)
794 ; tcInstStupidTheta con (mkTyVarTys tvs)
795 -- Remember to chuck in the constraints from the "silly context"
796 ; return (expr, tvs, tau) }
798 ; AGlobal (AnId id) | isNaughtyRecordSelector id
799 -> failWithTc (naughtyRecordSel id)
800 ; AGlobal (AnId id) -> instantiate id
801 -- A global cannot possibly be ill-staged
802 -- nor does it need the 'lifting' treatment
804 ; ATcId id th_level -> tc_local_id id th_level
806 ; other -> failWithTc (ppr other <+> ptext SLIT("used where a value identifer was expected"))
811 tc_local_id id th_bind_lvl -- Non-TH case
814 #else /* GHCI and TH is on */
815 tc_local_id id th_bind_lvl -- TH case
816 = -- Check for cross-stage lifting
817 getStage `thenM` \ use_stage ->
819 Brack use_lvl ps_var lie_var
820 | use_lvl > th_bind_lvl
821 -> if isExternalName id_name then
822 -- Top-level identifiers in this module,
823 -- (which have External Names)
824 -- are just like the imported case:
825 -- no need for the 'lifting' treatment
826 -- E.g. this is fine:
829 -- But we do need to put f into the keep-alive
830 -- set, because after desugaring the code will
831 -- only mention f's *name*, not f itself.
832 keepAliveTc id_name `thenM_`
835 else -- Nested identifiers, such as 'x' in
836 -- E.g. \x -> [| h x |]
837 -- We must behave as if the reference to x was
839 -- We use 'x' itself as the splice proxy, used by
840 -- the desugarer to stitch it all back together.
841 -- If 'x' occurs many times we may get many identical
842 -- bindings of the same splice proxy, but that doesn't
843 -- matter, although it's a mite untidy.
847 checkTc (isTauTy id_ty) (polySpliceErr id) `thenM_`
848 -- If x is polymorphic, its occurrence sites might
849 -- have different instantiations, so we can't use plain
850 -- 'x' as the splice proxy name. I don't know how to
851 -- solve this, and it's probably unimportant, so I'm
852 -- just going to flag an error for now
855 newMethodFromName orig id_ty DsMeta.liftName `thenM` \ lift ->
856 -- Put the 'lift' constraint into the right LIE
858 -- Update the pending splices
859 readMutVar ps_var `thenM` \ ps ->
860 writeMutVar ps_var ((id_name, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps) `thenM_`
862 returnM (HsVar id, [], id_ty))
865 checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage `thenM_`
869 instantiate :: TcId -> TcM (HsExpr TcId, [TcTyVar], TcRhoType)
870 instantiate fun_id = loop (HsVar fun_id) [] (idType fun_id)
872 loop (HsVar fun_id) tvs fun_ty
873 | want_method_inst fun_ty
874 = tcInstType fun_ty `thenM` \ (tyvars, theta, tau) ->
875 newMethodWithGivenTy orig fun_id
876 (mkTyVarTys tyvars) theta tau `thenM` \ meth_id ->
877 loop (HsVar meth_id) (tvs ++ tyvars) tau
881 = tcInstCall orig fun_ty `thenM` \ (inst_fn, new_tvs, tau) ->
882 loop (inst_fn <$> fun) (tvs ++ new_tvs) tau
885 = returnM (fun, tvs, fun_ty)
887 -- Hack Alert (want_method_inst)!
888 -- If f :: (%x :: T) => Int -> Int
889 -- Then if we have two separate calls, (f 3, f 4), we cannot
890 -- make a method constraint that then gets shared, thus:
891 -- let m = f %x in (m 3, m 4)
892 -- because that loses the linearity of the constraint.
893 -- The simplest thing to do is never to construct a method constraint
894 -- in the first place that has a linear implicit parameter in it.
895 want_method_inst fun_ty
896 | opt_NoMethodSharing = False
897 | otherwise = case tcSplitSigmaTy fun_ty of
898 (_,[],_) -> False -- Not overloaded
899 (_,theta,_) -> not (any isLinearPred theta)
902 %************************************************************************
904 \subsection{Record bindings}
906 %************************************************************************
908 Game plan for record bindings
909 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
910 1. Find the TyCon for the bindings, from the first field label.
912 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
914 For each binding field = value
916 3. Instantiate the field type (from the field label) using the type
919 4 Type check the value using tcArg, passing the field type as
920 the expected argument type.
922 This extends OK when the field types are universally quantified.
928 -> [(FieldLabel,TcType)] -- Expected type for each field
929 -> HsRecordBinds Name
930 -> TcM (HsRecordBinds TcId)
932 tcRecordBinds data_con flds_w_tys rbinds
933 = do { mb_binds <- mappM do_bind rbinds
934 ; return (catMaybes mb_binds) }
936 do_bind (L loc field_lbl, rhs)
937 | Just field_ty <- assocMaybe flds_w_tys field_lbl
938 = addErrCtxt (fieldCtxt field_lbl) $
939 do { rhs' <- tcCheckSigma rhs field_ty
940 ; sel_id <- tcLookupId field_lbl
941 ; ASSERT( isRecordSelector sel_id )
942 return (Just (L loc sel_id, rhs')) }
944 = do { addErrTc (badFieldCon data_con field_lbl)
947 badFields rbinds data_con
948 = filter (not . (`elem` field_names)) (recBindFields rbinds)
950 field_names = dataConFieldLabels data_con
952 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
953 checkMissingFields data_con rbinds
954 | null field_labels -- Not declared as a record;
955 -- But C{} is still valid if no strict fields
956 = if any isMarkedStrict field_strs then
957 -- Illegal if any arg is strict
958 addErrTc (missingStrictFields data_con [])
962 | otherwise -- A record
963 = checkM (null missing_s_fields)
964 (addErrTc (missingStrictFields data_con missing_s_fields)) `thenM_`
966 doptM Opt_WarnMissingFields `thenM` \ warn ->
967 checkM (not (warn && notNull missing_ns_fields))
968 (warnTc True (missingFields data_con missing_ns_fields))
972 = [ fl | (fl, str) <- field_info,
974 not (fl `elem` field_names_used)
977 = [ fl | (fl, str) <- field_info,
978 not (isMarkedStrict str),
979 not (fl `elem` field_names_used)
982 field_names_used = recBindFields rbinds
983 field_labels = dataConFieldLabels data_con
985 field_info = zipEqual "missingFields"
989 field_strs = dataConStrictMarks data_con
992 %************************************************************************
994 \subsection{@tcCheckRhos@ typechecks a {\em list} of expressions}
996 %************************************************************************
999 tcCheckRhos :: [LHsExpr Name] -> [TcType] -> TcM [LHsExpr TcId]
1001 tcCheckRhos [] [] = returnM []
1002 tcCheckRhos (expr:exprs) (ty:tys)
1003 = tcCheckRho expr ty `thenM` \ expr' ->
1004 tcCheckRhos exprs tys `thenM` \ exprs' ->
1005 returnM (expr':exprs')
1006 tcCheckRhos exprs tys = pprPanic "tcCheckRhos" (ppr exprs $$ ppr tys)
1010 %************************************************************************
1012 \subsection{Literals}
1014 %************************************************************************
1016 Overloaded literals.
1019 tcLit :: HsLit -> Expected TcRhoType -> TcM (HsExpr TcId)
1021 = zapExpectedTo res_ty (hsLitType lit) `thenM_`
1026 %************************************************************************
1028 \subsection{Errors and contexts}
1030 %************************************************************************
1032 Boring and alphabetical:
1035 = hang (ptext SLIT("In an arithmetic sequence:")) 4 (ppr expr)
1038 = hang (ptext SLIT("In a parallel array sequence:")) 4 (ppr expr)
1041 = hang (ptext SLIT("In the case expression:")) 4 (ppr expr)
1044 = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1047 = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1049 fieldCtxt field_name
1050 = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1052 funAppCtxt fun arg arg_no
1053 = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"),
1054 quotes (ppr fun) <> text ", namely"])
1055 4 (quotes (ppr arg))
1058 = hang (ptext SLIT("In the list element:")) 4 (ppr expr)
1061 = hang (ptext SLIT("In the parallel array element:")) 4 (ppr expr)
1064 = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1067 = ptext SLIT("In the application") <+> quotes (ppr the_app)
1069 the_app = foldl mkHsApp fun args -- Used in error messages
1072 = vcat [ptext SLIT("Record update for the non-Haskell-98 data type") <+> quotes (ppr tycon)
1073 <+> ptext SLIT("is not (yet) supported"),
1074 ptext SLIT("Use pattern-matching instead")]
1076 = hang (ptext SLIT("No constructor has all these fields:"))
1077 4 (pprQuotedList (recBindFields rbinds))
1079 recordUpdCtxt expr = ptext SLIT("In the record update:") <+> ppr expr
1080 recordConCtxt expr = ptext SLIT("In the record construction:") <+> ppr expr
1082 naughtyRecordSel sel_id
1083 = ptext SLIT("Cannot use record selector") <+> quotes (ppr sel_id) <+>
1084 ptext SLIT("as a function due to escaped type variables") $$
1085 ptext SLIT("Probably fix: use pattern-matching syntax instead")
1088 = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1090 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1091 missingStrictFields con fields
1094 rest | null fields = empty -- Happens for non-record constructors
1095 -- with strict fields
1096 | otherwise = colon <+> pprWithCommas ppr fields
1098 header = ptext SLIT("Constructor") <+> quotes (ppr con) <+>
1099 ptext SLIT("does not have the required strict field(s)")
1101 missingFields :: DataCon -> [FieldLabel] -> SDoc
1102 missingFields con fields
1103 = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:")
1104 <+> pprWithCommas ppr fields
1106 wrongArgsCtxt too_many_or_few fun args
1107 = hang (ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1108 <+> ptext SLIT("is applied to") <+> text too_many_or_few
1109 <+> ptext SLIT("arguments in the call"))
1110 4 (parens (ppr the_app))
1112 the_app = foldl mkHsApp fun args -- Used in error messages
1115 polySpliceErr :: Id -> SDoc
1117 = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)