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