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