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