Check InScopeSet in substTy and provide substTyUnchecked
[ghc.git] / compiler / typecheck / TcExpr.hs
1 {-
2 %
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, TupleSections, ScopedTypeVariables #-}
10
11 module TcExpr ( tcPolyExpr, tcPolyExprNC, tcMonoExpr, tcMonoExprNC,
12 tcInferSigma, tcInferSigmaNC, tcInferRho, tcInferRhoNC,
13 tcSyntaxOp, tcCheckId,
14 addExprErrCtxt,
15 getFixedTyVars ) where
16
17 #include "HsVersions.h"
18
19 import {-# SOURCE #-} TcSplice( tcSpliceExpr, tcTypedBracket, tcUntypedBracket )
20 import THNames( liftStringName, liftName )
21
22 import HsSyn
23 import TcHsSyn
24 import TcRnMonad
25 import TcUnify
26 import BasicTypes
27 import Inst
28 import TcBinds ( chooseInferredQuantifiers, tcLocalBinds
29 , tcUserTypeSig, tcExtendTyVarEnvFromSig )
30 import TcSimplify ( simplifyInfer )
31 import FamInst ( tcGetFamInstEnvs, tcLookupDataFamInst )
32 import FamInstEnv ( FamInstEnvs )
33 import RnEnv ( addUsedGRE, addNameClashErrRn
34 , unknownSubordinateErr )
35 import TcEnv
36 import TcArrows
37 import TcMatches
38 import TcHsType
39 import TcPatSyn( tcPatSynBuilderOcc, nonBidirectionalErr )
40 import TcPat
41 import TcMType
42 import TcType
43 import DsMonad
44 import Id
45 import IdInfo
46 import ConLike
47 import DataCon
48 import PatSyn
49 import Name
50 import RdrName
51 import TyCon
52 import Type
53 import TysPrim ( tYPE )
54 import TcEvidence
55 import VarSet
56 import TysWiredIn
57 import TysPrim( intPrimTy )
58 import PrimOp( tagToEnumKey )
59 import PrelNames
60 import MkId ( proxyHashId )
61 import DynFlags
62 import SrcLoc
63 import Util
64 import VarEnv ( emptyTidyEnv )
65 import ListSetOps
66 import Maybes
67 import Outputable
68 import FastString
69 import Control.Monad
70 import Class(classTyCon)
71 import qualified GHC.LanguageExtensions as LangExt
72
73 import Data.Function
74 import Data.List
75 import qualified Data.Set as Set
76
77 {-
78 ************************************************************************
79 * *
80 \subsection{Main wrappers}
81 * *
82 ************************************************************************
83 -}
84
85 tcPolyExpr, tcPolyExprNC
86 :: LHsExpr Name -- Expression to type check
87 -> TcSigmaType -- Expected type (could be a polytype)
88 -> TcM (LHsExpr TcId) -- Generalised expr with expected type
89
90 -- tcPolyExpr is a convenient place (frequent but not too frequent)
91 -- place to add context information.
92 -- The NC version does not do so, usually because the caller wants
93 -- to do so himself.
94
95 tcPolyExpr expr res_ty
96 = addExprErrCtxt expr $
97 do { traceTc "tcPolyExpr" (ppr res_ty); tcPolyExprNC expr res_ty }
98
99 tcPolyExprNC (L loc expr) res_ty
100 = do { traceTc "tcPolyExprNC_O" (ppr res_ty)
101 ; (wrap, expr')
102 <- tcSkolemise GenSigCtxt res_ty $ \ _ res_ty ->
103 setSrcSpan loc $
104 -- NB: setSrcSpan *after* skolemising, so we get better
105 -- skolem locations
106 tcExpr expr res_ty
107 ; return $ L loc (mkHsWrap wrap expr') }
108
109 ---------------
110 tcMonoExpr, tcMonoExprNC
111 :: LHsExpr Name -- Expression to type check
112 -> TcRhoType -- Expected type (could be a type variable)
113 -- Definitely no foralls at the top
114 -> TcM (LHsExpr TcId)
115
116 tcMonoExpr expr res_ty
117 = addErrCtxt (exprCtxt expr) $
118 tcMonoExprNC expr res_ty
119
120 tcMonoExprNC (L loc expr) res_ty
121 = ASSERT( not (isSigmaTy res_ty) )
122 setSrcSpan loc $
123 do { expr' <- tcExpr expr res_ty
124 ; return (L loc expr') }
125
126 ---------------
127 tcInferSigma, tcInferSigmaNC :: LHsExpr Name -> TcM ( LHsExpr TcId
128 , TcSigmaType )
129 -- Infer a *sigma*-type.
130 tcInferSigma expr = addErrCtxt (exprCtxt expr) (tcInferSigmaNC expr)
131
132 tcInferSigmaNC (L loc expr)
133 = setSrcSpan loc $
134 do { (expr', sigma) <- tcInfer (tcExpr expr)
135 ; return (L loc expr', sigma) }
136
137 tcInferRho, tcInferRhoNC :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
138 -- Infer a *rho*-type. The return type is always (shallowly) instantiated.
139 tcInferRho expr = addErrCtxt (exprCtxt expr) (tcInferRhoNC expr)
140
141 tcInferRhoNC expr
142 = do { (expr', sigma) <- tcInferSigmaNC expr
143 ; (wrap, rho) <- topInstantiate (exprCtOrigin (unLoc expr)) sigma
144 ; return (mkLHsWrap wrap expr', rho) }
145
146
147 {-
148 ************************************************************************
149 * *
150 tcExpr: the main expression typechecker
151 * *
152 ************************************************************************
153
154 NB: The res_ty is always deeply skolemised.
155 -}
156
157 tcExpr :: HsExpr Name -> TcRhoType -> TcM (HsExpr TcId)
158 tcExpr (HsVar (L _ name)) res_ty = tcCheckId name res_ty
159 tcExpr (HsUnboundVar v) res_ty = tcUnboundId v res_ty
160
161 tcExpr (HsApp e1 e2) res_ty
162 = do { (wrap, fun, args) <- tcApp Nothing e1 [e2] res_ty
163 ; return (mkHsWrap wrap $ unLoc $ foldl mkHsApp fun args) }
164
165 tcExpr e@(HsLit lit) res_ty = do { let lit_ty = hsLitType lit
166 ; tcWrapResult e (HsLit lit) lit_ty res_ty }
167
168 tcExpr (HsPar expr) res_ty = do { expr' <- tcMonoExprNC expr res_ty
169 ; return (HsPar expr') }
170
171 tcExpr (HsSCC src lbl expr) res_ty
172 = do { expr' <- tcMonoExpr expr res_ty
173 ; return (HsSCC src lbl expr') }
174
175 tcExpr (HsTickPragma src info srcInfo expr) res_ty
176 = do { expr' <- tcMonoExpr expr res_ty
177 ; return (HsTickPragma src info srcInfo expr') }
178
179 tcExpr (HsCoreAnn src lbl expr) res_ty
180 = do { expr' <- tcMonoExpr expr res_ty
181 ; return (HsCoreAnn src lbl expr') }
182
183 tcExpr (HsOverLit lit) res_ty
184 = do { (_wrap, lit') <- newOverloadedLit lit res_ty
185 (Shouldn'tHappenOrigin "HsOverLit")
186 ; MASSERT( isIdHsWrapper _wrap )
187 ; return (HsOverLit lit') }
188
189 tcExpr (NegApp expr neg_expr) res_ty
190 = do { neg_expr' <- tcSyntaxOp NegateOrigin neg_expr
191 (mkFunTy res_ty res_ty)
192 ; expr' <- tcMonoExpr expr res_ty
193 ; return (NegApp expr' neg_expr') }
194
195 tcExpr e@(HsIPVar x) res_ty
196 = do { {- Implicit parameters must have a *tau-type* not a
197 type scheme. We enforce this by creating a fresh
198 type variable as its type. (Because res_ty may not
199 be a tau-type.) -}
200 ip_ty <- newOpenFlexiTyVarTy
201 ; let ip_name = mkStrLitTy (hsIPNameFS x)
202 ; ipClass <- tcLookupClass ipClassName
203 ; ip_var <- emitWantedEvVar origin (mkClassPred ipClass [ip_name, ip_ty])
204 ; tcWrapResult e (fromDict ipClass ip_name ip_ty (HsVar (noLoc ip_var)))
205 ip_ty res_ty }
206 where
207 -- Coerces a dictionary for `IP "x" t` into `t`.
208 fromDict ipClass x ty = HsWrap $ mkWpCastR $
209 unwrapIP $ mkClassPred ipClass [x,ty]
210 origin = IPOccOrigin x
211
212 tcExpr e@(HsOverLabel l) res_ty -- See Note [Type-checking overloaded labels]
213 = do { isLabelClass <- tcLookupClass isLabelClassName
214 ; alpha <- newOpenFlexiTyVarTy
215 ; let lbl = mkStrLitTy l
216 pred = mkClassPred isLabelClass [lbl, alpha]
217 ; loc <- getSrcSpanM
218 ; var <- emitWantedEvVar origin pred
219 ; let proxy_arg = L loc (mkHsWrap (mkWpTyApps [typeSymbolKind, lbl])
220 (HsVar (L loc proxyHashId)))
221 tm = L loc (fromDict pred (HsVar (L loc var))) `HsApp` proxy_arg
222 ; tcWrapResult e tm alpha res_ty }
223 where
224 -- Coerces a dictionary for `IsLabel "x" t` into `Proxy# x -> t`.
225 fromDict pred = HsWrap $ mkWpCastR $ unwrapIP pred
226 origin = OverLabelOrigin l
227
228 tcExpr (HsLam match) res_ty
229 = do { (co_fn, _, match') <- tcMatchLambda herald match_ctxt match res_ty
230 ; return (mkHsWrap co_fn (HsLam match')) }
231 where
232 match_ctxt = MC { mc_what = LambdaExpr, mc_body = tcBody }
233 herald = sep [ text "The lambda expression" <+>
234 quotes (pprSetDepth (PartWay 1) $
235 pprMatches (LambdaExpr :: HsMatchContext Name) match),
236 -- The pprSetDepth makes the abstraction print briefly
237 text "has"]
238
239 tcExpr e@(HsLamCase _ matches) res_ty
240 = do { (co_fn, ~[arg_ty], matches')
241 <- tcMatchLambda msg match_ctxt matches res_ty
242 -- The laziness annotation is because we don't want to fail here
243 -- if there are multiple arguments
244 ; return (mkHsWrap co_fn $ HsLamCase arg_ty matches') }
245 where msg = sep [ text "The function" <+> quotes (ppr e)
246 , text "requires"]
247 match_ctxt = MC { mc_what = CaseAlt, mc_body = tcBody }
248
249 tcExpr e@(ExprWithTySig expr sig_ty) res_ty
250 = do { sig_info <- checkNoErrs $ -- Avoid error cascade
251 tcUserTypeSig sig_ty Nothing
252 ; (expr', poly_ty) <- tcExprSig expr sig_info
253 ; let expr'' = ExprWithTySigOut expr' sig_ty
254 ; tcWrapResult e expr'' poly_ty res_ty }
255
256 tcExpr (HsType ty) _
257 = failWithTc (sep [ text "Type argument used outside of a function argument:"
258 , ppr ty ])
259
260
261 {-
262 Note [Type-checking overloaded labels]
263 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
264 Recall that (in GHC.OverloadedLabels) we have
265
266 class IsLabel (x :: Symbol) a where
267 fromLabel :: Proxy# x -> a
268
269 When we see an overloaded label like `#foo`, we generate a fresh
270 variable `alpha` for the type and emit an `IsLabel "foo" alpha`
271 constraint. Because the `IsLabel` class has a single method, it is
272 represented by a newtype, so we can coerce `IsLabel "foo" alpha` to
273 `Proxy# "foo" -> alpha` (just like for implicit parameters). We then
274 apply it to `proxy#` of type `Proxy# "foo"`.
275
276 That is, we translate `#foo` to `fromLabel (proxy# :: Proxy# "foo")`.
277 -}
278
279
280 {-
281 ************************************************************************
282 * *
283 Infix operators and sections
284 * *
285 ************************************************************************
286
287 Note [Left sections]
288 ~~~~~~~~~~~~~~~~~~~~
289 Left sections, like (4 *), are equivalent to
290 \ x -> (*) 4 x,
291 or, if PostfixOperators is enabled, just
292 (*) 4
293 With PostfixOperators we don't actually require the function to take
294 two arguments at all. For example, (x `not`) means (not x); you get
295 postfix operators! Not Haskell 98, but it's less work and kind of
296 useful.
297
298 Note [Typing rule for ($)]
299 ~~~~~~~~~~~~~~~~~~~~~~~~~~
300 People write
301 runST $ blah
302 so much, where
303 runST :: (forall s. ST s a) -> a
304 that I have finally given in and written a special type-checking
305 rule just for saturated appliations of ($).
306 * Infer the type of the first argument
307 * Decompose it; should be of form (arg2_ty -> res_ty),
308 where arg2_ty might be a polytype
309 * Use arg2_ty to typecheck arg2
310
311 Note [Typing rule for seq]
312 ~~~~~~~~~~~~~~~~~~~~~~~~~~
313 We want to allow
314 x `seq` (# p,q #)
315 which suggests this type for seq:
316 seq :: forall (a:*) (b:Open). a -> b -> b,
317 with (b:Open) meaning that be can be instantiated with an unboxed
318 tuple. The trouble is that this might accept a partially-applied
319 'seq', and I'm just not certain that would work. I'm only sure it's
320 only going to work when it's fully applied, so it turns into
321 case x of _ -> (# p,q #)
322
323 So it seems more uniform to treat 'seq' as it it was a language
324 construct.
325
326 See also Note [seqId magic] in MkId
327 -}
328
329 tcExpr expr@(OpApp arg1 op fix arg2) res_ty
330 | (L loc (HsVar (L lv op_name))) <- op
331 , op_name `hasKey` seqIdKey -- Note [Typing rule for seq]
332 = do { arg1_ty <- newFlexiTyVarTy liftedTypeKind
333 ; let arg2_ty = res_ty
334 ; arg1' <- tcArg op (arg1, arg1_ty, 1)
335 ; arg2' <- tcArg op (arg2, arg2_ty, 2)
336 ; op_id <- tcLookupId op_name
337 ; let op' = L loc (HsWrap (mkWpTyApps [arg1_ty, arg2_ty])
338 (HsVar (L lv op_id)))
339 ; return $ OpApp arg1' op' fix arg2' }
340
341 | (L loc (HsVar (L lv op_name))) <- op
342 , op_name `hasKey` dollarIdKey -- Note [Typing rule for ($)]
343 = do { traceTc "Application rule" (ppr op)
344 ; (arg1', arg1_ty) <- tcInferSigma arg1
345
346 ; let doc = text "The first argument of ($) takes"
347 orig1 = exprCtOrigin (unLoc arg1)
348 ; (wrap_arg1, [arg2_sigma], op_res_ty) <-
349 matchActualFunTys doc orig1 1 arg1_ty
350
351 -- We have (arg1 $ arg2)
352 -- So: arg1_ty = arg2_ty -> op_res_ty
353 -- where arg2_sigma maybe polymorphic; that's the point
354
355 ; arg2' <- tcArg op (arg2, arg2_sigma, 2)
356
357 -- Make sure that the argument type has kind '*'
358 -- ($) :: forall (v:Levity) (a:*) (b:TYPE v). (a->b) -> a -> b
359 -- Eg we do not want to allow (D# $ 4.0#) Trac #5570
360 -- (which gives a seg fault)
361 -- We do this by unifying with a MetaTv; but of course
362 -- it must allow foralls in the type it unifies with (hence ReturnTv)!
363 --
364 -- The *result* type can have any kind (Trac #8739),
365 -- so we don't need to check anything for that
366 ; a2_tv <- newReturnTyVar liftedTypeKind
367 ; let a2_ty = mkTyVarTy a2_tv
368 ; co_a <- unifyType (Just arg2) arg2_sigma a2_ty -- arg2_sigma ~N a2_ty
369
370 ; wrap_res <- tcSubTypeHR orig1 (Just expr) op_res_ty res_ty
371 -- op_res -> res
372
373 ; op_id <- tcLookupId op_name
374 ; let op' = L loc (HsWrap (mkWpTyApps [ getLevity "tcExpr ($)" res_ty
375 , a2_ty
376 , res_ty])
377 (HsVar (L lv op_id)))
378 -- arg1' :: arg1_ty
379 -- wrap_arg1 :: arg1_ty "->" (arg2_sigma -> op_res_ty)
380 -- wrap_res :: op_res_ty "->" res_ty
381 -- co_a :: arg2_sigma ~N a2_ty
382 -- op' :: (a2_ty -> res_ty) -> a2_ty -> res_ty
383
384 -- wrap1 :: arg1_ty "->" (a2_ty -> res_ty)
385 wrap1 = mkWpFun (mkWpCastN (mkTcSymCo co_a))
386 wrap_res a2_ty res_ty <.> wrap_arg1
387
388 -- arg2' :: arg2_sigma
389 -- wrap_a :: a2_ty "->" arg2_sigma
390 ; return (OpApp (mkLHsWrap wrap1 arg1')
391 op' fix
392 (mkLHsWrapCo co_a arg2')) }
393
394 | (L loc (HsRecFld (Ambiguous lbl _))) <- op
395 , Just sig_ty <- obviousSig (unLoc arg1)
396 -- See Note [Disambiguating record fields]
397 = do { sig_tc_ty <- tcHsSigWcType ExprSigCtxt sig_ty
398 ; sel_name <- disambiguateSelector lbl sig_tc_ty
399 ; let op' = L loc (HsRecFld (Unambiguous lbl sel_name))
400 ; tcExpr (OpApp arg1 op' fix arg2) res_ty
401 }
402
403 | otherwise
404 = do { traceTc "Non Application rule" (ppr op)
405 ; (wrap, op', [arg1', arg2'])
406 <- tcApp (Just $ mk_op_msg op)
407 op [arg1, arg2] res_ty
408 ; return (mkHsWrap wrap $ OpApp arg1' op' fix arg2') }
409
410 -- Right sections, equivalent to \ x -> x `op` expr, or
411 -- \ x -> op x expr
412
413 tcExpr expr@(SectionR op arg2) res_ty
414 = do { (op', op_ty) <- tcInferFun op
415 ; (wrap_fun, [arg1_ty, arg2_ty], op_res_ty) <-
416 matchActualFunTys (mk_op_msg op) SectionOrigin 2 op_ty
417 ; wrap_res <- tcSubTypeHR SectionOrigin (Just expr)
418 (mkFunTy arg1_ty op_res_ty) res_ty
419 ; arg2' <- tcArg op (arg2, arg2_ty, 2)
420 ; return ( mkHsWrap wrap_res $
421 SectionR (mkLHsWrap wrap_fun op') arg2' ) }
422
423 tcExpr expr@(SectionL arg1 op) res_ty
424 = do { (op', op_ty) <- tcInferFun op
425 ; dflags <- getDynFlags -- Note [Left sections]
426 ; let n_reqd_args | xopt LangExt.PostfixOperators dflags = 1
427 | otherwise = 2
428
429 ; (wrap_fn, (arg1_ty:arg_tys), op_res_ty)
430 <- matchActualFunTys (mk_op_msg op) SectionOrigin n_reqd_args op_ty
431 ; wrap_res <- tcSubTypeHR SectionOrigin (Just expr)
432 (mkFunTys arg_tys op_res_ty) res_ty
433 ; arg1' <- tcArg op (arg1, arg1_ty, 1)
434 ; return ( mkHsWrap wrap_res $
435 SectionL arg1' (mkLHsWrap wrap_fn op') ) }
436
437 tcExpr expr@(ExplicitTuple tup_args boxity) res_ty
438 | all tupArgPresent tup_args
439 = do { let arity = length tup_args
440 tup_tc = tupleTyCon boxity arity
441 ; (coi, arg_tys) <- matchExpectedTyConApp tup_tc res_ty
442 -- Unboxed tuples have levity vars, which we
443 -- don't care about here
444 -- See Note [Unboxed tuple levity vars] in TyCon
445 ; let arg_tys' = case boxity of Unboxed -> drop arity arg_tys
446 Boxed -> arg_tys
447 ; tup_args1 <- tcTupArgs tup_args arg_tys'
448 ; return $ mkHsWrapCo coi (ExplicitTuple tup_args1 boxity) }
449
450 | otherwise
451 = -- The tup_args are a mixture of Present and Missing (for tuple sections)
452 do { let arity = length tup_args
453
454 ; arg_tys <- case boxity of
455 { Boxed -> newFlexiTyVarTys arity liftedTypeKind
456 ; Unboxed -> replicateM arity newOpenFlexiTyVarTy }
457 ; let actual_res_ty
458 = mkFunTys [ty | (ty, (L _ (Missing _))) <- arg_tys `zip` tup_args]
459 (mkTupleTy boxity arg_tys)
460
461 ; wrap <- tcSubTypeHR (Shouldn'tHappenOrigin "ExpTuple")
462 (Just expr)
463 actual_res_ty res_ty
464
465 -- Handle tuple sections where
466 ; tup_args1 <- tcTupArgs tup_args arg_tys
467
468 ; return $ mkHsWrap wrap (ExplicitTuple tup_args1 boxity) }
469
470 tcExpr (ExplicitList _ witness exprs) res_ty
471 = case witness of
472 Nothing -> do { (coi, elt_ty) <- matchExpectedListTy res_ty
473 ; exprs' <- mapM (tc_elt elt_ty) exprs
474 ; return $
475 mkHsWrapCo coi $ ExplicitList elt_ty Nothing exprs' }
476
477 Just fln -> do { list_ty <- newFlexiTyVarTy liftedTypeKind
478 ; fln' <- tcSyntaxOp ListOrigin fln (mkFunTys [intTy, list_ty] res_ty)
479 ; (coi, elt_ty) <- matchExpectedListTy list_ty
480 ; exprs' <- mapM (tc_elt elt_ty) exprs
481 ; return $
482 mkHsWrapCo coi $ ExplicitList elt_ty (Just fln') exprs' }
483 where tc_elt elt_ty expr = tcPolyExpr expr elt_ty
484
485 tcExpr (ExplicitPArr _ exprs) res_ty -- maybe empty
486 = do { (coi, elt_ty) <- matchExpectedPArrTy res_ty
487 ; exprs' <- mapM (tc_elt elt_ty) exprs
488 ; return $
489 mkHsWrapCo coi $ ExplicitPArr elt_ty exprs' }
490 where
491 tc_elt elt_ty expr = tcPolyExpr expr elt_ty
492
493 {-
494 ************************************************************************
495 * *
496 Let, case, if, do
497 * *
498 ************************************************************************
499 -}
500
501 tcExpr (HsLet (L l binds) expr) res_ty
502 = do { (binds', expr') <- tcLocalBinds binds $
503 tcMonoExpr expr res_ty
504 ; return (HsLet (L l binds') expr') }
505
506 tcExpr (HsCase scrut matches) exp_ty
507 = do { -- We used to typecheck the case alternatives first.
508 -- The case patterns tend to give good type info to use
509 -- when typechecking the scrutinee. For example
510 -- case (map f) of
511 -- (x:xs) -> ...
512 -- will report that map is applied to too few arguments
513 --
514 -- But now, in the GADT world, we need to typecheck the scrutinee
515 -- first, to get type info that may be refined in the case alternatives
516 (scrut', scrut_ty) <- tcInferRho scrut
517
518 ; traceTc "HsCase" (ppr scrut_ty)
519 ; matches' <- tcMatchesCase match_ctxt scrut_ty matches exp_ty
520 ; return (HsCase scrut' matches') }
521 where
522 match_ctxt = MC { mc_what = CaseAlt,
523 mc_body = tcBody }
524
525 tcExpr (HsIf Nothing pred b1 b2) res_ty -- Ordinary 'if'
526 = do { pred' <- tcMonoExpr pred boolTy
527 -- this forces the branches to be fully instantiated
528 -- (See #10619)
529 ; res_ty <- tauTvForReturnTv res_ty
530 ; b1' <- tcMonoExpr b1 res_ty
531 ; b2' <- tcMonoExpr b2 res_ty
532 ; return (HsIf Nothing pred' b1' b2') }
533
534 tcExpr (HsIf (Just fun) pred b1 b2) res_ty
535 -- Note [Rebindable syntax for if]
536 = do { (wrap, fun', [pred', b1', b2'])
537 <- tcApp (Just herald) (noLoc fun) [pred, b1, b2] res_ty
538 ; return ( mkHsWrap wrap $
539 HsIf (Just (unLoc fun')) pred' b1' b2' ) }
540 where
541 herald = text "Rebindable" <+> quotes (text "if") <+> text "takes"
542
543 tcExpr (HsMultiIf _ alts) res_ty
544 = do { alts' <- mapM (wrapLocM $ tcGRHS match_ctxt res_ty) alts
545 ; return (HsMultiIf res_ty alts') }
546 where match_ctxt = MC { mc_what = IfAlt, mc_body = tcBody }
547
548 tcExpr (HsDo do_or_lc stmts _) res_ty
549 = do { expr' <- tcDoStmts do_or_lc stmts res_ty
550 ; return expr' }
551
552 tcExpr (HsProc pat cmd) res_ty
553 = do { (pat', cmd', coi) <- tcProc pat cmd res_ty
554 ; return $ mkHsWrapCo coi (HsProc pat' cmd') }
555
556 tcExpr (HsStatic expr) res_ty
557 = do { staticPtrTyCon <- tcLookupTyCon staticPtrTyConName
558 ; (co, [expr_ty]) <- matchExpectedTyConApp staticPtrTyCon res_ty
559 ; (expr', lie) <- captureConstraints $
560 addErrCtxt (hang (text "In the body of a static form:")
561 2 (ppr expr)
562 ) $
563 tcPolyExprNC expr expr_ty
564 -- Require the type of the argument to be Typeable.
565 -- The evidence is not used, but asking the constraint ensures that
566 -- the current implementation is as restrictive as future versions
567 -- of the StaticPointers extension.
568 ; typeableClass <- tcLookupClass typeableClassName
569 ; _ <- emitWantedEvVar StaticOrigin $
570 mkTyConApp (classTyCon typeableClass)
571 [liftedTypeKind, expr_ty]
572 -- Insert the static form in a global list for later validation.
573 ; stWC <- tcg_static_wc <$> getGblEnv
574 ; updTcRef stWC (andWC lie)
575 ; return $ mkHsWrapCo co $ HsStatic expr'
576 }
577
578 {-
579 Note [Rebindable syntax for if]
580 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
581 The rebindable syntax for 'if' uses the most flexible possible type
582 for conditionals:
583 ifThenElse :: p -> b1 -> b2 -> res
584 to support expressions like this:
585
586 ifThenElse :: Maybe a -> (a -> b) -> b -> b
587 ifThenElse (Just a) f _ = f a
588 ifThenElse Nothing _ e = e
589
590 example :: String
591 example = if Just 2
592 then \v -> show v
593 else "No value"
594
595
596 ************************************************************************
597 * *
598 Record construction and update
599 * *
600 ************************************************************************
601 -}
602
603 tcExpr expr@(RecordCon { rcon_con_name = L loc con_name
604 , rcon_flds = rbinds }) res_ty
605 = do { con_like <- tcLookupConLike con_name
606
607 -- Check for missing fields
608 ; checkMissingFields con_like rbinds
609
610 ; (con_expr, con_sigma) <- tcInferId con_name
611 ; (con_wrap, con_tau) <-
612 topInstantiate (OccurrenceOf con_name) con_sigma
613 -- a shallow instantiation should really be enough for
614 -- a data constructor.
615 ; let arity = conLikeArity con_like
616 (arg_tys, actual_res_ty) = tcSplitFunTysN con_tau arity
617 ; case conLikeWrapId_maybe con_like of
618 Nothing -> nonBidirectionalErr (conLikeName con_like)
619 Just con_id -> do {
620 res_wrap <- tcSubTypeHR (Shouldn'tHappenOrigin "RecordCon")
621 (Just expr) actual_res_ty res_ty
622 ; rbinds' <- tcRecordBinds con_like arg_tys rbinds
623 ; return $
624 mkHsWrap res_wrap $
625 RecordCon { rcon_con_name = L loc con_id
626 , rcon_con_expr = mkHsWrap con_wrap con_expr
627 , rcon_con_like = con_like
628 , rcon_flds = rbinds' } } }
629
630 {-
631 Note [Type of a record update]
632 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
633 The main complication with RecordUpd is that we need to explicitly
634 handle the *non-updated* fields. Consider:
635
636 data T a b c = MkT1 { fa :: a, fb :: (b,c) }
637 | MkT2 { fa :: a, fb :: (b,c), fc :: c -> c }
638 | MkT3 { fd :: a }
639
640 upd :: T a b c -> (b',c) -> T a b' c
641 upd t x = t { fb = x}
642
643 The result type should be (T a b' c)
644 not (T a b c), because 'b' *is not* mentioned in a non-updated field
645 not (T a b' c'), because 'c' *is* mentioned in a non-updated field
646 NB that it's not good enough to look at just one constructor; we must
647 look at them all; cf Trac #3219
648
649 After all, upd should be equivalent to:
650 upd t x = case t of
651 MkT1 p q -> MkT1 p x
652 MkT2 a b -> MkT2 p b
653 MkT3 d -> error ...
654
655 So we need to give a completely fresh type to the result record,
656 and then constrain it by the fields that are *not* updated ("p" above).
657 We call these the "fixed" type variables, and compute them in getFixedTyVars.
658
659 Note that because MkT3 doesn't contain all the fields being updated,
660 its RHS is simply an error, so it doesn't impose any type constraints.
661 Hence the use of 'relevant_cont'.
662
663 Note [Implicit type sharing]
664 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
665 We also take into account any "implicit" non-update fields. For example
666 data T a b where { MkT { f::a } :: T a a; ... }
667 So the "real" type of MkT is: forall ab. (a~b) => a -> T a b
668
669 Then consider
670 upd t x = t { f=x }
671 We infer the type
672 upd :: T a b -> a -> T a b
673 upd (t::T a b) (x::a)
674 = case t of { MkT (co:a~b) (_:a) -> MkT co x }
675 We can't give it the more general type
676 upd :: T a b -> c -> T c b
677
678 Note [Criteria for update]
679 ~~~~~~~~~~~~~~~~~~~~~~~~~~
680 We want to allow update for existentials etc, provided the updated
681 field isn't part of the existential. For example, this should be ok.
682 data T a where { MkT { f1::a, f2::b->b } :: T a }
683 f :: T a -> b -> T b
684 f t b = t { f1=b }
685
686 The criterion we use is this:
687
688 The types of the updated fields
689 mention only the universally-quantified type variables
690 of the data constructor
691
692 NB: this is not (quite) the same as being a "naughty" record selector
693 (See Note [Naughty record selectors]) in TcTyClsDecls), at least
694 in the case of GADTs. Consider
695 data T a where { MkT :: { f :: a } :: T [a] }
696 Then f is not "naughty" because it has a well-typed record selector.
697 But we don't allow updates for 'f'. (One could consider trying to
698 allow this, but it makes my head hurt. Badly. And no one has asked
699 for it.)
700
701 In principle one could go further, and allow
702 g :: T a -> T a
703 g t = t { f2 = \x -> x }
704 because the expression is polymorphic...but that seems a bridge too far.
705
706 Note [Data family example]
707 ~~~~~~~~~~~~~~~~~~~~~~~~~~
708 data instance T (a,b) = MkT { x::a, y::b }
709 --->
710 data :TP a b = MkT { a::a, y::b }
711 coTP a b :: T (a,b) ~ :TP a b
712
713 Suppose r :: T (t1,t2), e :: t3
714 Then r { x=e } :: T (t3,t1)
715 --->
716 case r |> co1 of
717 MkT x y -> MkT e y |> co2
718 where co1 :: T (t1,t2) ~ :TP t1 t2
719 co2 :: :TP t3 t2 ~ T (t3,t2)
720 The wrapping with co2 is done by the constructor wrapper for MkT
721
722 Outgoing invariants
723 ~~~~~~~~~~~~~~~~~~~
724 In the outgoing (HsRecordUpd scrut binds cons in_inst_tys out_inst_tys):
725
726 * cons are the data constructors to be updated
727
728 * in_inst_tys, out_inst_tys have same length, and instantiate the
729 *representation* tycon of the data cons. In Note [Data
730 family example], in_inst_tys = [t1,t2], out_inst_tys = [t3,t2]
731
732 Note [Mixed Record Field Updates]
733 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
734 Consider the following pattern synonym.
735
736 data MyRec = MyRec { foo :: Int, qux :: String }
737
738 pattern HisRec{f1, f2} = MyRec{foo = f1, qux=f2}
739
740 This allows updates such as the following
741
742 updater :: MyRec -> MyRec
743 updater a = a {f1 = 1 }
744
745 It would also make sense to allow the following update (which we reject).
746
747 updater a = a {f1 = 1, qux = "two" } ==? MyRec 1 "two"
748
749 This leads to confusing behaviour when the selectors in fact refer the same
750 field.
751
752 updater a = a {f1 = 1, foo = 2} ==? ???
753
754 For this reason, we reject a mixture of pattern synonym and normal record
755 selectors in the same update block. Although of course we still allow the
756 following.
757
758 updater a = (a {f1 = 1}) {foo = 2}
759
760 > updater (MyRec 0 "str")
761 MyRec 2 "str"
762
763 -}
764
765 tcExpr expr@(RecordUpd { rupd_expr = record_expr, rupd_flds = rbnds }) res_ty
766 = ASSERT( notNull rbnds )
767 do { -- STEP -2: typecheck the record_expr, the record to be updated
768 (record_expr', record_rho) <- tcInferRho record_expr
769
770 -- STEP -1 See Note [Disambiguating record fields]
771 -- After this we know that rbinds is unambiguous
772 ; rbinds <- disambiguateRecordBinds record_expr record_rho rbnds res_ty
773 ; let upd_flds = map (unLoc . hsRecFieldLbl . unLoc) rbinds
774 upd_fld_occs = map (occNameFS . rdrNameOcc . rdrNameAmbiguousFieldOcc) upd_flds
775 sel_ids = map selectorAmbiguousFieldOcc upd_flds
776 -- STEP 0
777 -- Check that the field names are really field names
778 -- and they are all field names for proper records or
779 -- all field names for pattern synonyms.
780 ; let bad_guys = [ setSrcSpan loc $ addErrTc (notSelector fld_name)
781 | fld <- rbinds,
782 -- Excludes class ops
783 let L loc sel_id = hsRecUpdFieldId (unLoc fld),
784 not (isRecordSelector sel_id),
785 let fld_name = idName sel_id ]
786 ; unless (null bad_guys) (sequence bad_guys >> failM)
787 -- See note [Mixed Record Selectors]
788 ; let (data_sels, pat_syn_sels) =
789 partition isDataConRecordSelector sel_ids
790 ; MASSERT( all isPatSynRecordSelector pat_syn_sels )
791 ; checkTc ( null data_sels || null pat_syn_sels )
792 ( mixedSelectors data_sels pat_syn_sels )
793
794 -- STEP 1
795 -- Figure out the tycon and data cons from the first field name
796 ; let -- It's OK to use the non-tc splitters here (for a selector)
797 sel_id : _ = sel_ids
798
799 mtycon :: Maybe TyCon
800 mtycon = case idDetails sel_id of
801 RecSelId (RecSelData tycon) _ -> Just tycon
802 _ -> Nothing
803
804 con_likes :: [ConLike]
805 con_likes = case idDetails sel_id of
806 RecSelId (RecSelData tc) _
807 -> map RealDataCon (tyConDataCons tc)
808 RecSelId (RecSelPatSyn ps) _
809 -> [PatSynCon ps]
810 _ -> panic "tcRecordUpd"
811 -- NB: for a data type family, the tycon is the instance tycon
812
813 relevant_cons = conLikesWithFields con_likes upd_fld_occs
814 -- A constructor is only relevant to this process if
815 -- it contains *all* the fields that are being updated
816 -- Other ones will cause a runtime error if they occur
817
818 -- Step 2
819 -- Check that at least one constructor has all the named fields
820 -- i.e. has an empty set of bad fields returned by badFields
821 ; checkTc (not (null relevant_cons)) (badFieldsUpd rbinds con_likes)
822
823 -- Take apart a representative constructor
824 ; let con1 = ASSERT( not (null relevant_cons) ) head relevant_cons
825 (con1_tvs, _, _, _prov_theta, req_theta, con1_arg_tys, _)
826 = conLikeFullSig con1
827 con1_flds = map flLabel $ conLikeFieldLabels con1
828 con1_tv_tys = mkTyVarTys con1_tvs
829 con1_res_ty = case mtycon of
830 Just tc -> mkFamilyTyConApp tc con1_tv_tys
831 Nothing -> conLikeResTy con1 con1_tv_tys
832
833 -- Check that we're not dealing with a unidirectional pattern
834 -- synonym
835 ; unless (isJust $ conLikeWrapId_maybe con1)
836 (nonBidirectionalErr (conLikeName con1))
837
838 -- STEP 3 Note [Criteria for update]
839 -- Check that each updated field is polymorphic; that is, its type
840 -- mentions only the universally-quantified variables of the data con
841 ; let flds1_w_tys = zipEqual "tcExpr:RecConUpd" con1_flds con1_arg_tys
842 bad_upd_flds = filter bad_fld flds1_w_tys
843 con1_tv_set = mkVarSet con1_tvs
844 bad_fld (fld, ty) = fld `elem` upd_fld_occs &&
845 not (tyCoVarsOfType ty `subVarSet` con1_tv_set)
846 ; checkTc (null bad_upd_flds) (badFieldTypes bad_upd_flds)
847
848 -- STEP 4 Note [Type of a record update]
849 -- Figure out types for the scrutinee and result
850 -- Both are of form (T a b c), with fresh type variables, but with
851 -- common variables where the scrutinee and result must have the same type
852 -- These are variables that appear in *any* arg of *any* of the
853 -- relevant constructors *except* in the updated fields
854 --
855 ; let fixed_tvs = getFixedTyVars upd_fld_occs con1_tvs relevant_cons
856 is_fixed_tv tv = tv `elemVarSet` fixed_tvs
857
858 mk_inst_ty :: TCvSubst -> (TyVar, TcType) -> TcM (TCvSubst, TcType)
859 -- Deals with instantiation of kind variables
860 -- c.f. TcMType.newMetaTyVars
861 mk_inst_ty subst (tv, result_inst_ty)
862 | is_fixed_tv tv -- Same as result type
863 = return (extendTCvSubst subst tv result_inst_ty, result_inst_ty)
864 | otherwise -- Fresh type, of correct kind
865 = do { (subst', new_tv) <- newMetaTyVarX subst tv
866 ; return (subst', mkTyVarTy new_tv) }
867
868 ; (result_subst, con1_tvs') <- newMetaTyVars con1_tvs
869 ; let result_inst_tys = mkTyVarTys con1_tvs'
870
871 ; (scrut_subst, scrut_inst_tys) <- mapAccumLM mk_inst_ty emptyTCvSubst
872 (con1_tvs `zip` result_inst_tys)
873
874 ; let rec_res_ty = TcType.substTy result_subst con1_res_ty
875 scrut_ty = TcType.substTyUnchecked scrut_subst con1_res_ty
876 con1_arg_tys' = map (TcType.substTy result_subst) con1_arg_tys
877
878 ; wrap_res <- tcSubTypeHR (exprCtOrigin expr)
879 (Just expr) rec_res_ty res_ty
880 ; co_scrut <- unifyType (Just record_expr) record_rho scrut_ty
881 -- NB: normal unification is OK here (as opposed to subsumption),
882 -- because for this to work out, both record_rho and scrut_ty have
883 -- to be normal datatypes -- no contravariant stuff can go on
884
885 -- STEP 5
886 -- Typecheck the bindings
887 ; rbinds' <- tcRecordUpd con1 con1_arg_tys' rbinds
888
889 -- STEP 6: Deal with the stupid theta
890 ; let theta' = substTheta scrut_subst (conLikeStupidTheta con1)
891 ; instStupidTheta RecordUpdOrigin theta'
892
893 -- Step 7: make a cast for the scrutinee, in the
894 -- case that it's from a data family
895 ; let fam_co :: HsWrapper -- RepT t1 .. tn ~R scrut_ty
896 fam_co | Just tycon <- mtycon
897 , Just co_con <- tyConFamilyCoercion_maybe tycon
898 = mkWpCastR (mkTcUnbranchedAxInstCo co_con scrut_inst_tys [])
899 | otherwise
900 = idHsWrapper
901
902 -- Step 8: Check that the req constraints are satisfied
903 -- For normal data constructors req_theta is empty but we must do
904 -- this check for pattern synonyms.
905 ; let req_theta' = substTheta scrut_subst req_theta
906 ; req_wrap <- instCallConstraints RecordUpdOrigin req_theta'
907
908 -- Phew!
909 ; return $
910 mkHsWrap wrap_res $
911 RecordUpd { rupd_expr = mkLHsWrap fam_co (mkLHsWrapCo co_scrut record_expr')
912 , rupd_flds = rbinds'
913 , rupd_cons = relevant_cons, rupd_in_tys = scrut_inst_tys
914 , rupd_out_tys = result_inst_tys, rupd_wrap = req_wrap } }
915
916 tcExpr (HsRecFld f) res_ty
917 = tcCheckRecSelId f res_ty
918
919 {-
920 ************************************************************************
921 * *
922 Arithmetic sequences e.g. [a,b..]
923 and their parallel-array counterparts e.g. [: a,b.. :]
924
925 * *
926 ************************************************************************
927 -}
928
929 tcExpr (ArithSeq _ witness seq) res_ty
930 = tcArithSeq witness seq res_ty
931
932 tcExpr (PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
933 = do { (coi, elt_ty) <- matchExpectedPArrTy res_ty
934 ; expr1' <- tcPolyExpr expr1 elt_ty
935 ; expr2' <- tcPolyExpr expr2 elt_ty
936 ; enumFromToP <- initDsTc $ dsDPHBuiltin enumFromToPVar
937 ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq)
938 (idName enumFromToP) elt_ty
939 ; return $
940 mkHsWrapCo coi $ PArrSeq enum_from_to (FromTo expr1' expr2') }
941
942 tcExpr (PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
943 = do { (coi, elt_ty) <- matchExpectedPArrTy res_ty
944 ; expr1' <- tcPolyExpr expr1 elt_ty
945 ; expr2' <- tcPolyExpr expr2 elt_ty
946 ; expr3' <- tcPolyExpr expr3 elt_ty
947 ; enumFromThenToP <- initDsTc $ dsDPHBuiltin enumFromThenToPVar
948 ; eft <- newMethodFromName (PArrSeqOrigin seq)
949 (idName enumFromThenToP) elt_ty -- !!!FIXME: chak
950 ; return $
951 mkHsWrapCo coi $
952 PArrSeq eft (FromThenTo expr1' expr2' expr3') }
953
954 tcExpr (PArrSeq _ _) _
955 = panic "TcExpr.tcExpr: Infinite parallel array!"
956 -- the parser shouldn't have generated it and the renamer shouldn't have
957 -- let it through
958
959 {-
960 ************************************************************************
961 * *
962 Template Haskell
963 * *
964 ************************************************************************
965 -}
966
967 tcExpr (HsSpliceE splice) res_ty
968 = tcSpliceExpr splice res_ty
969 tcExpr (HsBracket brack) res_ty
970 = tcTypedBracket brack res_ty
971 tcExpr (HsRnBracketOut brack ps) res_ty
972 = tcUntypedBracket brack ps res_ty
973
974 {-
975 ************************************************************************
976 * *
977 Catch-all
978 * *
979 ************************************************************************
980 -}
981
982 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
983 -- Include ArrForm, ArrApp, which shouldn't appear at all
984 -- Also HsTcBracketOut, HsQuasiQuoteE
985
986 {-
987 ************************************************************************
988 * *
989 Arithmetic sequences [a..b] etc
990 * *
991 ************************************************************************
992 -}
993
994 tcArithSeq :: Maybe (SyntaxExpr Name) -> ArithSeqInfo Name -> TcRhoType
995 -> TcM (HsExpr TcId)
996
997 tcArithSeq witness seq@(From expr) res_ty
998 = do { (coi, elt_ty, wit') <- arithSeqEltType witness res_ty
999 ; expr' <- tcPolyExpr expr elt_ty
1000 ; enum_from <- newMethodFromName (ArithSeqOrigin seq)
1001 enumFromName elt_ty
1002 ; return $ mkHsWrapCo coi (ArithSeq enum_from wit' (From expr')) }
1003
1004 tcArithSeq witness seq@(FromThen expr1 expr2) res_ty
1005 = do { (coi, elt_ty, wit') <- arithSeqEltType witness res_ty
1006 ; expr1' <- tcPolyExpr expr1 elt_ty
1007 ; expr2' <- tcPolyExpr expr2 elt_ty
1008 ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq)
1009 enumFromThenName elt_ty
1010 ; return $ mkHsWrapCo coi (ArithSeq enum_from_then wit' (FromThen expr1' expr2')) }
1011
1012 tcArithSeq witness seq@(FromTo expr1 expr2) res_ty
1013 = do { (coi, elt_ty, wit') <- arithSeqEltType witness res_ty
1014 ; expr1' <- tcPolyExpr expr1 elt_ty
1015 ; expr2' <- tcPolyExpr expr2 elt_ty
1016 ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq)
1017 enumFromToName elt_ty
1018 ; return $ mkHsWrapCo coi (ArithSeq enum_from_to wit' (FromTo expr1' expr2')) }
1019
1020 tcArithSeq witness seq@(FromThenTo expr1 expr2 expr3) res_ty
1021 = do { (coi, elt_ty, wit') <- arithSeqEltType witness res_ty
1022 ; expr1' <- tcPolyExpr expr1 elt_ty
1023 ; expr2' <- tcPolyExpr expr2 elt_ty
1024 ; expr3' <- tcPolyExpr expr3 elt_ty
1025 ; eft <- newMethodFromName (ArithSeqOrigin seq)
1026 enumFromThenToName elt_ty
1027 ; return $ mkHsWrapCo coi (ArithSeq eft wit' (FromThenTo expr1' expr2' expr3')) }
1028
1029 -----------------
1030 arithSeqEltType :: Maybe (SyntaxExpr Name) -> TcRhoType
1031 -> TcM (TcCoercionN, TcType, Maybe (SyntaxExpr Id))
1032 arithSeqEltType Nothing res_ty
1033 = do { (coi, elt_ty) <- matchExpectedListTy res_ty
1034 ; return (coi, elt_ty, Nothing) }
1035 arithSeqEltType (Just fl) res_ty
1036 = do { list_ty <- newFlexiTyVarTy liftedTypeKind
1037 ; fl' <- tcSyntaxOp ListOrigin fl (mkFunTy list_ty res_ty)
1038 ; (coi, elt_ty) <- matchExpectedListTy list_ty
1039 ; return (coi, elt_ty, Just fl') }
1040
1041 {-
1042 ************************************************************************
1043 * *
1044 Applications
1045 * *
1046 ************************************************************************
1047 -}
1048
1049 tcApp :: Maybe SDoc -- like "The function `f' is applied to"
1050 -- or leave out to get exactly that message
1051 -> LHsExpr Name -> [LHsExpr Name] -- Function and args
1052 -> TcRhoType -> TcM (HsWrapper, LHsExpr TcId, [LHsExpr TcId])
1053 -- (wrap, fun, args). For an ordinary function application,
1054 -- these should be assembled as (wrap (fun args)).
1055 -- But OpApp is slightly different, so that's why the caller
1056 -- must assemble
1057
1058 tcApp m_herald orig_fun orig_args res_ty
1059 = go orig_fun orig_args
1060 where
1061 go (L _ (HsPar e)) args = go e args
1062 go (L _ (HsApp e1 e2)) args = go e1 (e2:args)
1063
1064 go (L loc (HsVar (L _ fun))) args
1065 | fun `hasKey` tagToEnumKey
1066 , count (not . isLHsTypeExpr) args == 1
1067 = do { (wrap, expr, args) <- tcTagToEnum loc fun args res_ty
1068 ; return (wrap, expr, args) }
1069
1070 | fun `hasKey` seqIdKey
1071 , count (not . isLHsTypeExpr) args == 2
1072 = do { (wrap, expr, args) <- tcSeq loc fun args res_ty
1073 ; return (wrap, expr, args) }
1074
1075 go (L loc (HsRecFld (Ambiguous lbl _))) args@(L _ arg : _)
1076 | Just sig_ty <- obviousSig arg
1077 = do { sig_tc_ty <- tcHsSigWcType ExprSigCtxt sig_ty
1078 ; sel_name <- disambiguateSelector lbl sig_tc_ty
1079 ; go (L loc (HsRecFld (Unambiguous lbl sel_name))) args }
1080
1081 go fun args
1082 = do { -- Type-check the function
1083 ; (fun1, fun_sigma) <- tcInferFun fun
1084 ; let orig = exprCtOrigin (unLoc fun)
1085
1086 ; (wrap_fun, args1, actual_res_ty)
1087 <- tcArgs fun fun_sigma orig args
1088 (m_herald `orElse` mk_app_msg fun)
1089
1090 -- this is just like tcWrapResult, but the types don't line
1091 -- up to call that function
1092 ; wrap_res <- addFunResCtxt True (unLoc fun) actual_res_ty res_ty $
1093 tcSubTypeDS_NC_O orig GenSigCtxt
1094 (Just $ foldl mkHsApp fun args)
1095 actual_res_ty res_ty
1096
1097 ; return (wrap_res, mkLHsWrap wrap_fun fun1, args1) }
1098
1099 mk_app_msg :: LHsExpr Name -> SDoc
1100 mk_app_msg fun = sep [ text "The function" <+> quotes (ppr fun)
1101 , text "is applied to"]
1102
1103 mk_op_msg :: LHsExpr Name -> SDoc
1104 mk_op_msg op = text "The operator" <+> quotes (ppr op) <+> text "takes"
1105
1106 ----------------
1107 tcInferFun :: LHsExpr Name -> TcM (LHsExpr TcId, TcSigmaType)
1108 -- Infer type of a function
1109 tcInferFun (L loc (HsVar (L _ name)))
1110 = do { (fun, ty) <- setSrcSpan loc (tcInferId name)
1111 -- Don't wrap a context around a plain Id
1112 ; return (L loc fun, ty) }
1113
1114 tcInferFun (L loc (HsRecFld f))
1115 = do { (fun, ty) <- setSrcSpan loc (tcInferRecSelId f)
1116 -- Don't wrap a context around a plain Id
1117 ; return (L loc fun, ty) }
1118
1119 tcInferFun fun
1120 = do { (fun, fun_ty) <- tcInferSigma fun
1121
1122 -- Zonk the function type carefully, to expose any polymorphism
1123 -- E.g. (( \(x::forall a. a->a). blah ) e)
1124 -- We can see the rank-2 type of the lambda in time to generalise e
1125 ; fun_ty' <- zonkTcType fun_ty
1126
1127 ; return (fun, fun_ty') }
1128
1129 ----------------
1130 -- | Type-check the arguments to a function, possibly including visible type
1131 -- applications
1132 tcArgs :: LHsExpr Name -- ^ The function itself (for err msgs only)
1133 -> TcSigmaType -- ^ the (uninstantiated) type of the function
1134 -> CtOrigin -- ^ the origin for the function's type
1135 -> [LHsExpr Name] -- ^ the args
1136 -> SDoc -- ^ the herald for matchActualFunTys
1137 -> TcM (HsWrapper, [LHsExpr TcId], TcSigmaType)
1138 -- ^ (a wrapper for the function, the tc'd args, result type)
1139 tcArgs fun orig_fun_ty fun_orig orig_args herald
1140 = go [] 1 orig_fun_ty orig_args
1141 where
1142 orig_arity = length orig_args
1143
1144 go _ _ fun_ty [] = return (idHsWrapper, [], fun_ty)
1145
1146 go acc_args n fun_ty (arg:args)
1147 | Just hs_ty_arg <- isLHsTypeExpr_maybe arg
1148 = do { (wrap1, upsilon_ty) <- topInstantiateInferred fun_orig fun_ty
1149 -- wrap1 :: fun_ty "->" upsilon_ty
1150 ; case tcSplitForAllTy_maybe upsilon_ty of
1151 Just (binder, inner_ty)
1152 | Just tv <- binderVar_maybe binder ->
1153 ASSERT( binderVisibility binder == Specified )
1154 do { let kind = tyVarKind tv
1155 ; ty_arg <- tcHsTypeApp hs_ty_arg kind
1156 ; let insted_ty = substTyWith [tv] [ty_arg] inner_ty
1157 ; (inner_wrap, args', res_ty)
1158 <- go acc_args (n+1) insted_ty args
1159 -- inner_wrap :: insted_ty "->" (map typeOf args') -> res_ty
1160 ; let inst_wrap = mkWpTyApps [ty_arg]
1161 ; return ( inner_wrap <.> inst_wrap <.> wrap1
1162 , L (getLoc arg) (HsTypeOut hs_ty_arg) : args'
1163 , res_ty ) }
1164 _ -> ty_app_err upsilon_ty hs_ty_arg }
1165
1166 | otherwise -- not a type application.
1167 = do { (wrap, [arg_ty], res_ty)
1168 <- matchActualFunTysPart herald fun_orig 1 fun_ty
1169 acc_args orig_arity
1170 -- wrap :: fun_ty "->" arg_ty -> res_ty
1171 ; arg' <- tcArg fun (arg, arg_ty, n)
1172 ; (inner_wrap, args', inner_res_ty)
1173 <- go (arg_ty : acc_args) (n+1) res_ty args
1174 -- inner_wrap :: res_ty "->" (map typeOf args') -> inner_res_ty
1175 ; return ( mkWpFun idHsWrapper inner_wrap arg_ty res_ty <.> wrap
1176 , arg' : args'
1177 , inner_res_ty ) }
1178
1179 ty_app_err ty arg
1180 = do { (_, ty) <- zonkTidyTcType emptyTidyEnv ty
1181 ; failWith $
1182 text "Cannot apply expression of type" <+> quotes (ppr ty) $$
1183 text "to a visible type argument" <+> quotes (ppr arg) }
1184
1185 ----------------
1186 tcArg :: LHsExpr Name -- The function (for error messages)
1187 -> (LHsExpr Name, TcSigmaType, Int) -- Actual argument and expected arg type
1188 -> TcM (LHsExpr TcId) -- Resulting argument
1189 tcArg fun (arg, ty, arg_no) = addErrCtxt (funAppCtxt fun arg arg_no)
1190 (tcPolyExprNC arg ty)
1191
1192 ----------------
1193 tcTupArgs :: [LHsTupArg Name] -> [TcSigmaType] -> TcM [LHsTupArg TcId]
1194 tcTupArgs args tys
1195 = ASSERT( equalLength args tys ) mapM go (args `zip` tys)
1196 where
1197 go (L l (Missing {}), arg_ty) = return (L l (Missing arg_ty))
1198 go (L l (Present expr), arg_ty) = do { expr' <- tcPolyExpr expr arg_ty
1199 ; return (L l (Present expr')) }
1200
1201 ---------------------------
1202 tcSyntaxOp :: CtOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
1203 -- Typecheck a syntax operator, checking that it has the specified type
1204 -- The operator is always a variable at this stage (i.e. renamer output)
1205 -- This version assumes res_ty is a monotype
1206 tcSyntaxOp orig (HsVar (L _ op)) res_ty
1207 = do { (expr, rho) <- tcInferId op
1208 ; tcWrapResultO orig expr rho res_ty }
1209
1210 tcSyntaxOp _ other _ = pprPanic "tcSyntaxOp" (ppr other)
1211
1212 {-
1213 Note [Push result type in]
1214 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1215 Unify with expected result before type-checking the args so that the
1216 info from res_ty percolates to args. This is when we might detect a
1217 too-few args situation. (One can think of cases when the opposite
1218 order would give a better error message.)
1219 experimenting with putting this first.
1220
1221 Here's an example where it actually makes a real difference
1222
1223 class C t a b | t a -> b
1224 instance C Char a Bool
1225
1226 data P t a = forall b. (C t a b) => MkP b
1227 data Q t = MkQ (forall a. P t a)
1228
1229 f1, f2 :: Q Char;
1230 f1 = MkQ (MkP True)
1231 f2 = MkQ (MkP True :: forall a. P Char a)
1232
1233 With the change, f1 will type-check, because the 'Char' info from
1234 the signature is propagated into MkQ's argument. With the check
1235 in the other order, the extra signature in f2 is reqd.
1236
1237 ************************************************************************
1238 * *
1239 Expressions with a type signature
1240 expr :: type
1241 * *
1242 ********************************************************************* -}
1243
1244 tcExprSig :: LHsExpr Name -> TcIdSigInfo -> TcM (LHsExpr TcId, TcType)
1245 tcExprSig expr sig@(TISI { sig_bndr = s_bndr
1246 , sig_skols = skol_prs
1247 , sig_theta = theta
1248 , sig_tau = tau })
1249 | null skol_prs -- Fast path when there is no quantification at all
1250 , null theta
1251 , CompleteSig {} <- s_bndr
1252 = do { expr' <- tcPolyExprNC expr tau
1253 ; return (expr', tau) }
1254
1255 | CompleteSig poly_id <- s_bndr
1256 = do { given <- newEvVars theta
1257 ; (ev_binds, expr') <- checkConstraints skol_info skol_tvs given $
1258 tcExtendTyVarEnvFromSig sig $
1259 tcPolyExprNC expr tau
1260
1261 ; let poly_wrap = mkWpTyLams skol_tvs
1262 <.> mkWpLams given
1263 <.> mkWpLet ev_binds
1264 ; return (mkLHsWrap poly_wrap expr', idType poly_id) }
1265
1266 | PartialSig { sig_name = name } <- s_bndr
1267 = do { (tclvl, wanted, expr') <- pushLevelAndCaptureConstraints $
1268 tcExtendTyVarEnvFromSig sig $
1269 tcPolyExprNC expr tau
1270 ; (qtvs, givens, ev_binds)
1271 <- simplifyInfer tclvl False [sig] [(name, tau)] wanted
1272 ; tau <- zonkTcType tau
1273 ; let inferred_theta = map evVarPred givens
1274 tau_tvs = tyCoVarsOfType tau
1275 ; (binders, my_theta) <- chooseInferredQuantifiers inferred_theta
1276 tau_tvs qtvs (Just sig)
1277 ; let inferred_sigma = mkInvSigmaTy qtvs inferred_theta tau
1278 my_sigma = mkForAllTys binders (mkPhiTy my_theta tau)
1279 ; wrap <- if inferred_sigma `eqType` my_sigma -- NB: eqType ignores vis.
1280 then return idHsWrapper -- Fast path; also avoids complaint when we infer
1281 -- an ambiguouse type and have AllowAmbiguousType
1282 -- e..g infer x :: forall a. F a -> Int
1283 else tcSubType_NC ExprSigCtxt inferred_sigma my_sigma
1284
1285 ; let poly_wrap = wrap
1286 <.> mkWpTyLams qtvs
1287 <.> mkWpLams givens
1288 <.> mkWpLet ev_binds
1289 ; return (mkLHsWrap poly_wrap expr', my_sigma) }
1290
1291 | otherwise = panic "tcExprSig" -- Can't happen
1292 where
1293 skol_info = SigSkol ExprSigCtxt (mkPhiTy theta tau)
1294 skol_tvs = map snd skol_prs
1295
1296 {- *********************************************************************
1297 * *
1298 tcInferId
1299 * *
1300 ********************************************************************* -}
1301
1302 tcCheckId :: Name -> TcRhoType -> TcM (HsExpr TcId)
1303 tcCheckId name res_ty
1304 = do { (expr, actual_res_ty) <- tcInferId name
1305 ; traceTc "tcCheckId" (vcat [ppr name, ppr actual_res_ty, ppr res_ty])
1306 ; addFunResCtxt False (HsVar (noLoc name)) actual_res_ty res_ty $
1307 tcWrapResultO (OccurrenceOf name) expr actual_res_ty res_ty }
1308
1309 tcCheckRecSelId :: AmbiguousFieldOcc Name -> TcRhoType -> TcM (HsExpr TcId)
1310 tcCheckRecSelId f@(Unambiguous (L _ lbl) _) res_ty
1311 = do { (expr, actual_res_ty) <- tcInferRecSelId f
1312 ; addFunResCtxt False (HsRecFld f) actual_res_ty res_ty $
1313 tcWrapResultO (OccurrenceOfRecSel lbl) expr actual_res_ty res_ty }
1314 tcCheckRecSelId (Ambiguous lbl _) res_ty
1315 = case tcSplitFunTy_maybe res_ty of
1316 Nothing -> ambiguousSelector lbl
1317 Just (arg, _) -> do { sel_name <- disambiguateSelector lbl arg
1318 ; tcCheckRecSelId (Unambiguous lbl sel_name) res_ty }
1319
1320 ------------------------
1321 tcInferRecSelId :: AmbiguousFieldOcc Name -> TcM (HsExpr TcId, TcRhoType)
1322 tcInferRecSelId (Unambiguous (L _ lbl) sel)
1323 = do { (expr', ty) <- tc_infer_id lbl sel
1324 ; return (expr', ty) }
1325 tcInferRecSelId (Ambiguous lbl _)
1326 = ambiguousSelector lbl
1327
1328 ------------------------
1329 tcInferId :: Name -> TcM (HsExpr TcId, TcSigmaType)
1330 -- Look up an occurrence of an Id
1331 tcInferId id_name
1332 | id_name `hasKey` tagToEnumKey
1333 = failWithTc (text "tagToEnum# must appear applied to one argument")
1334 -- tcApp catches the case (tagToEnum# arg)
1335
1336 | id_name `hasKey` assertIdKey
1337 = do { dflags <- getDynFlags
1338 ; if gopt Opt_IgnoreAsserts dflags
1339 then tc_infer_id (nameRdrName id_name) id_name
1340 else tc_infer_assert id_name }
1341
1342 | otherwise
1343 = do { (expr, ty) <- tc_infer_id (nameRdrName id_name) id_name
1344 ; traceTc "tcInferId" (ppr id_name <+> dcolon <+> ppr ty)
1345 ; return (expr, ty) }
1346
1347 tc_infer_assert :: Name -> TcM (HsExpr TcId, TcSigmaType)
1348 -- Deal with an occurrence of 'assert'
1349 -- See Note [Adding the implicit parameter to 'assert']
1350 tc_infer_assert assert_name
1351 = do { assert_error_id <- tcLookupId assertErrorName
1352 ; (wrap, id_rho) <- topInstantiate (OccurrenceOf assert_name)
1353 (idType assert_error_id)
1354 ; return (mkHsWrap wrap (HsVar (noLoc assert_error_id)), id_rho)
1355 }
1356
1357 tc_infer_id :: RdrName -> Name -> TcM (HsExpr TcId, TcSigmaType)
1358 tc_infer_id lbl id_name
1359 = do { thing <- tcLookup id_name
1360 ; case thing of
1361 ATcId { tct_id = id }
1362 -> do { check_naughty id -- Note [Local record selectors]
1363 ; checkThLocalId id
1364 ; return_id id }
1365
1366 AGlobal (AnId id)
1367 -> do { check_naughty id
1368 ; return_id id }
1369 -- A global cannot possibly be ill-staged
1370 -- nor does it need the 'lifting' treatment
1371 -- hence no checkTh stuff here
1372
1373 AGlobal (AConLike cl) -> case cl of
1374 RealDataCon con -> return_data_con con
1375 PatSynCon ps -> tcPatSynBuilderOcc ps
1376
1377 _ -> failWithTc $
1378 ppr thing <+> text "used where a value identifier was expected" }
1379 where
1380 return_id id = return (HsVar (noLoc id), idType id)
1381
1382 return_data_con con
1383 -- For data constructors, must perform the stupid-theta check
1384 | null stupid_theta
1385 = return_id con_wrapper_id
1386
1387 | otherwise
1388 -- See Note [Instantiating stupid theta]
1389 = do { let (tvs, theta, rho) = tcSplitSigmaTy (idType con_wrapper_id)
1390 ; (subst, tvs') <- newMetaTyVars tvs
1391 ; let tys' = mkTyVarTys tvs'
1392 theta' = substTheta subst theta
1393 rho' = substTy subst rho
1394 ; wrap <- instCall (OccurrenceOf id_name) tys' theta'
1395 ; addDataConStupidTheta con tys'
1396 ; return (mkHsWrap wrap (HsVar (noLoc con_wrapper_id)), rho') }
1397
1398 where
1399 con_wrapper_id = dataConWrapId con
1400 stupid_theta = dataConStupidTheta con
1401
1402 check_naughty id
1403 | isNaughtyRecordSelector id = failWithTc (naughtyRecordSel lbl)
1404 | otherwise = return ()
1405
1406
1407 tcUnboundId :: OccName -> TcRhoType -> TcM (HsExpr TcId)
1408 -- Typechedk an occurrence of an unbound Id
1409 --
1410 -- Some of these started life as a true hole "_". Others might simply
1411 -- be variables that accidentally have no binding site
1412 --
1413 -- We turn all of them into HsVar, since HsUnboundVar can't contain an
1414 -- Id; and indeed the evidence for the CHoleCan does bind it, so it's
1415 -- not unbound any more!
1416 tcUnboundId occ res_ty
1417 = do { ty <- newFlexiTyVarTy liftedTypeKind
1418 ; name <- newSysName occ
1419 ; let ev = mkLocalId name ty
1420 ; loc <- getCtLocM HoleOrigin Nothing
1421 ; let can = CHoleCan { cc_ev = CtWanted { ctev_pred = ty
1422 , ctev_dest = EvVarDest ev
1423 , ctev_loc = loc}
1424 , cc_occ = occ
1425 , cc_hole = ExprHole }
1426 ; emitInsoluble can
1427 ; tcWrapResultO (UnboundOccurrenceOf occ) (HsVar (noLoc ev)) ty res_ty }
1428
1429
1430 {-
1431 Note [Adding the implicit parameter to 'assert']
1432 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1433 The typechecker transforms (assert e1 e2) to (assertError e1 e2).
1434 This isn't really the Right Thing because there's no way to "undo"
1435 if you want to see the original source code in the typechecker
1436 output. We'll have fix this in due course, when we care more about
1437 being able to reconstruct the exact original program.
1438
1439 Note [tagToEnum#]
1440 ~~~~~~~~~~~~~~~~~
1441 Nasty check to ensure that tagToEnum# is applied to a type that is an
1442 enumeration TyCon. Unification may refine the type later, but this
1443 check won't see that, alas. It's crude, because it relies on our
1444 knowing *now* that the type is ok, which in turn relies on the
1445 eager-unification part of the type checker pushing enough information
1446 here. In theory the Right Thing to do is to have a new form of
1447 constraint but I definitely cannot face that! And it works ok as-is.
1448
1449 Here's are two cases that should fail
1450 f :: forall a. a
1451 f = tagToEnum# 0 -- Can't do tagToEnum# at a type variable
1452
1453 g :: Int
1454 g = tagToEnum# 0 -- Int is not an enumeration
1455
1456 When data type families are involved it's a bit more complicated.
1457 data family F a
1458 data instance F [Int] = A | B | C
1459 Then we want to generate something like
1460 tagToEnum# R:FListInt 3# |> co :: R:FListInt ~ F [Int]
1461 Usually that coercion is hidden inside the wrappers for
1462 constructors of F [Int] but here we have to do it explicitly.
1463
1464 It's all grotesquely complicated.
1465
1466 Note [Instantiating stupid theta]
1467 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1468 Normally, when we infer the type of an Id, we don't instantiate,
1469 because we wish to allow for visible type application later on.
1470 But if a datacon has a stupid theta, we're a bit stuck. We need
1471 to emit the stupid theta constraints with instantiated types. It's
1472 difficult to defer this to the lazy instantiation, because a stupid
1473 theta has no spot to put it in a type. So we just instantiate eagerly
1474 in this case. Thus, users cannot use visible type application with
1475 a data constructor sporting a stupid theta. I won't feel so bad for
1476 the users that complain.
1477
1478 -}
1479
1480 tcSeq :: SrcSpan -> Name -> [LHsExpr Name]
1481 -> TcRhoType -> TcM (HsWrapper, LHsExpr TcId, [LHsExpr TcId])
1482 -- (seq e1 e2) :: res_ty
1483 -- We need a special typing rule because res_ty can be unboxed
1484 -- See Note [Typing rule for seq]
1485 tcSeq loc fun_name args res_ty
1486 = do { fun <- tcLookupId fun_name
1487 ; (arg1_ty, args1) <- case args of
1488 (ty_arg_expr1 : args1)
1489 | Just hs_ty_arg1 <- isLHsTypeExpr_maybe ty_arg_expr1
1490 -> do { ty_arg1 <- tcHsTypeApp hs_ty_arg1 liftedTypeKind
1491 ; return (ty_arg1, args1) }
1492
1493 _ -> do { arg_ty1 <- newFlexiTyVarTy liftedTypeKind
1494 ; return (arg_ty1, args) }
1495
1496 ; (arg1, arg2) <- case args1 of
1497 [ty_arg_expr2, term_arg1, term_arg2]
1498 | Just hs_ty_arg2 <- isLHsTypeExpr_maybe ty_arg_expr2
1499 -> do { lev_ty <- newFlexiTyVarTy levityTy
1500 ; ty_arg2 <- tcHsTypeApp hs_ty_arg2 (tYPE lev_ty)
1501 -- see Note [Typing rule for seq]
1502 ; _ <- unifyType noThing ty_arg2 res_ty
1503 ; return (term_arg1, term_arg2) }
1504 [term_arg1, term_arg2] -> return (term_arg1, term_arg2)
1505 _ -> too_many_args
1506
1507 ; arg1' <- tcMonoExpr arg1 arg1_ty
1508 ; res_ty <- zonkTcType res_ty -- just in case we learned something
1509 -- interesting about it
1510 ; arg2' <- tcMonoExpr arg2 res_ty
1511 ; let fun' = L loc (HsWrap ty_args (HsVar (L loc fun)))
1512 ty_args = WpTyApp res_ty <.> WpTyApp arg1_ty
1513 ; return (idHsWrapper, fun', [arg1', arg2']) }
1514 where
1515 too_many_args :: TcM a
1516 too_many_args
1517 = failWith $
1518 hang (text "Too many type arguments to seq:")
1519 2 (sep (map pprParendExpr args))
1520
1521
1522 tcTagToEnum :: SrcSpan -> Name -> [LHsExpr Name] -> TcRhoType
1523 -> TcM (HsWrapper, LHsExpr TcId, [LHsExpr TcId])
1524 -- tagToEnum# :: forall a. Int# -> a
1525 -- See Note [tagToEnum#] Urgh!
1526 tcTagToEnum loc fun_name args res_ty
1527 = do { fun <- tcLookupId fun_name
1528
1529 ; arg <- case args of
1530 [ty_arg_expr, term_arg]
1531 | Just hs_ty_arg <- isLHsTypeExpr_maybe ty_arg_expr
1532 -> do { ty_arg <- tcHsTypeApp hs_ty_arg liftedTypeKind
1533 ; _ <- unifyType noThing ty_arg res_ty
1534 -- other than influencing res_ty, we just
1535 -- don't care about a type arg passed in.
1536 -- So drop the evidence.
1537 ; return term_arg }
1538 [term_arg] -> return term_arg
1539 _ -> too_many_args
1540
1541 ; ty' <- zonkTcType res_ty
1542
1543 -- Check that the type is algebraic
1544 ; let mb_tc_app = tcSplitTyConApp_maybe ty'
1545 Just (tc, tc_args) = mb_tc_app
1546 ; checkTc (isJust mb_tc_app)
1547 (mk_error ty' doc1)
1548
1549 -- Look through any type family
1550 ; fam_envs <- tcGetFamInstEnvs
1551 ; let (rep_tc, rep_args, coi)
1552 = tcLookupDataFamInst fam_envs tc tc_args
1553 -- coi :: tc tc_args ~R rep_tc rep_args
1554
1555 ; checkTc (isEnumerationTyCon rep_tc)
1556 (mk_error ty' doc2)
1557
1558 ; arg' <- tcMonoExpr arg intPrimTy
1559 ; let fun' = L loc (HsWrap (WpTyApp rep_ty) (HsVar (L loc fun)))
1560 rep_ty = mkTyConApp rep_tc rep_args
1561
1562 ; return (mkWpCastR (mkTcSymCo coi), fun', [arg']) }
1563 -- coi is a Representational coercion
1564 where
1565 doc1 = vcat [ text "Specify the type by giving a type signature"
1566 , text "e.g. (tagToEnum# x) :: Bool" ]
1567 doc2 = text "Result type must be an enumeration type"
1568
1569 mk_error :: TcType -> SDoc -> SDoc
1570 mk_error ty what
1571 = hang (text "Bad call to tagToEnum#"
1572 <+> text "at type" <+> ppr ty)
1573 2 what
1574
1575 too_many_args :: TcM a
1576 too_many_args
1577 = failWith $
1578 hang (text "Too many type arguments to tagToEnum#:")
1579 2 (sep (map pprParendExpr args))
1580
1581 {-
1582 ************************************************************************
1583 * *
1584 Template Haskell checks
1585 * *
1586 ************************************************************************
1587 -}
1588
1589 checkThLocalId :: Id -> TcM ()
1590 checkThLocalId id
1591 = do { mb_local_use <- getStageAndBindLevel (idName id)
1592 ; case mb_local_use of
1593 Just (top_lvl, bind_lvl, use_stage)
1594 | thLevel use_stage > bind_lvl
1595 , isNotTopLevel top_lvl
1596 -> checkCrossStageLifting id use_stage
1597 _ -> return () -- Not a locally-bound thing, or
1598 -- no cross-stage link
1599 }
1600
1601 --------------------------------------
1602 checkCrossStageLifting :: Id -> ThStage -> TcM ()
1603 -- If we are inside typed brackets, and (use_lvl > bind_lvl)
1604 -- we must check whether there's a cross-stage lift to do
1605 -- Examples \x -> [|| x ||]
1606 -- [|| map ||]
1607 -- There is no error-checking to do, because the renamer did that
1608 --
1609 -- This is similar to checkCrossStageLifting in RnSplice, but
1610 -- this code is applied to *typed* brackets.
1611
1612 checkCrossStageLifting id (Brack _ (TcPending ps_var lie_var))
1613 = -- Nested identifiers, such as 'x' in
1614 -- E.g. \x -> [|| h x ||]
1615 -- We must behave as if the reference to x was
1616 -- h $(lift x)
1617 -- We use 'x' itself as the splice proxy, used by
1618 -- the desugarer to stitch it all back together.
1619 -- If 'x' occurs many times we may get many identical
1620 -- bindings of the same splice proxy, but that doesn't
1621 -- matter, although it's a mite untidy.
1622 do { let id_ty = idType id
1623 ; checkTc (isTauTy id_ty) (polySpliceErr id)
1624 -- If x is polymorphic, its occurrence sites might
1625 -- have different instantiations, so we can't use plain
1626 -- 'x' as the splice proxy name. I don't know how to
1627 -- solve this, and it's probably unimportant, so I'm
1628 -- just going to flag an error for now
1629
1630 ; lift <- if isStringTy id_ty then
1631 do { sid <- tcLookupId THNames.liftStringName
1632 -- See Note [Lifting strings]
1633 ; return (HsVar (noLoc sid)) }
1634 else
1635 setConstraintVar lie_var $
1636 -- Put the 'lift' constraint into the right LIE
1637 newMethodFromName (OccurrenceOf (idName id))
1638 THNames.liftName id_ty
1639
1640 -- Update the pending splices
1641 ; ps <- readMutVar ps_var
1642 ; let pending_splice = PendingTcSplice (idName id) (nlHsApp (noLoc lift) (nlHsVar id))
1643 ; writeMutVar ps_var (pending_splice : ps)
1644
1645 ; return () }
1646
1647 checkCrossStageLifting _ _ = return ()
1648
1649 polySpliceErr :: Id -> SDoc
1650 polySpliceErr id
1651 = text "Can't splice the polymorphic local variable" <+> quotes (ppr id)
1652
1653 {-
1654 Note [Lifting strings]
1655 ~~~~~~~~~~~~~~~~~~~~~~
1656 If we see $(... [| s |] ...) where s::String, we don't want to
1657 generate a mass of Cons (CharL 'x') (Cons (CharL 'y') ...)) etc.
1658 So this conditional short-circuits the lifting mechanism to generate
1659 (liftString "xy") in that case. I didn't want to use overlapping instances
1660 for the Lift class in TH.Syntax, because that can lead to overlapping-instance
1661 errors in a polymorphic situation.
1662
1663 If this check fails (which isn't impossible) we get another chance; see
1664 Note [Converting strings] in Convert.hs
1665
1666 Local record selectors
1667 ~~~~~~~~~~~~~~~~~~~~~~
1668 Record selectors for TyCons in this module are ordinary local bindings,
1669 which show up as ATcIds rather than AGlobals. So we need to check for
1670 naughtiness in both branches. c.f. TcTyClsBindings.mkAuxBinds.
1671
1672
1673 ************************************************************************
1674 * *
1675 \subsection{Record bindings}
1676 * *
1677 ************************************************************************
1678 -}
1679
1680 getFixedTyVars :: [FieldLabelString] -> [TyVar] -> [ConLike] -> TyVarSet
1681 -- These tyvars must not change across the updates
1682 getFixedTyVars upd_fld_occs univ_tvs cons
1683 = mkVarSet [tv1 | con <- cons
1684 , let (u_tvs, _, eqspec, prov_theta
1685 , req_theta, arg_tys, _)
1686 = conLikeFullSig con
1687 theta = eqSpecPreds eqspec
1688 ++ prov_theta
1689 ++ req_theta
1690 flds = conLikeFieldLabels con
1691 fixed_tvs = exactTyCoVarsOfTypes fixed_tys
1692 -- fixed_tys: See Note [Type of a record update]
1693 `unionVarSet` tyCoVarsOfTypes theta
1694 -- Universally-quantified tyvars that
1695 -- appear in any of the *implicit*
1696 -- arguments to the constructor are fixed
1697 -- See Note [Implict type sharing]
1698
1699 fixed_tys = [ty | (fl, ty) <- zip flds arg_tys
1700 , not (flLabel fl `elem` upd_fld_occs)]
1701 , (tv1,tv) <- univ_tvs `zip` u_tvs
1702 , tv `elemVarSet` fixed_tvs ]
1703
1704 {-
1705 Note [Disambiguating record fields]
1706 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1707 When the -XDuplicateRecordFields extension is used, and the renamer
1708 encounters a record selector or update that it cannot immediately
1709 disambiguate (because it involves fields that belong to multiple
1710 datatypes), it will defer resolution of the ambiguity to the
1711 typechecker. In this case, the `Ambiguous` constructor of
1712 `AmbiguousFieldOcc` is used.
1713
1714 Consider the following definitions:
1715
1716 data S = MkS { foo :: Int }
1717 data T = MkT { foo :: Int, bar :: Int }
1718 data U = MkU { bar :: Int, baz :: Int }
1719
1720 When the renamer sees `foo` as a selector or an update, it will not
1721 know which parent datatype is in use.
1722
1723 For selectors, there are two possible ways to disambiguate:
1724
1725 1. Check if the pushed-in type is a function whose domain is a
1726 datatype, for example:
1727
1728 f s = (foo :: S -> Int) s
1729
1730 g :: T -> Int
1731 g = foo
1732
1733 This is checked by `tcCheckRecSelId` when checking `HsRecFld foo`.
1734
1735 2. Check if the selector is applied to an argument that has a type
1736 signature, for example:
1737
1738 h = foo (s :: S)
1739
1740 This is checked by `tcApp`.
1741
1742
1743 Updates are slightly more complex. The `disambiguateRecordBinds`
1744 function tries to determine the parent datatype in three ways:
1745
1746 1. Check for types that have all the fields being updated. For example:
1747
1748 f x = x { foo = 3, bar = 2 }
1749
1750 Here `f` must be updating `T` because neither `S` nor `U` have
1751 both fields. This may also discover that no possible type exists.
1752 For example the following will be rejected:
1753
1754 f' x = x { foo = 3, baz = 3 }
1755
1756 2. Use the type being pushed in, if it is already a TyConApp. The
1757 following are valid updates to `T`:
1758
1759 g :: T -> T
1760 g x = x { foo = 3 }
1761
1762 g' x = x { foo = 3 } :: T
1763
1764 3. Use the type signature of the record expression, if it exists and
1765 is a TyConApp. Thus this is valid update to `T`:
1766
1767 h x = (x :: T) { foo = 3 }
1768
1769
1770 Note that we do not look up the types of variables being updated, and
1771 no constraint-solving is performed, so for example the following will
1772 be rejected as ambiguous:
1773
1774 let bad (s :: S) = foo s
1775
1776 let r :: T
1777 r = blah
1778 in r { foo = 3 }
1779
1780 \r. (r { foo = 3 }, r :: T )
1781
1782 We could add further tests, of a more heuristic nature. For example,
1783 rather than looking for an explicit signature, we could try to infer
1784 the type of the argument to a selector or the record expression being
1785 updated, in case we are lucky enough to get a TyConApp straight
1786 away. However, it might be hard for programmers to predict whether a
1787 particular update is sufficiently obvious for the signature to be
1788 omitted. Moreover, this might change the behaviour of typechecker in
1789 non-obvious ways.
1790
1791 See also Note [HsRecField and HsRecUpdField] in HsPat.
1792 -}
1793
1794 -- Given a RdrName that refers to multiple record fields, and the type
1795 -- of its argument, try to determine the name of the selector that is
1796 -- meant.
1797 disambiguateSelector :: Located RdrName -> Type -> TcM Name
1798 disambiguateSelector lr@(L _ rdr) parent_type
1799 = do { fam_inst_envs <- tcGetFamInstEnvs
1800 ; case tyConOf fam_inst_envs parent_type of
1801 Nothing -> ambiguousSelector lr
1802 Just p ->
1803 do { xs <- lookupParents rdr
1804 ; let parent = RecSelData p
1805 ; case lookup parent xs of
1806 Just gre -> do { addUsedGRE True gre
1807 ; return (gre_name gre) }
1808 Nothing -> failWithTc (fieldNotInType parent rdr) } }
1809
1810 -- This field name really is ambiguous, so add a suitable "ambiguous
1811 -- occurrence" error, then give up.
1812 ambiguousSelector :: Located RdrName -> TcM a
1813 ambiguousSelector (L _ rdr)
1814 = do { env <- getGlobalRdrEnv
1815 ; let gres = lookupGRE_RdrName rdr env
1816 ; setErrCtxt [] $ addNameClashErrRn rdr gres
1817 ; failM }
1818
1819 -- Disambiguate the fields in a record update.
1820 -- See Note [Disambiguating record fields]
1821 disambiguateRecordBinds :: LHsExpr Name -> TcRhoType
1822 -> [LHsRecUpdField Name] -> Type
1823 -> TcM [LHsRecField' (AmbiguousFieldOcc Id) (LHsExpr Name)]
1824 disambiguateRecordBinds record_expr record_rho rbnds res_ty
1825 -- Are all the fields unambiguous?
1826 = case mapM isUnambiguous rbnds of
1827 -- If so, just skip to looking up the Ids
1828 -- Always the case if DuplicateRecordFields is off
1829 Just rbnds' -> mapM lookupSelector rbnds'
1830 Nothing -> -- If not, try to identify a single parent
1831 do { fam_inst_envs <- tcGetFamInstEnvs
1832 -- Look up the possible parents for each field
1833 ; rbnds_with_parents <- getUpdFieldsParents
1834 ; let possible_parents = map (map fst . snd) rbnds_with_parents
1835 -- Identify a single parent
1836 ; p <- identifyParent fam_inst_envs possible_parents
1837 -- Pick the right selector with that parent for each field
1838 ; checkNoErrs $ mapM (pickParent p) rbnds_with_parents }
1839 where
1840 -- Extract the selector name of a field update if it is unambiguous
1841 isUnambiguous :: LHsRecUpdField Name -> Maybe (LHsRecUpdField Name, Name)
1842 isUnambiguous x = case unLoc (hsRecFieldLbl (unLoc x)) of
1843 Unambiguous _ sel_name -> Just (x, sel_name)
1844 Ambiguous{} -> Nothing
1845
1846 -- Look up the possible parents and selector GREs for each field
1847 getUpdFieldsParents :: TcM [(LHsRecUpdField Name
1848 , [(RecSelParent, GlobalRdrElt)])]
1849 getUpdFieldsParents
1850 = fmap (zip rbnds) $ mapM
1851 (lookupParents . unLoc . hsRecUpdFieldRdr . unLoc)
1852 rbnds
1853
1854 -- Given a the lists of possible parents for each field,
1855 -- identify a single parent
1856 identifyParent :: FamInstEnvs -> [[RecSelParent]] -> TcM RecSelParent
1857 identifyParent fam_inst_envs possible_parents
1858 = case foldr1 intersect possible_parents of
1859 -- No parents for all fields: record update is ill-typed
1860 [] -> failWithTc (noPossibleParents rbnds)
1861
1862 -- Exactly one datatype with all the fields: use that
1863 [p] -> return p
1864
1865 -- Multiple possible parents: try harder to disambiguate
1866 -- Can we get a parent TyCon from the pushed-in type?
1867 _:_ | Just p <- tyConOf fam_inst_envs res_ty -> return (RecSelData p)
1868
1869 -- Does the expression being updated have a type signature?
1870 -- If so, try to extract a parent TyCon from it
1871 | Just {} <- obviousSig (unLoc record_expr)
1872 , Just tc <- tyConOf fam_inst_envs record_rho
1873 -> return (RecSelData tc)
1874
1875 -- Nothing else we can try...
1876 _ -> failWithTc badOverloadedUpdate
1877
1878 -- Make a field unambiguous by choosing the given parent.
1879 -- Emits an error if the field cannot have that parent,
1880 -- e.g. if the user writes
1881 -- r { x = e } :: T
1882 -- where T does not have field x.
1883 pickParent :: RecSelParent
1884 -> (LHsRecUpdField Name, [(RecSelParent, GlobalRdrElt)])
1885 -> TcM (LHsRecField' (AmbiguousFieldOcc Id) (LHsExpr Name))
1886 pickParent p (upd, xs)
1887 = case lookup p xs of
1888 -- Phew! The parent is valid for this field.
1889 -- Previously ambiguous fields must be marked as
1890 -- used now that we know which one is meant, but
1891 -- unambiguous ones shouldn't be recorded again
1892 -- (giving duplicate deprecation warnings).
1893 Just gre -> do { unless (null (tail xs)) $ do
1894 let L loc _ = hsRecFieldLbl (unLoc upd)
1895 setSrcSpan loc $ addUsedGRE True gre
1896 ; lookupSelector (upd, gre_name gre) }
1897 -- The field doesn't belong to this parent, so report
1898 -- an error but keep going through all the fields
1899 Nothing -> do { addErrTc (fieldNotInType p
1900 (unLoc (hsRecUpdFieldRdr (unLoc upd))))
1901 ; lookupSelector (upd, gre_name (snd (head xs))) }
1902
1903 -- Given a (field update, selector name) pair, look up the
1904 -- selector to give a field update with an unambiguous Id
1905 lookupSelector :: (LHsRecUpdField Name, Name)
1906 -> TcM (LHsRecField' (AmbiguousFieldOcc Id) (LHsExpr Name))
1907 lookupSelector (L l upd, n)
1908 = do { i <- tcLookupId n
1909 ; let L loc af = hsRecFieldLbl upd
1910 lbl = rdrNameAmbiguousFieldOcc af
1911 ; return $ L l upd { hsRecFieldLbl
1912 = L loc (Unambiguous (L loc lbl) i) } }
1913
1914
1915 -- Extract the outermost TyCon of a type, if there is one; for
1916 -- data families this is the representation tycon (because that's
1917 -- where the fields live). Look inside sigma-types, so that
1918 -- tyConOf _ (forall a. Q => T a) = T
1919 tyConOf :: FamInstEnvs -> Type -> Maybe TyCon
1920 tyConOf fam_inst_envs ty0 = case tcSplitTyConApp_maybe ty of
1921 Just (tc, tys) -> Just (fstOf3 (tcLookupDataFamInst fam_inst_envs tc tys))
1922 Nothing -> Nothing
1923 where
1924 (_, _, ty) = tcSplitSigmaTy ty0
1925
1926 -- For an ambiguous record field, find all the candidate record
1927 -- selectors (as GlobalRdrElts) and their parents.
1928 lookupParents :: RdrName -> RnM [(RecSelParent, GlobalRdrElt)]
1929 lookupParents rdr
1930 = do { env <- getGlobalRdrEnv
1931 ; let gres = lookupGRE_RdrName rdr env
1932 ; mapM lookupParent gres }
1933 where
1934 lookupParent :: GlobalRdrElt -> RnM (RecSelParent, GlobalRdrElt)
1935 lookupParent gre = do { id <- tcLookupId (gre_name gre)
1936 ; if isRecordSelector id
1937 then return (recordSelectorTyCon id, gre)
1938 else failWithTc (notSelector (gre_name gre)) }
1939
1940 -- A type signature on the argument of an ambiguous record selector or
1941 -- the record expression in an update must be "obvious", i.e. the
1942 -- outermost constructor ignoring parentheses.
1943 obviousSig :: HsExpr Name -> Maybe (LHsSigWcType Name)
1944 obviousSig (ExprWithTySig _ ty) = Just ty
1945 obviousSig (HsPar p) = obviousSig (unLoc p)
1946 obviousSig _ = Nothing
1947
1948
1949 {-
1950 Game plan for record bindings
1951 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1952 1. Find the TyCon for the bindings, from the first field label.
1953
1954 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1955
1956 For each binding field = value
1957
1958 3. Instantiate the field type (from the field label) using the type
1959 envt from step 2.
1960
1961 4 Type check the value using tcArg, passing the field type as
1962 the expected argument type.
1963
1964 This extends OK when the field types are universally quantified.
1965 -}
1966
1967 tcRecordBinds
1968 :: ConLike
1969 -> [TcType] -- Expected type for each field
1970 -> HsRecordBinds Name
1971 -> TcM (HsRecordBinds TcId)
1972
1973 tcRecordBinds con_like arg_tys (HsRecFields rbinds dd)
1974 = do { mb_binds <- mapM do_bind rbinds
1975 ; return (HsRecFields (catMaybes mb_binds) dd) }
1976 where
1977 fields = map flLabel $ conLikeFieldLabels con_like
1978 flds_w_tys = zipEqual "tcRecordBinds" fields arg_tys
1979
1980 do_bind :: LHsRecField Name (LHsExpr Name)
1981 -> TcM (Maybe (LHsRecField TcId (LHsExpr TcId)))
1982 do_bind (L l fld@(HsRecField { hsRecFieldLbl = f
1983 , hsRecFieldArg = rhs }))
1984
1985 = do { mb <- tcRecordField con_like flds_w_tys f rhs
1986 ; case mb of
1987 Nothing -> return Nothing
1988 Just (f', rhs') -> return (Just (L l (fld { hsRecFieldLbl = f'
1989 , hsRecFieldArg = rhs' }))) }
1990
1991 tcRecordUpd
1992 :: ConLike
1993 -> [TcType] -- Expected type for each field
1994 -> [LHsRecField' (AmbiguousFieldOcc Id) (LHsExpr Name)]
1995 -> TcM [LHsRecUpdField TcId]
1996
1997 tcRecordUpd con_like arg_tys rbinds = fmap catMaybes $ mapM do_bind rbinds
1998 where
1999 flds_w_tys = zipEqual "tcRecordUpd" (map flLabel $ conLikeFieldLabels con_like) arg_tys
2000
2001 do_bind :: LHsRecField' (AmbiguousFieldOcc Id) (LHsExpr Name) -> TcM (Maybe (LHsRecUpdField TcId))
2002 do_bind (L l fld@(HsRecField { hsRecFieldLbl = L loc af
2003 , hsRecFieldArg = rhs }))
2004 = do { let lbl = rdrNameAmbiguousFieldOcc af
2005 sel_id = selectorAmbiguousFieldOcc af
2006 f = L loc (FieldOcc (L loc lbl) (idName sel_id))
2007 ; mb <- tcRecordField con_like flds_w_tys f rhs
2008 ; case mb of
2009 Nothing -> return Nothing
2010 Just (f', rhs') ->
2011 return (Just
2012 (L l (fld { hsRecFieldLbl
2013 = L loc (Unambiguous (L loc lbl)
2014 (selectorFieldOcc (unLoc f')))
2015 , hsRecFieldArg = rhs' }))) }
2016
2017 tcRecordField :: ConLike -> Assoc FieldLabelString Type -> LFieldOcc Name -> LHsExpr Name
2018 -> TcM (Maybe (LFieldOcc Id, LHsExpr Id))
2019 tcRecordField con_like flds_w_tys (L loc (FieldOcc lbl sel_name)) rhs
2020 | Just field_ty <- assocMaybe flds_w_tys field_lbl
2021 = addErrCtxt (fieldCtxt field_lbl) $
2022 do { rhs' <- tcPolyExprNC rhs field_ty
2023 ; let field_id = mkUserLocal (nameOccName sel_name)
2024 (nameUnique sel_name)
2025 field_ty loc
2026 -- Yuk: the field_id has the *unique* of the selector Id
2027 -- (so we can find it easily)
2028 -- but is a LocalId with the appropriate type of the RHS
2029 -- (so the desugarer knows the type of local binder to make)
2030 ; return (Just (L loc (FieldOcc lbl field_id), rhs')) }
2031 | otherwise
2032 = do { addErrTc (badFieldCon con_like field_lbl)
2033 ; return Nothing }
2034 where
2035 field_lbl = occNameFS $ rdrNameOcc (unLoc lbl)
2036
2037
2038 checkMissingFields :: ConLike -> HsRecordBinds Name -> TcM ()
2039 checkMissingFields con_like rbinds
2040 | null field_labels -- Not declared as a record;
2041 -- But C{} is still valid if no strict fields
2042 = if any isBanged field_strs then
2043 -- Illegal if any arg is strict
2044 addErrTc (missingStrictFields con_like [])
2045 else
2046 return ()
2047
2048 | otherwise = do -- A record
2049 unless (null missing_s_fields)
2050 (addErrTc (missingStrictFields con_like missing_s_fields))
2051
2052 warn <- woptM Opt_WarnMissingFields
2053 unless (not (warn && notNull missing_ns_fields))
2054 (warnTc True (missingFields con_like missing_ns_fields))
2055
2056 where
2057 missing_s_fields
2058 = [ flLabel fl | (fl, str) <- field_info,
2059 isBanged str,
2060 not (fl `elemField` field_names_used)
2061 ]
2062 missing_ns_fields
2063 = [ flLabel fl | (fl, str) <- field_info,
2064 not (isBanged str),
2065 not (fl `elemField` field_names_used)
2066 ]
2067
2068 field_names_used = hsRecFields rbinds
2069 field_labels = conLikeFieldLabels con_like
2070
2071 field_info = zipEqual "missingFields"
2072 field_labels
2073 field_strs
2074
2075 field_strs = conLikeImplBangs con_like
2076
2077 fl `elemField` flds = any (\ fl' -> flSelector fl == fl') flds
2078
2079 {-
2080 ************************************************************************
2081 * *
2082 \subsection{Errors and contexts}
2083 * *
2084 ************************************************************************
2085
2086 Boring and alphabetical:
2087 -}
2088
2089 addExprErrCtxt :: LHsExpr Name -> TcM a -> TcM a
2090 addExprErrCtxt expr = addErrCtxt (exprCtxt expr)
2091
2092 exprCtxt :: LHsExpr Name -> SDoc
2093 exprCtxt expr
2094 = hang (text "In the expression:") 2 (ppr expr)
2095
2096 fieldCtxt :: FieldLabelString -> SDoc
2097 fieldCtxt field_name
2098 = text "In the" <+> quotes (ppr field_name) <+> ptext (sLit "field of a record")
2099
2100 addFunResCtxt :: Bool -- There is at least one argument
2101 -> HsExpr Name -> TcType -> TcType
2102 -> TcM a -> TcM a
2103 -- When we have a mis-match in the return type of a function
2104 -- try to give a helpful message about too many/few arguments
2105 --
2106 -- Used for naked variables too; but with has_args = False
2107 addFunResCtxt has_args fun fun_res_ty env_ty
2108 = addLandmarkErrCtxtM (\env -> (env, ) <$> mk_msg)
2109 -- NB: use a landmark error context, so that an empty context
2110 -- doesn't suppress some more useful context
2111 where
2112 mk_msg
2113 = do { fun_res' <- zonkTcType fun_res_ty
2114 ; env' <- zonkTcType env_ty
2115 ; let (_, _, fun_tau) = tcSplitSigmaTy fun_res'
2116 (_, _, env_tau) = tcSplitSigmaTy env'
2117 (args_fun, res_fun) = tcSplitFunTys fun_tau
2118 (args_env, res_env) = tcSplitFunTys env_tau
2119 n_fun = length args_fun
2120 n_env = length args_env
2121 info | n_fun == n_env = Outputable.empty
2122 | n_fun > n_env
2123 , not_fun res_env
2124 = text "Probable cause:" <+> quotes (ppr fun)
2125 <+> text "is applied to too few arguments"
2126
2127 | has_args
2128 , not_fun res_fun
2129 = text "Possible cause:" <+> quotes (ppr fun)
2130 <+> text "is applied to too many arguments"
2131
2132 | otherwise
2133 = Outputable.empty -- Never suggest that a naked variable is -- applied to too many args!
2134 ; return info }
2135 where
2136 not_fun ty -- ty is definitely not an arrow type,
2137 -- and cannot conceivably become one
2138 = case tcSplitTyConApp_maybe ty of
2139 Just (tc, _) -> isAlgTyCon tc
2140 Nothing -> False
2141
2142 badFieldTypes :: [(FieldLabelString,TcType)] -> SDoc
2143 badFieldTypes prs
2144 = hang (text "Record update for insufficiently polymorphic field"
2145 <> plural prs <> colon)
2146 2 (vcat [ ppr f <+> dcolon <+> ppr ty | (f,ty) <- prs ])
2147
2148 badFieldsUpd
2149 :: [LHsRecField' (AmbiguousFieldOcc Id) (LHsExpr Name)] -- Field names that don't belong to a single datacon
2150 -> [ConLike] -- Data cons of the type which the first field name belongs to
2151 -> SDoc
2152 badFieldsUpd rbinds data_cons
2153 = hang (text "No constructor has all these fields:")
2154 2 (pprQuotedList conflictingFields)
2155 -- See Note [Finding the conflicting fields]
2156 where
2157 -- A (preferably small) set of fields such that no constructor contains
2158 -- all of them. See Note [Finding the conflicting fields]
2159 conflictingFields = case nonMembers of
2160 -- nonMember belongs to a different type.
2161 (nonMember, _) : _ -> [aMember, nonMember]
2162 [] -> let
2163 -- All of rbinds belong to one type. In this case, repeatedly add
2164 -- a field to the set until no constructor contains the set.
2165
2166 -- Each field, together with a list indicating which constructors
2167 -- have all the fields so far.
2168 growingSets :: [(FieldLabelString, [Bool])]
2169 growingSets = scanl1 combine membership
2170 combine (_, setMem) (field, fldMem)
2171 = (field, zipWith (&&) setMem fldMem)
2172 in
2173 -- Fields that don't change the membership status of the set
2174 -- are redundant and can be dropped.
2175 map (fst . head) $ groupBy ((==) `on` snd) growingSets
2176
2177 aMember = ASSERT( not (null members) ) fst (head members)
2178 (members, nonMembers) = partition (or . snd) membership
2179
2180 -- For each field, which constructors contain the field?
2181 membership :: [(FieldLabelString, [Bool])]
2182 membership = sortMembership $
2183 map (\fld -> (fld, map (Set.member fld) fieldLabelSets)) $
2184 map (occNameFS . rdrNameOcc . rdrNameAmbiguousFieldOcc . unLoc . hsRecFieldLbl . unLoc) rbinds
2185
2186 fieldLabelSets :: [Set.Set FieldLabelString]
2187 fieldLabelSets = map (Set.fromList . map flLabel . conLikeFieldLabels) data_cons
2188
2189 -- Sort in order of increasing number of True, so that a smaller
2190 -- conflicting set can be found.
2191 sortMembership =
2192 map snd .
2193 sortBy (compare `on` fst) .
2194 map (\ item@(_, membershipRow) -> (countTrue membershipRow, item))
2195
2196 countTrue = length . filter id
2197
2198 {-
2199 Note [Finding the conflicting fields]
2200 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2201 Suppose we have
2202 data A = A {a0, a1 :: Int}
2203 | B {b0, b1 :: Int}
2204 and we see a record update
2205 x { a0 = 3, a1 = 2, b0 = 4, b1 = 5 }
2206 Then we'd like to find the smallest subset of fields that no
2207 constructor has all of. Here, say, {a0,b0}, or {a0,b1}, etc.
2208 We don't really want to report that no constructor has all of
2209 {a0,a1,b0,b1}, because when there are hundreds of fields it's
2210 hard to see what was really wrong.
2211
2212 We may need more than two fields, though; eg
2213 data T = A { x,y :: Int, v::Int }
2214 | B { y,z :: Int, v::Int }
2215 | C { z,x :: Int, v::Int }
2216 with update
2217 r { x=e1, y=e2, z=e3 }, we
2218
2219 Finding the smallest subset is hard, so the code here makes
2220 a decent stab, no more. See Trac #7989.
2221 -}
2222
2223 naughtyRecordSel :: RdrName -> SDoc
2224 naughtyRecordSel sel_id
2225 = text "Cannot use record selector" <+> quotes (ppr sel_id) <+>
2226 text "as a function due to escaped type variables" $$
2227 text "Probable fix: use pattern-matching syntax instead"
2228
2229 notSelector :: Name -> SDoc
2230 notSelector field
2231 = hsep [quotes (ppr field), text "is not a record selector"]
2232
2233 mixedSelectors :: [Id] -> [Id] -> SDoc
2234 mixedSelectors data_sels@(dc_rep_id:_) pat_syn_sels@(ps_rep_id:_)
2235 = ptext
2236 (sLit "Cannot use a mixture of pattern synonym and record selectors") $$
2237 text "Record selectors defined by"
2238 <+> quotes (ppr (tyConName rep_dc))
2239 <> text ":"
2240 <+> pprWithCommas ppr data_sels $$
2241 text "Pattern synonym selectors defined by"
2242 <+> quotes (ppr (patSynName rep_ps))
2243 <> text ":"
2244 <+> pprWithCommas ppr pat_syn_sels
2245 where
2246 RecSelPatSyn rep_ps = recordSelectorTyCon ps_rep_id
2247 RecSelData rep_dc = recordSelectorTyCon dc_rep_id
2248 mixedSelectors _ _ = panic "TcExpr: mixedSelectors emptylists"
2249
2250
2251 missingStrictFields :: ConLike -> [FieldLabelString] -> SDoc
2252 missingStrictFields con fields
2253 = header <> rest
2254 where
2255 rest | null fields = Outputable.empty -- Happens for non-record constructors
2256 -- with strict fields
2257 | otherwise = colon <+> pprWithCommas ppr fields
2258
2259 header = text "Constructor" <+> quotes (ppr con) <+>
2260 text "does not have the required strict field(s)"
2261
2262 missingFields :: ConLike -> [FieldLabelString] -> SDoc
2263 missingFields con fields
2264 = text "Fields of" <+> quotes (ppr con) <+> ptext (sLit "not initialised:")
2265 <+> pprWithCommas ppr fields
2266
2267 -- callCtxt fun args = text "In the call" <+> parens (ppr (foldl mkHsApp fun args))
2268
2269 noPossibleParents :: [LHsRecUpdField Name] -> SDoc
2270 noPossibleParents rbinds
2271 = hang (text "No type has all these fields:")
2272 2 (pprQuotedList fields)
2273 where
2274 fields = map (hsRecFieldLbl . unLoc) rbinds
2275
2276 badOverloadedUpdate :: SDoc
2277 badOverloadedUpdate = text "Record update is ambiguous, and requires a type signature"
2278
2279 fieldNotInType :: RecSelParent -> RdrName -> SDoc
2280 fieldNotInType p rdr
2281 = unknownSubordinateErr (text "field of type" <+> quotes (ppr p)) rdr