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