Comments and variable names only, in type checking of (e1 $ e2)
[ghc.git] / compiler / typecheck / TcExpr.hs
1 {-
2 c%
3 (c) The University of Glasgow 2006
4 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5
6 \section[TcExpr]{Typecheck an expression}
7 -}
8
9 {-# LANGUAGE CPP #-}
10
11 module TcExpr ( tcPolyExpr, tcPolyExprNC, tcMonoExpr, tcMonoExprNC,
12 tcInferRho, tcInferRhoNC,
13 tcSyntaxOp, tcCheckId,
14 addExprErrCtxt) where
15
16 #include "HsVersions.h"
17
18 import {-# SOURCE #-} TcSplice( tcSpliceExpr, tcTypedBracket, tcUntypedBracket )
19 #ifdef GHCI
20 import DsMeta( liftStringName, liftName )
21 #endif
22
23 import HsSyn
24 import TcHsSyn
25 import TcRnMonad
26 import TcUnify
27 import BasicTypes
28 import Inst
29 import TcBinds
30 import FamInst ( tcGetFamInstEnvs, tcLookupDataFamInst )
31 import TcEnv
32 import TcArrows
33 import TcMatches
34 import TcHsType
35 import TcPatSyn( tcPatSynBuilderOcc )
36 import TcPat
37 import TcMType
38 import TcType
39 import DsMonad hiding (Splice)
40 import Id
41 import ConLike
42 import DataCon
43 import RdrName
44 import Name
45 import TyCon
46 import Type
47 import TcEvidence
48 import Var
49 import VarSet
50 import VarEnv
51 import TysWiredIn
52 import TysPrim( intPrimTy, addrPrimTy )
53 import PrimOp( tagToEnumKey )
54 import PrelNames
55 import DynFlags
56 import SrcLoc
57 import Util
58 import ListSetOps
59 import Maybes
60 import ErrUtils
61 import Outputable
62 import FastString
63 import Control.Monad
64 import Class(classTyCon)
65 import Data.Function
66 import Data.List
67 import qualified Data.Set as Set
68
69 {-
70 ************************************************************************
71 * *
72 \subsection{Main wrappers}
73 * *
74 ************************************************************************
75 -}
76
77 tcPolyExpr, tcPolyExprNC
78 :: LHsExpr Name -- Expression to type check
79 -> TcSigmaType -- Expected type (could be a polytype)
80 -> TcM (LHsExpr TcId) -- Generalised expr with expected type
81
82 -- tcPolyExpr is a convenient place (frequent but not too frequent)
83 -- place to add context information.
84 -- The NC version does not do so, usually because the caller wants
85 -- to do so himself.
86
87 tcPolyExpr expr res_ty
88 = addExprErrCtxt expr $
89 do { traceTc "tcPolyExpr" (ppr res_ty); tcPolyExprNC expr res_ty }
90
91 tcPolyExprNC expr res_ty
92 = do { traceTc "tcPolyExprNC" (ppr res_ty)
93 ; (gen_fn, expr') <- tcGen GenSigCtxt res_ty $ \ _ rho ->
94 tcMonoExprNC expr rho
95 ; return (mkLHsWrap gen_fn expr') }
96
97 ---------------
98 tcMonoExpr, tcMonoExprNC
99 :: LHsExpr Name -- Expression to type check
100 -> TcRhoType -- Expected type (could be a type variable)
101 -- Definitely no foralls at the top
102 -> TcM (LHsExpr TcId)
103
104 tcMonoExpr expr res_ty
105 = addErrCtxt (exprCtxt expr) $
106 tcMonoExprNC expr res_ty
107
108 tcMonoExprNC (L loc expr) res_ty
109 = ASSERT( not (isSigmaTy res_ty) )
110 setSrcSpan loc $
111 do { expr' <- tcExpr expr res_ty
112 ; return (L loc expr') }
113
114 ---------------
115 tcInferRho, tcInferRhoNC :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
116 -- Infer a *rho*-type. This is, in effect, a special case
117 -- for ids and partial applications, so that if
118 -- f :: Int -> (forall a. a -> a) -> Int
119 -- then we can infer
120 -- f 3 :: (forall a. a -> a) -> Int
121 -- And that in turn is useful
122 -- (a) for the function part of any application (see tcApp)
123 -- (b) for the special rule for '$'
124 tcInferRho expr = addErrCtxt (exprCtxt expr) (tcInferRhoNC expr)
125
126 tcInferRhoNC (L loc expr)
127 = setSrcSpan loc $
128 do { (expr', rho) <- tcInfer (tcExpr expr)
129 ; return (L loc expr', rho) }
130
131 tcHole :: OccName -> TcRhoType -> TcM (HsExpr TcId)
132 tcHole occ res_ty
133 = do { ty <- newFlexiTyVarTy liftedTypeKind
134 ; name <- newSysName occ
135 ; let ev = mkLocalId name ty
136 ; loc <- getCtLoc HoleOrigin
137 ; let can = CHoleCan { cc_ev = CtWanted ty ev loc, cc_occ = occ
138 , cc_hole = ExprHole }
139 ; emitInsoluble can
140 ; tcWrapResult (HsVar ev) ty res_ty }
141
142 {-
143 ************************************************************************
144 * *
145 tcExpr: the main expression typechecker
146 * *
147 ************************************************************************
148 -}
149
150 tcExpr :: HsExpr Name -> TcRhoType -> TcM (HsExpr TcId)
151 tcExpr e res_ty | debugIsOn && isSigmaTy res_ty -- Sanity check
152 = pprPanic "tcExpr: sigma" (ppr res_ty $$ ppr e)
153
154 tcExpr (HsVar name) res_ty = tcCheckId name res_ty
155
156 tcExpr (HsApp e1 e2) res_ty = tcApp e1 [e2] res_ty
157
158 tcExpr (HsLit lit) res_ty = do { let lit_ty = hsLitType lit
159 ; tcWrapResult (HsLit lit) lit_ty res_ty }
160
161 tcExpr (HsPar expr) res_ty = do { expr' <- tcMonoExprNC expr res_ty
162 ; return (HsPar expr') }
163
164 tcExpr (HsSCC lbl expr) res_ty
165 = do { expr' <- tcMonoExpr expr res_ty
166 ; return (HsSCC lbl expr') }
167
168 tcExpr (HsTickPragma info expr) res_ty
169 = do { expr' <- tcMonoExpr expr res_ty
170 ; return (HsTickPragma info expr') }
171
172 tcExpr (HsCoreAnn lbl expr) res_ty
173 = do { expr' <- tcMonoExpr expr res_ty
174 ; return (HsCoreAnn lbl expr') }
175
176 tcExpr (HsOverLit lit) res_ty
177 = do { lit' <- newOverloadedLit (LiteralOrigin lit) lit res_ty
178 ; return (HsOverLit lit') }
179
180 tcExpr (NegApp expr neg_expr) res_ty
181 = do { neg_expr' <- tcSyntaxOp NegateOrigin neg_expr
182 (mkFunTy res_ty res_ty)
183 ; expr' <- tcMonoExpr expr res_ty
184 ; return (NegApp expr' neg_expr') }
185
186 tcExpr (HsIPVar x) res_ty
187 = do { let origin = IPOccOrigin x
188 ; ipClass <- tcLookupClass ipClassName
189 {- Implicit parameters must have a *tau-type* not a.
190 type scheme. We enforce this by creating a fresh
191 type variable as its type. (Because res_ty may not
192 be a tau-type.) -}
193 ; ip_ty <- newFlexiTyVarTy openTypeKind
194 ; let ip_name = mkStrLitTy (hsIPNameFS x)
195 ; ip_var <- emitWanted origin (mkClassPred ipClass [ip_name, ip_ty])
196 ; tcWrapResult (fromDict ipClass ip_name ip_ty (HsVar ip_var)) ip_ty res_ty }
197 where
198 -- Coerces a dictionary for `IP "x" t` into `t`.
199 fromDict ipClass x ty =
200 case unwrapNewTyCon_maybe (classTyCon ipClass) of
201 Just (_,_,ax) -> HsWrap $ mkWpCast $ mkTcUnbranchedAxInstCo Representational ax [x,ty]
202 Nothing -> panic "The dictionary for `IP` is not a newtype?"
203
204 tcExpr (HsLam match) res_ty
205 = do { (co_fn, match') <- tcMatchLambda match res_ty
206 ; return (mkHsWrap co_fn (HsLam match')) }
207
208 tcExpr e@(HsLamCase _ matches) res_ty
209 = do { (co_fn, [arg_ty], body_ty) <- matchExpectedFunTys msg 1 res_ty
210 ; matches' <- tcMatchesCase match_ctxt arg_ty matches body_ty
211 ; return $ mkHsWrapCo co_fn $ HsLamCase arg_ty matches' }
212 where msg = sep [ ptext (sLit "The function") <+> quotes (ppr e)
213 , ptext (sLit "requires")]
214 match_ctxt = MC { mc_what = CaseAlt, mc_body = tcBody }
215
216 tcExpr (ExprWithTySig expr sig_ty wcs) res_ty
217 = do { nwc_tvs <- mapM newWildcardVarMetaKind wcs
218 ; tcExtendTyVarEnv nwc_tvs $ do {
219 sig_tc_ty <- tcHsSigType ExprSigCtxt sig_ty
220 ; (gen_fn, expr')
221 <- tcGen ExprSigCtxt sig_tc_ty $ \ skol_tvs res_ty ->
222
223 -- Remember to extend the lexical type-variable environment
224 -- See Note [More instantiated than scoped] in TcBinds
225 tcExtendTyVarEnv2
226 [(n,tv) | (Just n, tv) <- findScopedTyVars sig_ty sig_tc_ty skol_tvs] $
227
228 tcMonoExprNC expr res_ty
229
230 ; let inner_expr = ExprWithTySigOut (mkLHsWrap gen_fn expr') sig_ty
231
232 ; (inst_wrap, rho) <- deeplyInstantiate ExprSigOrigin sig_tc_ty
233 ; addErrCtxt (pprSigCtxt ExprSigCtxt empty (ppr sig_ty)) $
234 emitWildcardHoleConstraints (zip wcs nwc_tvs)
235 ; tcWrapResult (mkHsWrap inst_wrap inner_expr) rho res_ty } }
236
237 tcExpr (HsType ty) _
238 = failWithTc (text "Can't handle type argument:" <+> ppr ty)
239 -- This is the syntax for type applications that I was planning
240 -- but there are difficulties (e.g. what order for type args)
241 -- so it's not enabled yet.
242 -- Can't eliminate it altogether from the parser, because the
243 -- same parser parses *patterns*.
244 tcExpr (HsUnboundVar v) res_ty
245 = tcHole (rdrNameOcc v) res_ty
246
247 {-
248 ************************************************************************
249 * *
250 Infix operators and sections
251 * *
252 ************************************************************************
253
254 Note [Left sections]
255 ~~~~~~~~~~~~~~~~~~~~
256 Left sections, like (4 *), are equivalent to
257 \ x -> (*) 4 x,
258 or, if PostfixOperators is enabled, just
259 (*) 4
260 With PostfixOperators we don't actually require the function to take
261 two arguments at all. For example, (x `not`) means (not x); you get
262 postfix operators! Not Haskell 98, but it's less work and kind of
263 useful.
264
265 Note [Typing rule for ($)]
266 ~~~~~~~~~~~~~~~~~~~~~~~~~~
267 People write
268 runST $ blah
269 so much, where
270 runST :: (forall s. ST s a) -> a
271 that I have finally given in and written a special type-checking
272 rule just for saturated appliations of ($).
273 * Infer the type of the first argument
274 * Decompose it; should be of form (arg2_ty -> res_ty),
275 where arg2_ty might be a polytype
276 * Use arg2_ty to typecheck arg2
277
278 Note [Typing rule for seq]
279 ~~~~~~~~~~~~~~~~~~~~~~~~~~
280 We want to allow
281 x `seq` (# p,q #)
282 which suggests this type for seq:
283 seq :: forall (a:*) (b:??). a -> b -> b,
284 with (b:??) meaning that be can be instantiated with an unboxed tuple.
285 But that's ill-kinded! Function arguments can't be unboxed tuples.
286 And indeed, you could not expect to do this with a partially-applied
287 'seq'; it's only going to work when it's fully applied. so it turns
288 into
289 case x of _ -> (# p,q #)
290
291 For a while I slid by by giving 'seq' an ill-kinded type, but then
292 the simplifier eta-reduced an application of seq and Lint blew up
293 with a kind error. It seems more uniform to treat 'seq' as it it
294 was a language construct.
295
296 See Note [seqId magic] in MkId, and
297 -}
298
299 tcExpr (OpApp arg1 op fix arg2) res_ty
300 | (L loc (HsVar op_name)) <- op
301 , op_name `hasKey` seqIdKey -- Note [Typing rule for seq]
302 = do { arg1_ty <- newFlexiTyVarTy liftedTypeKind
303 ; let arg2_ty = res_ty
304 ; arg1' <- tcArg op (arg1, arg1_ty, 1)
305 ; arg2' <- tcArg op (arg2, arg2_ty, 2)
306 ; op_id <- tcLookupId op_name
307 ; let op' = L loc (HsWrap (mkWpTyApps [arg1_ty, arg2_ty]) (HsVar op_id))
308 ; return $ OpApp arg1' op' fix arg2' }
309
310 | (L loc (HsVar op_name)) <- op
311 , op_name `hasKey` dollarIdKey -- Note [Typing rule for ($)]
312 = do { traceTc "Application rule" (ppr op)
313 ; (arg1', arg1_ty) <- tcInferRho arg1
314
315 ; let doc = ptext (sLit "The first argument of ($) takes")
316 ; (co_arg1, [arg2_ty], op_res_ty) <- matchExpectedFunTys doc 1 arg1_ty
317
318 -- We have (arg1 $ arg2)
319 -- So: arg1_ty = arg2_ty -> op_res_ty
320 -- where arg2_ty maybe polymorphic; that's the point
321
322 ; arg2' <- tcArg op (arg2, arg2_ty, 2)
323 ; co_b <- unifyType op_res_ty res_ty -- op_res ~ res
324
325 -- Make sure that the argument type has kind '*'
326 -- ($) :: forall (a2:*) (r:Open). (a2->r) -> a2 -> r
327 -- Eg we do not want to allow (D# $ 4.0#) Trac #5570
328 -- (which gives a seg fault)
329 -- We do this by unifying with a MetaTv; but of course
330 -- it must allow foralls in the type it unifies with (hence ReturnTv)!
331 --
332 -- The *result* type can have any kind (Trac #8739),
333 -- so we don't need to check anything for that
334 ; a2_tv <- newReturnTyVar liftedTypeKind
335 ; let a2_ty = mkTyVarTy a2_tv
336 ; co_a <- unifyType arg2_ty a2_ty -- arg2 ~ a2
337
338 ; op_id <- tcLookupId op_name
339 ; let op' = L loc (HsWrap (mkWpTyApps [a2_ty, res_ty]) (HsVar op_id))
340 ; return $
341 OpApp (mkLHsWrapCo (mkTcFunCo Nominal co_a co_b) $
342 mkLHsWrapCo co_arg1 arg1')
343 op' fix
344 (mkLHsWrapCo co_a arg2') }
345
346 | otherwise
347 = do { traceTc "Non Application rule" (ppr op)
348 ; (op', op_ty) <- tcInferFun op
349 ; (co_fn, arg_tys, op_res_ty) <- unifyOpFunTysWrap op 2 op_ty
350 ; co_res <- unifyType op_res_ty res_ty
351 ; [arg1', arg2'] <- tcArgs op [arg1, arg2] arg_tys
352 ; return $ mkHsWrapCo co_res $
353 OpApp arg1' (mkLHsWrapCo co_fn op') fix arg2' }
354
355 -- Right sections, equivalent to \ x -> x `op` expr, or
356 -- \ x -> op x expr
357
358 tcExpr (SectionR op arg2) res_ty
359 = do { (op', op_ty) <- tcInferFun op
360 ; (co_fn, [arg1_ty, arg2_ty], op_res_ty) <- unifyOpFunTysWrap op 2 op_ty
361 ; co_res <- unifyType (mkFunTy arg1_ty op_res_ty) res_ty
362 ; arg2' <- tcArg op (arg2, arg2_ty, 2)
363 ; return $ mkHsWrapCo co_res $
364 SectionR (mkLHsWrapCo co_fn op') arg2' }
365
366 tcExpr (SectionL arg1 op) res_ty
367 = do { (op', op_ty) <- tcInferFun op
368 ; dflags <- getDynFlags -- Note [Left sections]
369 ; let n_reqd_args | xopt Opt_PostfixOperators dflags = 1
370 | otherwise = 2
371
372 ; (co_fn, (arg1_ty:arg_tys), op_res_ty) <- unifyOpFunTysWrap op n_reqd_args op_ty
373 ; co_res <- unifyType (mkFunTys arg_tys op_res_ty) res_ty
374 ; arg1' <- tcArg op (arg1, arg1_ty, 1)
375 ; return $ mkHsWrapCo co_res $
376 SectionL arg1' (mkLHsWrapCo co_fn op') }
377
378 tcExpr (ExplicitTuple tup_args boxity) res_ty
379 | all tupArgPresent tup_args
380 = do { let tup_tc = tupleTyCon (boxityNormalTupleSort boxity) (length tup_args)
381 ; (coi, arg_tys) <- matchExpectedTyConApp tup_tc res_ty
382 ; tup_args1 <- tcTupArgs tup_args arg_tys
383 ; return $ mkHsWrapCo coi (ExplicitTuple tup_args1 boxity) }
384
385 | otherwise
386 = -- The tup_args are a mixture of Present and Missing (for tuple sections)
387 do { let kind = case boxity of { Boxed -> liftedTypeKind
388 ; Unboxed -> openTypeKind }
389 arity = length tup_args
390 tup_tc = tupleTyCon (boxityNormalTupleSort boxity) arity
391
392 ; arg_tys <- newFlexiTyVarTys (tyConArity tup_tc) kind
393 ; let actual_res_ty
394 = mkFunTys [ty | (ty, L _ (Missing _)) <- arg_tys `zip` tup_args]
395 (mkTyConApp tup_tc arg_tys)
396
397 ; coi <- unifyType actual_res_ty res_ty
398
399 -- Handle tuple sections where
400 ; tup_args1 <- tcTupArgs tup_args arg_tys
401
402 ; return $ mkHsWrapCo coi (ExplicitTuple tup_args1 boxity) }
403
404 tcExpr (ExplicitList _ witness exprs) res_ty
405 = case witness of
406 Nothing -> do { (coi, elt_ty) <- matchExpectedListTy res_ty
407 ; exprs' <- mapM (tc_elt elt_ty) exprs
408 ; return $ mkHsWrapCo coi (ExplicitList elt_ty Nothing exprs') }
409
410 Just fln -> do { list_ty <- newFlexiTyVarTy liftedTypeKind
411 ; fln' <- tcSyntaxOp ListOrigin fln (mkFunTys [intTy, list_ty] res_ty)
412 ; (coi, elt_ty) <- matchExpectedListTy list_ty
413 ; exprs' <- mapM (tc_elt elt_ty) exprs
414 ; return $ mkHsWrapCo coi (ExplicitList elt_ty (Just fln') exprs') }
415 where tc_elt elt_ty expr = tcPolyExpr expr elt_ty
416
417 tcExpr (ExplicitPArr _ exprs) res_ty -- maybe empty
418 = do { (coi, elt_ty) <- matchExpectedPArrTy res_ty
419 ; exprs' <- mapM (tc_elt elt_ty) exprs
420 ; return $ mkHsWrapCo coi (ExplicitPArr elt_ty exprs') }
421 where
422 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
423
424 {-
425 ************************************************************************
426 * *
427 Let, case, if, do
428 * *
429 ************************************************************************
430 -}
431
432 tcExpr (HsLet binds expr) res_ty
433 = do { (binds', expr') <- tcLocalBinds binds $
434 tcMonoExpr expr res_ty
435 ; return (HsLet binds' expr') }
436
437 tcExpr (HsCase scrut matches) exp_ty
438 = do { -- We used to typecheck the case alternatives first.
439 -- The case patterns tend to give good type info to use
440 -- when typechecking the scrutinee. For example
441 -- case (map f) of
442 -- (x:xs) -> ...
443 -- will report that map is applied to too few arguments
444 --
445 -- But now, in the GADT world, we need to typecheck the scrutinee
446 -- first, to get type info that may be refined in the case alternatives
447 (scrut', scrut_ty) <- tcInferRho scrut
448
449 ; traceTc "HsCase" (ppr scrut_ty)
450 ; matches' <- tcMatchesCase match_ctxt scrut_ty matches exp_ty
451 ; return (HsCase scrut' matches') }
452 where
453 match_ctxt = MC { mc_what = CaseAlt,
454 mc_body = tcBody }
455
456 tcExpr (HsIf Nothing pred b1 b2) res_ty -- Ordinary 'if'
457 = do { pred' <- tcMonoExpr pred boolTy
458 ; b1' <- tcMonoExpr b1 res_ty
459 ; b2' <- tcMonoExpr b2 res_ty
460 ; return (HsIf Nothing pred' b1' b2') }
461
462 tcExpr (HsIf (Just fun) pred b1 b2) res_ty -- Note [Rebindable syntax for if]
463 = do { pred_ty <- newFlexiTyVarTy openTypeKind
464 ; b1_ty <- newFlexiTyVarTy openTypeKind
465 ; b2_ty <- newFlexiTyVarTy openTypeKind
466 ; let if_ty = mkFunTys [pred_ty, b1_ty, b2_ty] res_ty
467 ; fun' <- tcSyntaxOp IfOrigin fun if_ty
468 ; pred' <- tcMonoExpr pred pred_ty
469 ; b1' <- tcMonoExpr b1 b1_ty
470 ; b2' <- tcMonoExpr b2 b2_ty
471 -- Fundamentally we are just typing (ifThenElse e1 e2 e3)
472 -- so maybe we should use the code for function applications
473 -- (which would allow ifThenElse to be higher rank).
474 -- But it's a little awkward, so I'm leaving it alone for now
475 -- and it maintains uniformity with other rebindable syntax
476 ; return (HsIf (Just fun') pred' b1' b2') }
477
478 tcExpr (HsMultiIf _ alts) res_ty
479 = do { alts' <- mapM (wrapLocM $ tcGRHS match_ctxt res_ty) alts
480 ; return $ HsMultiIf res_ty alts' }
481 where match_ctxt = MC { mc_what = IfAlt, mc_body = tcBody }
482
483 tcExpr (HsDo do_or_lc stmts _) res_ty
484 = tcDoStmts do_or_lc stmts res_ty
485
486 tcExpr (HsProc pat cmd) res_ty
487 = do { (pat', cmd', coi) <- tcProc pat cmd res_ty
488 ; return $ mkHsWrapCo coi (HsProc pat' cmd') }
489
490 {-
491 Note [Rebindable syntax for if]
492 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
493 The rebindable syntax for 'if' uses the most flexible possible type
494 for conditionals:
495 ifThenElse :: p -> b1 -> b2 -> res
496 to support expressions like this:
497
498 ifThenElse :: Maybe a -> (a -> b) -> b -> b
499 ifThenElse (Just a) f _ = f a
500 ifThenElse Nothing _ e = e
501
502 example :: String
503 example = if Just 2
504 then \v -> show v
505 else "No value"
506
507
508 ************************************************************************
509 * *
510 Record construction and update
511 * *
512 ************************************************************************
513 -}
514
515 tcExpr (RecordCon (L loc con_name) _ rbinds) res_ty
516 = do { data_con <- tcLookupDataCon con_name
517
518 -- Check for missing fields
519 ; checkMissingFields data_con rbinds
520
521 ; (con_expr, con_tau) <- tcInferId con_name
522 ; let arity = dataConSourceArity data_con
523 (arg_tys, actual_res_ty) = tcSplitFunTysN con_tau arity
524 con_id = dataConWrapId data_con
525
526 ; co_res <- unifyType actual_res_ty res_ty
527 ; rbinds' <- tcRecordBinds data_con arg_tys rbinds
528 ; return $ mkHsWrapCo co_res $
529 RecordCon (L loc con_id) con_expr rbinds' }
530
531 {-
532 Note [Type of a record update]
533 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
534 The main complication with RecordUpd is that we need to explicitly
535 handle the *non-updated* fields. Consider:
536
537 data T a b c = MkT1 { fa :: a, fb :: (b,c) }
538 | MkT2 { fa :: a, fb :: (b,c), fc :: c -> c }
539 | MkT3 { fd :: a }
540
541 upd :: T a b c -> (b',c) -> T a b' c
542 upd t x = t { fb = x}
543
544 The result type should be (T a b' c)
545 not (T a b c), because 'b' *is not* mentioned in a non-updated field
546 not (T a b' c'), because 'c' *is* mentioned in a non-updated field
547 NB that it's not good enough to look at just one constructor; we must
548 look at them all; cf Trac #3219
549
550 After all, upd should be equivalent to:
551 upd t x = case t of
552 MkT1 p q -> MkT1 p x
553 MkT2 a b -> MkT2 p b
554 MkT3 d -> error ...
555
556 So we need to give a completely fresh type to the result record,
557 and then constrain it by the fields that are *not* updated ("p" above).
558 We call these the "fixed" type variables, and compute them in getFixedTyVars.
559
560 Note that because MkT3 doesn't contain all the fields being updated,
561 its RHS is simply an error, so it doesn't impose any type constraints.
562 Hence the use of 'relevant_cont'.
563
564 Note [Implicit type sharing]
565 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
566 We also take into account any "implicit" non-update fields. For example
567 data T a b where { MkT { f::a } :: T a a; ... }
568 So the "real" type of MkT is: forall ab. (a~b) => a -> T a b
569
570 Then consider
571 upd t x = t { f=x }
572 We infer the type
573 upd :: T a b -> a -> T a b
574 upd (t::T a b) (x::a)
575 = case t of { MkT (co:a~b) (_:a) -> MkT co x }
576 We can't give it the more general type
577 upd :: T a b -> c -> T c b
578
579 Note [Criteria for update]
580 ~~~~~~~~~~~~~~~~~~~~~~~~~~
581 We want to allow update for existentials etc, provided the updated
582 field isn't part of the existential. For example, this should be ok.
583 data T a where { MkT { f1::a, f2::b->b } :: T a }
584 f :: T a -> b -> T b
585 f t b = t { f1=b }
586
587 The criterion we use is this:
588
589 The types of the updated fields
590 mention only the universally-quantified type variables
591 of the data constructor
592
593 NB: this is not (quite) the same as being a "naughty" record selector
594 (See Note [Naughty record selectors]) in TcTyClsDecls), at least
595 in the case of GADTs. Consider
596 data T a where { MkT :: { f :: a } :: T [a] }
597 Then f is not "naughty" because it has a well-typed record selector.
598 But we don't allow updates for 'f'. (One could consider trying to
599 allow this, but it makes my head hurt. Badly. And no one has asked
600 for it.)
601
602 In principle one could go further, and allow
603 g :: T a -> T a
604 g t = t { f2 = \x -> x }
605 because the expression is polymorphic...but that seems a bridge too far.
606
607 Note [Data family example]
608 ~~~~~~~~~~~~~~~~~~~~~~~~~~
609 data instance T (a,b) = MkT { x::a, y::b }
610 --->
611 data :TP a b = MkT { a::a, y::b }
612 coTP a b :: T (a,b) ~ :TP a b
613
614 Suppose r :: T (t1,t2), e :: t3
615 Then r { x=e } :: T (t3,t1)
616 --->
617 case r |> co1 of
618 MkT x y -> MkT e y |> co2
619 where co1 :: T (t1,t2) ~ :TP t1 t2
620 co2 :: :TP t3 t2 ~ T (t3,t2)
621 The wrapping with co2 is done by the constructor wrapper for MkT
622
623 Outgoing invariants
624 ~~~~~~~~~~~~~~~~~~~
625 In the outgoing (HsRecordUpd scrut binds cons in_inst_tys out_inst_tys):
626
627 * cons are the data constructors to be updated
628
629 * in_inst_tys, out_inst_tys have same length, and instantiate the
630 *representation* tycon of the data cons. In Note [Data
631 family example], in_inst_tys = [t1,t2], out_inst_tys = [t3,t2]
632 -}
633
634 tcExpr (RecordUpd record_expr rbinds _ _ _) res_ty
635 = ASSERT( notNull upd_fld_names )
636 do {
637 -- STEP 0
638 -- Check that the field names are really field names
639 ; sel_ids <- mapM tcLookupField upd_fld_names
640 -- The renamer has already checked that
641 -- selectors are all in scope
642 ; let bad_guys = [ setSrcSpan loc $ addErrTc (notSelector fld_name)
643 | (fld, sel_id) <- rec_flds rbinds `zip` sel_ids,
644 not (isRecordSelector sel_id), -- Excludes class ops
645 let L loc fld_name = hsRecFieldId (unLoc fld) ]
646 ; unless (null bad_guys) (sequence bad_guys >> failM)
647
648 -- STEP 1
649 -- Figure out the tycon and data cons from the first field name
650 ; let -- It's OK to use the non-tc splitters here (for a selector)
651 sel_id : _ = sel_ids
652 (tycon, _) = recordSelectorFieldLabel sel_id -- We've failed already if
653 data_cons = tyConDataCons tycon -- it's not a field label
654 -- NB: for a data type family, the tycon is the instance tycon
655
656 relevant_cons = filter is_relevant data_cons
657 is_relevant con = all (`elem` dataConFieldLabels con) upd_fld_names
658 -- A constructor is only relevant to this process if
659 -- it contains *all* the fields that are being updated
660 -- Other ones will cause a runtime error if they occur
661
662 -- Take apart a representative constructor
663 con1 = ASSERT( not (null relevant_cons) ) head relevant_cons
664 (con1_tvs, _, _, _, con1_arg_tys, _) = dataConFullSig con1
665 con1_flds = dataConFieldLabels con1
666 con1_res_ty = mkFamilyTyConApp tycon (mkTyVarTys con1_tvs)
667
668 -- Step 2
669 -- Check that at least one constructor has all the named fields
670 -- i.e. has an empty set of bad fields returned by badFields
671 ; checkTc (not (null relevant_cons)) (badFieldsUpd rbinds data_cons)
672
673 -- STEP 3 Note [Criteria for update]
674 -- Check that each updated field is polymorphic; that is, its type
675 -- mentions only the universally-quantified variables of the data con
676 ; let flds1_w_tys = zipEqual "tcExpr:RecConUpd" con1_flds con1_arg_tys
677 upd_flds1_w_tys = filter is_updated flds1_w_tys
678 is_updated (fld,_) = fld `elem` upd_fld_names
679
680 bad_upd_flds = filter bad_fld upd_flds1_w_tys
681 con1_tv_set = mkVarSet con1_tvs
682 bad_fld (fld, ty) = fld `elem` upd_fld_names &&
683 not (tyVarsOfType ty `subVarSet` con1_tv_set)
684 ; checkTc (null bad_upd_flds) (badFieldTypes bad_upd_flds)
685
686 -- STEP 4 Note [Type of a record update]
687 -- Figure out types for the scrutinee and result
688 -- Both are of form (T a b c), with fresh type variables, but with
689 -- common variables where the scrutinee and result must have the same type
690 -- These are variables that appear in *any* arg of *any* of the
691 -- relevant constructors *except* in the updated fields
692 --
693 ; let fixed_tvs = getFixedTyVars con1_tvs relevant_cons
694 is_fixed_tv tv = tv `elemVarSet` fixed_tvs
695
696 mk_inst_ty :: TvSubst -> (TKVar, TcType) -> TcM (TvSubst, TcType)
697 -- Deals with instantiation of kind variables
698 -- c.f. TcMType.tcInstTyVars
699 mk_inst_ty subst (tv, result_inst_ty)
700 | is_fixed_tv tv -- Same as result type
701 = return (extendTvSubst subst tv result_inst_ty, result_inst_ty)
702 | otherwise -- Fresh type, of correct kind
703 = do { new_ty <- newFlexiTyVarTy (TcType.substTy subst (tyVarKind tv))
704 ; return (extendTvSubst subst tv new_ty, new_ty) }
705
706 ; (result_subst, con1_tvs') <- tcInstTyVars con1_tvs
707 ; let result_inst_tys = mkTyVarTys con1_tvs'
708
709 ; (scrut_subst, scrut_inst_tys) <- mapAccumLM mk_inst_ty emptyTvSubst
710 (con1_tvs `zip` result_inst_tys)
711
712 ; let rec_res_ty = TcType.substTy result_subst con1_res_ty
713 scrut_ty = TcType.substTy scrut_subst con1_res_ty
714 con1_arg_tys' = map (TcType.substTy result_subst) con1_arg_tys
715
716 ; co_res <- unifyType rec_res_ty res_ty
717
718 -- STEP 5
719 -- Typecheck the thing to be updated, and the bindings
720 ; record_expr' <- tcMonoExpr record_expr scrut_ty
721 ; rbinds' <- tcRecordBinds con1 con1_arg_tys' rbinds
722
723 -- STEP 6: Deal with the stupid theta
724 ; let theta' = substTheta scrut_subst (dataConStupidTheta con1)
725 ; instStupidTheta RecordUpdOrigin theta'
726
727 -- Step 7: make a cast for the scrutinee, in the case that it's from a type family
728 ; let scrut_co | Just co_con <- tyConFamilyCoercion_maybe tycon
729 = mkWpCast (mkTcUnbranchedAxInstCo Representational co_con scrut_inst_tys)
730 | otherwise
731 = idHsWrapper
732 -- Phew!
733 ; return $ mkHsWrapCo co_res $
734 RecordUpd (mkLHsWrap scrut_co record_expr') rbinds'
735 relevant_cons scrut_inst_tys result_inst_tys }
736 where
737 upd_fld_names = hsRecFields rbinds
738
739 getFixedTyVars :: [TyVar] -> [DataCon] -> TyVarSet
740 -- These tyvars must not change across the updates
741 getFixedTyVars tvs1 cons
742 = mkVarSet [tv1 | con <- cons
743 , let (tvs, theta, arg_tys, _) = dataConSig con
744 flds = dataConFieldLabels con
745 fixed_tvs = exactTyVarsOfTypes fixed_tys
746 -- fixed_tys: See Note [Type of a record update]
747 `unionVarSet` tyVarsOfTypes theta
748 -- Universally-quantified tyvars that
749 -- appear in any of the *implicit*
750 -- arguments to the constructor are fixed
751 -- See Note [Implicit type sharing]
752
753 fixed_tys = [ty | (fld,ty) <- zip flds arg_tys
754 , not (fld `elem` upd_fld_names)]
755 , (tv1,tv) <- tvs1 `zip` tvs -- Discards existentials in tvs
756 , tv `elemVarSet` fixed_tvs ]
757
758 {-
759 ************************************************************************
760 * *
761 Arithmetic sequences e.g. [a,b..]
762 and their parallel-array counterparts e.g. [: a,b.. :]
763
764 * *
765 ************************************************************************
766 -}
767
768 tcExpr (ArithSeq _ witness seq) res_ty
769 = tcArithSeq witness seq res_ty
770
771 tcExpr (PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
772 = do { (coi, elt_ty) <- matchExpectedPArrTy res_ty
773 ; expr1' <- tcPolyExpr expr1 elt_ty
774 ; expr2' <- tcPolyExpr expr2 elt_ty
775 ; enumFromToP <- initDsTc $ dsDPHBuiltin enumFromToPVar
776 ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq)
777 (idName enumFromToP) elt_ty
778 ; return $ mkHsWrapCo coi
779 (PArrSeq enum_from_to (FromTo expr1' expr2')) }
780
781 tcExpr (PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
782 = do { (coi, elt_ty) <- matchExpectedPArrTy res_ty
783 ; expr1' <- tcPolyExpr expr1 elt_ty
784 ; expr2' <- tcPolyExpr expr2 elt_ty
785 ; expr3' <- tcPolyExpr expr3 elt_ty
786 ; enumFromThenToP <- initDsTc $ dsDPHBuiltin enumFromThenToPVar
787 ; eft <- newMethodFromName (PArrSeqOrigin seq)
788 (idName enumFromThenToP) elt_ty -- !!!FIXME: chak
789 ; return $ mkHsWrapCo coi
790 (PArrSeq eft (FromThenTo expr1' expr2' expr3')) }
791
792 tcExpr (PArrSeq _ _) _
793 = panic "TcExpr.tcExpr: Infinite parallel array!"
794 -- the parser shouldn't have generated it and the renamer shouldn't have
795 -- let it through
796
797 {-
798 ************************************************************************
799 * *
800 Template Haskell
801 * *
802 ************************************************************************
803 -}
804
805 tcExpr (HsSpliceE is_ty splice) res_ty
806 = ASSERT( is_ty ) -- Untyped splices are expanded by the renamer
807 tcSpliceExpr splice res_ty
808
809 tcExpr (HsBracket brack) res_ty = tcTypedBracket brack res_ty
810 tcExpr (HsRnBracketOut brack ps) res_ty = tcUntypedBracket brack ps res_ty
811
812 {-
813 ************************************************************************
814 * *
815 Catch-all
816 * *
817 ************************************************************************
818 -}
819
820 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
821 -- Include ArrForm, ArrApp, which shouldn't appear at all
822 -- Also HsTcBracketOut, HsQuasiQuoteE
823
824 {-
825 ************************************************************************
826 * *
827 Arithmetic sequences [a..b] etc
828 * *
829 ************************************************************************
830 -}
831
832 tcArithSeq :: Maybe (SyntaxExpr Name) -> ArithSeqInfo Name -> TcRhoType
833 -> TcM (HsExpr TcId)
834
835 tcArithSeq witness seq@(From expr) res_ty
836 = do { (coi, elt_ty, wit') <- arithSeqEltType witness res_ty
837 ; expr' <- tcPolyExpr expr elt_ty
838 ; enum_from <- newMethodFromName (ArithSeqOrigin seq)
839 enumFromName elt_ty
840 ; return $ mkHsWrapCo coi (ArithSeq enum_from wit' (From expr')) }
841
842 tcArithSeq witness seq@(FromThen expr1 expr2) res_ty
843 = do { (coi, elt_ty, wit') <- arithSeqEltType witness res_ty
844 ; expr1' <- tcPolyExpr expr1 elt_ty
845 ; expr2' <- tcPolyExpr expr2 elt_ty
846 ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq)
847 enumFromThenName elt_ty
848 ; return $ mkHsWrapCo coi (ArithSeq enum_from_then wit' (FromThen expr1' expr2')) }
849
850 tcArithSeq witness seq@(FromTo expr1 expr2) res_ty
851 = do { (coi, elt_ty, wit') <- arithSeqEltType witness res_ty
852 ; expr1' <- tcPolyExpr expr1 elt_ty
853 ; expr2' <- tcPolyExpr expr2 elt_ty
854 ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq)
855 enumFromToName elt_ty
856 ; return $ mkHsWrapCo coi (ArithSeq enum_from_to wit' (FromTo expr1' expr2')) }
857
858 tcArithSeq witness seq@(FromThenTo expr1 expr2 expr3) res_ty
859 = do { (coi, elt_ty, wit') <- arithSeqEltType witness res_ty
860 ; expr1' <- tcPolyExpr expr1 elt_ty
861 ; expr2' <- tcPolyExpr expr2 elt_ty
862 ; expr3' <- tcPolyExpr expr3 elt_ty
863 ; eft <- newMethodFromName (ArithSeqOrigin seq)
864 enumFromThenToName elt_ty
865 ; return $ mkHsWrapCo coi (ArithSeq eft wit' (FromThenTo expr1' expr2' expr3')) }
866
867 -----------------
868 arithSeqEltType :: Maybe (SyntaxExpr Name) -> TcRhoType
869 -> TcM (TcCoercion, TcType, Maybe (SyntaxExpr Id))
870 arithSeqEltType Nothing res_ty
871 = do { (coi, elt_ty) <- matchExpectedListTy res_ty
872 ; return (coi, elt_ty, Nothing) }
873 arithSeqEltType (Just fl) res_ty
874 = do { list_ty <- newFlexiTyVarTy liftedTypeKind
875 ; fl' <- tcSyntaxOp ListOrigin fl (mkFunTy list_ty res_ty)
876 ; (coi, elt_ty) <- matchExpectedListTy list_ty
877 ; return (coi, elt_ty, Just fl') }
878
879 {-
880 ************************************************************************
881 * *
882 Applications
883 * *
884 ************************************************************************
885 -}
886
887 tcApp :: LHsExpr Name -> [LHsExpr Name] -- Function and args
888 -> TcRhoType -> TcM (HsExpr TcId) -- Translated fun and args
889
890 tcApp (L _ (HsPar e)) args res_ty
891 = tcApp e args res_ty
892
893 tcApp (L _ (HsApp e1 e2)) args res_ty
894 = tcApp e1 (e2:args) res_ty -- Accumulate the arguments
895
896 tcApp (L loc (HsVar fun)) args res_ty
897 | fun `hasKey` tagToEnumKey
898 , [arg] <- args
899 = tcTagToEnum loc fun arg res_ty
900
901 | fun `hasKey` seqIdKey
902 , [arg1,arg2] <- args
903 = tcSeq loc fun arg1 arg2 res_ty
904
905 tcApp fun args res_ty
906 = do { -- Type-check the function
907 ; (fun1, fun_tau) <- tcInferFun fun
908
909 -- Extract its argument types
910 ; (co_fun, expected_arg_tys, actual_res_ty)
911 <- matchExpectedFunTys (mk_app_msg fun) (length args) fun_tau
912
913 -- Typecheck the result, thereby propagating
914 -- info (if any) from result into the argument types
915 -- Both actual_res_ty and res_ty are deeply skolemised
916 -- Rather like tcWrapResult, but (perhaps for historical reasons)
917 -- we do this before typechecking the arguments
918 ; wrap_res <- addErrCtxtM (funResCtxt True (unLoc fun) actual_res_ty res_ty) $
919 tcSubTypeDS_NC GenSigCtxt actual_res_ty res_ty
920
921 -- Typecheck the arguments
922 ; args1 <- tcArgs fun args expected_arg_tys
923
924 -- Assemble the result
925 ; let fun2 = mkLHsWrapCo co_fun fun1
926 app = mkLHsWrap wrap_res (foldl mkHsApp fun2 args1)
927
928 ; return (unLoc app) }
929
930
931 mk_app_msg :: LHsExpr Name -> SDoc
932 mk_app_msg fun = sep [ ptext (sLit "The function") <+> quotes (ppr fun)
933 , ptext (sLit "is applied to")]
934
935 ----------------
936 tcInferFun :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
937 -- Infer and instantiate the type of a function
938 tcInferFun (L loc (HsVar name))
939 = do { (fun, ty) <- setSrcSpan loc (tcInferId name)
940 -- Don't wrap a context around a plain Id
941 ; return (L loc fun, ty) }
942
943 tcInferFun fun
944 = do { (fun, fun_ty) <- tcInfer (tcMonoExpr fun)
945
946 -- Zonk the function type carefully, to expose any polymorphism
947 -- E.g. (( \(x::forall a. a->a). blah ) e)
948 -- We can see the rank-2 type of the lambda in time to generalise e
949 ; fun_ty' <- zonkTcType fun_ty
950
951 ; (wrap, rho) <- deeplyInstantiate AppOrigin fun_ty'
952 ; return (mkLHsWrap wrap fun, rho) }
953
954 ----------------
955 tcArgs :: LHsExpr Name -- The function (for error messages)
956 -> [LHsExpr Name] -> [TcSigmaType] -- Actual arguments and expected arg types
957 -> TcM [LHsExpr TcId] -- Resulting args
958
959 tcArgs fun args expected_arg_tys
960 = mapM (tcArg fun) (zip3 args expected_arg_tys [1..])
961
962 ----------------
963 tcArg :: LHsExpr Name -- The function (for error messages)
964 -> (LHsExpr Name, TcSigmaType, Int) -- Actual argument and expected arg type
965 -> TcM (LHsExpr TcId) -- Resulting argument
966 tcArg fun (arg, ty, arg_no) = addErrCtxt (funAppCtxt fun arg arg_no)
967 (tcPolyExprNC arg ty)
968
969 ----------------
970 tcTupArgs :: [LHsTupArg Name] -> [TcSigmaType] -> TcM [LHsTupArg TcId]
971 tcTupArgs args tys
972 = ASSERT( equalLength args tys ) mapM go (args `zip` tys)
973 where
974 go (L l (Missing {}), arg_ty) = return (L l (Missing arg_ty))
975 go (L l (Present expr), arg_ty) = do { expr' <- tcPolyExpr expr arg_ty
976 ; return (L l (Present expr')) }
977
978 ----------------
979 unifyOpFunTysWrap :: LHsExpr Name -> Arity -> TcRhoType
980 -> TcM (TcCoercion, [TcSigmaType], TcRhoType)
981 -- A wrapper for matchExpectedFunTys
982 unifyOpFunTysWrap op arity ty = matchExpectedFunTys herald arity ty
983 where
984 herald = ptext (sLit "The operator") <+> quotes (ppr op) <+> ptext (sLit "takes")
985
986 ---------------------------
987 tcSyntaxOp :: CtOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
988 -- Typecheck a syntax operator, checking that it has the specified type
989 -- The operator is always a variable at this stage (i.e. renamer output)
990 -- This version assumes res_ty is a monotype
991 tcSyntaxOp orig (HsVar op) res_ty = do { (expr, rho) <- tcInferIdWithOrig orig op
992 ; tcWrapResult expr rho res_ty }
993 tcSyntaxOp _ other _ = pprPanic "tcSyntaxOp" (ppr other)
994
995 {-
996 Note [Push result type in]
997 ~~~~~~~~~~~~~~~~~~~~~~~~~~
998 Unify with expected result before type-checking the args so that the
999 info from res_ty percolates to args. This is when we might detect a
1000 too-few args situation. (One can think of cases when the opposite
1001 order would give a better error message.)
1002 experimenting with putting this first.
1003
1004 Here's an example where it actually makes a real difference
1005
1006 class C t a b | t a -> b
1007 instance C Char a Bool
1008
1009 data P t a = forall b. (C t a b) => MkP b
1010 data Q t = MkQ (forall a. P t a)
1011
1012 f1, f2 :: Q Char;
1013 f1 = MkQ (MkP True)
1014 f2 = MkQ (MkP True :: forall a. P Char a)
1015
1016 With the change, f1 will type-check, because the 'Char' info from
1017 the signature is propagated into MkQ's argument. With the check
1018 in the other order, the extra signature in f2 is reqd.
1019
1020
1021 ************************************************************************
1022 * *
1023 tcInferId
1024 * *
1025 ************************************************************************
1026 -}
1027
1028 tcCheckId :: Name -> TcRhoType -> TcM (HsExpr TcId)
1029 tcCheckId name res_ty
1030 = do { (expr, actual_res_ty) <- tcInferId name
1031 ; traceTc "tcCheckId" (vcat [ppr name, ppr actual_res_ty, ppr res_ty])
1032 ; addErrCtxtM (funResCtxt False (HsVar name) actual_res_ty res_ty) $
1033 tcWrapResult expr actual_res_ty res_ty }
1034
1035 ------------------------
1036 tcInferId :: Name -> TcM (HsExpr TcId, TcRhoType)
1037 -- Infer type, and deeply instantiate
1038 tcInferId n = tcInferIdWithOrig (OccurrenceOf n) n
1039
1040 ------------------------
1041 tcInferIdWithOrig :: CtOrigin -> Name -> TcM (HsExpr TcId, TcRhoType)
1042 -- Look up an occurrence of an Id, and instantiate it (deeply)
1043
1044 tcInferIdWithOrig orig id_name
1045 | id_name `hasKey` tagToEnumKey
1046 = failWithTc (ptext (sLit "tagToEnum# must appear applied to one argument"))
1047 -- tcApp catches the case (tagToEnum# arg)
1048
1049 | id_name `hasKey` assertIdKey
1050 = do { dflags <- getDynFlags
1051 ; if gopt Opt_IgnoreAsserts dflags
1052 then tc_infer_id orig id_name
1053 else tc_infer_assert dflags orig }
1054
1055 | otherwise
1056 = tc_infer_id orig id_name
1057
1058 tc_infer_assert :: DynFlags -> CtOrigin -> TcM (HsExpr TcId, TcRhoType)
1059 -- Deal with an occurrence of 'assert'
1060 -- See Note [Adding the implicit parameter to 'assert']
1061 tc_infer_assert dflags orig
1062 = do { sloc <- getSrcSpanM
1063 ; assert_error_id <- tcLookupId assertErrorName
1064 ; (wrap, id_rho) <- deeplyInstantiate orig (idType assert_error_id)
1065 ; let (arg_ty, res_ty) = case tcSplitFunTy_maybe id_rho of
1066 Nothing -> pprPanic "assert type" (ppr id_rho)
1067 Just arg_res -> arg_res
1068 ; ASSERT( arg_ty `tcEqType` addrPrimTy )
1069 return (HsApp (L sloc (mkHsWrap wrap (HsVar assert_error_id)))
1070 (L sloc (srcSpanPrimLit dflags sloc))
1071 , res_ty) }
1072
1073 tc_infer_id :: CtOrigin -> Name -> TcM (HsExpr TcId, TcRhoType)
1074 -- Return type is deeply instantiated
1075 tc_infer_id orig id_name
1076 = do { thing <- tcLookup id_name
1077 ; case thing of
1078 ATcId { tct_id = id }
1079 -> do { check_naughty id -- Note [Local record selectors]
1080 ; checkThLocalId id
1081 ; inst_normal_id id }
1082
1083 AGlobal (AnId id)
1084 -> do { check_naughty id
1085 ; inst_normal_id id }
1086 -- A global cannot possibly be ill-staged
1087 -- nor does it need the 'lifting' treatment
1088 -- hence no checkTh stuff here
1089
1090 AGlobal (AConLike cl) -> case cl of
1091 RealDataCon con -> inst_data_con con
1092 PatSynCon ps -> tcPatSynBuilderOcc orig ps
1093
1094 _ -> failWithTc $
1095 ppr thing <+> ptext (sLit "used where a value identifer was expected") }
1096 where
1097 inst_normal_id id
1098 = do { (wrap, rho) <- deeplyInstantiate orig (idType id)
1099 ; return (mkHsWrap wrap (HsVar id), rho) }
1100
1101 inst_data_con con
1102 -- For data constructors,
1103 -- * Must perform the stupid-theta check
1104 -- * No need to deeply instantiate because type has all foralls at top
1105 = do { let wrap_id = dataConWrapId con
1106 (tvs, theta, rho) = tcSplitSigmaTy (idType wrap_id)
1107 ; (subst, tvs') <- tcInstTyVars tvs
1108 ; let tys' = mkTyVarTys tvs'
1109 theta' = substTheta subst theta
1110 rho' = substTy subst rho
1111 ; wrap <- instCall orig tys' theta'
1112 ; addDataConStupidTheta con tys'
1113 ; return (mkHsWrap wrap (HsVar wrap_id), rho') }
1114
1115 check_naughty id
1116 | isNaughtyRecordSelector id = failWithTc (naughtyRecordSel id)
1117 | otherwise = return ()
1118
1119 srcSpanPrimLit :: DynFlags -> SrcSpan -> HsExpr TcId
1120 srcSpanPrimLit dflags span
1121 = HsLit (HsStringPrim "" (unsafeMkByteString
1122 (showSDocOneLine dflags (ppr span))))
1123
1124 {-
1125 Note [Adding the implicit parameter to 'assert']
1126 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1127 The typechecker transforms (assert e1 e2) to (assertError "Foo.hs:27"
1128 e1 e2). This isn't really the Right Thing because there's no way to
1129 "undo" if you want to see the original source code in the typechecker
1130 output. We'll have fix this in due course, when we care more about
1131 being able to reconstruct the exact original program.
1132
1133 Note [tagToEnum#]
1134 ~~~~~~~~~~~~~~~~~
1135 Nasty check to ensure that tagToEnum# is applied to a type that is an
1136 enumeration TyCon. Unification may refine the type later, but this
1137 check won't see that, alas. It's crude, because it relies on our
1138 knowing *now* that the type is ok, which in turn relies on the
1139 eager-unification part of the type checker pushing enough information
1140 here. In theory the Right Thing to do is to have a new form of
1141 constraint but I definitely cannot face that! And it works ok as-is.
1142
1143 Here's are two cases that should fail
1144 f :: forall a. a
1145 f = tagToEnum# 0 -- Can't do tagToEnum# at a type variable
1146
1147 g :: Int
1148 g = tagToEnum# 0 -- Int is not an enumeration
1149
1150 When data type families are involved it's a bit more complicated.
1151 data family F a
1152 data instance F [Int] = A | B | C
1153 Then we want to generate something like
1154 tagToEnum# R:FListInt 3# |> co :: R:FListInt ~ F [Int]
1155 Usually that coercion is hidden inside the wrappers for
1156 constructors of F [Int] but here we have to do it explicitly.
1157
1158 It's all grotesquely complicated.
1159 -}
1160
1161 tcSeq :: SrcSpan -> Name -> LHsExpr Name -> LHsExpr Name
1162 -> TcRhoType -> TcM (HsExpr TcId)
1163 -- (seq e1 e2) :: res_ty
1164 -- We need a special typing rule because res_ty can be unboxed
1165 tcSeq loc fun_name arg1 arg2 res_ty
1166 = do { fun <- tcLookupId fun_name
1167 ; (arg1', arg1_ty) <- tcInfer (tcMonoExpr arg1)
1168 ; arg2' <- tcMonoExpr arg2 res_ty
1169 ; let fun' = L loc (HsWrap ty_args (HsVar fun))
1170 ty_args = WpTyApp res_ty <.> WpTyApp arg1_ty
1171 ; return (HsApp (L loc (HsApp fun' arg1')) arg2') }
1172
1173 tcTagToEnum :: SrcSpan -> Name -> LHsExpr Name -> TcRhoType -> TcM (HsExpr TcId)
1174 -- tagToEnum# :: forall a. Int# -> a
1175 -- See Note [tagToEnum#] Urgh!
1176 tcTagToEnum loc fun_name arg res_ty
1177 = do { fun <- tcLookupId fun_name
1178 ; ty' <- zonkTcType res_ty
1179
1180 -- Check that the type is algebraic
1181 ; let mb_tc_app = tcSplitTyConApp_maybe ty'
1182 Just (tc, tc_args) = mb_tc_app
1183 ; checkTc (isJust mb_tc_app)
1184 (mk_error ty' doc1)
1185
1186 -- Look through any type family
1187 ; fam_envs <- tcGetFamInstEnvs
1188 ; let (rep_tc, rep_args, coi) = tcLookupDataFamInst fam_envs tc tc_args
1189 -- coi :: tc tc_args ~ rep_tc rep_args
1190
1191 ; checkTc (isEnumerationTyCon rep_tc)
1192 (mk_error ty' doc2)
1193
1194 ; arg' <- tcMonoExpr arg intPrimTy
1195 ; let fun' = L loc (HsWrap (WpTyApp rep_ty) (HsVar fun))
1196 rep_ty = mkTyConApp rep_tc rep_args
1197
1198 ; return (mkHsWrapCoR (mkTcSymCo coi) $ HsApp fun' arg') }
1199 -- coi is a Representational coercion
1200 where
1201 doc1 = vcat [ ptext (sLit "Specify the type by giving a type signature")
1202 , ptext (sLit "e.g. (tagToEnum# x) :: Bool") ]
1203 doc2 = ptext (sLit "Result type must be an enumeration type")
1204
1205 mk_error :: TcType -> SDoc -> SDoc
1206 mk_error ty what
1207 = hang (ptext (sLit "Bad call to tagToEnum#")
1208 <+> ptext (sLit "at type") <+> ppr ty)
1209 2 what
1210
1211 {-
1212 ************************************************************************
1213 * *
1214 Template Haskell checks
1215 * *
1216 ************************************************************************
1217 -}
1218
1219 checkThLocalId :: Id -> TcM ()
1220 #ifndef GHCI /* GHCI and TH is off */
1221 --------------------------------------
1222 -- Check for cross-stage lifting
1223 checkThLocalId _id
1224 = return ()
1225
1226 #else /* GHCI and TH is on */
1227 checkThLocalId id
1228 = do { mb_local_use <- getStageAndBindLevel (idName id)
1229 ; case mb_local_use of
1230 Just (top_lvl, bind_lvl, use_stage)
1231 | thLevel use_stage > bind_lvl
1232 , isNotTopLevel top_lvl
1233 -> checkCrossStageLifting id use_stage
1234 _ -> return () -- Not a locally-bound thing, or
1235 -- no cross-stage link
1236 }
1237
1238 --------------------------------------
1239 checkCrossStageLifting :: Id -> ThStage -> TcM ()
1240 -- If we are inside brackets, and (use_lvl > bind_lvl)
1241 -- we must check whether there's a cross-stage lift to do
1242 -- Examples \x -> [| x |]
1243 -- [| map |]
1244 -- There is no error-checking to do, because the renamer did that
1245
1246 checkCrossStageLifting id (Brack _ (TcPending ps_var lie_var))
1247 = -- Nested identifiers, such as 'x' in
1248 -- E.g. \x -> [| h x |]
1249 -- We must behave as if the reference to x was
1250 -- h $(lift x)
1251 -- We use 'x' itself as the splice proxy, used by
1252 -- the desugarer to stitch it all back together.
1253 -- If 'x' occurs many times we may get many identical
1254 -- bindings of the same splice proxy, but that doesn't
1255 -- matter, although it's a mite untidy.
1256 do { let id_ty = idType id
1257 ; checkTc (isTauTy id_ty) (polySpliceErr id)
1258 -- If x is polymorphic, its occurrence sites might
1259 -- have different instantiations, so we can't use plain
1260 -- 'x' as the splice proxy name. I don't know how to
1261 -- solve this, and it's probably unimportant, so I'm
1262 -- just going to flag an error for now
1263
1264 ; lift <- if isStringTy id_ty then
1265 do { sid <- tcLookupId DsMeta.liftStringName
1266 -- See Note [Lifting strings]
1267 ; return (HsVar sid) }
1268 else
1269 setConstraintVar lie_var $
1270 -- Put the 'lift' constraint into the right LIE
1271 newMethodFromName (OccurrenceOf (idName id))
1272 DsMeta.liftName id_ty
1273
1274 -- Update the pending splices
1275 ; ps <- readMutVar ps_var
1276 ; let pending_splice = PendSplice (idName id) (nlHsApp (noLoc lift) (nlHsVar id))
1277 ; writeMutVar ps_var (pending_splice : ps)
1278
1279 ; return () }
1280
1281 checkCrossStageLifting _ _ = return ()
1282
1283 polySpliceErr :: Id -> SDoc
1284 polySpliceErr id
1285 = ptext (sLit "Can't splice the polymorphic local variable") <+> quotes (ppr id)
1286 #endif /* GHCI */
1287
1288 {-
1289 Note [Lifting strings]
1290 ~~~~~~~~~~~~~~~~~~~~~~
1291 If we see $(... [| s |] ...) where s::String, we don't want to
1292 generate a mass of Cons (CharL 'x') (Cons (CharL 'y') ...)) etc.
1293 So this conditional short-circuits the lifting mechanism to generate
1294 (liftString "xy") in that case. I didn't want to use overlapping instances
1295 for the Lift class in TH.Syntax, because that can lead to overlapping-instance
1296 errors in a polymorphic situation.
1297
1298 If this check fails (which isn't impossible) we get another chance; see
1299 Note [Converting strings] in Convert.lhs
1300
1301 Local record selectors
1302 ~~~~~~~~~~~~~~~~~~~~~~
1303 Record selectors for TyCons in this module are ordinary local bindings,
1304 which show up as ATcIds rather than AGlobals. So we need to check for
1305 naughtiness in both branches. c.f. TcTyClsBindings.mkAuxBinds.
1306
1307
1308 ************************************************************************
1309 * *
1310 \subsection{Record bindings}
1311 * *
1312 ************************************************************************
1313
1314 Game plan for record bindings
1315 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1316 1. Find the TyCon for the bindings, from the first field label.
1317
1318 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1319
1320 For each binding field = value
1321
1322 3. Instantiate the field type (from the field label) using the type
1323 envt from step 2.
1324
1325 4 Type check the value using tcArg, passing the field type as
1326 the expected argument type.
1327
1328 This extends OK when the field types are universally quantified.
1329 -}
1330
1331 tcRecordBinds
1332 :: DataCon
1333 -> [TcType] -- Expected type for each field
1334 -> HsRecordBinds Name
1335 -> TcM (HsRecordBinds TcId)
1336
1337 tcRecordBinds data_con arg_tys (HsRecFields rbinds dd)
1338 = do { mb_binds <- mapM do_bind rbinds
1339 ; return (HsRecFields (catMaybes mb_binds) dd) }
1340 where
1341 flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1342 do_bind (L l fld@(HsRecField { hsRecFieldId = L loc field_lbl
1343 , hsRecFieldArg = rhs }))
1344 | Just field_ty <- assocMaybe flds_w_tys field_lbl
1345 = addErrCtxt (fieldCtxt field_lbl) $
1346 do { rhs' <- tcPolyExprNC rhs field_ty
1347 ; let field_id = mkUserLocal (nameOccName field_lbl)
1348 (nameUnique field_lbl)
1349 field_ty loc
1350 -- Yuk: the field_id has the *unique* of the selector Id
1351 -- (so we can find it easily)
1352 -- but is a LocalId with the appropriate type of the RHS
1353 -- (so the desugarer knows the type of local binder to make)
1354 ; return (Just (L l (fld { hsRecFieldId = L loc field_id
1355 , hsRecFieldArg = rhs' }))) }
1356 | otherwise
1357 = do { addErrTc (badFieldCon (RealDataCon data_con) field_lbl)
1358 ; return Nothing }
1359
1360 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1361 checkMissingFields data_con rbinds
1362 | null field_labels -- Not declared as a record;
1363 -- But C{} is still valid if no strict fields
1364 = if any isBanged field_strs then
1365 -- Illegal if any arg is strict
1366 addErrTc (missingStrictFields data_con [])
1367 else
1368 return ()
1369
1370 | otherwise = do -- A record
1371 unless (null missing_s_fields)
1372 (addErrTc (missingStrictFields data_con missing_s_fields))
1373
1374 warn <- woptM Opt_WarnMissingFields
1375 unless (not (warn && notNull missing_ns_fields))
1376 (warnTc True (missingFields data_con missing_ns_fields))
1377
1378 where
1379 missing_s_fields
1380 = [ fl | (fl, str) <- field_info,
1381 isBanged str,
1382 not (fl `elem` field_names_used)
1383 ]
1384 missing_ns_fields
1385 = [ fl | (fl, str) <- field_info,
1386 not (isBanged str),
1387 not (fl `elem` field_names_used)
1388 ]
1389
1390 field_names_used = hsRecFields rbinds
1391 field_labels = dataConFieldLabels data_con
1392
1393 field_info = zipEqual "missingFields"
1394 field_labels
1395 field_strs
1396
1397 field_strs = dataConStrictMarks data_con
1398
1399 {-
1400 ************************************************************************
1401 * *
1402 \subsection{Errors and contexts}
1403 * *
1404 ************************************************************************
1405
1406 Boring and alphabetical:
1407 -}
1408
1409 addExprErrCtxt :: LHsExpr Name -> TcM a -> TcM a
1410 addExprErrCtxt expr = addErrCtxt (exprCtxt expr)
1411
1412 exprCtxt :: LHsExpr Name -> SDoc
1413 exprCtxt expr
1414 = hang (ptext (sLit "In the expression:")) 2 (ppr expr)
1415
1416 fieldCtxt :: Name -> SDoc
1417 fieldCtxt field_name
1418 = ptext (sLit "In the") <+> quotes (ppr field_name) <+> ptext (sLit "field of a record")
1419
1420 funAppCtxt :: LHsExpr Name -> LHsExpr Name -> Int -> SDoc
1421 funAppCtxt fun arg arg_no
1422 = hang (hsep [ ptext (sLit "In the"), speakNth arg_no, ptext (sLit "argument of"),
1423 quotes (ppr fun) <> text ", namely"])
1424 2 (quotes (ppr arg))
1425
1426 funResCtxt :: Bool -- There is at least one argument
1427 -> HsExpr Name -> TcType -> TcType
1428 -> TidyEnv -> TcM (TidyEnv, MsgDoc)
1429 -- When we have a mis-match in the return type of a function
1430 -- try to give a helpful message about too many/few arguments
1431 --
1432 -- Used for naked variables too; but with has_args = False
1433 funResCtxt has_args fun fun_res_ty env_ty tidy_env
1434 = do { fun_res' <- zonkTcType fun_res_ty
1435 ; env' <- zonkTcType env_ty
1436 ; let (args_fun, res_fun) = tcSplitFunTys fun_res'
1437 (args_env, res_env) = tcSplitFunTys env'
1438 n_fun = length args_fun
1439 n_env = length args_env
1440 info | n_fun == n_env = Outputable.empty
1441 | n_fun > n_env
1442 , not_fun res_env = ptext (sLit "Probable cause:") <+> quotes (ppr fun)
1443 <+> ptext (sLit "is applied to too few arguments")
1444 | has_args
1445 , not_fun res_fun = ptext (sLit "Possible cause:") <+> quotes (ppr fun)
1446 <+> ptext (sLit "is applied to too many arguments")
1447 | otherwise = Outputable.empty -- Never suggest that a naked variable is
1448 -- applied to too many args!
1449 ; return (tidy_env, info) }
1450 where
1451 not_fun ty -- ty is definitely not an arrow type,
1452 -- and cannot conceivably become one
1453 = case tcSplitTyConApp_maybe ty of
1454 Just (tc, _) -> isAlgTyCon tc
1455 Nothing -> False
1456
1457 badFieldTypes :: [(Name,TcType)] -> SDoc
1458 badFieldTypes prs
1459 = hang (ptext (sLit "Record update for insufficiently polymorphic field")
1460 <> plural prs <> colon)
1461 2 (vcat [ ppr f <+> dcolon <+> ppr ty | (f,ty) <- prs ])
1462
1463 badFieldsUpd
1464 :: HsRecFields Name a -- Field names that don't belong to a single datacon
1465 -> [DataCon] -- Data cons of the type which the first field name belongs to
1466 -> SDoc
1467 badFieldsUpd rbinds data_cons
1468 = hang (ptext (sLit "No constructor has all these fields:"))
1469 2 (pprQuotedList conflictingFields)
1470 -- See Note [Finding the conflicting fields]
1471 where
1472 -- A (preferably small) set of fields such that no constructor contains
1473 -- all of them. See Note [Finding the conflicting fields]
1474 conflictingFields = case nonMembers of
1475 -- nonMember belongs to a different type.
1476 (nonMember, _) : _ -> [aMember, nonMember]
1477 [] -> let
1478 -- All of rbinds belong to one type. In this case, repeatedly add
1479 -- a field to the set until no constructor contains the set.
1480
1481 -- Each field, together with a list indicating which constructors
1482 -- have all the fields so far.
1483 growingSets :: [(Name, [Bool])]
1484 growingSets = scanl1 combine membership
1485 combine (_, setMem) (field, fldMem)
1486 = (field, zipWith (&&) setMem fldMem)
1487 in
1488 -- Fields that don't change the membership status of the set
1489 -- are redundant and can be dropped.
1490 map (fst . head) $ groupBy ((==) `on` snd) growingSets
1491
1492 aMember = ASSERT( not (null members) ) fst (head members)
1493 (members, nonMembers) = partition (or . snd) membership
1494
1495 -- For each field, which constructors contain the field?
1496 membership :: [(Name, [Bool])]
1497 membership = sortMembership $
1498 map (\fld -> (fld, map (Set.member fld) fieldLabelSets)) $
1499 hsRecFields rbinds
1500
1501 fieldLabelSets :: [Set.Set Name]
1502 fieldLabelSets = map (Set.fromList . dataConFieldLabels) data_cons
1503
1504 -- Sort in order of increasing number of True, so that a smaller
1505 -- conflicting set can be found.
1506 sortMembership =
1507 map snd .
1508 sortBy (compare `on` fst) .
1509 map (\ item@(_, membershipRow) -> (countTrue membershipRow, item))
1510
1511 countTrue = length . filter id
1512
1513 {-
1514 Note [Finding the conflicting fields]
1515 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1516 Suppose we have
1517 data A = A {a0, a1 :: Int}
1518 | B {b0, b1 :: Int}
1519 and we see a record update
1520 x { a0 = 3, a1 = 2, b0 = 4, b1 = 5 }
1521 Then we'd like to find the smallest subset of fields that no
1522 constructor has all of. Here, say, {a0,b0}, or {a0,b1}, etc.
1523 We don't really want to report that no constructor has all of
1524 {a0,a1,b0,b1}, because when there are hundreds of fields it's
1525 hard to see what was really wrong.
1526
1527 We may need more than two fields, though; eg
1528 data T = A { x,y :: Int, v::Int }
1529 | B { y,z :: Int, v::Int }
1530 | C { z,x :: Int, v::Int }
1531 with update
1532 r { x=e1, y=e2, z=e3 }, we
1533
1534 Finding the smallest subset is hard, so the code here makes
1535 a decent stab, no more. See Trac #7989.
1536 -}
1537
1538 naughtyRecordSel :: TcId -> SDoc
1539 naughtyRecordSel sel_id
1540 = ptext (sLit "Cannot use record selector") <+> quotes (ppr sel_id) <+>
1541 ptext (sLit "as a function due to escaped type variables") $$
1542 ptext (sLit "Probable fix: use pattern-matching syntax instead")
1543
1544 notSelector :: Name -> SDoc
1545 notSelector field
1546 = hsep [quotes (ppr field), ptext (sLit "is not a record selector")]
1547
1548 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1549 missingStrictFields con fields
1550 = header <> rest
1551 where
1552 rest | null fields = Outputable.empty -- Happens for non-record constructors
1553 -- with strict fields
1554 | otherwise = colon <+> pprWithCommas ppr fields
1555
1556 header = ptext (sLit "Constructor") <+> quotes (ppr con) <+>
1557 ptext (sLit "does not have the required strict field(s)")
1558
1559 missingFields :: DataCon -> [FieldLabel] -> SDoc
1560 missingFields con fields
1561 = ptext (sLit "Fields of") <+> quotes (ppr con) <+> ptext (sLit "not initialised:")
1562 <+> pprWithCommas ppr fields
1563
1564 -- callCtxt fun args = ptext (sLit "In the call") <+> parens (ppr (foldl mkHsApp fun args))