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