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