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