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.
398 -- For record update we require that every constructor involved in the
399 -- update (i.e. that has all the specified fields) is "vanilla". I
400 -- don't know how to do the update otherwise.
403 tcExpr expr@(RecordUpd record_expr rbinds _ _) res_ty
404 = addErrCtxt (recordUpdCtxt expr) $
407 -- Check that the field names are really field names
408 ASSERT( notNull rbinds )
410 field_names = map fst rbinds
412 mappM (tcLookupGlobalId.unLoc) field_names `thenM` \ sel_ids ->
413 -- The renamer has already checked that they
416 bad_guys = [ setSrcSpan loc $ addErrTc (notSelector field_name)
417 | (L loc field_name, sel_id) <- field_names `zip` sel_ids,
418 not (isRecordSelector sel_id) -- Excludes class ops
421 checkM (null bad_guys) (sequenceM bad_guys `thenM_` failM) `thenM_`
424 -- Figure out the tycon and data cons from the first field name
426 -- It's OK to use the non-tc splitters here (for a selector)
427 upd_field_lbls = recBindFields rbinds
429 (tycon, _) = recordSelectorFieldLabel sel_id -- We've failed already if
430 data_cons = tyConDataCons tycon -- it's not a field label
431 relevant_cons = filter is_relevant data_cons
432 is_relevant con = all (`elem` dataConFieldLabels con) upd_field_lbls
436 -- Check that at least one constructor has all the named fields
437 -- i.e. has an empty set of bad fields returned by badFields
438 checkTc (not (null relevant_cons))
439 (badFieldsUpd rbinds) `thenM_`
441 -- Check that all relevant data cons are vanilla. Doing record updates on
442 -- GADTs and/or existentials is more than my tiny brain can cope with today
443 checkTc (all isVanillaDataCon relevant_cons)
444 (nonVanillaUpd tycon) `thenM_`
447 -- Use the un-updated fields to find a vector of booleans saying
448 -- which type arguments must be the same in updatee and result.
450 -- WARNING: this code assumes that all data_cons in a common tycon
451 -- have FieldLabels abstracted over the same tyvars.
453 -- A constructor is only relevant to this process if
454 -- it contains *all* the fields that are being updated
455 con1 = head relevant_cons -- A representative constructor
456 con1_tyvars = dataConTyVars con1
457 con1_fld_tys = dataConFieldLabels con1 `zip` dataConOrigArgTys con1
458 common_tyvars = tyVarsOfTypes [ty | (fld,ty) <- con1_fld_tys
459 , not (fld `elem` upd_field_lbls) ]
461 is_common_tv tv = tv `elemVarSet` common_tyvars
463 mk_inst_ty tv result_inst_ty
464 | is_common_tv tv = returnM result_inst_ty -- Same as result type
465 | otherwise = newTyFlexiVarTy (tyVarKind tv) -- Fresh type, of correct kind
467 tcInstTyVars con1_tyvars `thenM` \ (_, result_inst_tys, inst_env) ->
468 zipWithM mk_inst_ty con1_tyvars result_inst_tys `thenM` \ inst_tys ->
471 -- Typecheck the update bindings.
472 -- (Do this after checking for bad fields in case there's a field that
473 -- doesn't match the constructor.)
475 result_record_ty = mkTyConApp tycon result_inst_tys
476 inst_fld_tys = [(fld, substTy inst_env ty) | (fld, ty) <- con1_fld_tys]
478 zapExpectedTo res_ty result_record_ty `thenM_`
479 tcRecordBinds con1 inst_fld_tys rbinds `thenM` \ rbinds' ->
482 -- Typecheck the expression to be updated
484 record_ty = ASSERT( length inst_tys == tyConArity tycon )
485 mkTyConApp tycon inst_tys
486 -- This is one place where the isVanilla check is important
487 -- So that inst_tys matches the tycon
489 tcCheckRho record_expr record_ty `thenM` \ record_expr' ->
492 -- Figure out the LIE we need. We have to generate some
493 -- dictionaries for the data type context, since we are going to
494 -- do pattern matching over the data cons.
496 -- What dictionaries do we need?
497 -- We just take the context of the first data constructor
498 -- This isn't right, but I just can't bear to union up all the relevant ones
500 theta' = substTheta inst_env (tyConStupidTheta tycon)
502 newDicts RecordUpdOrigin theta' `thenM` \ dicts ->
503 extendLIEs dicts `thenM_`
506 returnM (RecordUpd record_expr' rbinds' record_ty result_record_ty)
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 = zapToListTy res_ty `thenM` \ elt_ty ->
521 tcCheckRho expr elt_ty `thenM` \ expr' ->
523 newMethodFromName (ArithSeqOrigin seq)
524 elt_ty enumFromName `thenM` \ enum_from ->
526 returnM (ArithSeq (HsVar enum_from) (From expr'))
528 tcExpr in_expr@(ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
529 = addErrCtxt (arithSeqCtxt in_expr) $
530 zapToListTy res_ty `thenM` \ elt_ty ->
531 tcCheckRho expr1 elt_ty `thenM` \ expr1' ->
532 tcCheckRho expr2 elt_ty `thenM` \ expr2' ->
533 newMethodFromName (ArithSeqOrigin seq)
534 elt_ty enumFromThenName `thenM` \ enum_from_then ->
536 returnM (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2'))
539 tcExpr in_expr@(ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
540 = addErrCtxt (arithSeqCtxt in_expr) $
541 zapToListTy res_ty `thenM` \ elt_ty ->
542 tcCheckRho expr1 elt_ty `thenM` \ expr1' ->
543 tcCheckRho expr2 elt_ty `thenM` \ expr2' ->
544 newMethodFromName (ArithSeqOrigin seq)
545 elt_ty enumFromToName `thenM` \ enum_from_to ->
547 returnM (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2'))
549 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
550 = addErrCtxt (arithSeqCtxt in_expr) $
551 zapToListTy res_ty `thenM` \ elt_ty ->
552 tcCheckRho expr1 elt_ty `thenM` \ expr1' ->
553 tcCheckRho expr2 elt_ty `thenM` \ expr2' ->
554 tcCheckRho expr3 elt_ty `thenM` \ expr3' ->
555 newMethodFromName (ArithSeqOrigin seq)
556 elt_ty enumFromThenToName `thenM` \ eft ->
558 returnM (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3'))
560 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
561 = addErrCtxt (parrSeqCtxt in_expr) $
562 zapToTyConApp parrTyCon res_ty `thenM` \ [elt_ty] ->
563 tcCheckRho expr1 elt_ty `thenM` \ expr1' ->
564 tcCheckRho expr2 elt_ty `thenM` \ expr2' ->
565 newMethodFromName (PArrSeqOrigin seq)
566 elt_ty enumFromToPName `thenM` \ enum_from_to ->
568 returnM (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2'))
570 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
571 = addErrCtxt (parrSeqCtxt in_expr) $
572 zapToTyConApp parrTyCon res_ty `thenM` \ [elt_ty] ->
573 tcCheckRho expr1 elt_ty `thenM` \ expr1' ->
574 tcCheckRho expr2 elt_ty `thenM` \ expr2' ->
575 tcCheckRho expr3 elt_ty `thenM` \ expr3' ->
576 newMethodFromName (PArrSeqOrigin seq)
577 elt_ty enumFromThenToPName `thenM` \ eft ->
579 returnM (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3'))
581 tcExpr (PArrSeq _ _) _
582 = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
583 -- the parser shouldn't have generated it and the renamer shouldn't have
588 %************************************************************************
592 %************************************************************************
595 #ifdef GHCI /* Only if bootstrapped */
596 -- Rename excludes these cases otherwise
597 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
598 tcExpr (HsBracket brack) res_ty = do { e <- tcBracket brack res_ty
604 %************************************************************************
608 %************************************************************************
611 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
615 %************************************************************************
617 \subsection{@tcApp@ typchecks an application}
619 %************************************************************************
623 tcApp :: LHsExpr Name -> [LHsExpr Name] -- Function and args
624 -> Expected TcRhoType -- Expected result type of application
625 -> TcM (HsExpr TcId) -- Translated fun and args
627 tcApp (L _ (HsApp e1 e2)) args res_ty
628 = tcApp e1 (e2:args) res_ty -- Accumulate the arguments
630 tcApp fun args res_ty
631 = do { let n_args = length args
632 ; (fun', fun_tvs, fun_tau) <- tcFun fun -- Type-check the function
634 -- Extract its argument types
635 ; (expected_arg_tys, actual_res_ty)
636 <- do { traceTc (text "tcApp" <+> (ppr fun $$ ppr fun_tau))
637 ; let msg = sep [ptext SLIT("The function") <+> quotes (ppr fun),
638 ptext SLIT("is applied to")
639 <+> speakN n_args <+> ptext SLIT("arguments")]
640 ; unifyFunTys msg n_args fun_tau }
643 Check _ -> do -- Connect to result type first
644 -- See Note [Push result type in]
645 { co_fn <- tcResult fun args res_ty actual_res_ty
646 ; the_app' <- tcArgs fun fun' args expected_arg_tys
647 ; traceTc (text "tcApp: check" <+> vcat [ppr fun <+> ppr args,
648 ppr the_app', ppr actual_res_ty])
649 ; returnM (co_fn <$> the_app') }
651 Infer _ -> do -- Type check args first, then
652 -- refine result type, then do tcResult
653 { the_app' <- tcArgs fun fun' args expected_arg_tys
654 ; subst <- refineTyVars fun_tvs
655 ; let actual_res_ty' = substTy subst actual_res_ty
656 ; co_fn <- tcResult fun args res_ty actual_res_ty'
657 ; traceTc (text "tcApp: infer" <+> vcat [ppr fun <+> ppr args, ppr the_app',
658 ppr actual_res_ty, ppr actual_res_ty'])
659 ; returnM (co_fn <$> the_app') }
662 -- Note [Push result type in]
664 -- Unify with expected result before (was: after) type-checking the args
665 -- so that the info from res_ty (was: args) percolates to args (was actual_res_ty).
666 -- This is when we might detect a too-few args situation.
667 -- (One can think of cases when the opposite order would give
668 -- a better error message.)
669 -- [March 2003: I'm experimenting with putting this first. Here's an
670 -- example where it actually makes a real difference
671 -- class C t a b | t a -> b
672 -- instance C Char a Bool
674 -- data P t a = forall b. (C t a b) => MkP b
675 -- data Q t = MkQ (forall a. P t a)
678 -- f1 = MkQ (MkP True)
679 -- f2 = MkQ (MkP True :: forall a. P Char a)
681 -- With the change, f1 will type-check, because the 'Char' info from
682 -- the signature is propagated into MkQ's argument. With the check
683 -- in the other order, the extra signature in f2 is reqd.]
686 tcFun :: LHsExpr Name -> TcM (LHsExpr TcId, [TcTyVar], TcRhoType)
687 -- Instantiate the function, returning the type variables used
688 -- If the function isn't simple, infer its type, and return no
690 tcFun (L loc (HsVar f)) = setSrcSpan loc $ do
691 { (fun', tvs, fun_tau) <- tcId (OccurrenceOf f) f
692 ; return (L loc fun', tvs, fun_tau) }
693 tcFun fun = do { (fun', fun_tau) <- tcInfer (tcMonoExpr fun)
694 ; return (fun', [], fun_tau) }
697 tcArgs :: LHsExpr Name -- The function (for error messages)
698 -> LHsExpr TcId -- The function (to build into result)
699 -> [LHsExpr Name] -> [TcSigmaType] -- Actual arguments and expected arg types
700 -> TcM (HsExpr TcId) -- Resulting application
702 tcArgs fun fun' args expected_arg_tys
703 = do { args' <- mappM (tcArg fun) (zip3 args expected_arg_tys [1..])
704 ; return (unLoc (foldl mkHsApp fun' args')) }
706 tcArg :: LHsExpr Name -- The function (for error messages)
707 -> (LHsExpr Name, TcSigmaType, Int) -- Actual argument and expected arg type
708 -> TcM (LHsExpr TcId) -- Resulting argument
709 tcArg fun (arg, ty, arg_no) = addErrCtxt (funAppCtxt fun arg arg_no)
710 (tcCheckSigma arg ty)
713 tcResult fun args res_ty actual_res_ty
714 = addErrCtxtM (checkArgsCtxt fun args res_ty actual_res_ty)
715 (tcSubExp res_ty actual_res_ty)
718 -- If an error happens we try to figure out whether the
719 -- function has been given too many or too few arguments,
721 -- The ~(Check...) is because in the Infer case the tcSubExp
722 -- definitely won't fail, so we can be certain we're in the Check branch
723 checkArgsCtxt fun args (Infer _) actual_res_ty tidy_env
724 = return (tidy_env, ptext SLIT("Urk infer"))
726 checkArgsCtxt fun args (Check expected_res_ty) actual_res_ty tidy_env
727 = zonkTcType expected_res_ty `thenM` \ exp_ty' ->
728 zonkTcType actual_res_ty `thenM` \ act_ty' ->
730 (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
731 (env2, act_ty'') = tidyOpenType env1 act_ty'
732 (exp_args, _) = tcSplitFunTys exp_ty''
733 (act_args, _) = tcSplitFunTys act_ty''
735 len_act_args = length act_args
736 len_exp_args = length exp_args
738 message | len_exp_args < len_act_args = wrongArgsCtxt "too few" fun args
739 | len_exp_args > len_act_args = wrongArgsCtxt "too many" fun args
740 | otherwise = appCtxt fun args
742 returnM (env2, message)
745 unifyInfixTy :: LHsExpr Name -> HsExpr Name -> TcType
746 -> TcM ([TcType], TcType)
747 -- This wrapper just prepares the error message for unifyFunTys
748 unifyInfixTy op expr op_ty
749 = unifyFunTys msg 2 op_ty
751 msg = sep [herald <+> quotes (ppr expr),
752 ptext SLIT("requires") <+> quotes (ppr op)
753 <+> ptext SLIT("to take two arguments")]
754 herald = case expr of
755 OpApp _ _ _ _ -> ptext SLIT("The infix expression")
756 other -> ptext SLIT("The operator section")
760 %************************************************************************
762 \subsection{@tcId@ typchecks an identifier occurrence}
764 %************************************************************************
766 tcId instantiates an occurrence of an Id.
767 The instantiate_it loop runs round instantiating the Id.
768 It has to be a loop because we are now prepared to entertain
770 f:: forall a. Eq a => forall b. Baz b => tau
771 We want to instantiate this to
772 f2::tau {f2 = f1 b (Baz b), f1 = f a (Eq a)}
774 The -fno-method-sharing flag controls what happens so far as the LIE
775 is concerned. The default case is that for an overloaded function we
776 generate a "method" Id, and add the Method Inst to the LIE. So you get
779 f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
780 If you specify -fno-method-sharing, the dictionary application
781 isn't shared, so we get
783 f = /\a (d:Num a) (x:a) -> (+) a d x x
784 This gets a bit less sharing, but
785 a) it's better for RULEs involving overloaded functions
786 b) perhaps fewer separated lambdas
789 tcId :: InstOrigin -> Name -> TcM (HsExpr TcId, [TcTyVar], TcRhoType)
790 -- Return the type variables at which the function
791 -- is instantiated, as well as the translated variable and its type
793 tcId orig id_name -- Look up the Id and instantiate its type
794 = tcLookup id_name `thenM` \ thing ->
796 AGlobal (ADataCon con) -- Similar, but instantiate the stupid theta too
797 -> do { (expr, tvs, tau) <- instantiate (dataConWrapId con)
798 ; tcInstStupidTheta con (mkTyVarTys tvs)
799 -- Remember to chuck in the constraints from the "silly context"
800 ; return (expr, tvs, tau) }
802 ; AGlobal (AnId id) | isNaughtyRecordSelector id
803 -> failWithTc (naughtyRecordSel id)
804 ; AGlobal (AnId id) -> instantiate id
805 -- A global cannot possibly be ill-staged
806 -- nor does it need the 'lifting' treatment
808 ; ATcId id th_level -> tc_local_id id th_level
810 ; other -> failWithTc (ppr other <+> ptext SLIT("used where a value identifer was expected"))
815 tc_local_id id th_bind_lvl -- Non-TH case
818 #else /* GHCI and TH is on */
819 tc_local_id id th_bind_lvl -- TH case
820 = -- Check for cross-stage lifting
821 getStage `thenM` \ use_stage ->
823 Brack use_lvl ps_var lie_var
824 | use_lvl > th_bind_lvl
825 -> if isExternalName id_name then
826 -- Top-level identifiers in this module,
827 -- (which have External Names)
828 -- are just like the imported case:
829 -- no need for the 'lifting' treatment
830 -- E.g. this is fine:
833 -- But we do need to put f into the keep-alive
834 -- set, because after desugaring the code will
835 -- only mention f's *name*, not f itself.
836 keepAliveTc id_name `thenM_`
839 else -- Nested identifiers, such as 'x' in
840 -- E.g. \x -> [| h x |]
841 -- We must behave as if the reference to x was
843 -- We use 'x' itself as the splice proxy, used by
844 -- the desugarer to stitch it all back together.
845 -- If 'x' occurs many times we may get many identical
846 -- bindings of the same splice proxy, but that doesn't
847 -- matter, although it's a mite untidy.
851 checkTc (isTauTy id_ty) (polySpliceErr id) `thenM_`
852 -- If x is polymorphic, its occurrence sites might
853 -- have different instantiations, so we can't use plain
854 -- 'x' as the splice proxy name. I don't know how to
855 -- solve this, and it's probably unimportant, so I'm
856 -- just going to flag an error for now
859 newMethodFromName orig id_ty DsMeta.liftName `thenM` \ lift ->
860 -- Put the 'lift' constraint into the right LIE
862 -- Update the pending splices
863 readMutVar ps_var `thenM` \ ps ->
864 writeMutVar ps_var ((id_name, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps) `thenM_`
866 returnM (HsVar id, [], id_ty))
869 checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage `thenM_`
873 instantiate :: TcId -> TcM (HsExpr TcId, [TcTyVar], TcRhoType)
874 instantiate fun_id = loop (HsVar fun_id) [] (idType fun_id)
876 loop (HsVar fun_id) tvs fun_ty
877 | want_method_inst fun_ty
878 = tcInstType fun_ty `thenM` \ (tyvars, theta, tau) ->
879 newMethodWithGivenTy orig fun_id
880 (mkTyVarTys tyvars) theta tau `thenM` \ meth_id ->
881 loop (HsVar meth_id) (tvs ++ tyvars) tau
885 = tcInstCall orig fun_ty `thenM` \ (inst_fn, new_tvs, tau) ->
886 loop (inst_fn <$> fun) (tvs ++ new_tvs) tau
889 = returnM (fun, tvs, fun_ty)
891 -- Hack Alert (want_method_inst)!
892 -- If f :: (%x :: T) => Int -> Int
893 -- Then if we have two separate calls, (f 3, f 4), we cannot
894 -- make a method constraint that then gets shared, thus:
895 -- let m = f %x in (m 3, m 4)
896 -- because that loses the linearity of the constraint.
897 -- The simplest thing to do is never to construct a method constraint
898 -- in the first place that has a linear implicit parameter in it.
899 want_method_inst fun_ty
900 | opt_NoMethodSharing = False
901 | otherwise = case tcSplitSigmaTy fun_ty of
902 (_,[],_) -> False -- Not overloaded
903 (_,theta,_) -> not (any isLinearPred theta)
906 %************************************************************************
908 \subsection{Record bindings}
910 %************************************************************************
912 Game plan for record bindings
913 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
914 1. Find the TyCon for the bindings, from the first field label.
916 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
918 For each binding field = value
920 3. Instantiate the field type (from the field label) using the type
923 4 Type check the value using tcArg, passing the field type as
924 the expected argument type.
926 This extends OK when the field types are universally quantified.
932 -> [(FieldLabel,TcType)] -- Expected type for each field
933 -> HsRecordBinds Name
934 -> TcM (HsRecordBinds TcId)
936 tcRecordBinds data_con flds_w_tys rbinds
937 = do { mb_binds <- mappM do_bind rbinds
938 ; return (catMaybes mb_binds) }
940 do_bind (L loc field_lbl, rhs)
941 | Just field_ty <- assocMaybe flds_w_tys field_lbl
942 = addErrCtxt (fieldCtxt field_lbl) $
943 do { rhs' <- tcCheckSigma rhs field_ty
944 ; sel_id <- tcLookupId field_lbl
945 ; ASSERT( isRecordSelector sel_id )
946 return (Just (L loc sel_id, rhs')) }
948 = do { addErrTc (badFieldCon data_con field_lbl)
951 badFields rbinds data_con
952 = filter (not . (`elem` field_names)) (recBindFields rbinds)
954 field_names = dataConFieldLabels data_con
956 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
957 checkMissingFields data_con rbinds
958 | null field_labels -- Not declared as a record;
959 -- But C{} is still valid if no strict fields
960 = if any isMarkedStrict field_strs then
961 -- Illegal if any arg is strict
962 addErrTc (missingStrictFields data_con [])
966 | otherwise -- A record
967 = checkM (null missing_s_fields)
968 (addErrTc (missingStrictFields data_con missing_s_fields)) `thenM_`
970 doptM Opt_WarnMissingFields `thenM` \ warn ->
971 checkM (not (warn && notNull missing_ns_fields))
972 (warnTc True (missingFields data_con missing_ns_fields))
976 = [ fl | (fl, str) <- field_info,
978 not (fl `elem` field_names_used)
981 = [ fl | (fl, str) <- field_info,
982 not (isMarkedStrict str),
983 not (fl `elem` field_names_used)
986 field_names_used = recBindFields rbinds
987 field_labels = dataConFieldLabels data_con
989 field_info = zipEqual "missingFields"
993 field_strs = dataConStrictMarks data_con
996 %************************************************************************
998 \subsection{@tcCheckRhos@ typechecks a {\em list} of expressions}
1000 %************************************************************************
1003 tcCheckRhos :: [LHsExpr Name] -> [TcType] -> TcM [LHsExpr TcId]
1005 tcCheckRhos [] [] = returnM []
1006 tcCheckRhos (expr:exprs) (ty:tys)
1007 = tcCheckRho expr ty `thenM` \ expr' ->
1008 tcCheckRhos exprs tys `thenM` \ exprs' ->
1009 returnM (expr':exprs')
1010 tcCheckRhos exprs tys = pprPanic "tcCheckRhos" (ppr exprs $$ ppr tys)
1014 %************************************************************************
1016 \subsection{Literals}
1018 %************************************************************************
1020 Overloaded literals.
1023 tcLit :: HsLit -> Expected TcRhoType -> TcM (HsExpr TcId)
1025 = zapExpectedTo res_ty (hsLitType lit) `thenM_`
1030 %************************************************************************
1032 \subsection{Errors and contexts}
1034 %************************************************************************
1036 Boring and alphabetical:
1039 = hang (ptext SLIT("In an arithmetic sequence:")) 4 (ppr expr)
1042 = hang (ptext SLIT("In a parallel array sequence:")) 4 (ppr expr)
1045 = hang (ptext SLIT("In the case expression:")) 4 (ppr expr)
1048 = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1051 = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1053 fieldCtxt field_name
1054 = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1056 funAppCtxt fun arg arg_no
1057 = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"),
1058 quotes (ppr fun) <> text ", namely"])
1059 4 (quotes (ppr arg))
1062 = hang (ptext SLIT("In the list element:")) 4 (ppr expr)
1065 = hang (ptext SLIT("In the parallel array element:")) 4 (ppr expr)
1068 = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1071 = ptext SLIT("In the application") <+> quotes (ppr the_app)
1073 the_app = foldl mkHsApp fun args -- Used in error messages
1076 = vcat [ptext SLIT("Record update for the non-Haskell-98 data type") <+> quotes (ppr tycon)
1077 <+> ptext SLIT("is not (yet) supported"),
1078 ptext SLIT("Use pattern-matching instead")]
1080 = hang (ptext SLIT("No constructor has all these fields:"))
1081 4 (pprQuotedList (recBindFields rbinds))
1083 recordUpdCtxt expr = ptext SLIT("In the record update:") <+> ppr expr
1084 recordConCtxt expr = ptext SLIT("In the record construction:") <+> ppr expr
1086 naughtyRecordSel sel_id
1087 = ptext SLIT("Cannot use record selector") <+> quotes (ppr sel_id) <+>
1088 ptext SLIT("as a function due to escaped type variables") $$
1089 ptext SLIT("Probably fix: use pattern-matching syntax instead")
1092 = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1094 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1095 missingStrictFields con fields
1098 rest | null fields = empty -- Happens for non-record constructors
1099 -- with strict fields
1100 | otherwise = colon <+> pprWithCommas ppr fields
1102 header = ptext SLIT("Constructor") <+> quotes (ppr con) <+>
1103 ptext SLIT("does not have the required strict field(s)")
1105 missingFields :: DataCon -> [FieldLabel] -> SDoc
1106 missingFields con fields
1107 = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:")
1108 <+> pprWithCommas ppr fields
1110 wrongArgsCtxt too_many_or_few fun args
1111 = hang (ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1112 <+> ptext SLIT("is applied to") <+> text too_many_or_few
1113 <+> ptext SLIT("arguments in the call"))
1114 4 (parens (ppr the_app))
1116 the_app = foldl mkHsApp fun args -- Used in error messages
1119 polySpliceErr :: Id -> SDoc
1121 = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)