2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 \section[TcExpr]{Typecheck an expression}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 module TcExpr ( tcPolyExpr, tcPolyExprNC, tcMonoExpr, tcMonoExprNC,
15 tcInferRho, tcInferRhoNC,
16 tcSyntaxOp, tcCheckId,
17 addExprErrCtxt ) where
19 #include "HsVersions.h"
21 #ifdef GHCI /* Only if bootstrapped */
22 import {-# SOURCE #-} TcSplice( tcSpliceExpr, tcBracket )
23 import qualified DsMeta
51 import TysPrim( intPrimTy, ecKind )
52 import PrimOp( tagToEnumKey )
66 %************************************************************************
68 \subsection{Main wrappers}
70 %************************************************************************
73 tcPolyExpr, tcPolyExprNC
74 :: LHsExpr Name -- Expression to type check
75 -> TcSigmaType -- Expected type (could be a polytpye)
76 -> TcM (LHsExpr TcId) -- Generalised expr with expected type
78 -- tcPolyExpr is a convenient place (frequent but not too frequent)
79 -- place to add context information.
80 -- The NC version does not do so, usually because the caller wants
83 tcPolyExpr expr res_ty
84 = addExprErrCtxt expr $
85 do { traceTc "tcPolyExpr" (ppr res_ty); tcPolyExprNC expr res_ty }
87 tcPolyExprNC expr res_ty
88 = do { traceTc "tcPolyExprNC" (ppr res_ty)
89 ; (gen_fn, expr') <- tcGen GenSigCtxt res_ty $ \ _ rho ->
91 ; return (mkLHsWrap gen_fn expr') }
94 tcMonoExpr, tcMonoExprNC
95 :: LHsExpr Name -- Expression to type check
96 -> TcRhoType -- Expected type (could be a type variable)
97 -- Definitely no foralls at the top
100 tcMonoExpr expr res_ty
101 = addErrCtxt (exprCtxt expr) $
102 tcMonoExprNC expr res_ty
104 tcMonoExprNC (L loc expr) res_ty
105 = ASSERT( not (isSigmaTy res_ty) )
107 do { expr' <- tcExpr expr res_ty
108 ; return (L loc expr') }
111 tcInferRho, tcInferRhoNC :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
112 -- Infer a *rho*-type. This is, in effect, a special case
113 -- for ids and partial applications, so that if
114 -- f :: Int -> (forall a. a -> a) -> Int
116 -- f 3 :: (forall a. a -> a) -> Int
117 -- And that in turn is useful
118 -- (a) for the function part of any application (see tcApp)
119 -- (b) for the special rule for '$'
120 tcInferRho expr = addErrCtxt (exprCtxt expr) (tcInferRhoNC expr)
122 tcInferRhoNC (L loc expr)
124 do { (expr', rho) <- tcInfExpr expr
125 ; return (L loc expr', rho) }
127 tcInfExpr :: HsExpr Name -> TcM (HsExpr TcId, TcRhoType)
128 tcInfExpr (HsVar f) = tcInferId f
129 tcInfExpr (HsPar e) = do { (e', ty) <- tcInferRhoNC e
130 ; return (HsPar e', ty) }
131 tcInfExpr (HsApp e1 e2) = tcInferApp e1 [e2]
132 tcInfExpr e = tcInfer (tcExpr e)
136 %************************************************************************
138 tcExpr: the main expression typechecker
140 %************************************************************************
144 updHetMetLevel :: ([TyVar] -> [TyVar]) -> TcM a -> TcM a
145 updHetMetLevel f comp =
147 (\oldenv -> let oldlev = (case oldenv of Env { env_lcl = e' } -> case e' of TcLclEnv { tcl_hetMetLevel = x } -> x)
148 in (oldenv { env_lcl = (env_lcl oldenv) { tcl_hetMetLevel = f oldlev } }))
152 addEscapes :: [TyVar] -> HsExpr Name -> HsExpr Name
154 addEscapes (t:ts) e = HsHetMetEsc (TyVarTy t) placeHolderType (noLoc (addEscapes ts e))
156 getIdLevel :: Name -> TcM [TyVar]
158 = do { thing <- tcLookup name
160 ATcId { tct_hetMetLevel = variable_hetMetLevel } -> return $ variable_hetMetLevel
164 tcExpr :: HsExpr Name -> TcRhoType -> TcM (HsExpr TcId)
165 tcExpr e res_ty | debugIsOn && isSigmaTy res_ty -- Sanity check
166 = pprPanic "tcExpr: sigma" (ppr res_ty $$ ppr e)
168 tcExpr (HsVar name) res_ty = tcCheckId name res_ty
170 tcExpr (HsHetMetBrak _ e) res_ty =
171 do { (coi, [inferred_name,elt_ty]) <- matchExpectedTyConApp hetMetCodeTypeTyCon res_ty
172 ; fresh_ec_name <- newFlexiTyVar ecKind
173 ; expr' <- updHetMetLevel (\old_lev -> (fresh_ec_name:old_lev))
174 $ tcPolyExpr e elt_ty
175 ; unifyType (TyVarTy fresh_ec_name) inferred_name
176 ; return $ mkHsWrapCo coi (HsHetMetBrak (TyVarTy fresh_ec_name) expr') }
177 tcExpr (HsHetMetEsc _ _ e) res_ty =
178 do { cur_level <- getHetMetLevel
179 ; expr' <- updHetMetLevel (\old_lev -> tail old_lev)
180 $ tcExpr (unLoc e) (mkTyConApp hetMetCodeTypeTyCon [(TyVarTy $ head cur_level),res_ty])
181 ; ty' <- zonkTcType res_ty
182 ; return $ HsHetMetEsc (TyVarTy $ head cur_level) ty' (noLoc expr') }
183 tcExpr (HsHetMetCSP _ e) res_ty =
184 do { cur_level <- getHetMetLevel
185 ; expr' <- updHetMetLevel (\old_lev -> tail old_lev)
186 $ tcExpr (unLoc e) res_ty
187 ; return $ HsHetMetCSP (TyVarTy $ head cur_level) (noLoc expr') }
189 tcExpr (HsKappa match) res_ty =
190 do { v1 <- newFlexiTyVar liftedTypeKind
191 ; v2 <- newFlexiTyVar liftedTypeKind
192 ; v3 <- newFlexiTyVar liftedTypeKind
193 ; (_, [ty_ab, ty_c]) <- matchExpectedTyConApp hetMetKappaTyCon res_ty
194 ; (_, [ty_a, ty_b]) <- matchExpectedTyConApp pairTyCon ty_ab
195 ; (co_fn, match') <- tcMatchLambda match (mkFunTy
196 (mkHetMetKappaTy unitTy ty_a)
197 (mkHetMetKappaTy ty_b ty_c))
198 ; return (HsKappa match') }
200 tcExpr (HsKappaApp e1 e2) res_ty =
201 do { v1 <- newFlexiTyVar liftedTypeKind
202 ; v2 <- newFlexiTyVar liftedTypeKind
203 ; v3 <- newFlexiTyVar liftedTypeKind
204 ; e1' <- tcExpr (unLoc e1) (mkHetMetKappaTy (mkTyConApp pairTyCon [(TyVarTy v1), (TyVarTy v2)]) (TyVarTy v3))
205 ; e2' <- tcExpr (unLoc e2) (mkHetMetKappaTy unitTy (TyVarTy v1))
206 ; unifyType res_ty (mkHetMetKappaTy (TyVarTy v2) (TyVarTy v3))
207 ; return (HsKappaApp (noLoc e1') (noLoc e2')) }
209 tcExpr (HsApp e1 e2) res_ty = tcApp e1 [e2] res_ty
211 tcExpr (HsLit lit) res_ty =
212 getHetMetLevel >>= \lev ->
214 [] -> do { let lit_ty = hsLitType lit
215 ; tcWrapResult (HsLit lit) lit_ty res_ty }
216 (ec:rest) -> let n = case lit of
217 (HsChar c) -> hetmet_guest_char_literal_name
218 (HsString str) -> hetmet_guest_string_literal_name
219 (HsInteger i _) -> hetmet_guest_integer_literal_name
220 (HsInt i) -> hetmet_guest_integer_literal_name
221 _ -> error "literals of this sort are not allowed at depth >0"
222 in tcExpr (HsHetMetEsc (TyVarTy ec) placeHolderType $ noLoc $
223 (HsApp (noLoc $ HsVar n) (noLoc $ HsLit lit))) res_ty
225 tcExpr (HsPar expr) res_ty = do { expr' <- tcMonoExprNC expr res_ty
226 ; return (HsPar expr') }
228 tcExpr (HsSCC lbl expr) res_ty
229 = do { expr' <- tcMonoExpr expr res_ty
230 ; return (HsSCC lbl expr') }
232 tcExpr (HsTickPragma info expr) res_ty
233 = do { expr' <- tcMonoExpr expr res_ty
234 ; return (HsTickPragma info expr') }
236 tcExpr (HsCoreAnn lbl expr) res_ty
237 = do { expr' <- tcMonoExpr expr res_ty
238 ; return (HsCoreAnn lbl expr') }
240 tcExpr (HsOverLit lit) res_ty =
241 getHetMetLevel >>= \lev ->
243 [] -> do { lit' <- newOverloadedLit (LiteralOrigin lit) lit res_ty
244 ; return (HsOverLit lit') }
245 (ec:rest) -> let n = case lit of
246 (OverLit { ol_val = HsIntegral i }) -> hetmet_guest_integer_literal_name
247 (OverLit { ol_val = HsIsString fs }) -> hetmet_guest_string_literal_name
248 (OverLit { ol_val = HsFractional f }) -> error "fractional literals not allowed at depth >0"
249 in tcExpr (HsHetMetEsc (TyVarTy ec) placeHolderType $ noLoc $
250 (HsApp (noLoc $ HsVar n) (noLoc $ HsOverLit lit))) res_ty
253 tcExpr (NegApp expr neg_expr) res_ty
254 = do { neg_expr' <- tcSyntaxOp NegateOrigin neg_expr
255 (mkFunTy res_ty res_ty)
256 ; expr' <- tcMonoExpr expr res_ty
257 ; return (NegApp expr' neg_expr') }
259 tcExpr (HsIPVar ip) res_ty
260 = do { let origin = IPOccOrigin ip
261 -- Implicit parameters must have a *tau-type* not a
262 -- type scheme. We enforce this by creating a fresh
263 -- type variable as its type. (Because res_ty may not
265 ; ip_ty <- newFlexiTyVarTy argTypeKind -- argTypeKind: it can't be an unboxed tuple
266 ; ip_var <- emitWanted origin (mkIPPred ip ip_ty)
267 ; tcWrapResult (HsIPVar (IPName ip_var)) ip_ty res_ty }
269 tcExpr (HsLam match) res_ty
270 = do { (co_fn, match') <- tcMatchLambda match res_ty
271 ; return (mkHsWrap co_fn (HsLam match')) }
273 tcExpr (ExprWithTySig expr sig_ty) res_ty
274 = do { sig_tc_ty <- tcHsSigType ExprSigCtxt sig_ty
276 -- Remember to extend the lexical type-variable environment
278 <- tcGen ExprSigCtxt sig_tc_ty $ \ skol_tvs res_ty ->
279 tcExtendTyVarEnv2 (hsExplicitTvs sig_ty `zip` mkTyVarTys skol_tvs) $
280 -- See Note [More instantiated than scoped] in TcBinds
281 tcMonoExprNC expr res_ty
283 ; let inner_expr = ExprWithTySigOut (mkLHsWrap gen_fn expr') sig_ty
285 ; (inst_wrap, rho) <- deeplyInstantiate ExprSigOrigin sig_tc_ty
286 ; tcWrapResult (mkHsWrap inst_wrap inner_expr) rho res_ty }
289 = failWithTc (text "Can't handle type argument:" <+> ppr ty)
290 -- This is the syntax for type applications that I was planning
291 -- but there are difficulties (e.g. what order for type args)
292 -- so it's not enabled yet.
293 -- Can't eliminate it altogether from the parser, because the
294 -- same parser parses *patterns*.
298 %************************************************************************
300 Infix operators and sections
302 %************************************************************************
306 Left sections, like (4 *), are equivalent to
308 or, if PostfixOperators is enabled, just
310 With PostfixOperators we don't actually require the function to take
311 two arguments at all. For example, (x `not`) means (not x); you get
312 postfix operators! Not Haskell 98, but it's less work and kind of
315 Note [Typing rule for ($)]
316 ~~~~~~~~~~~~~~~~~~~~~~~~~~
320 runST :: (forall s. ST s a) -> a
321 that I have finally given in and written a special type-checking
322 rule just for saturated appliations of ($).
323 * Infer the type of the first argument
324 * Decompose it; should be of form (arg2_ty -> res_ty),
325 where arg2_ty might be a polytype
326 * Use arg2_ty to typecheck arg2
328 Note [Typing rule for seq]
329 ~~~~~~~~~~~~~~~~~~~~~~~~~~
332 which suggests this type for seq:
333 seq :: forall (a:*) (b:??). a -> b -> b,
334 with (b:??) meaning that be can be instantiated with an unboxed tuple.
335 But that's ill-kinded! Function arguments can't be unboxed tuples.
336 And indeed, you could not expect to do this with a partially-applied
337 'seq'; it's only going to work when it's fully applied. so it turns
339 case x of _ -> (# p,q #)
341 For a while I slid by by giving 'seq' an ill-kinded type, but then
342 the simplifier eta-reduced an application of seq and Lint blew up
343 with a kind error. It seems more uniform to treat 'seq' as it it
344 was a language construct.
346 See Note [seqId magic] in MkId, and
350 tcExpr (OpApp arg1 op fix arg2) res_ty
351 | (L loc (HsVar op_name)) <- op
352 , op_name `hasKey` seqIdKey -- Note [Typing rule for seq]
353 = do { arg1_ty <- newFlexiTyVarTy liftedTypeKind
354 ; let arg2_ty = res_ty
355 ; arg1' <- tcArg op (arg1, arg1_ty, 1)
356 ; arg2' <- tcArg op (arg2, arg2_ty, 2)
357 ; op_id <- tcLookupId op_name
358 ; let op' = L loc (HsWrap (mkWpTyApps [arg1_ty, arg2_ty]) (HsVar op_id))
359 ; return $ OpApp arg1' op' fix arg2' }
361 | (L loc (HsVar op_name)) <- op
362 , op_name `hasKey` dollarIdKey -- Note [Typing rule for ($)]
363 = do { traceTc "Application rule" (ppr op)
364 ; (arg1', arg1_ty) <- tcInferRho arg1
365 ; let doc = ptext (sLit "The first argument of ($) takes")
366 ; (co_arg1, [arg2_ty], op_res_ty) <- matchExpectedFunTys doc 1 arg1_ty
367 -- arg2_ty maybe polymorphic; that's the point
368 ; arg2' <- tcArg op (arg2, arg2_ty, 2)
369 ; co_res <- unifyType op_res_ty res_ty
370 ; op_id <- tcLookupId op_name
371 ; let op' = L loc (HsWrap (mkWpTyApps [arg2_ty, op_res_ty]) (HsVar op_id))
372 ; return $ mkHsWrapCo co_res $
373 OpApp (mkLHsWrapCo co_arg1 arg1') op' fix arg2' }
376 = do { traceTc "Non Application rule" (ppr op)
377 ; (op', op_ty) <- tcInferFun op
378 ; (co_fn, arg_tys, op_res_ty) <- unifyOpFunTys op 2 op_ty
379 ; co_res <- unifyType op_res_ty res_ty
380 ; [arg1', arg2'] <- tcArgs op [arg1, arg2] arg_tys
381 ; return $ mkHsWrapCo co_res $
382 OpApp arg1' (mkLHsWrapCo co_fn op') fix arg2' }
384 -- Right sections, equivalent to \ x -> x `op` expr, or
387 tcExpr (SectionR op arg2) res_ty
388 = do { (op', op_ty) <- tcInferFun op
389 ; (co_fn, [arg1_ty, arg2_ty], op_res_ty) <- unifyOpFunTys op 2 op_ty
390 ; co_res <- unifyType (mkFunTy arg1_ty op_res_ty) res_ty
391 ; arg2' <- tcArg op (arg2, arg2_ty, 2)
392 ; return $ mkHsWrapCo co_res $
393 SectionR (mkLHsWrapCo co_fn op') arg2' }
395 tcExpr (SectionL arg1 op) res_ty
396 = do { (op', op_ty) <- tcInferFun op
397 ; dflags <- getDOpts -- Note [Left sections]
398 ; let n_reqd_args | xopt Opt_PostfixOperators dflags = 1
401 ; (co_fn, (arg1_ty:arg_tys), op_res_ty) <- unifyOpFunTys op n_reqd_args op_ty
402 ; co_res <- unifyType (mkFunTys arg_tys op_res_ty) res_ty
403 ; arg1' <- tcArg op (arg1, arg1_ty, 1)
404 ; return $ mkHsWrapCo co_res $
405 SectionL arg1' (mkLHsWrapCo co_fn op') }
407 tcExpr (ExplicitTuple tup_args boxity) res_ty
408 | all tupArgPresent tup_args
409 = do { let tup_tc = tupleTyCon boxity (length tup_args)
410 ; (coi, arg_tys) <- matchExpectedTyConApp tup_tc res_ty
411 ; tup_args1 <- tcTupArgs tup_args arg_tys
412 ; return $ mkHsWrapCo coi (ExplicitTuple tup_args1 boxity) }
415 = -- The tup_args are a mixture of Present and Missing (for tuple sections)
416 do { let kind = case boxity of { Boxed -> liftedTypeKind
417 ; Unboxed -> argTypeKind }
418 arity = length tup_args
419 tup_tc = tupleTyCon boxity arity
421 ; arg_tys <- newFlexiTyVarTys (tyConArity tup_tc) kind
423 = mkFunTys [ty | (ty, Missing _) <- arg_tys `zip` tup_args]
424 (mkTyConApp tup_tc arg_tys)
426 ; coi <- unifyType actual_res_ty res_ty
428 -- Handle tuple sections where
429 ; tup_args1 <- tcTupArgs tup_args arg_tys
431 ; return $ mkHsWrapCo coi (ExplicitTuple tup_args1 boxity) }
433 tcExpr (ExplicitList _ exprs) res_ty
434 = do { (coi, elt_ty) <- matchExpectedListTy res_ty
435 ; exprs' <- mapM (tc_elt elt_ty) exprs
436 ; return $ mkHsWrapCo coi (ExplicitList elt_ty exprs') }
438 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
440 tcExpr (ExplicitPArr _ exprs) res_ty -- maybe empty
441 = do { (coi, elt_ty) <- matchExpectedPArrTy res_ty
442 ; exprs' <- mapM (tc_elt elt_ty) exprs
443 ; return $ mkHsWrapCo coi (ExplicitPArr elt_ty exprs') }
445 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
448 %************************************************************************
452 %************************************************************************
455 tcExpr (HsLet binds expr) res_ty
456 = do { (binds', expr') <- tcLocalBinds binds $
457 tcMonoExpr expr res_ty
458 ; return (HsLet binds' expr') }
460 tcExpr (HsCase scrut matches) exp_ty
461 = do { -- We used to typecheck the case alternatives first.
462 -- The case patterns tend to give good type info to use
463 -- when typechecking the scrutinee. For example
466 -- will report that map is applied to too few arguments
468 -- But now, in the GADT world, we need to typecheck the scrutinee
469 -- first, to get type info that may be refined in the case alternatives
470 (scrut', scrut_ty) <- tcInferRho scrut
472 ; traceTc "HsCase" (ppr scrut_ty)
473 ; matches' <- tcMatchesCase match_ctxt scrut_ty matches exp_ty
474 ; return (HsCase scrut' matches') }
476 match_ctxt = MC { mc_what = CaseAlt,
479 tcExpr (HsIf Nothing pred b1 b2) res_ty -- Ordinary 'if'
480 = do { pred' <- tcMonoExpr pred boolTy
481 ; b1' <- tcMonoExpr b1 res_ty
482 ; b2' <- tcMonoExpr b2 res_ty
483 ; return (HsIf Nothing pred' b1' b2') }
485 tcExpr (HsIf (Just fun) pred b1 b2) res_ty -- Note [Rebindable syntax for if]
486 = do { pred_ty <- newFlexiTyVarTy openTypeKind
487 ; b1_ty <- newFlexiTyVarTy openTypeKind
488 ; b2_ty <- newFlexiTyVarTy openTypeKind
489 ; let if_ty = mkFunTys [pred_ty, b1_ty, b2_ty] res_ty
490 ; fun' <- tcSyntaxOp IfOrigin fun if_ty
491 ; pred' <- tcMonoExpr pred pred_ty
492 ; b1' <- tcMonoExpr b1 b1_ty
493 ; b2' <- tcMonoExpr b2 b2_ty
494 -- Fundamentally we are just typing (ifThenElse e1 e2 e3)
495 -- so maybe we should use the code for function applications
496 -- (which would allow ifThenElse to be higher rank).
497 -- But it's a little awkward, so I'm leaving it alone for now
498 -- and it maintains uniformity with other rebindable syntax
499 ; return (HsIf (Just fun') pred' b1' b2') }
501 tcExpr (HsDo do_or_lc stmts _) res_ty
502 = tcDoStmts do_or_lc stmts res_ty
504 tcExpr (HsProc pat cmd) res_ty
505 = do { (pat', cmd', coi) <- tcProc pat cmd res_ty
506 ; return $ mkHsWrapCo coi (HsProc pat' cmd') }
508 tcExpr e@(HsArrApp _ _ _ _ _) _
509 = failWithTc (vcat [ptext (sLit "The arrow command"), nest 2 (ppr e),
510 ptext (sLit "was found where an expression was expected")])
512 tcExpr e@(HsArrForm _ _ _) _
513 = failWithTc (vcat [ptext (sLit "The arrow command"), nest 2 (ppr e),
514 ptext (sLit "was found where an expression was expected")])
517 Note [Rebindable syntax for if]
518 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
519 The rebindable syntax for 'if' uses the most flexible possible type
521 ifThenElse :: p -> b1 -> b2 -> res
522 to support expressions like this:
524 ifThenElse :: Maybe a -> (a -> b) -> b -> b
525 ifThenElse (Just a) f _ = f a ifThenElse Nothing _ e = e
533 %************************************************************************
535 Record construction and update
537 %************************************************************************
540 tcExpr (RecordCon (L loc con_name) _ rbinds) res_ty
541 = do { data_con <- tcLookupDataCon con_name
543 -- Check for missing fields
544 ; checkMissingFields data_con rbinds
546 ; (con_expr, con_tau) <- tcInferId con_name
547 ; let arity = dataConSourceArity data_con
548 (arg_tys, actual_res_ty) = tcSplitFunTysN con_tau arity
549 con_id = dataConWrapId data_con
551 ; co_res <- unifyType actual_res_ty res_ty
552 ; rbinds' <- tcRecordBinds data_con arg_tys rbinds
553 ; return $ mkHsWrapCo co_res $
554 RecordCon (L loc con_id) con_expr rbinds' }
557 Note [Type of a record update]
558 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
559 The main complication with RecordUpd is that we need to explicitly
560 handle the *non-updated* fields. Consider:
562 data T a b c = MkT1 { fa :: a, fb :: (b,c) }
563 | MkT2 { fa :: a, fb :: (b,c), fc :: c -> c }
566 upd :: T a b c -> (b',c) -> T a b' c
567 upd t x = t { fb = x}
569 The result type should be (T a b' c)
570 not (T a b c), because 'b' *is not* mentioned in a non-updated field
571 not (T a b' c'), becuase 'c' *is* mentioned in a non-updated field
572 NB that it's not good enough to look at just one constructor; we must
573 look at them all; cf Trac #3219
575 After all, upd should be equivalent to:
581 So we need to give a completely fresh type to the result record,
582 and then constrain it by the fields that are *not* updated ("p" above).
583 We call these the "fixed" type variables, and compute them in getFixedTyVars.
585 Note that because MkT3 doesn't contain all the fields being updated,
586 its RHS is simply an error, so it doesn't impose any type constraints.
587 Hence the use of 'relevant_cont'.
589 Note [Implict type sharing]
590 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
591 We also take into account any "implicit" non-update fields. For example
592 data T a b where { MkT { f::a } :: T a a; ... }
593 So the "real" type of MkT is: forall ab. (a~b) => a -> T a b
598 upd :: T a b -> a -> T a b
599 upd (t::T a b) (x::a)
600 = case t of { MkT (co:a~b) (_:a) -> MkT co x }
601 We can't give it the more general type
602 upd :: T a b -> c -> T c b
604 Note [Criteria for update]
605 ~~~~~~~~~~~~~~~~~~~~~~~~~~
606 We want to allow update for existentials etc, provided the updated
607 field isn't part of the existential. For example, this should be ok.
608 data T a where { MkT { f1::a, f2::b->b } :: T a }
612 The criterion we use is this:
614 The types of the updated fields
615 mention only the universally-quantified type variables
616 of the data constructor
618 NB: this is not (quite) the same as being a "naughty" record selector
619 (See Note [Naughty record selectors]) in TcTyClsDecls), at least
620 in the case of GADTs. Consider
621 data T a where { MkT :: { f :: a } :: T [a] }
622 Then f is not "naughty" because it has a well-typed record selector.
623 But we don't allow updates for 'f'. (One could consider trying to
624 allow this, but it makes my head hurt. Badly. And no one has asked
627 In principle one could go further, and allow
629 g t = t { f2 = \x -> x }
630 because the expression is polymorphic...but that seems a bridge too far.
632 Note [Data family example]
633 ~~~~~~~~~~~~~~~~~~~~~~~~~~
634 data instance T (a,b) = MkT { x::a, y::b }
636 data :TP a b = MkT { a::a, y::b }
637 coTP a b :: T (a,b) ~ :TP a b
639 Suppose r :: T (t1,t2), e :: t3
640 Then r { x=e } :: T (t3,t1)
643 MkT x y -> MkT e y |> co2
644 where co1 :: T (t1,t2) ~ :TP t1 t2
645 co2 :: :TP t3 t2 ~ T (t3,t2)
646 The wrapping with co2 is done by the constructor wrapper for MkT
650 In the outgoing (HsRecordUpd scrut binds cons in_inst_tys out_inst_tys):
652 * cons are the data constructors to be updated
654 * in_inst_tys, out_inst_tys have same length, and instantiate the
655 *representation* tycon of the data cons. In Note [Data
656 family example], in_inst_tys = [t1,t2], out_inst_tys = [t3,t2]
659 tcExpr (RecordUpd record_expr rbinds _ _ _) res_ty
660 = ASSERT( notNull upd_fld_names )
663 -- Check that the field names are really field names
664 ; sel_ids <- mapM tcLookupField upd_fld_names
665 -- The renamer has already checked that
666 -- selectors are all in scope
667 ; let bad_guys = [ setSrcSpan loc $ addErrTc (notSelector fld_name)
668 | (fld, sel_id) <- rec_flds rbinds `zip` sel_ids,
669 not (isRecordSelector sel_id), -- Excludes class ops
670 let L loc fld_name = hsRecFieldId fld ]
671 ; unless (null bad_guys) (sequence bad_guys >> failM)
674 -- Figure out the tycon and data cons from the first field name
675 ; let -- It's OK to use the non-tc splitters here (for a selector)
677 (tycon, _) = recordSelectorFieldLabel sel_id -- We've failed already if
678 data_cons = tyConDataCons tycon -- it's not a field label
679 -- NB: for a data type family, the tycon is the instance tycon
681 relevant_cons = filter is_relevant data_cons
682 is_relevant con = all (`elem` dataConFieldLabels con) upd_fld_names
683 -- A constructor is only relevant to this process if
684 -- it contains *all* the fields that are being updated
685 -- Other ones will cause a runtime error if they occur
687 -- Take apart a representative constructor
688 con1 = ASSERT( not (null relevant_cons) ) head relevant_cons
689 (con1_tvs, _, _, _, con1_arg_tys, _) = dataConFullSig con1
690 con1_flds = dataConFieldLabels con1
691 con1_res_ty = mkFamilyTyConApp tycon (mkTyVarTys con1_tvs)
694 -- Check that at least one constructor has all the named fields
695 -- i.e. has an empty set of bad fields returned by badFields
696 ; checkTc (not (null relevant_cons)) (badFieldsUpd rbinds)
698 -- STEP 3 Note [Criteria for update]
699 -- Check that each updated field is polymorphic; that is, its type
700 -- mentions only the universally-quantified variables of the data con
701 ; let flds1_w_tys = zipEqual "tcExpr:RecConUpd" con1_flds con1_arg_tys
702 upd_flds1_w_tys = filter is_updated flds1_w_tys
703 is_updated (fld,_) = fld `elem` upd_fld_names
705 bad_upd_flds = filter bad_fld upd_flds1_w_tys
706 con1_tv_set = mkVarSet con1_tvs
707 bad_fld (fld, ty) = fld `elem` upd_fld_names &&
708 not (tyVarsOfType ty `subVarSet` con1_tv_set)
709 ; checkTc (null bad_upd_flds) (badFieldTypes bad_upd_flds)
711 -- STEP 4 Note [Type of a record update]
712 -- Figure out types for the scrutinee and result
713 -- Both are of form (T a b c), with fresh type variables, but with
714 -- common variables where the scrutinee and result must have the same type
715 -- These are variables that appear in *any* arg of *any* of the
716 -- relevant constructors *except* in the updated fields
718 ; let fixed_tvs = getFixedTyVars con1_tvs relevant_cons
719 is_fixed_tv tv = tv `elemVarSet` fixed_tvs
720 mk_inst_ty tv result_inst_ty
721 | is_fixed_tv tv = return result_inst_ty -- Same as result type
722 | otherwise = newFlexiTyVarTy (tyVarKind tv) -- Fresh type, of correct kind
724 ; (_, result_inst_tys, result_inst_env) <- tcInstTyVars con1_tvs
725 ; scrut_inst_tys <- zipWithM mk_inst_ty con1_tvs result_inst_tys
727 ; let rec_res_ty = TcType.substTy result_inst_env con1_res_ty
728 con1_arg_tys' = map (TcType.substTy result_inst_env) con1_arg_tys
729 scrut_subst = zipTopTvSubst con1_tvs scrut_inst_tys
730 scrut_ty = TcType.substTy scrut_subst con1_res_ty
732 ; co_res <- unifyType rec_res_ty res_ty
735 -- Typecheck the thing to be updated, and the bindings
736 ; record_expr' <- tcMonoExpr record_expr scrut_ty
737 ; rbinds' <- tcRecordBinds con1 con1_arg_tys' rbinds
739 -- STEP 6: Deal with the stupid theta
740 ; let theta' = substTheta scrut_subst (dataConStupidTheta con1)
741 ; instStupidTheta RecordUpdOrigin theta'
743 -- Step 7: make a cast for the scrutinee, in the case that it's from a type family
744 ; let scrut_co | Just co_con <- tyConFamilyCoercion_maybe tycon
745 = WpCast $ mkAxInstCo co_con scrut_inst_tys
749 ; return $ mkHsWrapCo co_res $
750 RecordUpd (mkLHsWrap scrut_co record_expr') rbinds'
751 relevant_cons scrut_inst_tys result_inst_tys }
753 upd_fld_names = hsRecFields rbinds
755 getFixedTyVars :: [TyVar] -> [DataCon] -> TyVarSet
756 -- These tyvars must not change across the updates
757 getFixedTyVars tvs1 cons
758 = mkVarSet [tv1 | con <- cons
759 , let (tvs, theta, arg_tys, _) = dataConSig con
760 flds = dataConFieldLabels con
761 fixed_tvs = exactTyVarsOfTypes fixed_tys
762 -- fixed_tys: See Note [Type of a record update]
763 `unionVarSet` tyVarsOfTheta theta
764 -- Universally-quantified tyvars that
765 -- appear in any of the *implicit*
766 -- arguments to the constructor are fixed
767 -- See Note [Implict type sharing]
769 fixed_tys = [ty | (fld,ty) <- zip flds arg_tys
770 , not (fld `elem` upd_fld_names)]
771 , (tv1,tv) <- tvs1 `zip` tvs -- Discards existentials in tvs
772 , tv `elemVarSet` fixed_tvs ]
775 %************************************************************************
777 Arithmetic sequences e.g. [a,b..]
778 and their parallel-array counterparts e.g. [: a,b.. :]
781 %************************************************************************
784 tcExpr (ArithSeq _ seq@(From expr)) res_ty
785 = do { (coi, elt_ty) <- matchExpectedListTy res_ty
786 ; expr' <- tcPolyExpr expr elt_ty
787 ; enum_from <- newMethodFromName (ArithSeqOrigin seq)
789 ; return $ mkHsWrapCo coi (ArithSeq enum_from (From expr')) }
791 tcExpr (ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
792 = do { (coi, elt_ty) <- matchExpectedListTy res_ty
793 ; expr1' <- tcPolyExpr expr1 elt_ty
794 ; expr2' <- tcPolyExpr expr2 elt_ty
795 ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq)
796 enumFromThenName elt_ty
797 ; return $ mkHsWrapCo coi
798 (ArithSeq enum_from_then (FromThen expr1' expr2')) }
800 tcExpr (ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
801 = do { (coi, elt_ty) <- matchExpectedListTy res_ty
802 ; expr1' <- tcPolyExpr expr1 elt_ty
803 ; expr2' <- tcPolyExpr expr2 elt_ty
804 ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq)
805 enumFromToName elt_ty
806 ; return $ mkHsWrapCo coi
807 (ArithSeq enum_from_to (FromTo expr1' expr2')) }
809 tcExpr (ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
810 = do { (coi, elt_ty) <- matchExpectedListTy res_ty
811 ; expr1' <- tcPolyExpr expr1 elt_ty
812 ; expr2' <- tcPolyExpr expr2 elt_ty
813 ; expr3' <- tcPolyExpr expr3 elt_ty
814 ; eft <- newMethodFromName (ArithSeqOrigin seq)
815 enumFromThenToName elt_ty
816 ; return $ mkHsWrapCo coi
817 (ArithSeq eft (FromThenTo expr1' expr2' expr3')) }
819 tcExpr (PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
820 = do { (coi, elt_ty) <- matchExpectedPArrTy res_ty
821 ; expr1' <- tcPolyExpr expr1 elt_ty
822 ; expr2' <- tcPolyExpr expr2 elt_ty
823 ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq)
824 (enumFromToPName basePackageId) elt_ty -- !!!FIXME: chak
825 ; return $ mkHsWrapCo coi
826 (PArrSeq enum_from_to (FromTo expr1' expr2')) }
828 tcExpr (PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
829 = do { (coi, elt_ty) <- matchExpectedPArrTy res_ty
830 ; expr1' <- tcPolyExpr expr1 elt_ty
831 ; expr2' <- tcPolyExpr expr2 elt_ty
832 ; expr3' <- tcPolyExpr expr3 elt_ty
833 ; eft <- newMethodFromName (PArrSeqOrigin seq)
834 (enumFromThenToPName basePackageId) elt_ty -- !!!FIXME: chak
835 ; return $ mkHsWrapCo coi
836 (PArrSeq eft (FromThenTo expr1' expr2' expr3')) }
838 tcExpr (PArrSeq _ _) _
839 = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
840 -- the parser shouldn't have generated it and the renamer shouldn't have
845 %************************************************************************
849 %************************************************************************
852 #ifdef GHCI /* Only if bootstrapped */
853 -- Rename excludes these cases otherwise
854 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
855 tcExpr (HsBracket brack) res_ty = do { e <- tcBracket brack res_ty
857 tcExpr e@(HsQuasiQuoteE _) _ =
858 pprPanic "Should never see HsQuasiQuoteE in type checker" (ppr e)
863 %************************************************************************
867 %************************************************************************
870 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
874 %************************************************************************
878 %************************************************************************
881 tcApp :: LHsExpr Name -> [LHsExpr Name] -- Function and args
882 -> TcRhoType -> TcM (HsExpr TcId) -- Translated fun and args
884 tcApp (L _ (HsPar e)) args res_ty
885 = tcApp e args res_ty
887 tcApp (L _ (HsApp e1 e2)) args res_ty
888 = tcApp e1 (e2:args) res_ty -- Accumulate the arguments
890 tcApp (L loc (HsVar fun)) args res_ty
891 | fun `hasKey` tagToEnumKey
893 = tcTagToEnum loc fun arg res_ty
895 tcApp fun args res_ty
896 = do { -- Type-check the function
897 ; (fun1, fun_tau) <- tcInferFun fun
899 -- Extract its argument types
900 ; (co_fun, expected_arg_tys, actual_res_ty)
901 <- matchExpectedFunTys (mk_app_msg fun) (length args) fun_tau
903 -- Typecheck the result, thereby propagating
904 -- info (if any) from result into the argument types
905 -- Both actual_res_ty and res_ty are deeply skolemised
906 ; co_res <- addErrCtxtM (funResCtxt fun actual_res_ty res_ty) $
907 unifyType actual_res_ty res_ty
909 -- Typecheck the arguments
910 ; args1 <- tcArgs fun args expected_arg_tys
912 -- Assemble the result
913 ; let fun2 = mkLHsWrapCo co_fun fun1
914 app = mkLHsWrapCo co_res (foldl mkHsApp fun2 args1)
916 ; return (unLoc app) }
919 mk_app_msg :: LHsExpr Name -> SDoc
920 mk_app_msg fun = sep [ ptext (sLit "The function") <+> quotes (ppr fun)
921 , ptext (sLit "is applied to")]
924 tcInferApp :: LHsExpr Name -> [LHsExpr Name] -- Function and args
925 -> TcM (HsExpr TcId, TcRhoType) -- Translated fun and args
927 tcInferApp (L _ (HsPar e)) args = tcInferApp e args
928 tcInferApp (L _ (HsApp e1 e2)) args = tcInferApp e1 (e2:args)
930 = -- Very like the tcApp version, except that there is
931 -- no expected result type passed in
932 do { (fun1, fun_tau) <- tcInferFun fun
933 ; (co_fun, expected_arg_tys, actual_res_ty)
934 <- matchExpectedFunTys (mk_app_msg fun) (length args) fun_tau
935 ; args1 <- tcArgs fun args expected_arg_tys
936 ; let fun2 = mkLHsWrapCo co_fun fun1
937 app = foldl mkHsApp fun2 args1
938 ; return (unLoc app, actual_res_ty) }
941 tcInferFun :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
942 -- Infer and instantiate the type of a function
943 tcInferFun (L loc (HsVar name))
944 = do { (fun, ty) <- setSrcSpan loc (tcInferId name)
945 -- Don't wrap a context around a plain Id
946 ; return (L loc fun, ty) }
949 = do { (fun, fun_ty) <- tcInfer (tcMonoExpr fun)
951 -- Zonk the function type carefully, to expose any polymorphism
952 -- E.g. (( \(x::forall a. a->a). blah ) e)
953 -- We can see the rank-2 type of the lambda in time to genrealise e
954 ; fun_ty' <- zonkTcTypeCarefully fun_ty
956 ; (wrap, rho) <- deeplyInstantiate AppOrigin fun_ty'
957 ; return (mkLHsWrap wrap fun, rho) }
960 tcArgs :: LHsExpr Name -- The function (for error messages)
961 -> [LHsExpr Name] -> [TcSigmaType] -- Actual arguments and expected arg types
962 -> TcM [LHsExpr TcId] -- Resulting args
964 tcArgs fun args expected_arg_tys
965 = mapM (tcArg fun) (zip3 args expected_arg_tys [1..])
968 tcArg :: LHsExpr Name -- The function (for error messages)
969 -> (LHsExpr Name, TcSigmaType, Int) -- Actual argument and expected arg type
970 -> TcM (LHsExpr TcId) -- Resulting argument
971 tcArg fun (arg, ty, arg_no) = addErrCtxt (funAppCtxt fun arg arg_no)
972 (tcPolyExprNC arg ty)
975 tcTupArgs :: [HsTupArg Name] -> [TcSigmaType] -> TcM [HsTupArg TcId]
977 = ASSERT( equalLength args tys ) mapM go (args `zip` tys)
979 go (Missing {}, arg_ty) = return (Missing arg_ty)
980 go (Present expr, arg_ty) = do { expr' <- tcPolyExpr expr arg_ty
981 ; return (Present expr') }
984 unifyOpFunTys :: LHsExpr Name -> Arity -> TcRhoType
985 -> TcM (Coercion, [TcSigmaType], TcRhoType)
986 -- A wrapper for matchExpectedFunTys
987 unifyOpFunTys op arity ty = matchExpectedFunTys herald arity ty
989 herald = ptext (sLit "The operator") <+> quotes (ppr op) <+> ptext (sLit "takes")
991 ---------------------------
992 tcSyntaxOp :: CtOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
993 -- Typecheck a syntax operator, checking that it has the specified type
994 -- The operator is always a variable at this stage (i.e. renamer output)
995 -- This version assumes res_ty is a monotype
996 tcSyntaxOp orig (HsVar op) res_ty = do { (expr, rho) <- tcInferIdWithOrig orig op
997 ; tcWrapResult expr rho res_ty }
998 tcSyntaxOp _ other _ = pprPanic "tcSyntaxOp" (ppr other)
1002 Note [Push result type in]
1003 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1004 Unify with expected result before type-checking the args so that the
1005 info from res_ty percolates to args. This is when we might detect a
1006 too-few args situation. (One can think of cases when the opposite
1007 order would give a better error message.)
1008 experimenting with putting this first.
1010 Here's an example where it actually makes a real difference
1012 class C t a b | t a -> b
1013 instance C Char a Bool
1015 data P t a = forall b. (C t a b) => MkP b
1016 data Q t = MkQ (forall a. P t a)
1020 f2 = MkQ (MkP True :: forall a. P Char a)
1022 With the change, f1 will type-check, because the 'Char' info from
1023 the signature is propagated into MkQ's argument. With the check
1024 in the other order, the extra signature in f2 is reqd.
1027 %************************************************************************
1031 %************************************************************************
1034 tcCheckId :: Name -> TcRhoType -> TcM (HsExpr TcId)
1035 tcCheckId name res_ty = do { (expr, rho) <- tcInferId name
1036 ; tcWrapResult expr rho res_ty }
1038 ------------------------
1039 tcInferId :: Name -> TcM (HsExpr TcId, TcRhoType)
1040 -- Infer type, and deeply instantiate
1041 tcInferId n = tcInferIdWithOrig (OccurrenceOf n) n
1043 ------------------------
1044 tcInferIdWithOrig :: CtOrigin -> Name -> TcM (HsExpr TcId, TcRhoType)
1045 -- Look up an occurrence of an Id, and instantiate it (deeply)
1047 tcInferIdWithOrig orig id_name =
1048 do { id_level <- getIdLevel id_name
1049 ; cur_level <- getHetMetLevel
1050 ; if (length id_level < length cur_level)
1051 then do { (lhexp, tcrho) <-
1052 tcInferRho (noLoc $ addEscapes (take ((length cur_level) - (length id_level)) cur_level) (HsVar id_name))
1053 ; return (unLoc lhexp, tcrho)
1055 else tcInferIdWithOrig' orig id_name
1058 tcInferIdWithOrig' orig id_name =
1059 do { id <- lookup_id
1060 ; (id_expr, id_rho) <- instantiateOuter orig id
1061 ; (wrap, rho) <- deeplyInstantiate orig id_rho
1062 ; return (mkHsWrap wrap id_expr, rho) }
1064 lookup_id :: TcM TcId
1066 = do { thing <- tcLookup id_name
1068 ATcId { tct_id = id, tct_level = lvl, tct_hetMetLevel = variable_hetMetLevel }
1069 -> do { check_naughty id -- Note [Local record selectors]
1070 ; checkThLocalId id lvl
1071 ; current_hetMetLevel <- getHetMetLevel
1073 (\(name1,name2) -> unifyType (TyVarTy name1) (TyVarTy name2))
1074 (zip variable_hetMetLevel current_hetMetLevel)
1078 -> do { check_naughty id
1080 -- A global cannot possibly be ill-staged in Template Haskell
1081 -- nor does it need the 'lifting' treatment
1082 -- hence no checkTh stuff here
1084 AGlobal (ADataCon con) -> return (dataConWrapId con)
1086 other -> failWithTc (bad_lookup other) }
1088 bad_lookup thing = ppr thing <+> ptext (sLit "used where a value identifer was expected")
1091 | isNaughtyRecordSelector id = failWithTc (naughtyRecordSel id)
1092 | otherwise = return ()
1094 ------------------------
1095 instantiateOuter :: CtOrigin -> TcId -> TcM (HsExpr TcId, TcSigmaType)
1096 -- Do just the first level of instantiation of an Id
1097 -- a) Deal with method sharing
1098 -- b) Deal with stupid checks
1099 -- Only look at the *outer level* of quantification
1100 -- See Note [Multiple instantiation]
1102 instantiateOuter orig id
1103 | null tvs && null theta
1104 = return (HsVar id, tau)
1107 = do { (_, tys, subst) <- tcInstTyVars tvs
1108 ; doStupidChecks id tys
1109 ; let theta' = substTheta subst theta
1110 ; traceTc "Instantiating" (ppr id <+> text "with" <+> (ppr tys $$ ppr theta'))
1111 ; wrap <- instCall orig tys theta'
1112 ; return (mkHsWrap wrap (HsVar id), TcType.substTy subst tau) }
1114 (tvs, theta, tau) = tcSplitSigmaTy (idType id)
1117 Note [Multiple instantiation]
1118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1119 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
1120 For example, consider
1121 f :: forall a. Eq a => forall b. Ord b => a -> b
1122 At a call to f, at say [Int, Bool], it's tempting to translate the call to
1126 f_m1 :: forall b. Ord b => Int -> b
1130 f_m2 = f_m1 Bool dOrdBool
1132 But notice that f_m2 has f_m1 as its meth_id. Now the danger is that if we do
1133 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
1135 But it's entirely possible that f_m2 will continue to float out, because it
1136 mentions no type variables. Result, f_m1 isn't in scope.
1138 Here's a concrete example that does this (test tc200):
1141 f :: Eq b => b -> a -> Int
1142 baz :: Eq a => Int -> a -> Int
1144 instance C Int where
1147 Current solution: only do the "method sharing" thing for the first type/dict
1148 application, not for the iterated ones. A horribly subtle point.
1150 Note [No method sharing]
1151 ~~~~~~~~~~~~~~~~~~~~~~~~
1152 The -fno-method-sharing flag controls what happens so far as the LIE
1153 is concerned. The default case is that for an overloaded function we
1154 generate a "method" Id, and add the Method Inst to the LIE. So you get
1156 f :: Num a => a -> a
1157 f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
1158 If you specify -fno-method-sharing, the dictionary application
1159 isn't shared, so we get
1160 f :: Num a => a -> a
1161 f = /\a (d:Num a) (x:a) -> (+) a d x x
1162 This gets a bit less sharing, but
1163 a) it's better for RULEs involving overloaded functions
1164 b) perhaps fewer separated lambdas
1167 doStupidChecks :: TcId
1170 -- Check two tiresome and ad-hoc cases
1171 -- (a) the "stupid theta" for a data con; add the constraints
1172 -- from the "stupid theta" of a data constructor (sigh)
1174 doStupidChecks fun_id tys
1175 | Just con <- isDataConId_maybe fun_id -- (a)
1176 = addDataConStupidTheta con tys
1178 | fun_id `hasKey` tagToEnumKey -- (b)
1179 = failWithTc (ptext (sLit "tagToEnum# must appear applied to one argument"))
1182 = return () -- The common case
1187 Nasty check to ensure that tagToEnum# is applied to a type that is an
1188 enumeration TyCon. Unification may refine the type later, but this
1189 check won't see that, alas. It's crude, because it relies on our
1190 knowing *now* that the type is ok, which in turn relies on the
1191 eager-unification part of the type checker pushing enough information
1192 here. In theory the Right Thing to do is to have a new form of
1193 constraint but I definitely cannot face that! And it works ok as-is.
1195 Here's are two cases that should fail
1197 f = tagToEnum# 0 -- Can't do tagToEnum# at a type variable
1200 g = tagToEnum# 0 -- Int is not an enumeration
1202 When data type families are involved it's a bit more complicated.
1204 data instance F [Int] = A | B | C
1205 Then we want to generate something like
1206 tagToEnum# R:FListInt 3# |> co :: R:FListInt ~ F [Int]
1207 Usually that coercion is hidden inside the wrappers for
1208 constructors of F [Int] but here we have to do it explicitly.
1210 It's all grotesquely complicated.
1213 tcTagToEnum :: SrcSpan -> Name -> LHsExpr Name -> TcRhoType -> TcM (HsExpr TcId)
1214 -- tagToEnum# :: forall a. Int# -> a
1215 -- See Note [tagToEnum#] Urgh!
1216 tcTagToEnum loc fun_name arg res_ty
1217 = do { fun <- tcLookupId fun_name
1218 ; ty' <- zonkTcType res_ty
1220 -- Check that the type is algebraic
1221 ; let mb_tc_app = tcSplitTyConApp_maybe ty'
1222 Just (tc, tc_args) = mb_tc_app
1223 ; checkTc (isJust mb_tc_app)
1224 (tagToEnumError ty' doc1)
1226 -- Look through any type family
1227 ; (coi, rep_tc, rep_args) <- get_rep_ty ty' tc tc_args
1229 ; checkTc (isEnumerationTyCon rep_tc)
1230 (tagToEnumError ty' doc2)
1232 ; arg' <- tcMonoExpr arg intPrimTy
1233 ; let fun' = L loc (HsWrap (WpTyApp rep_ty) (HsVar fun))
1234 rep_ty = mkTyConApp rep_tc rep_args
1236 ; return (mkHsWrapCo coi $ HsApp fun' arg') }
1238 doc1 = vcat [ ptext (sLit "Specify the type by giving a type signature")
1239 , ptext (sLit "e.g. (tagToEnum# x) :: Bool") ]
1240 doc2 = ptext (sLit "Result type must be an enumeration type")
1241 doc3 = ptext (sLit "No family instance for this type")
1243 get_rep_ty :: TcType -> TyCon -> [TcType]
1244 -> TcM (Coercion, TyCon, [TcType])
1245 -- Converts a family type (eg F [a]) to its rep type (eg FList a)
1246 -- and returns a coercion between the two
1247 get_rep_ty ty tc tc_args
1248 | not (isFamilyTyCon tc)
1249 = return (mkReflCo ty, tc, tc_args)
1251 = do { mb_fam <- tcLookupFamInst tc tc_args
1253 Nothing -> failWithTc (tagToEnumError ty doc3)
1254 Just (rep_tc, rep_args)
1255 -> return ( mkSymCo (mkAxInstCo co_tc rep_args)
1256 , rep_tc, rep_args )
1258 co_tc = expectJust "tcTagToEnum" $
1259 tyConFamilyCoercion_maybe rep_tc }
1261 tagToEnumError :: TcType -> SDoc -> SDoc
1262 tagToEnumError ty what
1263 = hang (ptext (sLit "Bad call to tagToEnum#")
1264 <+> ptext (sLit "at type") <+> ppr ty)
1269 %************************************************************************
1271 Template Haskell checks
1273 %************************************************************************
1276 checkThLocalId :: Id -> ThLevel -> TcM ()
1277 #ifndef GHCI /* GHCI and TH is off */
1278 --------------------------------------
1279 -- Check for cross-stage lifting
1280 checkThLocalId _id _bind_lvl
1283 #else /* GHCI and TH is on */
1284 checkThLocalId id bind_lvl
1285 = do { use_stage <- getStage -- TH case
1286 ; let use_lvl = thLevel use_stage
1287 ; checkWellStaged (quotes (ppr id)) bind_lvl use_lvl
1288 ; traceTc "thLocalId" (ppr id <+> ppr bind_lvl <+> ppr use_stage <+> ppr use_lvl)
1289 ; when (use_lvl > bind_lvl) $
1290 checkCrossStageLifting id bind_lvl use_stage }
1292 --------------------------------------
1293 checkCrossStageLifting :: Id -> ThLevel -> ThStage -> TcM ()
1294 -- We are inside brackets, and (use_lvl > bind_lvl)
1295 -- Now we must check whether there's a cross-stage lift to do
1296 -- Examples \x -> [| x |]
1299 checkCrossStageLifting _ _ Comp = return ()
1300 checkCrossStageLifting _ _ Splice = return ()
1302 checkCrossStageLifting id _ (Brack _ ps_var lie_var)
1304 = -- Top-level identifiers in this module,
1305 -- (which have External Names)
1306 -- are just like the imported case:
1307 -- no need for the 'lifting' treatment
1308 -- E.g. this is fine:
1311 -- But we do need to put f into the keep-alive
1312 -- set, because after desugaring the code will
1313 -- only mention f's *name*, not f itself.
1316 | otherwise -- bind_lvl = outerLevel presumably,
1317 -- but the Id is not bound at top level
1318 = -- Nested identifiers, such as 'x' in
1319 -- E.g. \x -> [| h x |]
1320 -- We must behave as if the reference to x was
1322 -- We use 'x' itself as the splice proxy, used by
1323 -- the desugarer to stitch it all back together.
1324 -- If 'x' occurs many times we may get many identical
1325 -- bindings of the same splice proxy, but that doesn't
1326 -- matter, although it's a mite untidy.
1327 do { let id_ty = idType id
1328 ; checkTc (isTauTy id_ty) (polySpliceErr id)
1329 -- If x is polymorphic, its occurrence sites might
1330 -- have different instantiations, so we can't use plain
1331 -- 'x' as the splice proxy name. I don't know how to
1332 -- solve this, and it's probably unimportant, so I'm
1333 -- just going to flag an error for now
1335 ; lift <- if isStringTy id_ty then
1336 do { sid <- tcLookupId DsMeta.liftStringName
1337 -- See Note [Lifting strings]
1338 ; return (HsVar sid) }
1340 setConstraintVar lie_var $ do
1341 -- Put the 'lift' constraint into the right LIE
1342 newMethodFromName (OccurrenceOf (idName id))
1343 DsMeta.liftName id_ty
1345 -- Update the pending splices
1346 ; ps <- readMutVar ps_var
1347 ; writeMutVar ps_var ((idName id, nlHsApp (noLoc lift) (nlHsVar id)) : ps)
1353 Note [Lifting strings]
1354 ~~~~~~~~~~~~~~~~~~~~~~
1355 If we see $(... [| s |] ...) where s::String, we don't want to
1356 generate a mass of Cons (CharL 'x') (Cons (CharL 'y') ...)) etc.
1357 So this conditional short-circuits the lifting mechanism to generate
1358 (liftString "xy") in that case. I didn't want to use overlapping instances
1359 for the Lift class in TH.Syntax, because that can lead to overlapping-instance
1360 errors in a polymorphic situation.
1362 If this check fails (which isn't impossible) we get another chance; see
1363 Note [Converting strings] in Convert.lhs
1365 Local record selectors
1366 ~~~~~~~~~~~~~~~~~~~~~~
1367 Record selectors for TyCons in this module are ordinary local bindings,
1368 which show up as ATcIds rather than AGlobals. So we need to check for
1369 naughtiness in both branches. c.f. TcTyClsBindings.mkAuxBinds.
1372 %************************************************************************
1374 \subsection{Record bindings}
1376 %************************************************************************
1378 Game plan for record bindings
1379 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1380 1. Find the TyCon for the bindings, from the first field label.
1382 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1384 For each binding field = value
1386 3. Instantiate the field type (from the field label) using the type
1389 4 Type check the value using tcArg, passing the field type as
1390 the expected argument type.
1392 This extends OK when the field types are universally quantified.
1398 -> [TcType] -- Expected type for each field
1399 -> HsRecordBinds Name
1400 -> TcM (HsRecordBinds TcId)
1402 tcRecordBinds data_con arg_tys (HsRecFields rbinds dd)
1403 = do { mb_binds <- mapM do_bind rbinds
1404 ; return (HsRecFields (catMaybes mb_binds) dd) }
1406 flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1407 do_bind fld@(HsRecField { hsRecFieldId = L loc field_lbl, hsRecFieldArg = rhs })
1408 | Just field_ty <- assocMaybe flds_w_tys field_lbl
1409 = addErrCtxt (fieldCtxt field_lbl) $
1410 do { rhs' <- tcPolyExprNC rhs field_ty
1411 ; let field_id = mkUserLocal (nameOccName field_lbl)
1412 (nameUnique field_lbl)
1414 -- Yuk: the field_id has the *unique* of the selector Id
1415 -- (so we can find it easily)
1416 -- but is a LocalId with the appropriate type of the RHS
1417 -- (so the desugarer knows the type of local binder to make)
1418 ; return (Just (fld { hsRecFieldId = L loc field_id, hsRecFieldArg = rhs' })) }
1420 = do { addErrTc (badFieldCon data_con field_lbl)
1423 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1424 checkMissingFields data_con rbinds
1425 | null field_labels -- Not declared as a record;
1426 -- But C{} is still valid if no strict fields
1427 = if any isBanged field_strs then
1428 -- Illegal if any arg is strict
1429 addErrTc (missingStrictFields data_con [])
1433 | otherwise = do -- A record
1434 unless (null missing_s_fields)
1435 (addErrTc (missingStrictFields data_con missing_s_fields))
1437 warn <- doptM Opt_WarnMissingFields
1438 unless (not (warn && notNull missing_ns_fields))
1439 (warnTc True (missingFields data_con missing_ns_fields))
1443 = [ fl | (fl, str) <- field_info,
1445 not (fl `elem` field_names_used)
1448 = [ fl | (fl, str) <- field_info,
1450 not (fl `elem` field_names_used)
1453 field_names_used = hsRecFields rbinds
1454 field_labels = dataConFieldLabels data_con
1456 field_info = zipEqual "missingFields"
1460 field_strs = dataConStrictMarks data_con
1463 %************************************************************************
1465 \subsection{Errors and contexts}
1467 %************************************************************************
1469 Boring and alphabetical:
1471 addExprErrCtxt :: LHsExpr Name -> TcM a -> TcM a
1472 addExprErrCtxt expr = addErrCtxt (exprCtxt expr)
1474 exprCtxt :: LHsExpr Name -> SDoc
1476 = hang (ptext (sLit "In the expression:")) 2 (ppr expr)
1478 fieldCtxt :: Name -> SDoc
1479 fieldCtxt field_name
1480 = ptext (sLit "In the") <+> quotes (ppr field_name) <+> ptext (sLit "field of a record")
1482 funAppCtxt :: LHsExpr Name -> LHsExpr Name -> Int -> SDoc
1483 funAppCtxt fun arg arg_no
1484 = hang (hsep [ ptext (sLit "In the"), speakNth arg_no, ptext (sLit "argument of"),
1485 quotes (ppr fun) <> text ", namely"])
1486 2 (quotes (ppr arg))
1488 funResCtxt :: LHsExpr Name -> TcType -> TcType
1489 -> TidyEnv -> TcM (TidyEnv, Message)
1490 -- When we have a mis-match in the return type of a function
1491 -- try to give a helpful message about too many/few arguments
1492 funResCtxt fun fun_res_ty res_ty env0
1493 = do { fun_res' <- zonkTcType fun_res_ty
1494 ; res' <- zonkTcType res_ty
1495 ; let n_fun = length (fst (tcSplitFunTys fun_res'))
1496 n_res = length (fst (tcSplitFunTys res'))
1497 what | n_fun > n_res = ptext (sLit "few")
1498 | otherwise = ptext (sLit "many")
1499 extra | n_fun == n_res = empty
1500 | otherwise = ptext (sLit "Probable cause:") <+> quotes (ppr fun)
1501 <+> ptext (sLit "is applied to too") <+> what
1502 <+> ptext (sLit "arguments")
1503 msg = ptext (sLit "In the return type of a call of") <+> quotes (ppr fun)
1504 ; return (env0, msg $$ extra) }
1506 badFieldTypes :: [(Name,TcType)] -> SDoc
1508 = hang (ptext (sLit "Record update for insufficiently polymorphic field")
1509 <> plural prs <> colon)
1510 2 (vcat [ ppr f <+> dcolon <+> ppr ty | (f,ty) <- prs ])
1512 badFieldsUpd :: HsRecFields Name a -> SDoc
1514 = hang (ptext (sLit "No constructor has all these fields:"))
1515 2 (pprQuotedList (hsRecFields rbinds))
1517 naughtyRecordSel :: TcId -> SDoc
1518 naughtyRecordSel sel_id
1519 = ptext (sLit "Cannot use record selector") <+> quotes (ppr sel_id) <+>
1520 ptext (sLit "as a function due to escaped type variables") $$
1521 ptext (sLit "Probable fix: use pattern-matching syntax instead")
1523 notSelector :: Name -> SDoc
1525 = hsep [quotes (ppr field), ptext (sLit "is not a record selector")]
1527 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1528 missingStrictFields con fields
1531 rest | null fields = empty -- Happens for non-record constructors
1532 -- with strict fields
1533 | otherwise = colon <+> pprWithCommas ppr fields
1535 header = ptext (sLit "Constructor") <+> quotes (ppr con) <+>
1536 ptext (sLit "does not have the required strict field(s)")
1538 missingFields :: DataCon -> [FieldLabel] -> SDoc
1539 missingFields con fields
1540 = ptext (sLit "Fields of") <+> quotes (ppr con) <+> ptext (sLit "not initialised:")
1541 <+> pprWithCommas ppr fields
1543 -- callCtxt fun args = ptext (sLit "In the call") <+> parens (ppr (foldl mkHsApp fun args))
1546 polySpliceErr :: Id -> SDoc
1548 = ptext (sLit "Can't splice the polymorphic local variable") <+> quotes (ppr id)