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