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