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