Expand and implement Note [The tcType invariant]
[ghc.git] / compiler / typecheck / TcHsType.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5 \section[TcMonoType]{Typechecking user-specified @MonoTypes@}
6 -}
7
8 {-# LANGUAGE CPP, TupleSections, MultiWayIf, RankNTypes #-}
9 {-# LANGUAGE ScopedTypeVariables #-}
10
11 module TcHsType (
12 -- Type signatures
13 kcHsSigType, tcClassSigType,
14 tcHsSigType, tcHsSigWcType,
15 tcHsPartialSigType,
16 funsSigCtxt, addSigCtxt, pprSigCtxt,
17
18 tcHsClsInstType,
19 tcHsDeriv, tcDerivStrategy,
20 tcHsTypeApp,
21 UserTypeCtxt(..),
22 tcImplicitTKBndrs, tcImplicitQTKBndrs,
23 tcExplicitTKBndrs,
24 kcExplicitTKBndrs, kcImplicitTKBndrs,
25
26 -- Type checking type and class decls
27 kcLookupTcTyCon, kcTyClTyVars, tcTyClTyVars,
28 tcDataKindSig,
29
30 -- tyvars
31 scopeTyVars, scopeTyVars2,
32
33 -- Kind-checking types
34 -- No kind generalisation, no checkValidType
35 kcLHsQTyVars,
36 tcWildCardBinders,
37 tcHsLiftedType, tcHsOpenType,
38 tcHsLiftedTypeNC, tcHsOpenTypeNC,
39 tcLHsType, tcLHsTypeUnsaturated, tcCheckLHsType,
40 tcHsMbContext, tcHsContext, tcLHsPredType, tcInferApps,
41 solveEqualities, -- useful re-export
42
43 typeLevelMode, kindLevelMode,
44
45 kindGeneralize, checkExpectedKindX, instantiateTyUntilN,
46 reportFloatingKvs,
47
48 -- Sort-checking kinds
49 tcLHsKindSig, badKindSig,
50
51 -- Zonking and promoting
52 zonkPromoteType,
53
54 -- Pattern type signatures
55 tcHsPatSigType, tcPatSig, funAppCtxt
56 ) where
57
58 #include "HsVersions.h"
59
60 import GhcPrelude
61
62 import HsSyn
63 import TcRnMonad
64 import TcEvidence
65 import TcEnv
66 import TcMType
67 import TcValidity
68 import TcUnify
69 import TcIface
70 import TcSimplify
71 import TcType
72 import TcHsSyn( zonkSigType )
73 import Inst ( tcInstTyBinders, tcInstTyBinder )
74 import TyCoRep( TyBinder(..) ) -- Used in tcDataKindSig
75 import Type
76 import Coercion
77 import Kind
78 import RdrName( lookupLocalRdrOcc )
79 import Var
80 import VarSet
81 import TyCon
82 import ConLike
83 import DataCon
84 import Class
85 import Name
86 import NameEnv
87 import NameSet
88 import VarEnv
89 import TysWiredIn
90 import BasicTypes
91 import SrcLoc
92 import Constants ( mAX_CTUPLE_SIZE )
93 import ErrUtils( MsgDoc )
94 import Unique
95 import Util
96 import UniqSupply
97 import Outputable
98 import FastString
99 import PrelNames hiding ( wildCardName )
100 import qualified GHC.LanguageExtensions as LangExt
101
102 import Maybes
103 import Data.List ( find, mapAccumR )
104 import Control.Monad
105
106 {-
107 ----------------------------
108 General notes
109 ----------------------------
110
111 Unlike with expressions, type-checking types both does some checking and
112 desugars at the same time. This is necessary because we often want to perform
113 equality checks on the types right away, and it would be incredibly painful
114 to do this on un-desugared types. Luckily, desugared types are close enough
115 to HsTypes to make the error messages sane.
116
117 During type-checking, we perform as little validity checking as possible.
118 This is because some type-checking is done in a mutually-recursive knot, and
119 if we look too closely at the tycons, we'll loop. This is why we always must
120 use mkNakedTyConApp and mkNakedAppTys, etc., which never look at a tycon.
121 The mkNamed... functions don't uphold Type invariants, but zonkTcTypeToType
122 will repair this for us. Note that zonkTcType *is* safe within a knot, and
123 can be done repeatedly with no ill effect: it just squeezes out metavariables.
124
125 Generally, after type-checking, you will want to do validity checking, say
126 with TcValidity.checkValidType.
127
128 Validity checking
129 ~~~~~~~~~~~~~~~~~
130 Some of the validity check could in principle be done by the kind checker,
131 but not all:
132
133 - During desugaring, we normalise by expanding type synonyms. Only
134 after this step can we check things like type-synonym saturation
135 e.g. type T k = k Int
136 type S a = a
137 Then (T S) is ok, because T is saturated; (T S) expands to (S Int);
138 and then S is saturated. This is a GHC extension.
139
140 - Similarly, also a GHC extension, we look through synonyms before complaining
141 about the form of a class or instance declaration
142
143 - Ambiguity checks involve functional dependencies, and it's easier to wait
144 until knots have been resolved before poking into them
145
146 Also, in a mutually recursive group of types, we can't look at the TyCon until we've
147 finished building the loop. So to keep things simple, we postpone most validity
148 checking until step (3).
149
150 Knot tying
151 ~~~~~~~~~~
152 During step (1) we might fault in a TyCon defined in another module, and it might
153 (via a loop) refer back to a TyCon defined in this module. So when we tie a big
154 knot around type declarations with ARecThing, so that the fault-in code can get
155 the TyCon being defined.
156
157 %************************************************************************
158 %* *
159 Check types AND do validity checking
160 * *
161 ************************************************************************
162 -}
163
164 funsSigCtxt :: [Located Name] -> UserTypeCtxt
165 -- Returns FunSigCtxt, with no redundant-context-reporting,
166 -- form a list of located names
167 funsSigCtxt (L _ name1 : _) = FunSigCtxt name1 False
168 funsSigCtxt [] = panic "funSigCtxt"
169
170 addSigCtxt :: UserTypeCtxt -> LHsType GhcRn -> TcM a -> TcM a
171 addSigCtxt ctxt hs_ty thing_inside
172 = setSrcSpan (getLoc hs_ty) $
173 addErrCtxt (pprSigCtxt ctxt hs_ty) $
174 thing_inside
175
176 pprSigCtxt :: UserTypeCtxt -> LHsType GhcRn -> SDoc
177 -- (pprSigCtxt ctxt <extra> <type>)
178 -- prints In the type signature for 'f':
179 -- f :: <type>
180 -- The <extra> is either empty or "the ambiguity check for"
181 pprSigCtxt ctxt hs_ty
182 | Just n <- isSigMaybe ctxt
183 = hang (text "In the type signature:")
184 2 (pprPrefixOcc n <+> dcolon <+> ppr hs_ty)
185
186 | otherwise
187 = hang (text "In" <+> pprUserTypeCtxt ctxt <> colon)
188 2 (ppr hs_ty)
189
190 tcHsSigWcType :: UserTypeCtxt -> LHsSigWcType GhcRn -> TcM Type
191 -- This one is used when we have a LHsSigWcType, but in
192 -- a place where wildards aren't allowed. The renamer has
193 -- already checked this, so we can simply ignore it.
194 tcHsSigWcType ctxt sig_ty = tcHsSigType ctxt (dropWildCards sig_ty)
195
196 kcHsSigType :: SkolemInfo -> [Located Name] -> LHsSigType GhcRn -> TcM ()
197 kcHsSigType skol_info names (HsIB { hsib_body = hs_ty
198 , hsib_ext = HsIBRn { hsib_vars = sig_vars }})
199 = addSigCtxt (funsSigCtxt names) hs_ty $
200 discardResult $
201 tcImplicitTKBndrs skol_info sig_vars $
202 tc_lhs_type typeLevelMode hs_ty liftedTypeKind
203 kcHsSigType _ _ (XHsImplicitBndrs _) = panic "kcHsSigType"
204
205 tcClassSigType :: SkolemInfo -> [Located Name] -> LHsSigType GhcRn -> TcM Type
206 -- Does not do validity checking; this must be done outside
207 -- the recursive class declaration "knot"
208 tcClassSigType skol_info names sig_ty
209 = addSigCtxt (funsSigCtxt names) (hsSigType sig_ty) $
210 tc_hs_sig_type_and_gen skol_info sig_ty liftedTypeKind
211
212 tcHsSigType :: UserTypeCtxt -> LHsSigType GhcRn -> TcM Type
213 -- Does validity checking
214 -- See Note [Recipe for checking a signature]
215 tcHsSigType ctxt sig_ty
216 = addSigCtxt ctxt (hsSigType sig_ty) $
217 do { traceTc "tcHsSigType {" (ppr sig_ty)
218 ; kind <- case expectedKindInCtxt ctxt of
219 AnythingKind -> newMetaKindVar
220 TheKind k -> return k
221 OpenKind -> newOpenTypeKind
222 -- The kind is checked by checkValidType, and isn't necessarily
223 -- of kind * in a Template Haskell quote eg [t| Maybe |]
224
225 -- Generalise here: see Note [Kind generalisation]
226 ; do_kind_gen <- decideKindGeneralisationPlan sig_ty
227 ; ty <- if do_kind_gen
228 then tc_hs_sig_type_and_gen skol_info sig_ty kind
229 else tc_hs_sig_type skol_info sig_ty kind
230
231 ; checkValidType ctxt ty
232 ; traceTc "end tcHsSigType }" (ppr ty)
233 ; return ty }
234 where
235 skol_info = SigTypeSkol ctxt
236
237 tc_hs_sig_type_and_gen :: SkolemInfo -> LHsSigType GhcRn -> Kind -> TcM Type
238 -- Kind-checks/desugars an 'LHsSigType',
239 -- solve equalities,
240 -- and then kind-generalizes.
241 -- This will never emit constraints, as it uses solveEqualities interally.
242 -- No validity checking, but it does zonk en route to generalization
243 tc_hs_sig_type_and_gen skol_info (HsIB { hsib_ext
244 = HsIBRn { hsib_vars = sig_vars }
245 , hsib_body = hs_ty }) kind
246 = do { (tkvs, ty) <- solveEqualities $
247 tcImplicitTKBndrs skol_info sig_vars $
248 tc_lhs_type typeLevelMode hs_ty kind
249 -- NB the call to solveEqualities, which unifies all those
250 -- kind variables floating about, immediately prior to
251 -- kind generalisation
252
253 -- We use the "InKnot" zonker, because this is called
254 -- on class method sigs in the knot
255 ; ty1 <- zonkPromoteTypeInKnot $ mkSpecForAllTys tkvs ty
256 ; kvs <- kindGeneralize ty1
257 ; zonkSigType (mkInvForAllTys kvs ty1) }
258
259 tc_hs_sig_type_and_gen _ (XHsImplicitBndrs _) _ = panic "tc_hs_sig_type_and_gen"
260
261 tc_hs_sig_type :: SkolemInfo -> LHsSigType GhcRn -> Kind -> TcM Type
262 -- Kind-check/desugar a 'LHsSigType', but does not solve
263 -- the equalities that arise from doing so; instead it may
264 -- emit kind-equality constraints into the monad
265 -- Zonking, but no validity checking
266 tc_hs_sig_type skol_info (HsIB { hsib_ext = HsIBRn { hsib_vars = sig_vars }
267 , hsib_body = hs_ty }) kind
268 = do { (tkvs, ty) <- tcImplicitTKBndrs skol_info sig_vars $
269 tc_lhs_type typeLevelMode hs_ty kind
270
271 -- need to promote any remaining metavariables; test case:
272 -- dependent/should_fail/T14066e.
273 ; zonkPromoteType (mkSpecForAllTys tkvs ty) }
274
275 tc_hs_sig_type _ (XHsImplicitBndrs _) _ = panic "tc_hs_sig_type"
276
277 -----------------
278 tcHsDeriv :: LHsSigType GhcRn -> TcM ([TyVar], (Class, [Type], [Kind]))
279 -- Like tcHsSigType, but for the ...deriving( C t1 ty2 ) clause
280 -- Returns the C, [ty1, ty2, and the kinds of C's remaining arguments
281 -- E.g. class C (a::*) (b::k->k)
282 -- data T a b = ... deriving( C Int )
283 -- returns ([k], C, [k, Int], [k->k])
284 tcHsDeriv hs_ty
285 = do { cls_kind <- newMetaKindVar
286 -- always safe to kind-generalize, because there
287 -- can be no covars in an outer scope
288 ; ty <- checkNoErrs $
289 -- avoid redundant error report with "illegal deriving", below
290 tc_hs_sig_type_and_gen (SigTypeSkol DerivClauseCtxt) hs_ty cls_kind
291 ; cls_kind <- zonkTcType cls_kind
292 ; let (tvs, pred) = splitForAllTys ty
293 ; let (args, _) = splitFunTys cls_kind
294 ; case getClassPredTys_maybe pred of
295 Just (cls, tys) -> return (tvs, (cls, tys, args))
296 Nothing -> failWithTc (text "Illegal deriving item" <+> quotes (ppr hs_ty)) }
297
298 -- | Typecheck something within the context of a deriving strategy.
299 -- This is of particular importance when the deriving strategy is @via@.
300 -- For instance:
301 --
302 -- @
303 -- deriving via (S a) instance C (T a)
304 -- @
305 --
306 -- We need to typecheck @S a@, and moreover, we need to extend the tyvar
307 -- environment with @a@ before typechecking @C (T a)@, since @S a@ quantified
308 -- the type variable @a@.
309 tcDerivStrategy
310 :: forall a.
311 UserTypeCtxt
312 -> Maybe (DerivStrategy GhcRn) -- ^ The deriving strategy
313 -> TcM ([TyVar], a) -- ^ The thing to typecheck within the context of the
314 -- deriving strategy, which might quantify some type
315 -- variables of its own.
316 -> TcM (Maybe (DerivStrategy GhcTc), [TyVar], a)
317 -- ^ The typechecked deriving strategy, all quantified tyvars, and
318 -- the payload of the typechecked thing.
319 tcDerivStrategy user_ctxt mds thing_inside
320 = case mds of
321 Nothing -> boring_case Nothing
322 Just ds -> do (ds', tvs, thing) <- tc_deriv_strategy ds
323 pure (Just ds', tvs, thing)
324 where
325 tc_deriv_strategy :: DerivStrategy GhcRn
326 -> TcM (DerivStrategy GhcTc, [TyVar], a)
327 tc_deriv_strategy StockStrategy = boring_case StockStrategy
328 tc_deriv_strategy AnyclassStrategy = boring_case AnyclassStrategy
329 tc_deriv_strategy NewtypeStrategy = boring_case NewtypeStrategy
330 tc_deriv_strategy (ViaStrategy ty) = do
331 cls_kind <- newMetaKindVar
332 ty' <- checkNoErrs $
333 tc_hs_sig_type_and_gen (SigTypeSkol user_ctxt) ty cls_kind
334 let (via_tvs, via_pred) = splitForAllTys ty'
335 tcExtendTyVarEnv via_tvs $ do
336 (thing_tvs, thing) <- thing_inside
337 pure (ViaStrategy via_pred, via_tvs ++ thing_tvs, thing)
338
339 boring_case :: mds -> TcM (mds, [TyVar], a)
340 boring_case mds = do
341 (thing_tvs, thing) <- thing_inside
342 pure (mds, thing_tvs, thing)
343
344 tcHsClsInstType :: UserTypeCtxt -- InstDeclCtxt or SpecInstCtxt
345 -> LHsSigType GhcRn
346 -> TcM ([TyVar], ThetaType, Class, [Type])
347 -- Like tcHsSigType, but for a class instance declaration
348 tcHsClsInstType user_ctxt hs_inst_ty
349 = setSrcSpan (getLoc (hsSigType hs_inst_ty)) $
350 do { inst_ty <- tc_hs_sig_type_and_gen (SigTypeSkol user_ctxt) hs_inst_ty constraintKind
351 ; checkValidInstance user_ctxt hs_inst_ty inst_ty }
352
353 ----------------------------------------------
354 -- | Type-check a visible type application
355 tcHsTypeApp :: LHsWcType GhcRn -> Kind -> TcM Type
356 -- See Note [Recipe for checking a signature] in TcHsType
357 tcHsTypeApp wc_ty kind
358 | HsWC { hswc_ext = sig_wcs, hswc_body = hs_ty } <- wc_ty
359 = do { ty <- solveLocalEqualities $
360 -- We are looking at a user-written type, very like a
361 -- signature so we want to solve its equalities right now
362 tcWildCardBindersX newWildTyVar Nothing sig_wcs $ \ _ ->
363 tcCheckLHsType hs_ty kind
364 ; ty <- zonkPromoteType ty
365 ; checkValidType TypeAppCtxt ty
366 ; return ty }
367 -- NB: we don't call emitWildcardHoleConstraints here, because
368 -- we want any holes in visible type applications to be used
369 -- without fuss. No errors, warnings, extensions, etc.
370 tcHsTypeApp (XHsWildCardBndrs _) _ = panic "tcHsTypeApp"
371
372 {-
373 ************************************************************************
374 * *
375 The main kind checker: no validity checks here
376 * *
377 ************************************************************************
378
379 First a couple of simple wrappers for kcHsType
380 -}
381
382 ---------------------------
383 tcHsOpenType, tcHsLiftedType,
384 tcHsOpenTypeNC, tcHsLiftedTypeNC :: LHsType GhcRn -> TcM TcType
385 -- Used for type signatures
386 -- Do not do validity checking
387 tcHsOpenType ty = addTypeCtxt ty $ tcHsOpenTypeNC ty
388 tcHsLiftedType ty = addTypeCtxt ty $ tcHsLiftedTypeNC ty
389
390 tcHsOpenTypeNC ty = do { ek <- newOpenTypeKind
391 ; tc_lhs_type typeLevelMode ty ek }
392 tcHsLiftedTypeNC ty = tc_lhs_type typeLevelMode ty liftedTypeKind
393
394 -- Like tcHsType, but takes an expected kind
395 tcCheckLHsType :: LHsType GhcRn -> Kind -> TcM TcType
396 tcCheckLHsType hs_ty exp_kind
397 = addTypeCtxt hs_ty $
398 tc_lhs_type typeLevelMode hs_ty exp_kind
399
400 tcLHsType :: LHsType GhcRn -> TcM (TcType, TcKind)
401 -- Called from outside: set the context
402 tcLHsType ty = addTypeCtxt ty (tc_infer_lhs_type typeLevelMode ty)
403
404 -- Like tcLHsType, but use it in a context where type synonyms and type families
405 -- do not need to be saturated, like in a GHCi :kind call
406 tcLHsTypeUnsaturated :: LHsType GhcRn -> TcM (TcType, TcKind)
407 tcLHsTypeUnsaturated ty = addTypeCtxt ty (tc_infer_lhs_type mode ty)
408 where
409 mode = allowUnsaturated typeLevelMode
410
411 ---------------------------
412 -- | Should we generalise the kind of this type signature?
413 -- We *should* generalise if the type is closed
414 -- or if NoMonoLocalBinds is set. Otherwise, nope.
415 -- See Note [Kind generalisation plan]
416 decideKindGeneralisationPlan :: LHsSigType GhcRn -> TcM Bool
417 decideKindGeneralisationPlan sig_ty@(HsIB { hsib_ext
418 = HsIBRn { hsib_closed = closed } })
419 = do { mono_locals <- xoptM LangExt.MonoLocalBinds
420 ; let should_gen = not mono_locals || closed
421 ; traceTc "decideKindGeneralisationPlan"
422 (ppr sig_ty $$ text "should gen?" <+> ppr should_gen)
423 ; return should_gen }
424 decideKindGeneralisationPlan(XHsImplicitBndrs _)
425 = panic "decideKindGeneralisationPlan"
426
427 {- Note [Kind generalisation plan]
428 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
429 When should we do kind-generalisation for user-written type signature?
430 Answer: we use the same rule as for value bindings:
431
432 * We always kind-generalise if the type signature is closed
433 * Additionally, we attempt to generalise if we have NoMonoLocalBinds
434
435 Trac #13337 shows the problem if we kind-generalise an open type (i.e.
436 one that mentions in-scope type variable
437 foo :: forall k (a :: k) proxy. (Typeable k, Typeable a)
438 => proxy a -> String
439 foo _ = case eqT :: Maybe (k :~: Type) of
440 Nothing -> ...
441 Just Refl -> case eqT :: Maybe (a :~: Int) of ...
442
443 In the expression type sig on the last line, we have (a :: k)
444 but (Int :: Type). Since (:~:) is kind-homogeneous, this requires
445 k ~ *, which is true in the Refl branch of the outer case.
446
447 That equality will be solved if we allow it to float out to the
448 implication constraint for the Refl match, but not not if we aggressively
449 attempt to solve all equalities the moment they occur; that is, when
450 checking (Maybe (a :~: Int)). (NB: solveEqualities fails unless it
451 solves all the kind equalities, which is the right thing at top level.)
452
453 So here the right thing is simply not to do kind generalisation!
454
455 ************************************************************************
456 * *
457 Type-checking modes
458 * *
459 ************************************************************************
460
461 The kind-checker is parameterised by a TcTyMode, which contains some
462 information about where we're checking a type.
463
464 The renamer issues errors about what it can. All errors issued here must
465 concern things that the renamer can't handle.
466
467 -}
468
469 -- | Info about the context in which we're checking a type. Currently,
470 -- differentiates only between types and kinds, but this will likely
471 -- grow, at least to include the distinction between patterns and
472 -- not-patterns.
473 data TcTyMode
474 = TcTyMode { mode_level :: TypeOrKind
475 , mode_unsat :: Bool -- True <=> allow unsaturated type families
476 }
477 -- The mode_unsat field is solely so that type families/synonyms can be unsaturated
478 -- in GHCi :kind calls
479
480 typeLevelMode :: TcTyMode
481 typeLevelMode = TcTyMode { mode_level = TypeLevel, mode_unsat = False }
482
483 kindLevelMode :: TcTyMode
484 kindLevelMode = TcTyMode { mode_level = KindLevel, mode_unsat = False }
485
486 allowUnsaturated :: TcTyMode -> TcTyMode
487 allowUnsaturated mode = mode { mode_unsat = True }
488
489 -- switch to kind level
490 kindLevel :: TcTyMode -> TcTyMode
491 kindLevel mode = mode { mode_level = KindLevel }
492
493 instance Outputable TcTyMode where
494 ppr = ppr . mode_level
495
496 {-
497 Note [Bidirectional type checking]
498 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
499 In expressions, whenever we see a polymorphic identifier, say `id`, we are
500 free to instantiate it with metavariables, knowing that we can always
501 re-generalize with type-lambdas when necessary. For example:
502
503 rank2 :: (forall a. a -> a) -> ()
504 x = rank2 id
505
506 When checking the body of `x`, we can instantiate `id` with a metavariable.
507 Then, when we're checking the application of `rank2`, we notice that we really
508 need a polymorphic `id`, and then re-generalize over the unconstrained
509 metavariable.
510
511 In types, however, we're not so lucky, because *we cannot re-generalize*!
512 There is no lambda. So, we must be careful only to instantiate at the last
513 possible moment, when we're sure we're never going to want the lost polymorphism
514 again. This is done in calls to tcInstTyBinders.
515
516 To implement this behavior, we use bidirectional type checking, where we
517 explicitly think about whether we know the kind of the type we're checking
518 or not. Note that there is a difference between not knowing a kind and
519 knowing a metavariable kind: the metavariables are TauTvs, and cannot become
520 forall-quantified kinds. Previously (before dependent types), there were
521 no higher-rank kinds, and so we could instantiate early and be sure that
522 no types would have polymorphic kinds, and so we could always assume that
523 the kind of a type was a fresh metavariable. Not so anymore, thus the
524 need for two algorithms.
525
526 For HsType forms that can never be kind-polymorphic, we implement only the
527 "down" direction, where we safely assume a metavariable kind. For HsType forms
528 that *can* be kind-polymorphic, we implement just the "up" (functions with
529 "infer" in their name) version, as we gain nothing by also implementing the
530 "down" version.
531
532 Note [Future-proofing the type checker]
533 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
534 As discussed in Note [Bidirectional type checking], each HsType form is
535 handled in *either* tc_infer_hs_type *or* tc_hs_type. These functions
536 are mutually recursive, so that either one can work for any type former.
537 But, we want to make sure that our pattern-matches are complete. So,
538 we have a bunch of repetitive code just so that we get warnings if we're
539 missing any patterns.
540
541 Note [The tcType invariant]
542 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
543 (IT1) If tc_ty = tc_hs_type hs_ty exp_kind
544 then typeKind tc_ty = exp_kind
545 without any zonking needed. The reason for this is that in
546 tcInferApps we see (F ty), and we kind-check 'ty' with an
547 expected-kind coming from F. Then, to make the resulting application
548 well kinded --- see Note [The well-kinded type invariant] in TcType ---
549 we need the kind-checked 'ty' to have exactly the kind that F expects,
550 with no funny zonking nonsense in between.
551
552 The tcType invariant also applies to checkExpectedKind:
553
554 (IT2) if
555 (tc_ty, _, _) = checkExpectedKind ty act_ki exp_ki
556 then
557 typeKind tc_ty = exp_ki
558
559 These other invariants are all necessary, too, as these functions
560 are used within tc_hs_type:
561
562 (IT3) If (ty, ki) <- tc_infer_hs_type ..., then typeKind ty == ki.
563
564 (IT4) If (ty, ki) <- tc_infer_hs_type ..., then zonk ki == ki.
565 (In other words, the result kind of tc_infer_hs_type is zonked.)
566
567 (IT5) If (ty, ki) <- tcTyVar ..., then typeKind ty == ki.
568
569 (IT6) If (ty, ki) <- tcTyVar ..., then zonk ki == ki.
570 (In other words, the result kind of tcTyVar is zonked.)
571
572 -}
573
574 ------------------------------------------
575 -- | Check and desugar a type, returning the core type and its
576 -- possibly-polymorphic kind. Much like 'tcInferRho' at the expression
577 -- level.
578 tc_infer_lhs_type :: TcTyMode -> LHsType GhcRn -> TcM (TcType, TcKind)
579 tc_infer_lhs_type mode (L span ty)
580 = setSrcSpan span $
581 do { (ty', kind) <- tc_infer_hs_type mode ty
582 ; return (ty', kind) }
583
584 -- | Infer the kind of a type and desugar. This is the "up" type-checker,
585 -- as described in Note [Bidirectional type checking]
586 tc_infer_hs_type :: TcTyMode -> HsType GhcRn -> TcM (TcType, TcKind)
587 tc_infer_hs_type mode (HsParTy _ t) = tc_infer_lhs_type mode t
588 tc_infer_hs_type mode (HsTyVar _ _ (L _ tv)) = tcTyVar mode tv
589
590 tc_infer_hs_type mode (HsAppTy _ ty1 ty2)
591 = do { let (hs_fun_ty, hs_arg_tys) = splitHsAppTys ty1 [ty2]
592 ; (fun_ty, fun_kind) <- tc_infer_lhs_type mode hs_fun_ty
593 -- NB: (IT4) of Note [The tcType invariant] ensures that fun_kind is zonked
594 ; tcTyApps mode hs_fun_ty fun_ty fun_kind hs_arg_tys }
595
596 tc_infer_hs_type mode (HsOpTy _ lhs lhs_op@(L _ hs_op) rhs)
597 | not (hs_op `hasKey` funTyConKey)
598 = do { (op, op_kind) <- tcTyVar mode hs_op
599 ; tcTyApps mode (noLoc $ HsTyVar noExt NotPromoted lhs_op) op op_kind
600 [lhs, rhs] }
601
602 tc_infer_hs_type mode (HsKindSig _ ty sig)
603 = do { sig' <- tcLHsKindSig KindSigCtxt sig
604 -- We must typecheck the kind signature, and solve all
605 -- its equalities etc; from this point on we may do
606 -- things like instantiate its foralls, so it needs
607 -- to be fully determined (Trac #14904)
608 ; traceTc "tc_infer_hs_type:sig" (ppr ty $$ ppr sig')
609 ; ty' <- tc_lhs_type mode ty sig'
610 ; return (ty', sig') }
611
612 -- HsSpliced is an annotation produced by 'RnSplice.rnSpliceType' to communicate
613 -- the splice location to the typechecker. Here we skip over it in order to have
614 -- the same kind inferred for a given expression whether it was produced from
615 -- splices or not.
616 --
617 -- See Note [Delaying modFinalizers in untyped splices].
618 tc_infer_hs_type mode (HsSpliceTy _ (HsSpliced _ _ (HsSplicedTy ty)))
619 = tc_infer_hs_type mode ty
620
621 tc_infer_hs_type mode (HsDocTy _ ty _) = tc_infer_lhs_type mode ty
622 tc_infer_hs_type _ (XHsType (NHsCoreTy ty))
623 = do { ty <- zonkTcType ty -- (IT3) and (IT4) of Note [The tcType invariant]
624 ; return (ty, typeKind ty) }
625 tc_infer_hs_type mode other_ty
626 = do { kv <- newMetaKindVar
627 ; ty' <- tc_hs_type mode other_ty kv
628 ; return (ty', kv) }
629
630 ------------------------------------------
631 tc_lhs_type :: TcTyMode -> LHsType GhcRn -> TcKind -> TcM TcType
632 tc_lhs_type mode (L span ty) exp_kind
633 = setSrcSpan span $
634 tc_hs_type mode ty exp_kind
635
636 ------------------------------------------
637 tc_fun_type :: TcTyMode -> LHsType GhcRn -> LHsType GhcRn -> TcKind
638 -> TcM TcType
639 tc_fun_type mode ty1 ty2 exp_kind = case mode_level mode of
640 TypeLevel ->
641 do { arg_k <- newOpenTypeKind
642 ; res_k <- newOpenTypeKind
643 ; ty1' <- tc_lhs_type mode ty1 arg_k
644 ; ty2' <- tc_lhs_type mode ty2 res_k
645 ; checkExpectedKind (HsFunTy noExt ty1 ty2) (mkFunTy ty1' ty2')
646 liftedTypeKind exp_kind }
647 KindLevel -> -- no representation polymorphism in kinds. yet.
648 do { ty1' <- tc_lhs_type mode ty1 liftedTypeKind
649 ; ty2' <- tc_lhs_type mode ty2 liftedTypeKind
650 ; checkExpectedKind (HsFunTy noExt ty1 ty2) (mkFunTy ty1' ty2')
651 liftedTypeKind exp_kind }
652
653 ------------------------------------------
654 tc_hs_type :: TcTyMode -> HsType GhcRn -> TcKind -> TcM TcType
655 -- See Note [The tcType invariant]
656 -- See Note [Bidirectional type checking]
657
658 tc_hs_type mode (HsParTy _ ty) exp_kind = tc_lhs_type mode ty exp_kind
659 tc_hs_type mode (HsDocTy _ ty _) exp_kind = tc_lhs_type mode ty exp_kind
660 tc_hs_type _ ty@(HsBangTy _ bang _) _
661 -- While top-level bangs at this point are eliminated (eg !(Maybe Int)),
662 -- other kinds of bangs are not (eg ((!Maybe) Int)). These kinds of
663 -- bangs are invalid, so fail. (#7210, #14761)
664 = do { let bangError err = failWith $
665 text "Unexpected" <+> text err <+> text "annotation:" <+> ppr ty $$
666 text err <+> text "annotation cannot appear nested inside a type"
667 ; case bang of
668 HsSrcBang _ SrcUnpack _ -> bangError "UNPACK"
669 HsSrcBang _ SrcNoUnpack _ -> bangError "NOUNPACK"
670 HsSrcBang _ NoSrcUnpack SrcLazy -> bangError "laziness"
671 HsSrcBang _ _ _ -> bangError "strictness" }
672 tc_hs_type _ ty@(HsRecTy {}) _
673 -- Record types (which only show up temporarily in constructor
674 -- signatures) should have been removed by now
675 = failWithTc (text "Record syntax is illegal here:" <+> ppr ty)
676
677 -- HsSpliced is an annotation produced by 'RnSplice.rnSpliceType'.
678 -- Here we get rid of it and add the finalizers to the global environment
679 -- while capturing the local environment.
680 --
681 -- See Note [Delaying modFinalizers in untyped splices].
682 tc_hs_type mode (HsSpliceTy _ (HsSpliced _ mod_finalizers (HsSplicedTy ty)))
683 exp_kind
684 = do addModFinalizersWithLclEnv mod_finalizers
685 tc_hs_type mode ty exp_kind
686
687 -- This should never happen; type splices are expanded by the renamer
688 tc_hs_type _ ty@(HsSpliceTy {}) _exp_kind
689 = failWithTc (text "Unexpected type splice:" <+> ppr ty)
690
691 ---------- Functions and applications
692 tc_hs_type mode (HsFunTy _ ty1 ty2) exp_kind
693 = tc_fun_type mode ty1 ty2 exp_kind
694
695 tc_hs_type mode (HsOpTy _ ty1 (L _ op) ty2) exp_kind
696 | op `hasKey` funTyConKey
697 = tc_fun_type mode ty1 ty2 exp_kind
698
699 --------- Foralls
700 tc_hs_type mode forall@(HsForAllTy { hst_bndrs = hs_tvs, hst_body = ty }) exp_kind
701 = do { (tvs', ty') <- tcExplicitTKBndrs (ForAllSkol (ppr forall)) hs_tvs $
702 tc_lhs_type mode ty exp_kind
703 -- Do not kind-generalise here! See Note [Kind generalisation]
704 -- Why exp_kind? See Note [Body kind of HsForAllTy]
705 ; let bndrs = mkTyVarBinders Specified tvs'
706 ; return (mkForAllTys bndrs ty') }
707
708 tc_hs_type mode (HsQualTy { hst_ctxt = ctxt, hst_body = ty }) exp_kind
709 | null (unLoc ctxt)
710 = tc_lhs_type mode ty exp_kind
711
712 | otherwise
713 = do { ctxt' <- tc_hs_context mode ctxt
714
715 -- See Note [Body kind of a HsQualTy]
716 ; ty' <- if isConstraintKind exp_kind
717 then tc_lhs_type mode ty constraintKind
718 else do { ek <- newOpenTypeKind
719 -- The body kind (result of the function)
720 -- can be TYPE r, for any r, hence newOpenTypeKind
721 ; ty' <- tc_lhs_type mode ty ek
722 ; checkExpectedKind (unLoc ty) ty' liftedTypeKind exp_kind }
723
724 ; return (mkPhiTy ctxt' ty') }
725
726 --------- Lists, arrays, and tuples
727 tc_hs_type mode rn_ty@(HsListTy _ elt_ty) exp_kind
728 = do { tau_ty <- tc_lhs_type mode elt_ty liftedTypeKind
729 ; checkWiredInTyCon listTyCon
730 ; checkExpectedKind rn_ty (mkListTy tau_ty) liftedTypeKind exp_kind }
731
732 -- See Note [Distinguishing tuple kinds] in HsTypes
733 -- See Note [Inferring tuple kinds]
734 tc_hs_type mode rn_ty@(HsTupleTy _ HsBoxedOrConstraintTuple hs_tys) exp_kind
735 -- (NB: not zonking before looking at exp_k, to avoid left-right bias)
736 | Just tup_sort <- tupKindSort_maybe exp_kind
737 = traceTc "tc_hs_type tuple" (ppr hs_tys) >>
738 tc_tuple rn_ty mode tup_sort hs_tys exp_kind
739 | otherwise
740 = do { traceTc "tc_hs_type tuple 2" (ppr hs_tys)
741 ; (tys, kinds) <- mapAndUnzipM (tc_infer_lhs_type mode) hs_tys
742 ; kinds <- mapM zonkTcType kinds
743 -- Infer each arg type separately, because errors can be
744 -- confusing if we give them a shared kind. Eg Trac #7410
745 -- (Either Int, Int), we do not want to get an error saying
746 -- "the second argument of a tuple should have kind *->*"
747
748 ; let (arg_kind, tup_sort)
749 = case [ (k,s) | k <- kinds
750 , Just s <- [tupKindSort_maybe k] ] of
751 ((k,s) : _) -> (k,s)
752 [] -> (liftedTypeKind, BoxedTuple)
753 -- In the [] case, it's not clear what the kind is, so guess *
754
755 ; tys' <- sequence [ setSrcSpan loc $
756 checkExpectedKind hs_ty ty kind arg_kind
757 | ((L loc hs_ty),ty,kind) <- zip3 hs_tys tys kinds ]
758
759 ; finish_tuple rn_ty tup_sort tys' (map (const arg_kind) tys') exp_kind }
760
761
762 tc_hs_type mode rn_ty@(HsTupleTy _ hs_tup_sort tys) exp_kind
763 = tc_tuple rn_ty mode tup_sort tys exp_kind
764 where
765 tup_sort = case hs_tup_sort of -- Fourth case dealt with above
766 HsUnboxedTuple -> UnboxedTuple
767 HsBoxedTuple -> BoxedTuple
768 HsConstraintTuple -> ConstraintTuple
769 _ -> panic "tc_hs_type HsTupleTy"
770
771 tc_hs_type mode rn_ty@(HsSumTy _ hs_tys) exp_kind
772 = do { let arity = length hs_tys
773 ; arg_kinds <- mapM (\_ -> newOpenTypeKind) hs_tys
774 ; tau_tys <- zipWithM (tc_lhs_type mode) hs_tys arg_kinds
775 ; let arg_reps = map getRuntimeRepFromKind arg_kinds
776 arg_tys = arg_reps ++ tau_tys
777 ; checkExpectedKind rn_ty
778 (mkTyConApp (sumTyCon arity) arg_tys)
779 (unboxedSumKind arg_reps)
780 exp_kind
781 }
782
783 --------- Promoted lists and tuples
784 tc_hs_type mode rn_ty@(HsExplicitListTy _ _ tys) exp_kind
785 = do { tks <- mapM (tc_infer_lhs_type mode) tys
786 ; (taus', kind) <- unifyKinds tys tks
787 ; let ty = (foldr (mk_cons kind) (mk_nil kind) taus')
788 ; checkExpectedKind rn_ty ty (mkListTy kind) exp_kind }
789 where
790 mk_cons k a b = mkTyConApp (promoteDataCon consDataCon) [k, a, b]
791 mk_nil k = mkTyConApp (promoteDataCon nilDataCon) [k]
792
793 tc_hs_type mode rn_ty@(HsExplicitTupleTy _ tys) exp_kind
794 -- using newMetaKindVar means that we force instantiations of any polykinded
795 -- types. At first, I just used tc_infer_lhs_type, but that led to #11255.
796 = do { ks <- replicateM arity newMetaKindVar
797 ; taus <- zipWithM (tc_lhs_type mode) tys ks
798 ; let kind_con = tupleTyCon Boxed arity
799 ty_con = promotedTupleDataCon Boxed arity
800 tup_k = mkTyConApp kind_con ks
801 ; checkExpectedKind rn_ty (mkTyConApp ty_con (ks ++ taus)) tup_k exp_kind }
802 where
803 arity = length tys
804
805 --------- Constraint types
806 tc_hs_type mode rn_ty@(HsIParamTy _ (L _ n) ty) exp_kind
807 = do { MASSERT( isTypeLevel (mode_level mode) )
808 ; ty' <- tc_lhs_type mode ty liftedTypeKind
809 ; let n' = mkStrLitTy $ hsIPNameFS n
810 ; ipClass <- tcLookupClass ipClassName
811 ; checkExpectedKind rn_ty (mkClassPred ipClass [n',ty'])
812 constraintKind exp_kind }
813
814 tc_hs_type _ rn_ty@(HsStarTy _ _) exp_kind
815 -- Desugaring 'HsStarTy' to 'Data.Kind.Type' here means that we don't have to
816 -- handle it in 'coreView' and 'tcView'.
817 = checkExpectedKind rn_ty liftedTypeKind liftedTypeKind exp_kind
818
819 --------- Literals
820 tc_hs_type _ rn_ty@(HsTyLit _ (HsNumTy _ n)) exp_kind
821 = do { checkWiredInTyCon typeNatKindCon
822 ; checkExpectedKind rn_ty (mkNumLitTy n) typeNatKind exp_kind }
823
824 tc_hs_type _ rn_ty@(HsTyLit _ (HsStrTy _ s)) exp_kind
825 = do { checkWiredInTyCon typeSymbolKindCon
826 ; checkExpectedKind rn_ty (mkStrLitTy s) typeSymbolKind exp_kind }
827
828 --------- Potentially kind-polymorphic types: call the "up" checker
829 -- See Note [Future-proofing the type checker]
830 tc_hs_type mode ty@(HsTyVar {}) ek = tc_infer_hs_type_ek mode ty ek
831 tc_hs_type mode ty@(HsAppTy {}) ek = tc_infer_hs_type_ek mode ty ek
832 tc_hs_type mode ty@(HsOpTy {}) ek = tc_infer_hs_type_ek mode ty ek
833 tc_hs_type mode ty@(HsKindSig {}) ek = tc_infer_hs_type_ek mode ty ek
834 tc_hs_type mode ty@(XHsType (NHsCoreTy{})) ek = tc_infer_hs_type_ek mode ty ek
835
836 tc_hs_type _ (HsWildCardTy wc) exp_kind
837 = do { wc_ty <- tcWildCardOcc wc exp_kind
838 ; return (mkNakedCastTy wc_ty (mkTcNomReflCo exp_kind))
839 -- Take care here! Even though the coercion is Refl,
840 -- we still need it to establish Note [The tcType invariant]
841 }
842
843 tcWildCardOcc :: HsWildCardInfo -> Kind -> TcM TcType
844 tcWildCardOcc wc_info exp_kind
845 = do { wc_tv <- tcLookupTyVar (wildCardName wc_info)
846 -- The wildcard's kind should be an un-filled-in meta tyvar
847 ; checkExpectedKind (HsWildCardTy wc_info) (mkTyVarTy wc_tv)
848 (tyVarKind wc_tv) exp_kind }
849
850 ---------------------------
851 -- | Call 'tc_infer_hs_type' and check its result against an expected kind.
852 tc_infer_hs_type_ek :: HasDebugCallStack => TcTyMode -> HsType GhcRn -> TcKind -> TcM TcType
853 tc_infer_hs_type_ek mode hs_ty ek
854 = do { (ty, k) <- tc_infer_hs_type mode hs_ty
855 ; checkExpectedKind hs_ty ty k ek }
856
857 ---------------------------
858 tupKindSort_maybe :: TcKind -> Maybe TupleSort
859 tupKindSort_maybe k
860 | Just (k', _) <- splitCastTy_maybe k = tupKindSort_maybe k'
861 | Just k' <- tcView k = tupKindSort_maybe k'
862 | isConstraintKind k = Just ConstraintTuple
863 | isLiftedTypeKind k = Just BoxedTuple
864 | otherwise = Nothing
865
866 tc_tuple :: HsType GhcRn -> TcTyMode -> TupleSort -> [LHsType GhcRn] -> TcKind -> TcM TcType
867 tc_tuple rn_ty mode tup_sort tys exp_kind
868 = do { arg_kinds <- case tup_sort of
869 BoxedTuple -> return (nOfThem arity liftedTypeKind)
870 UnboxedTuple -> mapM (\_ -> newOpenTypeKind) tys
871 ConstraintTuple -> return (nOfThem arity constraintKind)
872 ; tau_tys <- zipWithM (tc_lhs_type mode) tys arg_kinds
873 ; finish_tuple rn_ty tup_sort tau_tys arg_kinds exp_kind }
874 where
875 arity = length tys
876
877 finish_tuple :: HsType GhcRn
878 -> TupleSort
879 -> [TcType] -- ^ argument types
880 -> [TcKind] -- ^ of these kinds
881 -> TcKind -- ^ expected kind of the whole tuple
882 -> TcM TcType
883 finish_tuple rn_ty tup_sort tau_tys tau_kinds exp_kind
884 = do { traceTc "finish_tuple" (ppr res_kind $$ ppr tau_kinds $$ ppr exp_kind)
885 ; let arg_tys = case tup_sort of
886 -- See also Note [Unboxed tuple RuntimeRep vars] in TyCon
887 UnboxedTuple -> tau_reps ++ tau_tys
888 BoxedTuple -> tau_tys
889 ConstraintTuple -> tau_tys
890 ; tycon <- case tup_sort of
891 ConstraintTuple
892 | arity > mAX_CTUPLE_SIZE
893 -> failWith (bigConstraintTuple arity)
894 | otherwise -> tcLookupTyCon (cTupleTyConName arity)
895 BoxedTuple -> do { let tc = tupleTyCon Boxed arity
896 ; checkWiredInTyCon tc
897 ; return tc }
898 UnboxedTuple -> return (tupleTyCon Unboxed arity)
899 ; checkExpectedKind rn_ty (mkTyConApp tycon arg_tys) res_kind exp_kind }
900 where
901 arity = length tau_tys
902 tau_reps = map getRuntimeRepFromKind tau_kinds
903 res_kind = case tup_sort of
904 UnboxedTuple -> unboxedTupleKind tau_reps
905 BoxedTuple -> liftedTypeKind
906 ConstraintTuple -> constraintKind
907
908 bigConstraintTuple :: Arity -> MsgDoc
909 bigConstraintTuple arity
910 = hang (text "Constraint tuple arity too large:" <+> int arity
911 <+> parens (text "max arity =" <+> int mAX_CTUPLE_SIZE))
912 2 (text "Instead, use a nested tuple")
913
914 ---------------------------
915 -- | Apply a type of a given kind to a list of arguments. This instantiates
916 -- invisible parameters as necessary. Always consumes all the arguments,
917 -- using matchExpectedFunKind as necessary.
918 -- This takes an optional @VarEnv Kind@ which maps kind variables to kinds.
919 -- These kinds should be used to instantiate invisible kind variables;
920 -- they come from an enclosing class for an associated type/data family.
921 tcInferApps :: TcTyMode
922 -> Maybe (VarEnv Kind) -- ^ Possibly, kind info (see above)
923 -> LHsType GhcRn -- ^ Function (for printing only)
924 -> TcType -- ^ Function (could be knot-tied)
925 -> TcKind -- ^ Function kind (zonked)
926 -> [LHsType GhcRn] -- ^ Args
927 -> TcM (TcType, [TcType], TcKind) -- ^ (f args, args, result kind)
928 -- Precondition: typeKind fun_ty = fun_ki
929 -- Reason: we will return a type application like (fun_ty arg1 ... argn),
930 -- and that type must be well-kinded
931 -- See Note [The tcType invariant]
932 -- Postcondition: Result kind is zonked.
933 tcInferApps mode mb_kind_info orig_hs_ty fun_ty fun_ki orig_hs_args
934 = do { traceTc "tcInferApps {" (ppr orig_hs_ty $$ ppr orig_hs_args $$ ppr fun_ki)
935 ; (f_args, args, res_k) <- go 1 [] empty_subst fun_ty orig_ki_binders orig_inner_ki orig_hs_args
936 ; traceTc "tcInferApps }" empty
937 ; res_k <- zonkTcType res_k -- nec'y to uphold (IT4) of Note [The tcType invariant]
938 ; return (f_args, args, res_k) }
939 where
940 empty_subst = mkEmptyTCvSubst $ mkInScopeSet $
941 tyCoVarsOfType fun_ki
942 (orig_ki_binders, orig_inner_ki) = tcSplitPiTys fun_ki
943
944 go :: Int -- the # of the next argument
945 -> [TcType] -- already type-checked args, in reverse order
946 -> TCvSubst -- instantiating substitution
947 -> TcType -- function applied to some args, could be knot-tied
948 -> [TyBinder] -- binders in function kind (both vis. and invis.)
949 -> TcKind -- function kind body (not a Pi-type)
950 -> [LHsType GhcRn] -- un-type-checked args
951 -> TcM (TcType, [TcType], TcKind) -- same as overall return type
952
953 -- no user-written args left. We're done!
954 go _ acc_args subst fun ki_binders inner_ki []
955 = return ( fun
956 , reverse acc_args
957 , nakedSubstTy subst $ mkPiTys ki_binders inner_ki)
958 -- nakedSubstTy: see Note [The well-kinded type invariant]
959
960 -- The function's kind has a binder. Is it visible or invisible?
961 go n acc_args subst fun (ki_binder:ki_binders) inner_ki
962 all_args@(arg:args)
963 | isInvisibleBinder ki_binder
964 -- It's invisible. Instantiate.
965 = do { traceTc "tcInferApps (invis)" (ppr ki_binder $$ ppr subst)
966 ; (subst', arg') <- tcInstTyBinder mb_kind_info subst ki_binder
967 ; go n (arg' : acc_args) subst' (mkNakedAppTy fun arg')
968 ki_binders inner_ki all_args }
969
970 | otherwise
971 -- It's visible. Check the next user-written argument
972 = do { traceTc "tcInferApps (vis)" (vcat [ ppr ki_binder, ppr arg
973 , ppr (tyBinderType ki_binder)
974 , ppr subst ])
975 ; let exp_kind = nakedSubstTy subst $ tyBinderType ki_binder
976 -- nakedSubstTy: see Note [The well-kinded type invariant]
977 ; arg' <- addErrCtxt (funAppCtxt orig_hs_ty arg n) $
978 tc_lhs_type mode arg exp_kind
979 ; traceTc "tcInferApps (vis 1)" (vcat [ ppr exp_kind
980 , ppr arg'
981 , ppr (typeKind arg') ])
982 ; let subst' = extendTvSubstBinderAndInScope subst ki_binder arg'
983 ; go (n+1) (arg' : acc_args) subst'
984 (mkNakedAppTy fun arg') -- See Note [The well-kinded type invariant]
985 ki_binders inner_ki args }
986
987 -- We've run out of known binders in the functions's kind.
988 go n acc_args subst fun [] inner_ki all_args
989 | not (null new_ki_binders)
990 -- But, after substituting, we have more binders.
991 = go n acc_args zapped_subst fun new_ki_binders new_inner_ki all_args
992
993 | otherwise
994 -- Even after substituting, still no binders. Use matchExpectedFunKind
995 = do { traceTc "tcInferApps (no binder)" (ppr new_inner_ki $$ ppr zapped_subst)
996 ; (co, arg_k, res_k) <- matchExpectedFunKind hs_ty substed_inner_ki
997 ; let new_in_scope = tyCoVarsOfTypes [arg_k, res_k]
998 subst' = zapped_subst `extendTCvInScopeSet` new_in_scope
999 ; go n acc_args subst'
1000 (fun `mkNakedCastTy` co) -- See Note [The well-kinded type invariant]
1001 [mkAnonBinder arg_k]
1002 res_k all_args }
1003 where
1004 substed_inner_ki = substTy subst inner_ki
1005 (new_ki_binders, new_inner_ki) = tcSplitPiTys substed_inner_ki
1006 zapped_subst = zapTCvSubst subst
1007 hs_ty = mkHsAppTys orig_hs_ty (take (n-1) orig_hs_args)
1008
1009
1010 -- | Applies a type to a list of arguments.
1011 -- Always consumes all the arguments, using 'matchExpectedFunKind' as
1012 -- necessary. If you wish to apply a type to a list of HsTypes, this is
1013 -- your function.
1014 -- Used for type-checking types only.
1015 tcTyApps :: TcTyMode
1016 -> LHsType GhcRn -- ^ Function (for printing only)
1017 -> TcType -- ^ Function (could be knot-tied)
1018 -> TcKind -- ^ Function kind (zonked)
1019 -> [LHsType GhcRn] -- ^ Args
1020 -> TcM (TcType, TcKind) -- ^ (f args, result kind) result kind is zonked
1021 -- Precondition: see precondition for tcInferApps
1022 tcTyApps mode orig_hs_ty fun_ty fun_ki args
1023 = do { (ty', _args, ki') <- tcInferApps mode Nothing orig_hs_ty fun_ty fun_ki args
1024 ; return (ty' `mkNakedCastTy` mkRepReflCo ki', ki') }
1025 -- The mkNakedCastTy is for (IT3) of Note [The tcType invariant]
1026
1027 --------------------------
1028 -- Like checkExpectedKindX, but returns only the final type; convenient wrapper
1029 -- Obeys Note [The tcType invariant]
1030 checkExpectedKind :: HasDebugCallStack
1031 => HsType GhcRn -- type we're checking (for printing)
1032 -> TcType -- type we're checking (might be knot-tied)
1033 -> TcKind -- the known kind of that type
1034 -> TcKind -- the expected kind
1035 -> TcM TcType
1036 checkExpectedKind hs_ty ty act exp
1037 = fstOf3 <$> checkExpectedKindX Nothing (ppr hs_ty) ty act exp
1038
1039 checkExpectedKindX :: HasDebugCallStack
1040 => Maybe (VarEnv Kind) -- Possibly, instantiations for kind vars
1041 -> SDoc -- HsType whose kind we're checking
1042 -> TcType -- the type whose kind we're checking
1043 -> TcKind -- the known kind of that type, k
1044 -> TcKind -- the expected kind, exp_kind
1045 -> TcM (TcType, [TcType], TcCoercionN)
1046 -- (the new args, the coercion)
1047 -- Instantiate a kind (if necessary) and then call unifyType
1048 -- (checkExpectedKind ty act_kind exp_kind)
1049 -- checks that the actual kind act_kind is compatible
1050 -- with the expected kind exp_kind
1051 checkExpectedKindX mb_kind_env pp_hs_ty ty act_kind exp_kind
1052 = do { -- We need to make sure that both kinds have the same number of implicit
1053 -- foralls out front. If the actual kind has more, instantiate accordingly.
1054 -- Otherwise, just pass the type & kind through: the errors are caught
1055 -- in unifyType.
1056 let (exp_bndrs, _) = splitPiTysInvisible exp_kind
1057 n_exp = length exp_bndrs
1058 ; (new_args, act_kind') <- instantiateTyUntilN mb_kind_env n_exp act_kind
1059
1060 ; let origin = TypeEqOrigin { uo_actual = act_kind'
1061 , uo_expected = exp_kind
1062 , uo_thing = Just pp_hs_ty
1063 , uo_visible = True } -- the hs_ty is visible
1064 ty' = mkNakedAppTys ty new_args
1065
1066 ; traceTc "checkExpectedKind" $
1067 vcat [ pp_hs_ty
1068 , text "act_kind:" <+> ppr act_kind
1069 , text "act_kind':" <+> ppr act_kind'
1070 , text "exp_kind:" <+> ppr exp_kind ]
1071
1072 ; if act_kind' `tcEqType` exp_kind
1073 then return (ty', new_args, mkTcNomReflCo exp_kind) -- This is very common
1074 else do { co_k <- uType KindLevel origin act_kind' exp_kind
1075 ; traceTc "checkExpectedKind" (vcat [ ppr act_kind
1076 , ppr exp_kind
1077 , ppr co_k ])
1078 ; let result_ty = ty' `mkNakedCastTy` co_k
1079 -- See Note [The tcType invariant]
1080 ; return (result_ty, new_args, co_k) } }
1081
1082 -- | Instantiate @n@ invisible arguments to a type. If @n <= 0@, no instantiation
1083 -- occurs. If @n@ is too big, then all available invisible arguments are instantiated.
1084 -- (In other words, this function is very forgiving about bad values of @n@.)
1085 -- Why zonk the result? So that tcTyVar can obey (IT6) of Note [The tcType invariant]
1086 instantiateTyN :: Maybe (VarEnv Kind) -- ^ Predetermined instantiations
1087 -- (for assoc. type patterns)
1088 -> Int -- ^ @n@
1089 -> [TyBinder] -> TcKind -- ^ its kind (zonked)
1090 -> TcM ([TcType], TcKind) -- ^ The inst'ed type, new args, kind (zonked)
1091 instantiateTyN mb_kind_env n bndrs inner_ki
1092 | n <= 0
1093 = return ([], ki)
1094
1095 | otherwise
1096 = do { (subst, inst_args) <- tcInstTyBinders empty_subst mb_kind_env inst_bndrs
1097 ; let rebuilt_ki = mkPiTys leftover_bndrs inner_ki
1098 ; ki' <- zonkTcType (substTy subst rebuilt_ki)
1099 ; traceTc "instantiateTyN" (vcat [ ppr ki
1100 , ppr n
1101 , ppr subst
1102 , ppr rebuilt_ki
1103 , ppr ki' ])
1104 ; return (inst_args, ki') }
1105 where
1106 -- NB: splitAt is forgiving with invalid numbers
1107 (inst_bndrs, leftover_bndrs) = splitAt n bndrs
1108 ki = mkPiTys bndrs inner_ki
1109 empty_subst = mkEmptyTCvSubst (mkInScopeSet (tyCoVarsOfType ki))
1110
1111 -- | Instantiate a type to have at most @n@ invisible arguments.
1112 instantiateTyUntilN :: Maybe (VarEnv Kind) -- ^ Possibly, instantiations for vars
1113 -> Int -- ^ @n@
1114 -> TcKind -- ^ its kind
1115 -> TcM ([TcType], TcKind) -- ^ The new args, final kind
1116 instantiateTyUntilN mb_kind_env n ki
1117 = let (bndrs, inner_ki) = splitPiTysInvisible ki
1118 num_to_inst = length bndrs - n
1119 in
1120 instantiateTyN mb_kind_env num_to_inst bndrs inner_ki
1121
1122 ---------------------------
1123 tcHsMbContext :: Maybe (LHsContext GhcRn) -> TcM [PredType]
1124 tcHsMbContext Nothing = return []
1125 tcHsMbContext (Just cxt) = tcHsContext cxt
1126
1127 tcHsContext :: LHsContext GhcRn -> TcM [PredType]
1128 tcHsContext = tc_hs_context typeLevelMode
1129
1130 tcLHsPredType :: LHsType GhcRn -> TcM PredType
1131 tcLHsPredType = tc_lhs_pred typeLevelMode
1132
1133 tc_hs_context :: TcTyMode -> LHsContext GhcRn -> TcM [PredType]
1134 tc_hs_context mode ctxt = mapM (tc_lhs_pred mode) (unLoc ctxt)
1135
1136 tc_lhs_pred :: TcTyMode -> LHsType GhcRn -> TcM PredType
1137 tc_lhs_pred mode pred = tc_lhs_type mode pred constraintKind
1138
1139 ---------------------------
1140 tcTyVar :: TcTyMode -> Name -> TcM (TcType, TcKind)
1141 -- See Note [Type checking recursive type and class declarations]
1142 -- in TcTyClsDecls
1143 tcTyVar mode name -- Could be a tyvar, a tycon, or a datacon
1144 = do { traceTc "lk1" (ppr name)
1145 ; thing <- tcLookup name
1146 ; case thing of
1147 ATyVar _ tv -> -- Important: zonk before returning
1148 -- We may have the application ((a::kappa) b)
1149 -- where kappa is already unified to (k1 -> k2)
1150 -- Then we want to see that arrow. Best done
1151 -- here because we are also maintaining
1152 -- Note [The tcType invariant], so we don't just
1153 -- want to zonk the kind, leaving the TyVar
1154 -- un-zonked (Trac #114873)
1155 do { ty <- zonkTcTyVar tv
1156 ; return (ty, typeKind ty) }
1157
1158 ATcTyCon tc_tc -> do { -- See Note [GADT kind self-reference]
1159 unless
1160 (isTypeLevel (mode_level mode))
1161 (promotionErr name TyConPE)
1162 ; check_tc tc_tc
1163 ; tc <- get_loopy_tc name tc_tc
1164 ; handle_tyfams tc tc_tc }
1165 -- mkNakedTyConApp: see Note [Type-checking inside the knot]
1166
1167 AGlobal (ATyCon tc)
1168 -> do { check_tc tc
1169 ; handle_tyfams tc tc }
1170
1171 AGlobal (AConLike (RealDataCon dc))
1172 -> do { data_kinds <- xoptM LangExt.DataKinds
1173 ; unless (data_kinds || specialPromotedDc dc) $
1174 promotionErr name NoDataKindsDC
1175 ; when (isFamInstTyCon (dataConTyCon dc)) $
1176 -- see Trac #15245
1177 promotionErr name FamDataConPE
1178 ; let (_, _, _, theta, _, _) = dataConFullSig dc
1179 ; case dc_theta_illegal_constraint theta of
1180 Just pred -> promotionErr name $
1181 ConstrainedDataConPE pred
1182 Nothing -> pure ()
1183 ; let tc = promoteDataCon dc
1184 ; return (mkNakedTyConApp tc [], tyConKind tc) }
1185
1186 APromotionErr err -> promotionErr name err
1187
1188 _ -> wrongThingErr "type" thing name }
1189 where
1190 check_tc :: TyCon -> TcM ()
1191 check_tc tc = do { data_kinds <- xoptM LangExt.DataKinds
1192 ; unless (isTypeLevel (mode_level mode) ||
1193 data_kinds ||
1194 isKindTyCon tc) $
1195 promotionErr name NoDataKindsTC }
1196
1197 -- if we are type-checking a type family tycon, we must instantiate
1198 -- any invisible arguments right away. Otherwise, we get #11246
1199 handle_tyfams :: TyCon -- the tycon to instantiate (might be loopy)
1200 -> TcTyCon -- a non-loopy version of the tycon
1201 -> TcM (TcType, TcKind)
1202 handle_tyfams tc tc_tc
1203 | mightBeUnsaturatedTyCon tc_tc || mode_unsat mode
1204 -- This is where mode_unsat is used
1205 = do { tc_kind <- zonkTcType (tyConKind tc_tc) -- (IT6) of Note [The tcType invariant]
1206 ; traceTc "tcTyVar2a" (ppr tc_tc $$ ppr tc_kind)
1207 ; return (mkNakedTyConApp tc [] `mkNakedCastTy` mkRepReflCo tc_kind, tc_kind) }
1208 -- the mkNakedCastTy ensures (IT5) of Note [The tcType invariant]
1209
1210 | otherwise
1211 = do { tc_kind <- zonkTcType (tyConKind tc_tc)
1212 ; let (tc_kind_bndrs, tc_inner_ki) = splitPiTysInvisible tc_kind
1213 ; (tc_args, kind) <- instantiateTyN Nothing (length (tyConBinders tc_tc))
1214 tc_kind_bndrs tc_inner_ki
1215 ; let tc_ty = mkNakedTyConApp tc tc_args `mkNakedCastTy` mkRepReflCo kind
1216 -- mkNakedCastTy is for (IT5) of Note [The tcType invariant]
1217 -- tc and tc_ty must not be traced here, because that would
1218 -- force the evaluation of a potentially knot-tied variable (tc),
1219 -- and the typechecker would hang, as per #11708
1220 ; traceTc "tcTyVar2b" (vcat [ ppr tc_tc <+> dcolon <+> ppr tc_kind
1221 , ppr kind ])
1222 ; return (tc_ty, kind) }
1223
1224 get_loopy_tc :: Name -> TyCon -> TcM TyCon
1225 -- Return the knot-tied global TyCon if there is one
1226 -- Otherwise the local TcTyCon; we must be doing kind checking
1227 -- but we still want to return a TyCon of some sort to use in
1228 -- error messages
1229 get_loopy_tc name tc_tc
1230 = do { env <- getGblEnv
1231 ; case lookupNameEnv (tcg_type_env env) name of
1232 Just (ATyCon tc) -> return tc
1233 _ -> do { traceTc "lk1 (loopy)" (ppr name)
1234 ; return tc_tc } }
1235
1236 -- We cannot promote a data constructor with a context that contains
1237 -- constraints other than equalities, so error if we find one.
1238 -- See Note [Constraints handled in types] in Inst.
1239 dc_theta_illegal_constraint :: ThetaType -> Maybe PredType
1240 dc_theta_illegal_constraint = find go
1241 where
1242 go :: PredType -> Bool
1243 go pred | Just tc <- tyConAppTyCon_maybe pred
1244 = not $ tc `hasKey` eqTyConKey
1245 || tc `hasKey` heqTyConKey
1246 | otherwise = True
1247
1248 {-
1249 Note [Type-checking inside the knot]
1250 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1251 Suppose we are checking the argument types of a data constructor. We
1252 must zonk the types before making the DataCon, because once built we
1253 can't change it. So we must traverse the type.
1254
1255 BUT the parent TyCon is knot-tied, so we can't look at it yet.
1256
1257 So we must be careful not to use "smart constructors" for types that
1258 look at the TyCon or Class involved.
1259
1260 * Hence the use of mkNakedXXX functions. These do *not* enforce
1261 the invariants (for example that we use (FunTy s t) rather
1262 than (TyConApp (->) [s,t])).
1263
1264 * The zonking functions establish invariants (even zonkTcType, a change from
1265 previous behaviour). So we must never inspect the result of a
1266 zonk that might mention a knot-tied TyCon. This is generally OK
1267 because we zonk *kinds* while kind-checking types. And the TyCons
1268 in kinds shouldn't be knot-tied, because they come from a previous
1269 mutually recursive group.
1270
1271 * TcHsSyn.zonkTcTypeToType also can safely check/establish
1272 invariants.
1273
1274 This is horribly delicate. I hate it. A good example of how
1275 delicate it is can be seen in Trac #7903.
1276
1277 Note [GADT kind self-reference]
1278 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1279
1280 A promoted type cannot be used in the body of that type's declaration.
1281 Trac #11554 shows this example, which made GHC loop:
1282
1283 import Data.Kind
1284 data P (x :: k) = Q
1285 data A :: Type where
1286 B :: forall (a :: A). P a -> A
1287
1288 In order to check the constructor B, we need to have the promoted type A, but in
1289 order to get that promoted type, B must first be checked. To prevent looping, a
1290 TyConPE promotion error is given when tcTyVar checks an ATcTyCon in kind mode.
1291 Any ATcTyCon is a TyCon being defined in the current recursive group (see data
1292 type decl for TcTyThing), and all such TyCons are illegal in kinds.
1293
1294 Trac #11962 proposes checking the head of a data declaration separately from
1295 its constructors. This would allow the example above to pass.
1296
1297 Note [Body kind of a HsForAllTy]
1298 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1299 The body of a forall is usually a type, but in principle
1300 there's no reason to prohibit *unlifted* types.
1301 In fact, GHC can itself construct a function with an
1302 unboxed tuple inside a for-all (via CPR analysis; see
1303 typecheck/should_compile/tc170).
1304
1305 Moreover in instance heads we get forall-types with
1306 kind Constraint.
1307
1308 It's tempting to check that the body kind is either * or #. But this is
1309 wrong. For example:
1310
1311 class C a b
1312 newtype N = Mk Foo deriving (C a)
1313
1314 We're doing newtype-deriving for C. But notice how `a` isn't in scope in
1315 the predicate `C a`. So we quantify, yielding `forall a. C a` even though
1316 `C a` has kind `* -> Constraint`. The `forall a. C a` is a bit cheeky, but
1317 convenient. Bottom line: don't check for * or # here.
1318
1319 Note [Body kind of a HsQualTy]
1320 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1321 If ctxt is non-empty, the HsQualTy really is a /function/, so the
1322 kind of the result really is '*', and in that case the kind of the
1323 body-type can be lifted or unlifted.
1324
1325 However, consider
1326 instance Eq a => Eq [a] where ...
1327 or
1328 f :: (Eq a => Eq [a]) => blah
1329 Here both body-kind of the HsQualTy is Constraint rather than *.
1330 Rather crudely we tell the difference by looking at exp_kind. It's
1331 very convenient to typecheck instance types like any other HsSigType.
1332
1333 Admittedly the '(Eq a => Eq [a]) => blah' case is erroneous, but it's
1334 better to reject in checkValidType. If we say that the body kind
1335 should be '*' we risk getting TWO error messages, one saying that Eq
1336 [a] doens't have kind '*', and one saying that we need a Constraint to
1337 the left of the outer (=>).
1338
1339 How do we figure out the right body kind? Well, it's a bit of a
1340 kludge: I just look at the expected kind. If it's Constraint, we
1341 must be in this instance situation context. It's a kludge because it
1342 wouldn't work if any unification was involved to compute that result
1343 kind -- but it isn't. (The true way might be to use the 'mode'
1344 parameter, but that seemed like a sledgehammer to crack a nut.)
1345
1346 Note [Inferring tuple kinds]
1347 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1348 Give a tuple type (a,b,c), which the parser labels as HsBoxedOrConstraintTuple,
1349 we try to figure out whether it's a tuple of kind * or Constraint.
1350 Step 1: look at the expected kind
1351 Step 2: infer argument kinds
1352
1353 If after Step 2 it's not clear from the arguments that it's
1354 Constraint, then it must be *. Once having decided that we re-check
1355 the Check the arguments again to give good error messages
1356 in eg. `(Maybe, Maybe)`
1357
1358 Note that we will still fail to infer the correct kind in this case:
1359
1360 type T a = ((a,a), D a)
1361 type family D :: Constraint -> Constraint
1362
1363 While kind checking T, we do not yet know the kind of D, so we will default the
1364 kind of T to * -> *. It works if we annotate `a` with kind `Constraint`.
1365
1366 Note [Desugaring types]
1367 ~~~~~~~~~~~~~~~~~~~~~~~
1368 The type desugarer is phase 2 of dealing with HsTypes. Specifically:
1369
1370 * It transforms from HsType to Type
1371
1372 * It zonks any kinds. The returned type should have no mutable kind
1373 or type variables (hence returning Type not TcType):
1374 - any unconstrained kind variables are defaulted to (Any *) just
1375 as in TcHsSyn.
1376 - there are no mutable type variables because we are
1377 kind-checking a type
1378 Reason: the returned type may be put in a TyCon or DataCon where
1379 it will never subsequently be zonked.
1380
1381 You might worry about nested scopes:
1382 ..a:kappa in scope..
1383 let f :: forall b. T '[a,b] -> Int
1384 In this case, f's type could have a mutable kind variable kappa in it;
1385 and we might then default it to (Any *) when dealing with f's type
1386 signature. But we don't expect this to happen because we can't get a
1387 lexically scoped type variable with a mutable kind variable in it. A
1388 delicate point, this. If it becomes an issue we might need to
1389 distinguish top-level from nested uses.
1390
1391 Moreover
1392 * it cannot fail,
1393 * it does no unifications
1394 * it does no validity checking, except for structural matters, such as
1395 (a) spurious ! annotations.
1396 (b) a class used as a type
1397
1398 Note [Kind of a type splice]
1399 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1400 Consider these terms, each with TH type splice inside:
1401 [| e1 :: Maybe $(..blah..) |]
1402 [| e2 :: $(..blah..) |]
1403 When kind-checking the type signature, we'll kind-check the splice
1404 $(..blah..); we want to give it a kind that can fit in any context,
1405 as if $(..blah..) :: forall k. k.
1406
1407 In the e1 example, the context of the splice fixes kappa to *. But
1408 in the e2 example, we'll desugar the type, zonking the kind unification
1409 variables as we go. When we encounter the unconstrained kappa, we
1410 want to default it to '*', not to (Any *).
1411
1412 Help functions for type applications
1413 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1414 -}
1415
1416 addTypeCtxt :: LHsType GhcRn -> TcM a -> TcM a
1417 -- Wrap a context around only if we want to show that contexts.
1418 -- Omit invisible ones and ones user's won't grok
1419 addTypeCtxt (L _ ty) thing
1420 = addErrCtxt doc thing
1421 where
1422 doc = text "In the type" <+> quotes (ppr ty)
1423
1424 {-
1425 ************************************************************************
1426 * *
1427 Type-variable binders
1428 %* *
1429 %************************************************************************
1430
1431 Note [Dependent LHsQTyVars]
1432 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1433 We track (in the renamer) which explicitly bound variables in a
1434 LHsQTyVars are manifestly dependent; only precisely these variables
1435 may be used within the LHsQTyVars. We must do this so that kcLHsQTyVars
1436 can produce the right TyConBinders, and tell Anon vs. Required.
1437
1438 Example data T k1 (a:k1) (b:k2) c
1439 = MkT (Proxy a) (Proxy b) (Proxy c)
1440
1441 Here
1442 (a:k1),(b:k2),(c:k3)
1443 are Anon (explicitly specified as a binder, not used
1444 in the kind of any other binder
1445 k1 is Required (explicitly specifed as a binder, but used
1446 in the kind of another binder i.e. dependently)
1447 k2 is Specified (not explicitly bound, but used in the kind
1448 of another binder)
1449 k3 in Inferred (not lexically in scope at all, but inferred
1450 by kind inference)
1451 and
1452 T :: forall {k3} k1. forall k3 -> k1 -> k2 -> k3 -> *
1453
1454 See Note [TyVarBndrs, TyVarBinders, TyConBinders, and visibility]
1455 in TyCoRep.
1456
1457 kcLHsQTyVars uses the hsq_dependent field to decide whether
1458 k1, a, b, c should be Required or Anon.
1459
1460 Earlier, thought it would work simply to do a free-variable check
1461 during kcLHsQTyVars, but this is bogus, because there may be
1462 unsolved equalities about. And we don't want to eagerly solve the
1463 equalities, because we may get further information after
1464 kcLHsQTyVars is called. (Recall that kcLHsQTyVars is called
1465 only from getInitialKind.)
1466 This is what implements the rule that all variables intended to be
1467 dependent must be manifestly so.
1468
1469 Sidenote: It's quite possible that later, we'll consider (t -> s)
1470 as a degenerate case of some (pi (x :: t) -> s) and then this will
1471 all get more permissive.
1472
1473 Note [Kind generalisation and SigTvs]
1474 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1475 Consider
1476 data T (a :: k1) x = MkT (S a ())
1477 data S (b :: k2) y = MkS (T b ())
1478
1479 While we are doing kind inference for the mutually-recursive S,T,
1480 we will end up unifying k1 and k2 together. So they can't be skolems.
1481 We therefore make them SigTvs, which can unify with type variables,
1482 but not with general types. All this is very similar at the level
1483 of terms: see Note [Quantified variables in partial type signatures]
1484 in TcBinds.
1485
1486 There are some wrinkles
1487
1488 * We always want to kind-generalise over SigTvs, and /not/ default
1489 them to Type. Another way to say this is: a SigTV should /never/
1490 stand for a type, even via defaulting. Hence the check in
1491 TcSimplify.defaultTyVarTcS, and TcMType.defaultTyVar. Here's
1492 another example (Trac #14555):
1493 data Exp :: [TYPE rep] -> TYPE rep -> Type where
1494 Lam :: Exp (a:xs) b -> Exp xs (a -> b)
1495 We want to kind-generalise over the 'rep' variable.
1496 Trac #14563 is another example.
1497
1498 * Consider Trac #11203
1499 data SameKind :: k -> k -> *
1500 data Q (a :: k1) (b :: k2) c = MkQ (SameKind a b)
1501 Here we will unify k1 with k2, but this time doing so is an error,
1502 because k1 and k2 are bound in the same delcaration.
1503
1504 We sort this out using findDupSigTvs, in TcTyClTyVars; very much
1505 as we do with partial type signatures in mk_psig_qtvs in
1506 TcBinds.chooseInferredQuantifiers
1507
1508 Note [Keeping scoped variables in order: Explicit]
1509 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1510 When the user writes `forall a b c. blah`, we bring a, b, and c into
1511 scope and then check blah. In the process of checking blah, we might
1512 learn the kinds of a, b, and c, and these kinds might indicate that
1513 b depends on c, and thus that we should reject the user-written type.
1514
1515 One approach to doing this would be to bring each of a, b, and c into
1516 scope, one at a time, creating an implication constraint and
1517 bumping the TcLevel for each one. This would work, because the kind
1518 of, say, b would be untouchable when c is in scope (and the constraint
1519 couldn't float out because c blocks it). However, it leads to terrible
1520 error messages, complaining about skolem escape. While it is indeed
1521 a problem of skolem escape, we can do better.
1522
1523 Instead, our approach is to bring the block of variables into scope
1524 all at once, creating one implication constraint for the lot. The
1525 user-written variables are skolems in the implication constraint. In
1526 TcSimplify.setImplicationStatus, we check to make sure that the ordering
1527 is correct, choosing ImplicationStatus IC_BadTelescope if they aren't.
1528 Then, in TcErrors, we report if there is a bad telescope. This way,
1529 we can report a suggested ordering to the user if there is a problem.
1530
1531 Note [Keeping scoped variables in order: Implicit]
1532 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1533 When the user implicitly quantifies over variables (say, in a type
1534 signature), we need to come up with some ordering on these variables.
1535 This is done by bumping the TcLevel, bringing the tyvars into scope,
1536 and then type-checking the thing_inside. The constraints are all
1537 wrapped in an implication, which is then solved. Finally, we can
1538 zonk all the binders and then order them with toposortTyVars.
1539
1540 It's critical to solve before zonking and ordering in order to uncover
1541 any unifications. You might worry that this eager solving could cause
1542 trouble elsewhere. I don't think it will. Because it will solve only
1543 in an increased TcLevel, it can't unify anything that was mentioned
1544 elsewhere. Additionally, we require that the order of implicitly
1545 quantified variables is manifest by the scope of these variables, so
1546 we're not going to learn more information later that will help order
1547 these variables.
1548
1549 Note [Recipe for checking a signature]
1550 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1551 Checking a user-written signature requires several steps:
1552
1553 1. Generate constraints.
1554 2. Solve constraints.
1555 3. Zonk and promote tyvars.
1556 4. (Optional) Kind-generalize.
1557 5. Check validity.
1558
1559 There may be some surprises in here:
1560
1561 Step 2 is necessary for two reasons: most signatures also bring
1562 implicitly quantified variables into scope, and solving is necessary
1563 to get these in the right order (see Note [Keeping scoped variables in
1564 order: Implicit]). Additionally, solving is necessary in order to
1565 kind-generalize correctly.
1566
1567 Step 3 requires *promoting* type variables. If there are any foralls
1568 in a type, the TcLevel will be bumped within the forall. This might
1569 lead to the generation of matavars with a high level. If we don't promote,
1570 we violate MetaTvInv of Note [TcLevel and untouchable type variables]
1571 in TcType.
1572
1573 -}
1574
1575 tcWildCardBinders :: SkolemInfo
1576 -> [Name]
1577 -> ([(Name, TcTyVar)] -> TcM a)
1578 -> TcM a
1579 tcWildCardBinders info = tcWildCardBindersX new_tv (Just info)
1580 where
1581 new_tv name = do { kind <- newMetaKindVar
1582 ; newSkolemTyVar name kind }
1583
1584 tcWildCardBindersX :: (Name -> TcM TcTyVar)
1585 -> Maybe SkolemInfo -- Just <=> we're bringing fresh vars
1586 -- into scope; use scopeTyVars
1587 -> [Name]
1588 -> ([(Name, TcTyVar)] -> TcM a)
1589 -> TcM a
1590 tcWildCardBindersX new_wc maybe_skol_info wc_names thing_inside
1591 = do { wcs <- mapM new_wc wc_names
1592 ; let wc_prs = wc_names `zip` wcs
1593 ; scope_tvs wc_prs $
1594 thing_inside wc_prs }
1595 where
1596 scope_tvs
1597 | Just info <- maybe_skol_info = scopeTyVars2 info
1598 | otherwise = tcExtendNameTyVarEnv
1599
1600 -- | Kind-check a 'LHsQTyVars'. If the decl under consideration has a complete,
1601 -- user-supplied kind signature (CUSK), generalise the result.
1602 -- Used in 'getInitialKind' (for tycon kinds and other kinds)
1603 -- and in kind-checking (but not for tycon kinds, which are checked with
1604 -- tcTyClDecls). See also Note [Complete user-supplied kind signatures] in
1605 -- HsDecls.
1606 --
1607 -- This function does not do telescope checking.
1608 kcLHsQTyVars :: Name -- ^ of the thing being checked
1609 -> TyConFlavour -- ^ What sort of 'TyCon' is being checked
1610 -> Bool -- ^ True <=> the decl being checked has a CUSK
1611 -> LHsQTyVars GhcRn
1612 -> TcM Kind -- ^ The result kind
1613 -> TcM TcTyCon -- ^ A suitably-kinded TcTyCon
1614 kcLHsQTyVars name flav cusk
1615 user_tyvars@(HsQTvs { hsq_ext = HsQTvsRn { hsq_implicit = kv_ns
1616 , hsq_dependent = dep_names }
1617 , hsq_explicit = hs_tvs }) thing_inside
1618 | cusk
1619 = do { (scoped_kvs, (tc_tvs, res_kind))
1620 <- solveEqualities $
1621 tcImplicitQTKBndrs skol_info kv_ns $
1622 kcLHsQTyVarBndrs cusk open_fam skol_info hs_tvs thing_inside
1623
1624 -- Now, because we're in a CUSK, quantify over the mentioned
1625 -- kind vars, in dependency order.
1626 ; let tc_binders_unzonked = zipWith mk_tc_binder hs_tvs tc_tvs
1627 ; dvs <- zonkTcTypeAndSplitDepVars (mkSpecForAllTys scoped_kvs $
1628 mkTyConKind tc_binders_unzonked res_kind)
1629 ; qkvs <- quantifyTyVars emptyVarSet dvs
1630 -- don't call tcGetGlobalTyCoVars. For associated types, it gets the
1631 -- tyvars from the enclosing class -- but that's wrong. We *do* want
1632 -- to quantify over those tyvars.
1633
1634 ; scoped_kvs <- mapM zonkTcTyVarToTyVar scoped_kvs
1635 ; tc_tvs <- mapM zonkTcTyVarToTyVar tc_tvs
1636 ; res_kind <- zonkTcType res_kind
1637 ; let tc_binders = zipWith mk_tc_binder hs_tvs tc_tvs
1638
1639 -- If any of the scoped_kvs aren't actually mentioned in a binder's
1640 -- kind (or the return kind), then we're in the CUSK case from
1641 -- Note [Free-floating kind vars]
1642 ; let all_tc_tvs = scoped_kvs ++ tc_tvs
1643 all_mentioned_tvs = mapUnionVarSet (tyCoVarsOfType . tyVarKind)
1644 all_tc_tvs
1645 `unionVarSet` tyCoVarsOfType res_kind
1646 unmentioned_kvs = filterOut (`elemVarSet` all_mentioned_tvs)
1647 scoped_kvs
1648 ; reportFloatingKvs name flav all_tc_tvs unmentioned_kvs
1649
1650 ; let final_binders = map (mkNamedTyConBinder Inferred) qkvs
1651 ++ map (mkNamedTyConBinder Specified) scoped_kvs
1652 ++ tc_binders
1653 tycon = mkTcTyCon name (ppr user_tyvars) final_binders res_kind
1654 (mkTyVarNamePairs (scoped_kvs ++ tc_tvs))
1655 flav
1656 -- the tvs contain the binders already
1657 -- in scope from an enclosing class, but
1658 -- re-adding tvs to the env't doesn't cause
1659 -- harm
1660
1661 ; traceTc "kcLHsQTyVars: cusk" $
1662 vcat [ ppr name, ppr kv_ns, ppr hs_tvs, ppr dep_names
1663 , ppr tc_tvs, ppr (mkTyConKind final_binders res_kind)
1664 , ppr qkvs, ppr final_binders ]
1665
1666 ; return tycon }
1667
1668 | otherwise
1669 = do { (scoped_kvs, (tc_tvs, res_kind))
1670 -- Why kcImplicitTKBndrs which uses newSigTyVar?
1671 -- See Note [Kind generalisation and sigTvs]
1672 <- kcImplicitTKBndrs kv_ns $
1673 kcLHsQTyVarBndrs cusk open_fam skol_info hs_tvs thing_inside
1674
1675 ; let -- NB: Don't add scoped_kvs to tyConTyVars, because they
1676 -- must remain lined up with the binders
1677 tc_binders = zipWith mk_tc_binder hs_tvs tc_tvs
1678 tycon = mkTcTyCon name (ppr user_tyvars) tc_binders res_kind
1679 (mkTyVarNamePairs (scoped_kvs ++ tc_tvs))
1680 flav
1681
1682 ; traceTc "kcLHsQTyVars: not-cusk" $
1683 vcat [ ppr name, ppr kv_ns, ppr hs_tvs, ppr dep_names
1684 , ppr tc_tvs, ppr (mkTyConKind tc_binders res_kind) ]
1685 ; return tycon }
1686 where
1687 open_fam = tcFlavourIsOpen flav
1688 skol_info = TyConSkol flav name
1689
1690 mk_tc_binder :: LHsTyVarBndr GhcRn -> TyVar -> TyConBinder
1691 -- See Note [Dependent LHsQTyVars]
1692 mk_tc_binder hs_tv tv
1693 | hsLTyVarName hs_tv `elemNameSet` dep_names
1694 = mkNamedTyConBinder Required tv
1695 | otherwise
1696 = mkAnonTyConBinder tv
1697
1698 kcLHsQTyVars _ _ _ (XLHsQTyVars _) _ = panic "kcLHsQTyVars"
1699
1700 kcLHsQTyVarBndrs :: Bool -- True <=> bump the TcLevel when bringing vars into scope
1701 -> Bool -- True <=> Default un-annotated tyvar
1702 -- binders to kind *
1703 -> SkolemInfo
1704 -> [LHsTyVarBndr GhcRn]
1705 -> TcM r
1706 -> TcM ([TyVar], r)
1707 -- There may be dependency between the explicit "ty" vars.
1708 -- So, we have to handle them one at a time.
1709 kcLHsQTyVarBndrs _ _ _ [] thing
1710 = do { stuff <- thing; return ([], stuff) }
1711
1712 kcLHsQTyVarBndrs cusk open_fam skol_info (L _ hs_tv : hs_tvs) thing
1713 = do { tv_pair@(tv, _) <- kc_hs_tv hs_tv
1714 -- NB: Bring all tvs into scope, even non-dependent ones,
1715 -- as they're needed in type synonyms, data constructors, etc.
1716
1717 ; (tvs, stuff) <- bind_unless_scoped tv_pair $
1718 kcLHsQTyVarBndrs cusk open_fam skol_info hs_tvs $
1719 thing
1720
1721 ; return ( tv : tvs, stuff ) }
1722 where
1723 -- | Bind the tyvar in the env't unless the bool is True
1724 bind_unless_scoped :: (TcTyVar, Bool) -> TcM a -> TcM a
1725 bind_unless_scoped (_, True) thing_inside = thing_inside
1726 bind_unless_scoped (tv, False) thing_inside
1727 | cusk = scopeTyVars skol_info [tv] thing_inside
1728 | otherwise = tcExtendTyVarEnv [tv] thing_inside
1729 -- These variables haven't settled down yet, so we don't want to bump
1730 -- the TcLevel. If we do, then we'll have metavars of too high a level
1731 -- floating about. Changing this causes many, many failures in the
1732 -- `dependent` testsuite directory.
1733
1734 kc_hs_tv :: HsTyVarBndr GhcRn -> TcM (TcTyVar, Bool)
1735 -- Special handling for the case where the binder is already in scope
1736 -- See Note [Associated type tyvar names] in Class and
1737 -- Note [TyVar binders for associated decls] in HsDecls
1738 kc_hs_tv (UserTyVar _ (L _ name))
1739 = do { mb_tv <- tcLookupLcl_maybe name
1740 ; case mb_tv of -- See Note [TyVar binders for associated decls]
1741 Just (ATyVar _ tv) -> return (tv, True)
1742 _ -> do { kind <- if open_fam
1743 then return liftedTypeKind
1744 else newMetaKindVar
1745 -- Open type/data families default their variables
1746 -- variables to kind *. But don't default in-scope
1747 -- class tyvars, of course
1748 ; tv <- newSkolemTyVar name kind
1749 ; return (tv, False) } }
1750
1751 kc_hs_tv (KindedTyVar _ lname@(L _ name) lhs_kind)
1752 = do { kind <- tcLHsKindSig (TyVarBndrKindCtxt name) lhs_kind
1753 ; mb_tv <- tcLookupLcl_maybe name
1754 ; case mb_tv of
1755 Just (ATyVar _ tv)
1756 -> do { discardResult $
1757 unifyKind (Just (HsTyVar noExt NotPromoted lname))
1758 kind (tyVarKind tv)
1759 ; return (tv, True) }
1760 _ -> do { tv <- newSkolemTyVar name kind
1761 ; return (tv, False) } }
1762
1763 kc_hs_tv (XTyVarBndr{}) = panic "kc_hs_tv"
1764
1765 {- Note [Kind-checking tyvar binders for associated types]
1766 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1767 When kind-checking the type-variable binders for associated
1768 data/newtype decls
1769 family decls
1770 we behave specially for type variables that are already in scope;
1771 that is, bound by the enclosing class decl. This is done in
1772 kcLHsQTyVarBndrs:
1773 * The use of tcImplicitQTKBndrs
1774 * The tcLookupLocal_maybe code in kc_hs_tv
1775
1776 See Note [Associated type tyvar names] in Class and
1777 Note [TyVar binders for associated decls] in HsDecls
1778
1779 We must do the same for family instance decls, where the in-scope
1780 variables may be bound by the enclosing class instance decl.
1781 Hence the use of tcImplicitQTKBndrs in tcFamTyPats.
1782 -}
1783
1784
1785 --------------------------------------
1786 -- Implicit binders
1787 --------------------------------------
1788
1789 -- | Bring implicitly quantified type/kind variables into scope during
1790 -- kind checking. Uses SigTvs, as per Note [Use SigTvs in kind-checking pass]
1791 -- in TcTyClsDecls.
1792 kcImplicitTKBndrs :: [Name] -- of the vars
1793 -> TcM a
1794 -> TcM ([TcTyVar], a) -- returns the tyvars created
1795 -- these are *not* dependency ordered
1796 kcImplicitTKBndrs var_ns thing_inside
1797 = do { tkvs <- mapM newFlexiKindedSigTyVar var_ns
1798 ; result <- tcExtendTyVarEnv tkvs thing_inside
1799 ; return (tkvs, result) }
1800
1801
1802 tcImplicitTKBndrs, tcImplicitTKBndrsSig, tcImplicitQTKBndrs
1803 :: SkolemInfo
1804 -> [Name]
1805 -> TcM a
1806 -> TcM ([TcTyVar], a)
1807 tcImplicitTKBndrs = tcImplicitTKBndrsX newFlexiKindedSkolemTyVar
1808 tcImplicitTKBndrsSig = tcImplicitTKBndrsX newFlexiKindedSigTyVar
1809 tcImplicitQTKBndrs = tcImplicitTKBndrsX newFlexiKindedQTyVar
1810
1811 tcImplicitTKBndrsX :: (Name -> TcM TcTyVar) -- new_tv function
1812 -> SkolemInfo
1813 -> [Name]
1814 -> TcM a
1815 -> TcM ([TcTyVar], a) -- these tyvars are dependency-ordered
1816 -- * Guarantees to call solveLocalEqualities to unify
1817 -- all constraints from thing_inside.
1818 --
1819 -- * Returned TcTyVars have the supplied HsTyVarBndrs,
1820 -- but may be in different order to the original [Name]
1821 -- (because of sorting to respect dependency)
1822 --
1823 -- * Returned TcTyVars have zonked kinds
1824 -- See Note [Keeping scoped variables in order: Implicit]
1825 tcImplicitTKBndrsX new_tv skol_info tv_names thing_inside
1826 | null tv_names -- Short cut for the common case where there
1827 -- are no implicit type variables to bind
1828 = do { result <- solveLocalEqualities thing_inside
1829 ; return ([], result) }
1830
1831 | otherwise
1832 = do { (skol_tvs, result)
1833 <- solveLocalEqualities $
1834 checkTvConstraints skol_info Nothing $
1835 do { tkvs <- mapM new_tv tv_names
1836 ; result <- tcExtendTyVarEnv tkvs thing_inside
1837 ; return (tkvs, result) }
1838
1839 ; skol_tvs <- mapM zonkTcTyCoVarBndr skol_tvs
1840 -- use zonkTcTyCoVarBndr because a skol_tv might be a SigTv
1841
1842 ; let final_tvs = toposortTyVars skol_tvs
1843 ; traceTc "tcImplicitTKBndrs" (ppr tv_names $$ ppr final_tvs)
1844 ; return (final_tvs, result) }
1845
1846 newFlexiKindedQTyVar :: Name -> TcM TcTyVar
1847 -- Make a new skolem for an implicit binder in a type/class/type
1848 -- instance declaration, with a flexi-kind
1849 -- But check for in-scope-ness, and if so return that instead
1850 newFlexiKindedQTyVar name
1851 = do { mb_tv <- tcLookupLcl_maybe name
1852 ; case mb_tv of
1853 Just (ATyVar _ tv) -> return tv
1854 _ -> newFlexiKindedSkolemTyVar name }
1855
1856 newFlexiKindedTyVar :: (Name -> Kind -> TcM TyVar) -> Name -> TcM TyVar
1857 newFlexiKindedTyVar new_tv name
1858 = do { kind <- newMetaKindVar
1859 ; new_tv name kind }
1860
1861 newFlexiKindedSkolemTyVar :: Name -> TcM TyVar
1862 newFlexiKindedSkolemTyVar = newFlexiKindedTyVar newSkolemTyVar
1863
1864 newFlexiKindedSigTyVar :: Name -> TcM TyVar
1865 newFlexiKindedSigTyVar = newFlexiKindedTyVar newSigTyVar
1866
1867 --------------------------------------
1868 -- Explicit binders
1869 --------------------------------------
1870
1871 -- | Used during the "kind-checking" pass in TcTyClsDecls only,
1872 -- and even then only for data-con declarations.
1873 -- See Note [Use SigTvs in kind-checking pass] in TcTyClsDecls
1874 kcExplicitTKBndrs :: [LHsTyVarBndr GhcRn]
1875 -> TcM a
1876 -> TcM a
1877 kcExplicitTKBndrs [] thing_inside = thing_inside
1878 kcExplicitTKBndrs (L _ hs_tv : hs_tvs) thing_inside
1879 = do { tv <- tcHsTyVarBndr newSigTyVar hs_tv
1880 ; tcExtendTyVarEnv [tv] $
1881 kcExplicitTKBndrs hs_tvs thing_inside }
1882
1883 tcExplicitTKBndrs :: SkolemInfo
1884 -> [LHsTyVarBndr GhcRn]
1885 -> TcM a
1886 -> TcM ([TcTyVar], a)
1887 tcExplicitTKBndrs skol_info hs_tvs thing_inside
1888 -- Used for the forall'd binders in type signatures of various kinds:
1889 -- - function signatures
1890 -- - data con signatures in GADT-style decls
1891 -- - pattern synonym signatures
1892 -- - expression type signatures
1893 --
1894 -- Specifically NOT used for the binders of a data type
1895 -- or type family decl. So the forall'd variables always /shadow/
1896 -- anything already in scope, and the complications of
1897 -- tcHsQTyVarName to not apply.
1898 --
1899 -- This function brings into scope a telescope of binders as written by
1900 -- the user. At first blush, it would then seem that we should bring
1901 -- them into scope one at a time, bumping the TcLevel each time.
1902 -- (Recall that we bump the level to prevent skolem escape from happening.)
1903 -- However, this leads to terrible error messages, because we end up
1904 -- failing to unify with some `k0`. Better would be to allow type inference
1905 -- to work, potentially creating a skolem-escape problem, and then to
1906 -- notice that the telescope is out of order. That's what we do here,
1907 -- following the logic of tcImplicitTKBndrsX.
1908 -- See also Note [Keeping scoped variables in order: Explicit]
1909 --
1910 -- No cloning: returned TyVars have the same Name as the incoming LHsTyVarBndrs
1911 | null hs_tvs -- Short cut that avoids creating an implication
1912 -- constraint in the common case where none is needed
1913 = do { result <- thing_inside
1914 ; return ([], result) }
1915
1916 | otherwise
1917 = do { (skol_tvs, result) <- checkTvConstraints skol_info (Just doc) $
1918 bind_tvbs hs_tvs
1919
1920 ; traceTc "tcExplicitTKBndrs" $
1921 vcat [ text "Hs vars:" <+> ppr hs_tvs
1922 , text "tvs:" <+> pprTyVars skol_tvs ]
1923
1924 ; return (skol_tvs, result) }
1925
1926 where
1927 bind_tvbs [] = do { result <- thing_inside
1928 ; return ([], result) }
1929 bind_tvbs (L _ tvb : tvbs)
1930 = do { tv <- tcHsTyVarBndr newSkolemTyVar tvb
1931 ; tcExtendTyVarEnv [tv] $
1932 do { (tvs, result) <- bind_tvbs tvbs
1933 ; return (tv : tvs, result) }}
1934
1935 doc = sep (map ppr hs_tvs)
1936
1937 -----------------
1938 tcHsTyVarBndr :: (Name -> Kind -> TcM TyVar)
1939 -> HsTyVarBndr GhcRn -> TcM TcTyVar
1940 -- Return a TcTyVar, built using the provided function
1941 -- Typically the Kind inside the HsTyVarBndr will be a tyvar
1942 -- with a mutable kind in it.
1943 --
1944 -- Returned TcTyVar has the same name; no cloning
1945 tcHsTyVarBndr new_tv (UserTyVar _ (L _ tv_nm))
1946 = newFlexiKindedTyVar new_tv tv_nm
1947 tcHsTyVarBndr new_tv (KindedTyVar _ (L _ tv_nm) lhs_kind)
1948 = do { kind <- tcLHsKindSig (TyVarBndrKindCtxt tv_nm) lhs_kind
1949 ; new_tv tv_nm kind }
1950 tcHsTyVarBndr _ (XTyVarBndr _) = panic "tcHsTyVarBndr"
1951
1952 -----------------
1953 newWildTyVar :: Name -> TcM TcTyVar
1954 -- ^ New unification variable for a wildcard
1955 newWildTyVar _name
1956 = do { kind <- newMetaKindVar
1957 ; uniq <- newUnique
1958 ; details <- newMetaDetails TauTv
1959 ; let name = mkSysTvName uniq (fsLit "w")
1960 tyvar = (mkTcTyVar name kind details)
1961 ; traceTc "newWildTyVar" (ppr tyvar)
1962 ; return tyvar }
1963
1964 --------------------------
1965 -- Bringing tyvars into scope
1966 --------------------------
1967
1968 -- | Bring tyvars into scope, wrapping the thing_inside in an implication
1969 -- constraint. The implication constraint is necessary to provide SkolemInfo
1970 -- for the tyvars and to ensure that no unification variables made outside
1971 -- the scope of these tyvars (i.e. lower TcLevel) unify with the locally-scoped
1972 -- tyvars (i.e. higher TcLevel).
1973 --
1974 -- INVARIANT: The thing_inside must check only types, never terms.
1975 --
1976 -- Use this (not tcExtendTyVarEnv) wherever you expect a Λ or ∀ in Core.
1977 -- Use tcExtendTyVarEnv otherwise.
1978 scopeTyVars :: SkolemInfo -> [TcTyVar] -> TcM a -> TcM a
1979 scopeTyVars skol_info tvs = scopeTyVars2 skol_info [(tyVarName tv, tv) | tv <- tvs]
1980
1981 -- | Like 'scopeTyVars', but allows you to specify different scoped names
1982 -- than the Names stored within the tyvars.
1983 scopeTyVars2 :: SkolemInfo -> [(Name, TcTyVar)] -> TcM a -> TcM a
1984 scopeTyVars2 skol_info prs thing_inside
1985 = fmap snd $ -- discard the TcEvBinds, which will always be empty
1986 checkConstraints skol_info (map snd prs) [{- no EvVars -}] $
1987 tcExtendNameTyVarEnv prs $
1988 thing_inside
1989
1990 ------------------
1991 kindGeneralize :: TcType -> TcM [KindVar]
1992 -- Quantify the free kind variables of a kind or type
1993 -- In the latter case the type is closed, so it has no free
1994 -- type variables. So in both cases, all the free vars are kind vars
1995 -- Input must be zonked.
1996 -- NB: You must call solveEqualities or solveLocalEqualities before
1997 -- kind generalization
1998 kindGeneralize kind_or_type
1999 = do { let kvs = tyCoVarsOfTypeDSet kind_or_type
2000 dvs = DV { dv_kvs = kvs, dv_tvs = emptyDVarSet }
2001 ; gbl_tvs <- tcGetGlobalTyCoVars -- Already zonked
2002 ; quantifyTyVars gbl_tvs dvs }
2003
2004 {-
2005 Note [Kind generalisation]
2006 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2007 We do kind generalisation only at the outer level of a type signature.
2008 For example, consider
2009 T :: forall k. k -> *
2010 f :: (forall a. T a -> Int) -> Int
2011 When kind-checking f's type signature we generalise the kind at
2012 the outermost level, thus:
2013 f1 :: forall k. (forall (a:k). T k a -> Int) -> Int -- YES!
2014 and *not* at the inner forall:
2015 f2 :: (forall k. forall (a:k). T k a -> Int) -> Int -- NO!
2016 Reason: same as for HM inference on value level declarations,
2017 we want to infer the most general type. The f2 type signature
2018 would be *less applicable* than f1, because it requires a more
2019 polymorphic argument.
2020
2021 NB: There are no explicit kind variables written in f's signature.
2022 When there are, the renamer adds these kind variables to the list of
2023 variables bound by the forall, so you can indeed have a type that's
2024 higher-rank in its kind. But only by explicit request.
2025
2026 Note [Kinds of quantified type variables]
2027 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2028 tcTyVarBndrsGen quantifies over a specified list of type variables,
2029 *and* over the kind variables mentioned in the kinds of those tyvars.
2030
2031 Note that we must zonk those kinds (obviously) but less obviously, we
2032 must return type variables whose kinds are zonked too. Example
2033 (a :: k7) where k7 := k9 -> k9
2034 We must return
2035 [k9, a:k9->k9]
2036 and NOT
2037 [k9, a:k7]
2038 Reason: we're going to turn this into a for-all type,
2039 forall k9. forall (a:k7). blah
2040 which the type checker will then instantiate, and instantiate does not
2041 look through unification variables!
2042
2043 Hence using zonked_kinds when forming tvs'.
2044
2045 Note [Free-floating kind vars]
2046 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2047 Consider
2048
2049 data T = MkT (forall (a :: k). Proxy a)
2050 -- from test ghci/scripts/T7873
2051
2052 This is not an existential datatype, but a higher-rank one (the forall
2053 to the right of MkT). Also consider
2054
2055 data S a = MkS (Proxy (a :: k))
2056
2057 According to the rules around implicitly-bound kind variables, in both
2058 cases those k's scope over the whole declaration. The renamer grabs
2059 it and adds it to the hsq_implicits field of the HsQTyVars of the
2060 tycon. So it must be in scope during type-checking, but we want to
2061 reject T while accepting S.
2062
2063 Why reject T? Because the kind variable isn't fixed by anything. For
2064 a variable like k to be implicit, it needs to be mentioned in the kind
2065 of a tycon tyvar. But it isn't.
2066
2067 Why accept S? Because kind inference tells us that a has kind k, so it's
2068 all OK.
2069
2070 Our approach depends on whether or not the datatype has a CUSK.
2071
2072 Non-CUSK: In the first pass (kcTyClTyVars) we just bring
2073 k into scope. In the second pass (tcTyClTyVars),
2074 we check to make sure that k has been unified with some other variable
2075 (or generalized over, making k into a skolem). If it hasn't been, then
2076 it must be a free-floating kind var. Error.
2077
2078 CUSK: When we determine the tycon's final, never-to-be-changed kind
2079 in kcLHsQTyVars, we check to make sure all implicitly-bound kind
2080 vars are indeed mentioned in a kind somewhere. If not, error.
2081
2082 We also perform free-floating kind var analysis for type family instances
2083 (see #13985). Here is an interesting example:
2084
2085 type family T :: k
2086 type instance T = (Nothing :: Maybe a)
2087
2088 Upon a cursory glance, it may appear that the kind variable `a` is
2089 free-floating above, since there are no (visible) LHS patterns in `T`. However,
2090 there is an *invisible* pattern due to the return kind, so inside of GHC, the
2091 instance looks closer to this:
2092
2093 type family T @k :: k
2094 type instance T @(Maybe a) = (Nothing :: Maybe a)
2095
2096 Here, we can see that `a` really is bound by a LHS type pattern, so `a` is in
2097 fact not free-floating. Contrast that with this example:
2098
2099 type instance T = Proxy (Nothing :: Maybe a)
2100
2101 This would looks like this inside of GHC:
2102
2103 type instance T @(*) = Proxy (Nothing :: Maybe a)
2104
2105 So this time, `a` is neither bound by a visible nor invisible type pattern on
2106 the LHS, so it would be reported as free-floating.
2107
2108 Finally, here's one more brain-teaser (from #9574). In the example below:
2109
2110 class Funct f where
2111 type Codomain f :: *
2112 instance Funct ('KProxy :: KProxy o) where
2113 type Codomain 'KProxy = NatTr (Proxy :: o -> *)
2114
2115 As it turns out, `o` is not free-floating in this example. That is because `o`
2116 bound by the kind signature of the LHS type pattern 'KProxy. To make this more
2117 obvious, one can also write the instance like so:
2118
2119 instance Funct ('KProxy :: KProxy o) where
2120 type Codomain ('KProxy :: KProxy o) = NatTr (Proxy :: o -> *)
2121
2122 -}
2123
2124 --------------------
2125 -- getInitialKind has made a suitably-shaped kind for the type or class
2126 -- Look it up in the local environment. This is used only for tycons
2127 -- that we're currently type-checking, so we're sure to find a TcTyCon.
2128 kcLookupTcTyCon :: Name -> TcM TcTyCon
2129 kcLookupTcTyCon nm
2130 = do { tc_ty_thing <- tcLookup nm
2131 ; return $ case tc_ty_thing of
2132 ATcTyCon tc -> tc
2133 _ -> pprPanic "kcLookupTcTyCon" (ppr tc_ty_thing) }
2134
2135 -----------------------
2136 -- | Bring tycon tyvars into scope. This is used during the "kind-checking"
2137 -- pass in TcTyClsDecls. (Never in getInitialKind, never in the
2138 -- "type-checking"/desugaring pass.)
2139 -- Never emits constraints, though the thing_inside might.
2140 kcTyClTyVars :: Name -> TcM a -> TcM a
2141 kcTyClTyVars tycon_name thing_inside
2142 -- See Note [Use SigTvs in kind-checking pass] in TcTyClsDecls
2143 = do { tycon <- kcLookupTcTyCon tycon_name
2144 ; tcExtendNameTyVarEnv (tcTyConScopedTyVars tycon) $ thing_inside }
2145
2146 tcTyClTyVars :: Name
2147 -> ([TyConBinder] -> Kind -> TcM a) -> TcM a
2148 -- ^ Used for the type variables of a type or class decl
2149 -- on the second full pass (type-checking/desugaring) in TcTyClDecls.
2150 -- This is *not* used in the initial-kind run, nor in the "kind-checking" pass.
2151 -- Accordingly, everything passed to the continuation is fully zonked.
2152 --
2153 -- (tcTyClTyVars T [a,b] thing_inside)
2154 -- where T : forall k1 k2 (a:k1 -> *) (b:k1). k2 -> *
2155 -- calls thing_inside with arguments
2156 -- [k1,k2,a,b] [k1:*, k2:*, Anon (k1 -> *), Anon k1] (k2 -> *)
2157 -- having also extended the type environment with bindings
2158 -- for k1,k2,a,b
2159 --
2160 -- Never emits constraints.
2161 --
2162 -- The LHsTyVarBndrs is always user-written, and the full, generalised
2163 -- kind of the tycon is available in the local env.
2164 tcTyClTyVars tycon_name thing_inside
2165 = do { tycon <- kcLookupTcTyCon tycon_name
2166
2167 -- Do checks on scoped tyvars
2168 -- See Note [Free-floating kind vars]
2169 ; let flav = tyConFlavour tycon
2170 scoped_prs = tcTyConScopedTyVars tycon
2171 scoped_tvs = map snd scoped_prs
2172 still_sig_tvs = filter isSigTyVar scoped_tvs
2173
2174 ; mapM_ report_sig_tv_err (findDupSigTvs scoped_prs)
2175
2176 ; checkNoErrs $ reportFloatingKvs tycon_name flav
2177 scoped_tvs still_sig_tvs
2178
2179 ; let res_kind = tyConResKind tycon
2180 binders = correct_binders (tyConBinders tycon) res_kind
2181 ; traceTc "tcTyClTyVars" (ppr tycon_name <+> ppr binders)
2182 ; scopeTyVars2 (TyConSkol flav tycon_name) scoped_prs $
2183 thing_inside binders res_kind }
2184 where
2185 report_sig_tv_err (n1, n2)
2186 = setSrcSpan (getSrcSpan n2) $
2187 addErrTc (text "Couldn't match" <+> quotes (ppr n1)
2188 <+> text "with" <+> quotes (ppr n2))
2189
2190 -- Given some TyConBinders and a TyCon's result kind, make sure that the
2191 -- correct any wrong Named/Anon choices. For example, consider
2192 -- type Syn k = forall (a :: k). Proxy a
2193 -- At first, it looks like k should be named -- after all, it appears on the RHS.
2194 -- However, the correct kind for Syn is (* -> *).
2195 -- (Why? Because k is the kind of a type, so k's kind is *. And the RHS also has
2196 -- kind *.) See also #13963.
2197 correct_binders :: [TyConBinder] -> Kind -> [TyConBinder]
2198 correct_binders binders kind
2199 = binders'
2200 where
2201 (_, binders') = mapAccumR go (tyCoVarsOfType kind) binders
2202
2203 go :: TyCoVarSet -> TyConBinder -> (TyCoVarSet, TyConBinder)
2204 go fvs binder
2205 | isNamedTyConBinder binder
2206 , not (tv `elemVarSet` fvs)
2207 = (new_fvs, mkAnonTyConBinder tv)
2208
2209 | not (isNamedTyConBinder binder)
2210 , tv `elemVarSet` fvs
2211 = (new_fvs, mkNamedTyConBinder Required tv)
2212 -- always Required, because it was anonymous (i.e. visible) previously
2213
2214 | otherwise
2215 = (new_fvs, binder)
2216
2217 where
2218 tv = binderVar binder
2219 new_fvs = fvs `delVarSet` tv `unionVarSet` tyCoVarsOfType (tyVarKind tv)
2220
2221 -----------------------------------
2222 tcDataKindSig :: [TyConBinder]
2223 -> Kind
2224 -> TcM ([TyConBinder], Kind)
2225 -- GADT decls can have a (perhaps partial) kind signature
2226 -- e.g. data T a :: * -> * -> * where ...
2227 -- This function makes up suitable (kinded) TyConBinders for the
2228 -- argument kinds. E.g. in this case it might return
2229 -- ([b::*, c::*], *)
2230 -- Never emits constraints.
2231 -- It's a little trickier than you might think: see
2232 -- Note [TyConBinders for the result kind signature of a data type]
2233 tcDataKindSig tc_bndrs kind
2234 = do { loc <- getSrcSpanM
2235 ; uniqs <- newUniqueSupply
2236 ; rdr_env <- getLocalRdrEnv
2237 ; let new_occs = [ occ
2238 | str <- allNameStrings
2239 , let occ = mkOccName tvName str
2240 , isNothing (lookupLocalRdrOcc rdr_env occ)
2241 -- Note [Avoid name clashes for associated data types]
2242 , not (occ `elem` lhs_occs) ]
2243 new_uniqs = uniqsFromSupply uniqs
2244 subst = mkEmptyTCvSubst (mkInScopeSet (mkVarSet lhs_tvs))
2245 ; return (go loc new_occs new_uniqs subst [] kind) }
2246 where
2247 lhs_tvs = map binderVar tc_bndrs
2248 lhs_occs = map getOccName lhs_tvs
2249
2250 go loc occs uniqs subst acc kind
2251 = case splitPiTy_maybe kind of
2252 Nothing -> (reverse acc, substTy subst kind)
2253
2254 Just (Anon arg, kind')
2255 -> go loc occs' uniqs' subst' (tcb : acc) kind'
2256 where
2257 arg' = substTy subst arg
2258 tv = mkTyVar (mkInternalName uniq occ loc) arg'
2259 subst' = extendTCvInScope subst tv
2260 tcb = TvBndr tv AnonTCB
2261 (uniq:uniqs') = uniqs
2262 (occ:occs') = occs
2263
2264 Just (Named (TvBndr tv vis), kind')
2265 -> go loc occs uniqs subst' (tcb : acc) kind'
2266 where
2267 (subst', tv') = substTyVarBndr subst tv
2268 tcb = TvBndr tv' (NamedTCB vis)
2269
2270 badKindSig :: Bool -> Kind -> SDoc
2271 badKindSig check_for_type kind
2272 = hang (sep [ text "Kind signature on data type declaration has non-*"
2273 , (if check_for_type then empty else text "and non-variable") <+>
2274 text "return kind" ])
2275 2 (ppr kind)
2276
2277 {- Note [TyConBinders for the result kind signature of a data type]
2278 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2279 Given
2280 data T (a::*) :: * -> forall k. k -> *
2281 we want to generate the extra TyConBinders for T, so we finally get
2282 (a::*) (b::*) (k::*) (c::k)
2283 The function tcDataKindSig generates these extra TyConBinders from
2284 the result kind signature.
2285
2286 We need to take care to give the TyConBinders
2287 (a) OccNames that are fresh (because the TyConBinders of a TyCon
2288 must have distinct OccNames
2289
2290 (b) Uniques that are fresh (obviously)
2291
2292 For (a) we need to avoid clashes with the tyvars declared by
2293 the user before the "::"; in the above example that is 'a'.
2294 And also see Note [Avoid name clashes for associated data types].
2295
2296 For (b) suppose we have
2297 data T :: forall k. k -> forall k. k -> *
2298 where the two k's are identical even up to their uniques. Surprisingly,
2299 this can happen: see Trac #14515.
2300
2301 It's reasonably easy to solve all this; just run down the list with a
2302 substitution; hence the recursive 'go' function. But it has to be
2303 done.
2304
2305 Note [Avoid name clashes for associated data types]
2306 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2307 Consider class C a b where
2308 data D b :: * -> *
2309 When typechecking the decl for D, we'll invent an extra type variable
2310 for D, to fill out its kind. Ideally we don't want this type variable
2311 to be 'a', because when pretty printing we'll get
2312 class C a b where
2313 data D b a0
2314 (NB: the tidying happens in the conversion to IfaceSyn, which happens
2315 as part of pretty-printing a TyThing.)
2316
2317 That's why we look in the LocalRdrEnv to see what's in scope. This is
2318 important only to get nice-looking output when doing ":info C" in GHCi.
2319 It isn't essential for correctness.
2320
2321
2322 ************************************************************************
2323 * *
2324 Partial signatures
2325 * *
2326 ************************************************************************
2327
2328 -}
2329
2330 tcHsPartialSigType
2331 :: UserTypeCtxt
2332 -> LHsSigWcType GhcRn -- The type signature
2333 -> TcM ( [(Name, TcTyVar)] -- Wildcards
2334 , Maybe TcType -- Extra-constraints wildcard
2335 , [Name] -- Original tyvar names, in correspondence with ...
2336 , [TcTyVar] -- ... Implicitly and explicitly bound type variables
2337 , TcThetaType -- Theta part
2338 , TcType ) -- Tau part
2339 -- See Note [Recipe for checking a signature]
2340 tcHsPartialSigType ctxt sig_ty
2341 | HsWC { hswc_ext = sig_wcs, hswc_body = ib_ty } <- sig_ty
2342 , HsIB { hsib_ext = HsIBRn { hsib_vars = implicit_hs_tvs }
2343 , hsib_body = hs_ty } <- ib_ty
2344 , (explicit_hs_tvs, L _ hs_ctxt, hs_tau) <- splitLHsSigmaTy hs_ty
2345 = addSigCtxt ctxt hs_ty $
2346 do { (implicit_tvs, (explicit_tvs, (wcs, wcx, theta, tau)))
2347 <- tcWildCardBindersX newWildTyVar Nothing sig_wcs $ \ wcs ->
2348 tcImplicitTKBndrsSig skol_info implicit_hs_tvs $
2349 tcExplicitTKBndrs skol_info explicit_hs_tvs $
2350 do { -- Instantiate the type-class context; but if there
2351 -- is an extra-constraints wildcard, just discard it here
2352 (theta, wcx) <- tcPartialContext hs_ctxt
2353
2354 ; tau <- tcHsOpenType hs_tau
2355
2356 ; return (wcs, wcx, theta, tau) }
2357
2358 -- We must return these separately, because all the zonking below
2359 -- might change the name of a SigTv. This, in turn, causes trouble
2360 -- in partial type signatures that bind scoped type variables, as
2361 -- we bring the wrong name into scope in the function body.
2362 -- Test case: partial-sigs/should_compile/LocalDefinitionBug
2363 ; let tv_names = map tyVarName (implicit_tvs ++ explicit_tvs)
2364
2365 -- Spit out the wildcards (including the extra-constraints one)
2366 -- as "hole" constraints, so that they'll be reported if necessary
2367 -- See Note [Extra-constraint holes in partial type signatures]
2368 ; emitWildCardHoleConstraints wcs
2369
2370 -- The SigTvs created above will sometimes have too high a TcLevel
2371 -- (note that they are generated *after* bumping the level in
2372 -- the tc{Im,Ex}plicitTKBndrsSig functions. Bumping the level
2373 -- is still important here, because the kinds of these variables
2374 -- do indeed need to have the higher level, so they can unify
2375 -- with other local type variables. But, now that we've type-checked
2376 -- everything (and solved equalities in the tcImplicit call)
2377 -- we need to promote the SigTvs so we don't violate the TcLevel
2378 -- invariant
2379 ; all_tvs <- mapM zonkPromoteTyCoVarBndr (implicit_tvs ++ explicit_tvs)
2380 -- zonkPromoteTyCoVarBndr deals well with SigTvs
2381
2382 ; theta <- mapM zonkPromoteType theta
2383 ; tau <- zonkPromoteType tau
2384
2385 ; checkValidType ctxt (mkSpecForAllTys all_tvs $ mkPhiTy theta tau)
2386
2387 ; traceTc "tcHsPartialSigType" (ppr all_tvs)
2388 ; return (wcs, wcx, tv_names, all_tvs, theta, tau) }
2389 where
2390 skol_info = SigTypeSkol ctxt
2391 tcHsPartialSigType _ (HsWC _ (XHsImplicitBndrs _)) = panic "tcHsPartialSigType"
2392 tcHsPartialSigType _ (XHsWildCardBndrs _) = panic "tcHsPartialSigType"
2393
2394 tcPartialContext :: HsContext GhcRn -> TcM (TcThetaType, Maybe TcType)
2395 tcPartialContext hs_theta
2396 | Just (hs_theta1, hs_ctxt_last) <- snocView hs_theta
2397 , L _ (HsWildCardTy wc) <- ignoreParens hs_ctxt_last
2398 = do { wc_tv_ty <- tcWildCardOcc wc constraintKind
2399 ; theta <- mapM tcLHsPredType hs_theta1
2400 ; return (theta, Just wc_tv_ty) }
2401 | otherwise
2402 = do { theta <- mapM tcLHsPredType hs_theta
2403 ; return (theta, Nothing) }
2404
2405 {- Note [Extra-constraint holes in partial type signatures]
2406 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2407 Consider
2408 f :: (_) => a -> a
2409 f x = ...
2410
2411 * The renamer makes a wildcard name for the "_", and puts it in
2412 the hswc_wcs field.
2413
2414 * Then, in tcHsPartialSigType, we make a new hole TcTyVar, in
2415 tcWildCardBindersX.
2416
2417 * TcBinds.chooseInferredQuantifiers fills in that hole TcTyVar
2418 with the inferred constraints, e.g. (Eq a, Show a)
2419
2420 * TcErrors.mkHoleError finally reports the error.
2421
2422 An annoying difficulty happens if there are more than 62 inferred
2423 constraints. Then we need to fill in the TcTyVar with (say) a 70-tuple.
2424 Where do we find the TyCon? For good reasons we only have constraint
2425 tuples up to 62 (see Note [How tuples work] in TysWiredIn). So how
2426 can we make a 70-tuple? This was the root cause of Trac #14217.
2427
2428 It's incredibly tiresome, because we only need this type to fill
2429 in the hole, to communicate to the error reporting machinery. Nothing
2430 more. So I use a HACK:
2431
2432 * I make an /ordinary/ tuple of the constraints, in
2433 TcBinds.chooseInferredQuantifiers. This is ill-kinded because
2434 ordinary tuples can't contain constraints, but it works fine. And for
2435 ordinary tuples we don't have the same limit as for constraint
2436 tuples (which need selectors and an assocated class).
2437
2438 * Because it is ill-kinded, it trips an assert in writeMetaTyVar,
2439 so now I disable the assertion if we are writing a type of
2440 kind Constraint. (That seldom/never normally happens so we aren't
2441 losing much.)
2442
2443 Result works fine, but it may eventually bite us.
2444
2445
2446 ************************************************************************
2447 * *
2448 Pattern signatures (i.e signatures that occur in patterns)
2449 * *
2450 ********************************************************************* -}
2451
2452 tcHsPatSigType :: UserTypeCtxt
2453 -> LHsSigWcType GhcRn -- The type signature
2454 -> TcM ( [(Name, TcTyVar)] -- Wildcards
2455 , [(Name, TcTyVar)] -- The new bit of type environment, binding
2456 -- the scoped type variables
2457 , TcType) -- The type
2458 -- Used for type-checking type signatures in
2459 -- (a) patterns e.g f (x::Int) = e
2460 -- (b) RULE forall bndrs e.g. forall (x::Int). f x = x
2461 --
2462 -- This may emit constraints
2463 -- See Note [Recipe for checking a signature]
2464 tcHsPatSigType ctxt sig_ty
2465 | HsWC { hswc_ext = sig_wcs, hswc_body = ib_ty } <- sig_ty
2466 , HsIB { hsib_ext = HsIBRn { hsib_vars = sig_vars}
2467 , hsib_body = hs_ty } <- ib_ty
2468 = addSigCtxt ctxt hs_ty $
2469 do { sig_tkvs <- mapM new_implicit_tv sig_vars
2470 ; (wcs, sig_ty)
2471 <- tcWildCardBindersX newWildTyVar Nothing sig_wcs $ \ wcs ->
2472 tcExtendTyVarEnv sig_tkvs $
2473 do { sig_ty <- tcHsOpenType hs_ty
2474 ; return (wcs, sig_ty) }
2475
2476 ; emitWildCardHoleConstraints wcs
2477
2478 -- sig_ty might have tyvars that are at a higher TcLevel (if hs_ty
2479 -- contains a forall). Promote these.
2480 ; sig_ty <- zonkPromoteType sig_ty
2481 ; checkValidType ctxt sig_ty
2482
2483 ; tv_pairs <- mapM mk_tv_pair sig_tkvs
2484
2485 ; traceTc "tcHsPatSigType" (ppr sig_vars)
2486 ; return (wcs, tv_pairs, sig_ty) }
2487 where
2488 new_implicit_tv name = do { kind <- newMetaKindVar
2489 ; new_tv name kind }
2490
2491 new_tv = case ctxt of
2492 RuleSigCtxt {} -> newSkolemTyVar
2493 _ -> newSigTyVar
2494 -- See Note [Pattern signature binders]
2495 -- See Note [Unifying SigTvs]
2496
2497 mk_tv_pair tv = do { tv' <- zonkTcTyVarToTyVar tv
2498 ; return (tyVarName tv, tv') }
2499 -- The Name is one of sig_vars, the lexically scoped name
2500 -- But if it's a SigTyVar, it might have been unified
2501 -- with an existing in-scope skolem, so we must zonk
2502 -- here. See Note [Pattern signature binders]
2503 tcHsPatSigType _ (HsWC _ (XHsImplicitBndrs _)) = panic "tcHsPatSigType"
2504 tcHsPatSigType _ (XHsWildCardBndrs _) = panic "tcHsPatSigType"
2505
2506 tcPatSig :: Bool -- True <=> pattern binding
2507 -> LHsSigWcType GhcRn
2508 -> ExpSigmaType
2509 -> TcM (TcType, -- The type to use for "inside" the signature
2510 [(Name,TcTyVar)], -- The new bit of type environment, binding
2511 -- the scoped type variables
2512 [(Name,TcTyVar)], -- The wildcards
2513 HsWrapper) -- Coercion due to unification with actual ty
2514 -- Of shape: res_ty ~ sig_ty
2515 tcPatSig in_pat_bind sig res_ty
2516 = do { (sig_wcs, sig_tvs, sig_ty) <- tcHsPatSigType PatSigCtxt sig
2517 -- sig_tvs are the type variables free in 'sig',
2518 -- and not already in scope. These are the ones
2519 -- that should be brought into scope
2520
2521 ; if null sig_tvs then do {
2522 -- Just do the subsumption check and return
2523 wrap <- addErrCtxtM (mk_msg sig_ty) $
2524 tcSubTypeET PatSigOrigin PatSigCtxt res_ty sig_ty
2525 ; return (sig_ty, [], sig_wcs, wrap)
2526 } else do
2527 -- Type signature binds at least one scoped type variable
2528
2529 -- A pattern binding cannot bind scoped type variables
2530 -- It is more convenient to make the test here
2531 -- than in the renamer
2532 { when in_pat_bind (addErr (patBindSigErr sig_tvs))
2533
2534 -- Check that all newly-in-scope tyvars are in fact
2535 -- constrained by the pattern. This catches tiresome
2536 -- cases like
2537 -- type T a = Int
2538 -- f :: Int -> Int
2539 -- f (x :: T a) = ...
2540 -- Here 'a' doesn't get a binding. Sigh
2541 ; let bad_tvs = [ tv | (_,tv) <- sig_tvs
2542 , not (tv `elemVarSet` exactTyCoVarsOfType sig_ty) ]
2543 ; checkTc (null bad_tvs) (badPatSigTvs sig_ty bad_tvs)
2544
2545 -- Now do a subsumption check of the pattern signature against res_ty
2546 ; wrap <- addErrCtxtM (mk_msg sig_ty) $
2547 tcSubTypeET PatSigOrigin PatSigCtxt res_ty sig_ty
2548
2549 -- Phew!
2550 ; return (sig_ty, sig_tvs, sig_wcs, wrap)
2551 } }
2552 where
2553 mk_msg sig_ty tidy_env
2554 = do { (tidy_env, sig_ty) <- zonkTidyTcType tidy_env sig_ty
2555 ; res_ty <- readExpType res_ty -- should be filled in by now
2556 ; (tidy_env, res_ty) <- zonkTidyTcType tidy_env res_ty
2557 ; let msg = vcat [ hang (text "When checking that the pattern signature:")
2558 4 (ppr sig_ty)
2559 , nest 2 (hang (text "fits the type of its context:")
2560 2 (ppr res_ty)) ]
2561 ; return (tidy_env, msg) }
2562
2563 patBindSigErr :: [(Name,TcTyVar)] -> SDoc
2564 patBindSigErr sig_tvs
2565 = hang (text "You cannot bind scoped type variable" <> plural sig_tvs
2566 <+> pprQuotedList (map fst sig_tvs))
2567 2 (text "in a pattern binding signature")
2568
2569 {- Note [Pattern signature binders]
2570 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2571 Consider
2572 data T = forall a. T a (a->Int)
2573 f (T x (f :: b->Int)) = blah
2574
2575 Here
2576 * The pattern (T p1 p2) creates a *skolem* type variable 'a_sk',
2577 It must be a skolem so that that it retains its identity, and
2578 TcErrors.getSkolemInfo can thereby find the binding site for the skolem.
2579
2580 * The type signature pattern (f :: b->Int) makes a fresh meta-tyvar b_sig
2581 (a SigTv), and binds "b" :-> b_sig in the envt
2582
2583 * Then unification makes b_sig := a_sk
2584 That's why we must make b_sig a MetaTv (albeit a SigTv),
2585 not a SkolemTv, so that it can unify to a_sk.
2586
2587 * Finally, in 'blah' we must have the envt "b" :-> a_sk. The pair
2588 ("b" :-> a_sk) is returned by tcHsPatSigType, constructed by
2589 mk_tv_pair in that function.
2590
2591 Another example (Trac #13881):
2592 fl :: forall (l :: [a]). Sing l -> Sing l
2593 fl (SNil :: Sing (l :: [y])) = SNil
2594 When we reach the pattern signature, 'l' is in scope from the
2595 outer 'forall':
2596 "a" :-> a_sk :: *
2597 "l" :-> l_sk :: [a_sk]
2598 We make up a fresh meta-SigTv, y_sig, for 'y', and kind-check
2599 the pattern signature
2600 Sing (l :: [y])
2601 That unifies y_sig := a_sk. We return from tcHsPatSigType with
2602 the pair ("y" :-> a_sk).
2603
2604 For RULE binders, though, things are a bit different (yuk).
2605 RULE "foo" forall (x::a) (y::[a]). f x y = ...
2606 Here this really is the binding site of the type variable so we'd like
2607 to use a skolem, so that we get a complaint if we unify two of them
2608 together.
2609
2610 Note [Unifying SigTvs]
2611 ~~~~~~~~~~~~~~~~~~~~~~
2612 ALAS we have no decent way of avoiding two SigTvs getting unified.
2613 Consider
2614 f (x::(a,b)) (y::c)) = [fst x, y]
2615 Here we'd really like to complain that 'a' and 'c' are unified. But
2616 for the reasons above we can't make a,b,c into skolems, so they
2617 are just SigTvs that can unify. And indeed, this would be ok,
2618 f x (y::c) = case x of
2619 (x1 :: a1, True) -> [x,y]
2620 (x1 :: a2, False) -> [x,y,y]
2621 Here the type of x's first component is called 'a1' in one branch and
2622 'a2' in the other. We could try insisting on the same OccName, but
2623 they definitely won't have the sane lexical Name.
2624
2625 I think we could solve this by recording in a SigTv a list of all the
2626 in-scope variables that it should not unify with, but it's fiddly.
2627
2628
2629 ************************************************************************
2630 * *
2631 Checking kinds
2632 * *
2633 ************************************************************************
2634
2635 -}
2636
2637 unifyKinds :: [LHsType GhcRn] -> [(TcType, TcKind)] -> TcM ([TcType], TcKind)
2638 unifyKinds rn_tys act_kinds
2639 = do { kind <- newMetaKindVar
2640 ; let check rn_ty (ty, act_kind) = checkExpectedKind (unLoc rn_ty) ty act_kind kind
2641 ; tys' <- zipWithM check rn_tys act_kinds
2642 ; return (tys', kind) }
2643
2644 {-
2645 ************************************************************************
2646 * *
2647 Promotion
2648 * *
2649 ************************************************************************
2650 -}
2651
2652 -- | Whenever a type is about to be added to the environment, it's necessary
2653 -- to make sure that any free meta-tyvars in the type are promoted to the
2654 -- current TcLevel. (They might be at a higher level due to the level-bumping
2655 -- in tcExplicitTKBndrs, for example.) This function both zonks *and*
2656 -- promotes.
2657 zonkPromoteType :: TcType -> TcM TcType
2658 zonkPromoteType = mapType zonkPromoteMapper ()
2659
2660 -- cf. TcMType.zonkTcTypeMapper
2661 zonkPromoteMapper :: TyCoMapper () TcM
2662 zonkPromoteMapper = TyCoMapper { tcm_smart = True
2663 , tcm_tyvar = const zonkPromoteTcTyVar
2664 , tcm_covar = const covar
2665 , tcm_hole = const hole
2666 , tcm_tybinder = const tybinder }
2667 where
2668 covar cv
2669 = mkCoVarCo <$> zonkPromoteTyCoVarKind cv
2670
2671 hole :: CoercionHole -> TcM Coercion
2672 hole h
2673 = do { contents <- unpackCoercionHole_maybe h
2674 ; case contents of
2675 Just co -> do { co <- zonkPromoteCoercion co
2676 ; checkCoercionHole cv co }
2677 Nothing -> do { cv' <- zonkPromoteTyCoVarKind cv
2678 ; return $ mkHoleCo (setCoHoleCoVar h cv') } }
2679 where
2680 cv = coHoleCoVar h
2681
2682 tybinder :: TyVar -> ArgFlag -> TcM ((), TyVar)
2683 tybinder tv _flag = ((), ) <$> zonkPromoteTyCoVarKind tv
2684
2685 zonkPromoteTcTyVar :: TyCoVar -> TcM TcType
2686 zonkPromoteTcTyVar tv
2687 | isMetaTyVar tv
2688 = do { let ref = metaTyVarRef tv
2689 ; contents <- readTcRef ref
2690 ; case contents of
2691 Flexi -> do { promoted <- promoteTyVar tv
2692 ; if promoted
2693 then zonkPromoteTcTyVar tv -- read it again
2694 else mkTyVarTy <$> zonkPromoteTyCoVarKind tv }
2695 Indirect ty -> zonkPromoteType ty }
2696
2697 | isTcTyVar tv && isSkolemTyVar tv -- NB: isSkolemTyVar says "True" to pure TyVars
2698 = do { tc_lvl <- getTcLevel
2699 ; mkTyVarTy <$> zonkPromoteTyCoVarKind (promoteSkolem tc_lvl tv) }
2700
2701 | otherwise
2702 = mkTyVarTy <$> zonkPromoteTyCoVarKind tv
2703
2704 zonkPromoteTyCoVarKind :: TyCoVar -> TcM TyCoVar
2705 zonkPromoteTyCoVarKind = updateTyVarKindM zonkPromoteType
2706
2707 zonkPromoteTyCoVarBndr :: TyCoVar -> TcM TyCoVar
2708 zonkPromoteTyCoVarBndr tv
2709 | isSigTyVar tv
2710 = tcGetTyVar "zonkPromoteTyCoVarBndr SigTv" <$> zonkPromoteTcTyVar tv
2711
2712 | isTcTyVar tv && isSkolemTyVar tv
2713 = do { tc_lvl <- getTcLevel
2714 ; zonkPromoteTyCoVarKind (promoteSkolem tc_lvl tv) }
2715
2716 | otherwise
2717 = zonkPromoteTyCoVarKind tv
2718
2719 zonkPromoteCoercion :: Coercion -> TcM Coercion
2720 zonkPromoteCoercion = mapCoercion zonkPromoteMapper ()
2721
2722 zonkPromoteTypeInKnot :: TcType -> TcM TcType
2723 zonkPromoteTypeInKnot = mapType (zonkPromoteMapper { tcm_smart = False }) ()
2724 -- NB: Just changing smart to False will still use the smart zonker (not suitable
2725 -- for in-the-knot) for kinds. But that's OK, because kinds aren't knot-tied.
2726
2727 {-
2728 ************************************************************************
2729 * *
2730 Sort checking kinds
2731 * *
2732 ************************************************************************
2733
2734 tcLHsKindSig converts a user-written kind to an internal, sort-checked kind.
2735 It does sort checking and desugaring at the same time, in one single pass.
2736 -}
2737
2738 tcLHsKindSig :: UserTypeCtxt -> LHsKind GhcRn -> TcM Kind
2739 tcLHsKindSig ctxt hs_kind
2740 -- See Note [Recipe for checking a signature] in TcHsType
2741 -- Result is zonked
2742 = do { kind <- solveLocalEqualities $
2743 tc_lhs_kind kindLevelMode hs_kind
2744 ; traceTc "tcLHsKindSig" (ppr kind)
2745 ; kind <- zonkPromoteType kind
2746 -- This zonk is very important in the case of higher rank kinds
2747 -- E.g. Trac #13879 f :: forall (p :: forall z (y::z). <blah>).
2748 -- <more blah>
2749 -- When instantiating p's kind at occurrences of p in <more blah>
2750 -- it's crucial that the kind we instantiate is fully zonked,
2751 -- else we may fail to substitute properly
2752
2753 ; checkValidType ctxt kind
2754 ; traceTc "tcLHsKindSig2" (ppr kind)
2755 ; return kind }
2756
2757 tc_lhs_kind :: TcTyMode -> LHsKind GhcRn -> TcM Kind
2758 tc_lhs_kind mode k
2759 = addErrCtxt (text "In the kind" <+> quotes (ppr k)) $
2760 tc_lhs_type (kindLevel mode) k liftedTypeKind
2761
2762 promotionErr :: Name -> PromotionErr -> TcM a
2763 promotionErr name err
2764 = failWithTc (hang (pprPECategory err <+> quotes (ppr name) <+> text "cannot be used here")
2765 2 (parens reason))
2766 where
2767 reason = case err of
2768 ConstrainedDataConPE pred
2769 -> text "it has an unpromotable context"
2770 <+> quotes (ppr pred)
2771 FamDataConPE -> text "it comes from a data family instance"
2772 NoDataKindsTC -> text "perhaps you intended to use DataKinds"
2773 NoDataKindsDC -> text "perhaps you intended to use DataKinds"
2774 PatSynPE -> text "pattern synonyms cannot be promoted"
2775 PatSynExPE -> sep [ text "the existential variables of a pattern synonym"
2776 , text "signature do not scope over the pattern" ]
2777 _ -> text "it is defined and used in the same recursive group"
2778
2779 {-
2780 ************************************************************************
2781 * *
2782 Scoped type variables
2783 * *
2784 ************************************************************************
2785 -}
2786
2787 badPatSigTvs :: TcType -> [TyVar] -> SDoc
2788 badPatSigTvs sig_ty bad_tvs
2789 = vcat [ fsep [text "The type variable" <> plural bad_tvs,
2790 quotes (pprWithCommas ppr bad_tvs),
2791 text "should be bound by the pattern signature" <+> quotes (ppr sig_ty),
2792 text "but are actually discarded by a type synonym" ]
2793 , text "To fix this, expand the type synonym"
2794 , text "[Note: I hope to lift this restriction in due course]" ]
2795
2796 {-
2797 ************************************************************************
2798 * *
2799 Error messages and such
2800 * *
2801 ************************************************************************
2802 -}
2803
2804 -- | Make an appropriate message for an error in a function argument.
2805 -- Used for both expressions and types.
2806 funAppCtxt :: (Outputable fun, Outputable arg) => fun -> arg -> Int -> SDoc
2807 funAppCtxt fun arg arg_no
2808 = hang (hsep [ text "In the", speakNth arg_no, ptext (sLit "argument of"),
2809 quotes (ppr fun) <> text ", namely"])
2810 2 (quotes (ppr arg))
2811
2812 -- See Note [Free-floating kind vars]
2813 reportFloatingKvs :: Name -- of the tycon
2814 -> TyConFlavour -- What sort of TyCon it is
2815 -> [TcTyVar] -- all tyvars, not necessarily zonked
2816 -> [TcTyVar] -- floating tyvars
2817 -> TcM ()
2818 reportFloatingKvs tycon_name flav all_tvs bad_tvs
2819 = unless (null bad_tvs) $ -- don't bother zonking if there's no error
2820 do { all_tvs <- mapM zonkTcTyVarToTyVar all_tvs
2821 ; bad_tvs <- mapM zonkTcTyVarToTyVar bad_tvs
2822 ; let (tidy_env, tidy_all_tvs) = tidyOpenTyCoVars emptyTidyEnv all_tvs
2823 tidy_bad_tvs = map (tidyTyVarOcc tidy_env) bad_tvs
2824 ; mapM_ (report tidy_all_tvs) tidy_bad_tvs }
2825 where
2826 report tidy_all_tvs tidy_bad_tv
2827 = addErr $
2828 vcat [ text "Kind variable" <+> quotes (ppr tidy_bad_tv) <+>
2829 text "is implicitly bound in" <+> ppr flav
2830 , quotes (ppr tycon_name) <> comma <+>
2831 text "but does not appear as the kind of any"
2832 , text "of its type variables. Perhaps you meant"
2833 , text "to bind it explicitly somewhere?"
2834 , ppWhen (not (null tidy_all_tvs)) $
2835 hang (text "Type variables with inferred kinds:")
2836 2 (ppr_tv_bndrs tidy_all_tvs) ]
2837
2838 ppr_tv_bndrs tvs = sep (map pp_tv tvs)
2839 pp_tv tv = parens (ppr tv <+> dcolon <+> ppr (tyVarKind tv))