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