cd80be649cf148e7f33fd8e65f3c57e7ffdfcaeb
[ghc.git] / compiler / typecheck / TcTyClsDecls.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The AQUA Project, Glasgow University, 1996-1998
4
5
6 TcTyClsDecls: Typecheck type and class declarations
7 -}
8
9 {-# LANGUAGE CPP, TupleSections, MultiWayIf #-}
10 {-# LANGUAGE TypeFamilies #-}
11
12 module TcTyClsDecls (
13 tcTyAndClassDecls,
14
15 -- Functions used by TcInstDcls to check
16 -- data/type family instance declarations
17 kcDataDefn, tcConDecls, dataDeclChecks, checkValidTyCon,
18 tcFamTyPats, tcTyFamInstEqn,
19 tcAddTyFamInstCtxt, tcMkDataFamInstCtxt, tcAddDataFamInstCtxt,
20 wrongKindOfFamily, dataConCtxt
21 ) where
22
23 #include "HsVersions.h"
24
25 import GhcPrelude
26
27 import HsSyn
28 import HscTypes
29 import BuildTyCl
30 import TcRnMonad
31 import TcEnv
32 import TcValidity
33 import TcHsSyn
34 import TcTyDecls
35 import TcClassDcl
36 import {-# SOURCE #-} TcInstDcls( tcInstDecls1 )
37 import TcDeriv (DerivInfo)
38 import TcEvidence ( tcCoercionKind, isEmptyTcEvBinds )
39 import TcUnify ( checkConstraints )
40 import TcHsType
41 import TcMType
42 import TysWiredIn ( unitTy )
43 import TcType
44 import RnEnv( lookupConstructorFields )
45 import FamInst
46 import FamInstEnv
47 import Coercion
48 import Type
49 import TyCoRep -- for checkValidRoles
50 import Class
51 import CoAxiom
52 import TyCon
53 import DataCon
54 import Id
55 import Var
56 import VarEnv
57 import VarSet
58 import Module
59 import Name
60 import NameSet
61 import NameEnv
62 import Outputable
63 import Maybes
64 import Unify
65 import Util
66 import Pair
67 import SrcLoc
68 import ListSetOps
69 import DynFlags
70 import Unique
71 import ConLike( ConLike(..) )
72 import BasicTypes
73 import qualified GHC.LanguageExtensions as LangExt
74
75 import Control.Monad
76 import Data.List
77 import Data.List.NonEmpty ( NonEmpty(..) )
78 import qualified Data.Set as Set
79
80
81 {-
82 ************************************************************************
83 * *
84 \subsection{Type checking for type and class declarations}
85 * *
86 ************************************************************************
87
88 Note [Grouping of type and class declarations]
89 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
90 tcTyAndClassDecls is called on a list of `TyClGroup`s. Each group is a strongly
91 connected component of mutually dependent types and classes. We kind check and
92 type check each group separately to enhance kind polymorphism. Take the
93 following example:
94
95 type Id a = a
96 data X = X (Id Int)
97
98 If we were to kind check the two declarations together, we would give Id the
99 kind * -> *, since we apply it to an Int in the definition of X. But we can do
100 better than that, since Id really is kind polymorphic, and should get kind
101 forall (k::*). k -> k. Since it does not depend on anything else, it can be
102 kind-checked by itself, hence getting the most general kind. We then kind check
103 X, which works fine because we then know the polymorphic kind of Id, and simply
104 instantiate k to *.
105
106 Note [Check role annotations in a second pass]
107 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
108 Role inference potentially depends on the types of all of the datacons declared
109 in a mutually recursive group. The validity of a role annotation, in turn,
110 depends on the result of role inference. Because the types of datacons might
111 be ill-formed (see #7175 and Note [Checking GADT return types]) we must check
112 *all* the tycons in a group for validity before checking *any* of the roles.
113 Thus, we take two passes over the resulting tycons, first checking for general
114 validity and then checking for valid role annotations.
115 -}
116
117 tcTyAndClassDecls :: [TyClGroup GhcRn] -- Mutually-recursive groups in
118 -- dependency order
119 -> TcM ( TcGblEnv -- Input env extended by types and
120 -- classes
121 -- and their implicit Ids,DataCons
122 , [InstInfo GhcRn] -- Source-code instance decls info
123 , [DerivInfo] -- data family deriving info
124 )
125 -- Fails if there are any errors
126 tcTyAndClassDecls tyclds_s
127 -- The code recovers internally, but if anything gave rise to
128 -- an error we'd better stop now, to avoid a cascade
129 -- Type check each group in dependency order folding the global env
130 = checkNoErrs $ fold_env [] [] tyclds_s
131 where
132 fold_env :: [InstInfo GhcRn]
133 -> [DerivInfo]
134 -> [TyClGroup GhcRn]
135 -> TcM (TcGblEnv, [InstInfo GhcRn], [DerivInfo])
136 fold_env inst_info deriv_info []
137 = do { gbl_env <- getGblEnv
138 ; return (gbl_env, inst_info, deriv_info) }
139 fold_env inst_info deriv_info (tyclds:tyclds_s)
140 = do { (tcg_env, inst_info', deriv_info') <- tcTyClGroup tyclds
141 ; setGblEnv tcg_env $
142 -- remaining groups are typechecked in the extended global env.
143 fold_env (inst_info' ++ inst_info)
144 (deriv_info' ++ deriv_info)
145 tyclds_s }
146
147 tcTyClGroup :: TyClGroup GhcRn
148 -> TcM (TcGblEnv, [InstInfo GhcRn], [DerivInfo])
149 -- Typecheck one strongly-connected component of type, class, and instance decls
150 -- See Note [TyClGroups and dependency analysis] in HsDecls
151 tcTyClGroup (TyClGroup { group_tyclds = tyclds
152 , group_roles = roles
153 , group_instds = instds })
154 = do { let role_annots = mkRoleAnnotEnv roles
155
156 -- Step 1: Typecheck the type/class declarations
157 ; traceTc "---- tcTyClGroup ---- {" empty
158 ; traceTc "Decls for" (ppr (map (tcdName . unLoc) tyclds))
159 ; tyclss <- tcTyClDecls tyclds role_annots
160
161 -- Step 1.5: Make sure we don't have any type synonym cycles
162 ; traceTc "Starting synonym cycle check" (ppr tyclss)
163 ; this_uid <- fmap thisPackage getDynFlags
164 ; checkSynCycles this_uid tyclss tyclds
165 ; traceTc "Done synonym cycle check" (ppr tyclss)
166
167 -- Step 2: Perform the validity check on those types/classes
168 -- We can do this now because we are done with the recursive knot
169 -- Do it before Step 3 (adding implicit things) because the latter
170 -- expects well-formed TyCons
171 ; traceTc "Starting validity check" (ppr tyclss)
172 ; tyclss <- concatMapM checkValidTyCl tyclss
173 ; traceTc "Done validity check" (ppr tyclss)
174 ; mapM_ (recoverM (return ()) . checkValidRoleAnnots role_annots) tyclss
175 -- See Note [Check role annotations in a second pass]
176
177 ; traceTc "---- end tcTyClGroup ---- }" empty
178
179 -- Step 3: Add the implicit things;
180 -- we want them in the environment because
181 -- they may be mentioned in interface files
182 ; gbl_env <- addTyConsToGblEnv tyclss
183
184 -- Step 4: check instance declarations
185 ; setGblEnv gbl_env $
186 tcInstDecls1 instds }
187
188 tcTyClGroup (XTyClGroup _) = panic "tcTyClGroup"
189
190 tcTyClDecls :: [LTyClDecl GhcRn] -> RoleAnnotEnv -> TcM [TyCon]
191 tcTyClDecls tyclds role_annots
192 = tcExtendKindEnv promotion_err_env $ --- See Note [Type environment evolution]
193 do { -- Step 1: kind-check this group and returns the final
194 -- (possibly-polymorphic) kind of each TyCon and Class
195 -- See Note [Kind checking for type and class decls]
196 tc_tycons <- kcTyClGroup tyclds
197 ; traceTc "tcTyAndCl generalized kinds" (vcat (map ppr_tc_tycon tc_tycons))
198
199 -- Step 2: type-check all groups together, returning
200 -- the final TyCons and Classes
201 --
202 -- NB: We have to be careful here to NOT eagerly unfold
203 -- type synonyms, as we have not tested for type synonym
204 -- loops yet and could fall into a black hole.
205 ; fixM $ \ ~rec_tyclss -> do
206 { tcg_env <- getGblEnv
207 ; let roles = inferRoles (tcg_src tcg_env) role_annots rec_tyclss
208
209 -- Populate environment with knot-tied ATyCon for TyCons
210 -- NB: if the decls mention any ill-staged data cons
211 -- (see Note [Recursion and promoting data constructors])
212 -- we will have failed already in kcTyClGroup, so no worries here
213 ; tcExtendRecEnv (zipRecTyClss tc_tycons rec_tyclss) $
214
215 -- Also extend the local type envt with bindings giving
216 -- a TcTyCon for each each knot-tied TyCon or Class
217 -- See Note [Type checking recursive type and class declarations]
218 -- and Note [Type environment evolution]
219 tcExtendKindEnvWithTyCons tc_tycons $
220
221 -- Kind and type check declarations for this group
222 mapM (tcTyClDecl roles) tyclds
223 } }
224 where
225 promotion_err_env = mkPromotionErrorEnv tyclds
226 ppr_tc_tycon tc = parens (sep [ ppr (tyConName tc) <> comma
227 , ppr (tyConBinders tc) <> comma
228 , ppr (tyConResKind tc)
229 , ppr (isTcTyCon tc) ])
230
231 zipRecTyClss :: [TcTyCon]
232 -> [TyCon] -- Knot-tied
233 -> [(Name,TyThing)]
234 -- Build a name-TyThing mapping for the TyCons bound by decls
235 -- being careful not to look at the knot-tied [TyThing]
236 -- The TyThings in the result list must have a visible ATyCon,
237 -- because typechecking types (in, say, tcTyClDecl) looks at
238 -- this outer constructor
239 zipRecTyClss tc_tycons rec_tycons
240 = [ (name, ATyCon (get name)) | tc_tycon <- tc_tycons, let name = getName tc_tycon ]
241 where
242 rec_tc_env :: NameEnv TyCon
243 rec_tc_env = foldr add_tc emptyNameEnv rec_tycons
244
245 add_tc :: TyCon -> NameEnv TyCon -> NameEnv TyCon
246 add_tc tc env = foldr add_one_tc env (tc : tyConATs tc)
247
248 add_one_tc :: TyCon -> NameEnv TyCon -> NameEnv TyCon
249 add_one_tc tc env = extendNameEnv env (tyConName tc) tc
250
251 get name = case lookupNameEnv rec_tc_env name of
252 Just tc -> tc
253 other -> pprPanic "zipRecTyClss" (ppr name <+> ppr other)
254
255 {-
256 ************************************************************************
257 * *
258 Kind checking
259 * *
260 ************************************************************************
261
262 Note [Kind checking for type and class decls]
263 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
264 Kind checking is done thus:
265
266 1. Make up a kind variable for each parameter of the declarations,
267 and extend the kind environment (which is in the TcLclEnv)
268
269 2. Kind check the declarations
270
271 We need to kind check all types in the mutually recursive group
272 before we know the kind of the type variables. For example:
273
274 class C a where
275 op :: D b => a -> b -> b
276
277 class D c where
278 bop :: (Monad c) => ...
279
280 Here, the kind of the locally-polymorphic type variable "b"
281 depends on *all the uses of class D*. For example, the use of
282 Monad c in bop's type signature means that D must have kind Type->Type.
283
284 Note: we don't treat type synonyms specially (we used to, in the past);
285 in particular, even if we have a type synonym cycle, we still kind check
286 it normally, and test for cycles later (checkSynCycles). The reason
287 we can get away with this is because we have more systematic TYPE r
288 inference, which means that we can do unification between kinds that
289 aren't lifted (this historically was not true.)
290
291 The downside of not directly reading off the kinds off the RHS of
292 type synonyms in topological order is that we don't transparently
293 support making synonyms of types with higher-rank kinds. But
294 you can always specify a CUSK directly to make this work out.
295 See tc269 for an example.
296
297 Note [Skip decls with CUSKs in kcLTyClDecl]
298 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
299 Consider
300
301 data T (a :: *) = MkT (S a) -- Has CUSK
302 data S a = MkS (T Int) (S a) -- No CUSK
303
304 Via getInitialKinds we get
305 T :: * -> *
306 S :: kappa -> *
307
308 Then we call kcTyClDecl on each decl in the group, to constrain the
309 kind unification variables. BUT we /skip/ the RHS of any decl with
310 a CUSK. Here we skip the RHS of T, so we eventually get
311 S :: forall k. k -> *
312
313 This gets us more polymorphism than we would otherwise get, similar
314 (but implemented strangely differently from) the treatment of type
315 signatures in value declarations.
316
317 Open type families
318 ~~~~~~~~~~~~~~~~~~
319 This treatment of type synonyms only applies to Haskell 98-style synonyms.
320 General type functions can be recursive, and hence, appear in `alg_decls'.
321
322 The kind of an open type family is solely determinded by its kind signature;
323 hence, only kind signatures participate in the construction of the initial
324 kind environment (as constructed by `getInitialKind'). In fact, we ignore
325 instances of families altogether in the following. However, we need to include
326 the kinds of *associated* families into the construction of the initial kind
327 environment. (This is handled by `allDecls').
328
329 See also Note [Kind checking recursive type and class declarations]
330
331 Note [How TcTyCons work]
332 ~~~~~~~~~~~~~~~~~~~~~~~~
333 TcTyCons are used for two distinct purposes
334
335 1. When recovering from a type error in a type declaration,
336 we want to put the erroneous TyCon in the environment in a
337 way that won't lead to more errors. We use a TcTyCon for this;
338 see makeRecoveryTyCon.
339
340 2. When checking a type/class declaration (in module TcTyClsDecls), we come
341 upon knowledge of the eventual tycon in bits and pieces.
342
343 S1) First, we use getInitialKinds to look over the user-provided
344 kind signature of a tycon (including, for example, the number
345 of parameters written to the tycon) to get an initial shape of
346 the tycon's kind. We record that shape in a TcTyCon.
347
348 S2) Then, using these initial kinds, we kind-check the body of the
349 tycon (class methods, data constructors, etc.), filling in the
350 metavariables in the tycon's initial kind.
351
352 S3) We then generalize to get the tycon's final, fixed
353 kind. Finally, once this has happened for all tycons in a
354 mutually recursive group, we can desugar the lot.
355
356 For convenience, we store partially-known tycons in TcTyCons, which
357 might store meta-variables. These TcTyCons are stored in the local
358 environment in TcTyClsDecls, until the real full TyCons can be created
359 during desugaring. A desugared program should never have a TcTyCon.
360
361 A challenging piece in all of this is that we end up taking three separate
362 passes over every declaration:
363 - one in getInitialKind (this pass look only at the head, not the body)
364 - one in kcTyClDecls (to kind-check the body)
365 - a final one in tcTyClDecls (to desugar)
366 In the latter two passes, we need to connect the user-written type
367 variables in an LHsQTyVars with the variables in the tycon's
368 inferred kind. Because the tycon might not have a CUSK, this
369 matching up is, in general, quite hard to do. (Look through the
370 git history between Dec 2015 and Apr 2016 for
371 TcHsType.splitTelescopeTvs!) Instead of trying, we just store the
372 list of type variables to bring into scope, in the
373 tyConScopedTyVars field of the TcTyCon. These tyvars are brought
374 into scope in kcTyClTyVars and tcTyClTyVars, both in TcHsType.
375
376 In a TcTyCon, everything is zonked after the kind-checking pass (S2).
377
378 See also Note [Type checking recursive type and class declarations].
379
380 Note [Check telescope again during generalisation]
381 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
382 The telescope check before kind generalisation is useful to catch something
383 like this:
384
385 data T a k = MkT (Proxy (a :: k))
386
387 Clearly, the k has to come first. Checking for this problem must come before
388 kind generalisation, as described in Note [Bad telescopes] in
389 TcValidity.
390
391 However, we have to check again *after* kind generalisation, to catch something
392 like this:
393
394 data SameKind :: k -> k -> Type -- to force unification
395 data S a (b :: a) (d :: SameKind c b)
396
397 Note that c has no explicit binding site. As such, it's quantified by kind
398 generalisation. (Note that kcHsTyVarBndrs does not return such variables
399 as binders in its returned TcTyCon.) The user-written part of this telescope
400 is well-ordered; no earlier variables depend on later ones. However, after
401 kind generalisation, we put c up front, like so:
402
403 data S {c :: a} a (b :: a) (d :: SameKind c b)
404
405 We now have a problem. We could detect this problem just by looking at the
406 free vars of the kinds of the generalised variables (the kvs), but we get
407 such a nice error message out of checkValidTelescope that it seems like the
408 right thing to do.
409
410 Note [Type environment evolution]
411 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
412 As we typecheck a group of declarations the type environment evolves.
413 Consider for example:
414 data B (a :: Type) = MkB (Proxy 'MkB)
415
416 We do the following steps:
417
418 1. Start of tcTyClDecls: use mkPromotionErrorEnv to initialise the
419 type env with promotion errors
420 B :-> TyConPE
421 MkB :-> DataConPE
422
423 2. kcTyCLGruup
424 - Do getInitialKinds, which will signal a promotion
425 error if B is used in any of the kinds needed to initialse
426 B's kind (e.g. (a :: Type)) here
427
428 - Extend the type env with these initial kinds (monomorphic for
429 decls that lack a CUSK)
430 B :-> TcTyCon <initial kind>
431 (thereby overriding the B :-> TyConPE binding)
432 and do kcLTyClDecl on each decl to get equality constraints on
433 all those inital kinds
434
435 - Generalise the inital kind, making a poly-kinded TcTyCon
436
437 3. Back in tcTyDecls, extend the envt with bindings of the poly-kinded
438 TcTyCons, again overriding the promotion-error bindings.
439
440 But note that the data constructor promotion errors are still in place
441 so that (in our example) a use of MkB will sitll be signalled as
442 an error.
443
444 4. Typecheck the decls.
445
446 5. In tcTyClGroup, extend the envt with bindings for TyCon and DataCons
447
448
449 Note [Missed opportunity to retain higher-rank kinds]
450 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
451 In 'kcTyClGroup', there is a missed opportunity to make kind
452 inference work in a few more cases. The idea is analogous
453 to Note [Single function non-recursive binding special-case]:
454
455 * If we have an SCC with a single decl, which is non-recursive,
456 instead of creating a unification variable representing the
457 kind of the decl and unifying it with the rhs, we can just
458 read the type directly of the rhs.
459
460 * Furthermore, we can update our SCC analysis to ignore
461 dependencies on declarations which have CUSKs: we don't
462 have to kind-check these all at once, since we can use
463 the CUSK to initialize the kind environment.
464
465 Unfortunately this requires reworking a bit of the code in
466 'kcLTyClDecl' so I've decided to punt unless someone shouts about it.
467
468 Note [Don't process associated types in kcLHsQTyVars]
469 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
470 Previously, we processed associated types in the thing_inside in kcLHsQTyVars,
471 but this was wrong -- we want to do ATs sepearately.
472 The consequence for not doing it this way is #15142:
473
474 class ListTuple (tuple :: Type) (as :: [(k, Type)]) where
475 type ListToTuple as :: Type
476
477 We assign k a kind kappa[1]. When checking the tuple (k, Type), we try to unify
478 kappa ~ Type, but this gets deferred because we bumped the TcLevel as we bring
479 `tuple` into scope. Thus, when we check ListToTuple, kappa[1] still hasn't
480 unified with Type. And then, when we generalize the kind of ListToTuple (which
481 indeed has a CUSK, according to the rules), we skolemize the free metavariable
482 kappa. Note that we wouldn't skolemize kappa when generalizing the kind of ListTuple,
483 because the solveEqualities in kcLHsQTyVars is at TcLevel 1 and so kappa[1]
484 will unify with Type.
485
486 Bottom line: as associated types should have no effect on a CUSK enclosing class,
487 we move processing them to a separate action, run after the outer kind has
488 been generalized.
489
490 -}
491
492 kcTyClGroup :: [LTyClDecl GhcRn] -> TcM [TcTyCon]
493
494 -- Kind check this group, kind generalize, and return the resulting local env
495 -- This binds the TyCons and Classes of the group, but not the DataCons
496 -- See Note [Kind checking for type and class decls]
497 -- Third return value is Nothing if the tycon be unsaturated; otherwise,
498 -- the arity
499 kcTyClGroup decls
500 = do { mod <- getModule
501 ; traceTc "---- kcTyClGroup ---- {" (text "module" <+> ppr mod $$ vcat (map ppr decls))
502
503 -- Kind checking;
504 -- 1. Bind kind variables for decls
505 -- 2. Kind-check decls
506 -- 3. Generalise the inferred kinds
507 -- See Note [Kind checking for type and class decls]
508
509 -- Step 1: Bind kind variables for all decls
510 ; initial_tcs <- getInitialKinds decls
511 ; traceTc "kcTyClGroup: initial kinds" $
512 ppr_tc_kinds initial_tcs
513
514 -- Step 2: Set extended envt, kind-check the decls
515 -- NB: the environment extension overrides the tycon
516 -- promotion-errors bindings
517 -- See Note [Type environment evolution]
518
519 ; solveEqualities $
520 tcExtendKindEnvWithTyCons initial_tcs $
521 mapM_ kcLTyClDecl decls
522
523 -- Step 3: generalisation
524 -- Kind checking done for this group
525 -- Now we have to kind generalize the flexis
526 ; poly_tcs <- mapAndReportM generalise initial_tcs
527
528 ; traceTc "---- kcTyClGroup end ---- }" (ppr_tc_kinds poly_tcs)
529 ; return poly_tcs }
530
531 where
532 ppr_tc_kinds tcs = vcat (map pp_tc tcs)
533 pp_tc tc = ppr (tyConName tc) <+> dcolon <+> ppr (tyConKind tc)
534
535 generalise :: TcTyCon -> TcM TcTyCon
536 -- For polymorphic things this is a no-op
537 generalise tc
538 = setSrcSpan (getSrcSpan tc) $
539 addTyConCtxt tc $
540 do { let name = tyConName tc
541 ; tc_binders <- mapM zonkTcTyVarBinder (tyConBinders tc)
542 ; tc_res_kind <- zonkTcType (tyConResKind tc)
543 ; let scoped_tvs = tcTyConScopedTyVars tc
544 user_tyvars = tcTyConUserTyVars tc
545
546 -- See Note [checkValidDependency]
547 ; checkValidDependency tc_binders tc_res_kind
548
549 -- See Note [Bad telescopes] in TcValidity
550 ; checkValidTelescope tc_binders user_tyvars empty
551 ; kvs <- kindGeneralize (mkTyConKind tc_binders tc_res_kind)
552
553 ; let all_binders = mkNamedTyConBinders Inferred kvs ++ tc_binders
554
555 ; (env, all_binders') <- zonkTyVarBindersX emptyZonkEnv all_binders
556 ; tc_res_kind' <- zonkTcTypeToType env tc_res_kind
557 ; scoped_tvs' <- zonkSigTyVarPairs scoped_tvs
558
559 -- See Note [Check telescope again during generalisation]
560 ; let extra = text "NB: Implicitly declared variables come before others."
561 ; checkValidTelescope all_binders user_tyvars extra
562
563 -- Make sure tc_kind' has the final, zonked kind variables
564 ; traceTc "Generalise kind" $
565 vcat [ ppr name, ppr tc_binders, ppr (mkTyConKind tc_binders tc_res_kind)
566 , ppr kvs, ppr all_binders, ppr tc_res_kind
567 , ppr all_binders', ppr tc_res_kind'
568 , ppr scoped_tvs ]
569
570 ; return (mkTcTyCon name user_tyvars all_binders' tc_res_kind'
571 scoped_tvs'
572 (tyConFlavour tc)) }
573
574
575 --------------
576 tcExtendKindEnvWithTyCons :: [TcTyCon] -> TcM a -> TcM a
577 tcExtendKindEnvWithTyCons tcs
578 = tcExtendKindEnvList [ (tyConName tc, ATcTyCon tc) | tc <- tcs ]
579
580 --------------
581 mkPromotionErrorEnv :: [LTyClDecl GhcRn] -> TcTypeEnv
582 -- Maps each tycon/datacon to a suitable promotion error
583 -- tc :-> APromotionErr TyConPE
584 -- dc :-> APromotionErr RecDataConPE
585 -- See Note [Recursion and promoting data constructors]
586
587 mkPromotionErrorEnv decls
588 = foldr (plusNameEnv . mk_prom_err_env . unLoc)
589 emptyNameEnv decls
590
591 mk_prom_err_env :: TyClDecl GhcRn -> TcTypeEnv
592 mk_prom_err_env (ClassDecl { tcdLName = L _ nm, tcdATs = ats })
593 = unitNameEnv nm (APromotionErr ClassPE)
594 `plusNameEnv`
595 mkNameEnv [ (name, APromotionErr TyConPE)
596 | L _ (FamilyDecl { fdLName = L _ name }) <- ats ]
597
598 mk_prom_err_env (DataDecl { tcdLName = L _ name
599 , tcdDataDefn = HsDataDefn { dd_cons = cons } })
600 = unitNameEnv name (APromotionErr TyConPE)
601 `plusNameEnv`
602 mkNameEnv [ (con, APromotionErr RecDataConPE)
603 | L _ con' <- cons, L _ con <- getConNames con' ]
604
605 mk_prom_err_env decl
606 = unitNameEnv (tcdName decl) (APromotionErr TyConPE)
607 -- Works for family declarations too
608
609 --------------
610 getInitialKinds :: [LTyClDecl GhcRn] -> TcM [TcTyCon]
611 -- Returns a TcTyCon for each TyCon bound by the decls,
612 -- each with its initial kind
613
614 getInitialKinds decls = concatMapM (addLocM getInitialKind) decls
615
616 getInitialKind :: TyClDecl GhcRn -> TcM [TcTyCon]
617 -- Allocate a fresh kind variable for each TyCon and Class
618 -- For each tycon, return a TcTyCon with kind k
619 -- where k is the kind of tc, derived from the LHS
620 -- of the definition (and probably including
621 -- kind unification variables)
622 -- Example: data T a b = ...
623 -- return (T, kv1 -> kv2 -> kv3)
624 --
625 -- This pass deals with (ie incorporates into the kind it produces)
626 -- * The kind signatures on type-variable binders
627 -- * The result kinds signature on a TyClDecl
628 --
629 -- No family instances are passed to getInitialKinds
630
631 getInitialKind decl@(ClassDecl { tcdLName = L _ name, tcdTyVars = ktvs, tcdATs = ats })
632 = do { let cusk = hsDeclHasCusk decl
633 ; tycon <- kcLHsQTyVars name ClassFlavour cusk ktvs $
634 return constraintKind
635 -- See Note [Don't process associated types in kcLHsQTyVars]
636 ; inner_tcs <- tcExtendNameTyVarEnv (tcTyConScopedTyVars tycon) $
637 getFamDeclInitialKinds (Just cusk) ats
638 ; return (tycon : inner_tcs) }
639
640 getInitialKind decl@(DataDecl { tcdLName = L _ name
641 , tcdTyVars = ktvs
642 , tcdDataDefn = HsDataDefn { dd_kindSig = m_sig
643 , dd_ND = new_or_data } })
644 = do { tycon <-
645 kcLHsQTyVars name (newOrDataToFlavour new_or_data) (hsDeclHasCusk decl) ktvs $
646 case m_sig of
647 Just ksig -> tcLHsKindSig (DataKindCtxt name) ksig
648 Nothing -> return liftedTypeKind
649 ; return [tycon] }
650
651 getInitialKind (FamDecl { tcdFam = decl })
652 = do { tc <- getFamDeclInitialKind Nothing decl
653 ; return [tc] }
654
655 getInitialKind decl@(SynDecl { tcdLName = L _ name
656 , tcdTyVars = ktvs
657 , tcdRhs = rhs })
658 = do { tycon <- kcLHsQTyVars name TypeSynonymFlavour (hsDeclHasCusk decl) ktvs $
659 case kind_annotation rhs of
660 Nothing -> newMetaKindVar
661 Just ksig -> tcLHsKindSig (TySynKindCtxt name) ksig
662 ; return [tycon] }
663 where
664 -- Keep this synchronized with 'hsDeclHasCusk'.
665 kind_annotation (L _ ty) = case ty of
666 HsParTy _ lty -> kind_annotation lty
667 HsKindSig _ _ k -> Just k
668 _ -> Nothing
669
670 getInitialKind (DataDecl _ (L _ _) _ _ (XHsDataDefn _)) = panic "getInitialKind"
671 getInitialKind (XTyClDecl _) = panic "getInitialKind"
672
673 ---------------------------------
674 getFamDeclInitialKinds :: Maybe Bool -- if assoc., CUSKness of assoc. class
675 -> [LFamilyDecl GhcRn]
676 -> TcM [TcTyCon]
677 getFamDeclInitialKinds mb_cusk decls
678 = mapM (addLocM (getFamDeclInitialKind mb_cusk)) decls
679
680 getFamDeclInitialKind :: Maybe Bool -- if assoc., CUSKness of assoc. class
681 -> FamilyDecl GhcRn
682 -> TcM TcTyCon
683 getFamDeclInitialKind mb_cusk decl@(FamilyDecl { fdLName = L _ name
684 , fdTyVars = ktvs
685 , fdResultSig = L _ resultSig
686 , fdInfo = info })
687 = do { tycon <- kcLHsQTyVars name flav cusk ktvs $
688 case resultSig of
689 KindSig _ ki -> tcLHsKindSig ctxt ki
690 TyVarSig _ (L _ (KindedTyVar _ _ ki)) -> tcLHsKindSig ctxt ki
691 _ -- open type families have * return kind by default
692 | tcFlavourIsOpen flav -> return liftedTypeKind
693 -- closed type families have their return kind inferred
694 -- by default
695 | otherwise -> newMetaKindVar
696 ; return tycon }
697 where
698 cusk = famDeclHasCusk mb_cusk decl
699 flav = case info of
700 DataFamily -> DataFamilyFlavour (isJust mb_cusk)
701 OpenTypeFamily -> OpenTypeFamilyFlavour (isJust mb_cusk)
702 ClosedTypeFamily _ -> ClosedTypeFamilyFlavour
703 ctxt = TyFamResKindCtxt name
704 getFamDeclInitialKind _ (XFamilyDecl _) = panic "getFamDeclInitialKind"
705
706 ------------------------------------------------------------------------
707 kcLTyClDecl :: LTyClDecl GhcRn -> TcM ()
708 -- See Note [Kind checking for type and class decls]
709 kcLTyClDecl (L loc decl)
710 | hsDeclHasCusk decl -- See Note [Skip decls with CUSKs in kcLTyClDecl]
711 = traceTc "kcTyClDecl skipped due to cusk" (ppr tc_name)
712
713 | otherwise
714 = setSrcSpan loc $
715 tcAddDeclCtxt decl $
716 do { traceTc "kcTyClDecl {" (ppr tc_name)
717 ; kcTyClDecl decl
718 ; traceTc "kcTyClDecl done }" (ppr tc_name) }
719 where
720 tc_name = tyClDeclLName decl
721
722 kcTyClDecl :: TyClDecl GhcRn -> TcM ()
723 -- This function is used solely for its side effect on kind variables
724 -- NB kind signatures on the type variables and
725 -- result kind signature have already been dealt with
726 -- by getInitialKind, so we can ignore them here.
727
728 kcTyClDecl (DataDecl { tcdLName = L _ name, tcdDataDefn = defn })
729 | HsDataDefn { dd_cons = cons@(L _ (ConDeclGADT {}) : _), dd_ctxt = L _ [] } <- defn
730 = mapM_ (wrapLocM kcConDecl) cons
731 -- hs_tvs and dd_kindSig already dealt with in getInitialKind
732 -- This must be a GADT-style decl,
733 -- (see invariants of DataDefn declaration)
734 -- so (a) we don't need to bring the hs_tvs into scope, because the
735 -- ConDecls bind all their own variables
736 -- (b) dd_ctxt is not allowed for GADT-style decls, so we can ignore it
737
738 | HsDataDefn { dd_ctxt = ctxt, dd_cons = cons } <- defn
739 = kcTyClTyVars name $
740 do { _ <- tcHsContext ctxt
741 ; mapM_ (wrapLocM kcConDecl) cons }
742
743 kcTyClDecl (SynDecl { tcdLName = L _ name, tcdRhs = lrhs })
744 = kcTyClTyVars name $
745 do { syn_tc <- kcLookupTcTyCon name
746 -- NB: check against the result kind that we allocated
747 -- in getInitialKinds.
748 ; discardResult $ tcCheckLHsType lrhs (tyConResKind syn_tc) }
749
750 kcTyClDecl (ClassDecl { tcdLName = L _ name
751 , tcdCtxt = ctxt, tcdSigs = sigs })
752 = kcTyClTyVars name $
753 do { _ <- tcHsContext ctxt
754 ; mapM_ (wrapLocM kc_sig) sigs }
755 where
756 kc_sig (ClassOpSig _ _ nms op_ty)
757 = kcHsSigType (TyConSkol ClassFlavour name) nms op_ty
758 kc_sig _ = return ()
759
760 kcTyClDecl (FamDecl _ (FamilyDecl { fdLName = L _ fam_tc_name
761 , fdInfo = fd_info }))
762 -- closed type families look at their equations, but other families don't
763 -- do anything here
764 = case fd_info of
765 ClosedTypeFamily (Just eqns) ->
766 do { fam_tc <- kcLookupTcTyCon fam_tc_name
767 ; mapM_ (kcTyFamInstEqn fam_tc) eqns }
768 _ -> return ()
769 kcTyClDecl (FamDecl _ (XFamilyDecl _)) = panic "kcTyClDecl"
770 kcTyClDecl (DataDecl _ (L _ _) _ _ (XHsDataDefn _)) = panic "kcTyClDecl"
771 kcTyClDecl (XTyClDecl _) = panic "kcTyClDecl"
772
773 -------------------
774 kcConDecl :: ConDecl GhcRn -> TcM ()
775 kcConDecl (ConDeclH98 { con_name = name, con_ex_tvs = ex_tvs
776 , con_mb_cxt = ex_ctxt, con_args = args })
777 = addErrCtxt (dataConCtxtName [name]) $
778 -- See Note [Use SigTvs in kind-checking pass]
779 kcExplicitTKBndrs ex_tvs $
780 do { _ <- tcHsMbContext ex_ctxt
781 ; mapM_ (tcHsOpenType . getBangType) (hsConDeclArgTys args) }
782 -- We don't need to check the telescope here, because that's
783 -- done in tcConDecl
784
785 kcConDecl (ConDeclGADT { con_names = names
786 , con_qvars = qtvs, con_mb_cxt = cxt
787 , con_args = args, con_res_ty = res_ty })
788 | HsQTvs { hsq_ext = HsQTvsRn { hsq_implicit = implicit_tkv_nms }
789 , hsq_explicit = explicit_tkv_nms } <- qtvs
790 = -- Even though the data constructor's type is closed, we
791 -- must still kind-check the type, because that may influence
792 -- the inferred kind of the /type/ constructor. Example:
793 -- data T f a where
794 -- MkT :: f a -> T f a
795 -- If we don't look at MkT we won't get the correct kind
796 -- for the type constructor T
797 addErrCtxt (dataConCtxtName names) $
798 discardResult $
799 kcImplicitTKBndrs implicit_tkv_nms $
800 kcExplicitTKBndrs explicit_tkv_nms $
801 do { _ <- tcHsMbContext cxt
802 ; mapM_ (tcHsOpenType . getBangType) (hsConDeclArgTys args)
803 ; _ <- tcHsOpenType res_ty
804 ; return () }
805 kcConDecl (XConDecl _) = panic "kcConDecl"
806 kcConDecl (ConDeclGADT _ _ _ (XLHsQTyVars _) _ _ _ _) = panic "kcConDecl"
807
808 {-
809 Note [Recursion and promoting data constructors]
810 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
811 We don't want to allow promotion in a strongly connected component
812 when kind checking.
813
814 Consider:
815 data T f = K (f (K Any))
816
817 When kind checking the `data T' declaration the local env contains the
818 mappings:
819 T -> ATcTyCon <some initial kind>
820 K -> APromotionErr
821
822 APromotionErr is only used for DataCons, and only used during type checking
823 in tcTyClGroup.
824
825 Note [Use SigTvs in kind-checking pass]
826 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
827 Consider
828
829 data Proxy a where
830 MkProxy1 :: forall k (b :: k). Proxy b
831 MkProxy2 :: forall j (c :: j). Proxy c
832
833 It seems reasonable that this should be accepted. But something very strange
834 is going on here: when we're kind-checking this declaration, we need to unify
835 the kind of `a` with k and j -- even though k and j's scopes are local to the type of
836 MkProxy{1,2}. The best approach we've come up with is to use SigTvs during
837 the kind-checking pass. First off, note that it's OK if the kind-checking pass
838 is too permissive: we'll snag the problems in the type-checking pass later.
839 (This extra permissiveness might happen with something like
840
841 data SameKind :: k -> k -> Type
842 data Bad a where
843 MkBad :: forall k1 k2 (a :: k1) (b :: k2). Bad (SameKind a b)
844
845 which would be accepted if k1 and k2 were SigTvs. This is correctly rejected
846 in the second pass, though. Test case: polykinds/SigTvKinds3)
847 Recall that the kind-checking pass exists solely to collect constraints
848 on the kinds and to power unification.
849
850 To achieve the use of SigTvs, we must be careful to use specialized functions
851 that produce SigTvs, not ordinary skolems. This is why we need
852 kcExplicitTKBndrs and kcImplicitTKBndrs in TcHsType, separate from their
853 tc... variants.
854
855 The drawback of this approach is sometimes it will accept a definition that
856 a (hypothetical) declarative specification would likely reject. As a general
857 rule, we don't want to allow polymorphic recursion without a CUSK. Indeed,
858 the whole point of CUSKs is to allow polymorphic recursion. Yet, the SigTvs
859 approach allows a limited form of polymorphic recursion *without* a CUSK.
860
861 To wit:
862 data T a = forall k (b :: k). MkT (T b) Int
863 (test case: dependent/should_compile/T14066a)
864
865 Note that this is polymorphically recursive, with the recursive occurrence
866 of T used at a kind other than a's kind. The approach outlined here accepts
867 this definition, because this kind is still a kind variable (and so the
868 SigTvs unify). Stepping back, I (Richard) have a hard time envisioning a
869 way to describe exactly what declarations will be accepted and which will
870 be rejected (without a CUSK). However, the accepted definitions are indeed
871 well-kinded and any rejected definitions would be accepted with a CUSK,
872 and so this wrinkle need not cause anyone to lose sleep.
873
874 ************************************************************************
875 * *
876 \subsection{Type checking}
877 * *
878 ************************************************************************
879
880 Note [Type checking recursive type and class declarations]
881 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
882 At this point we have completed *kind-checking* of a mutually
883 recursive group of type/class decls (done in kcTyClGroup). However,
884 we discarded the kind-checked types (eg RHSs of data type decls);
885 note that kcTyClDecl returns (). There are two reasons:
886
887 * It's convenient, because we don't have to rebuild a
888 kinded HsDecl (a fairly elaborate type)
889
890 * It's necessary, because after kind-generalisation, the
891 TyCons/Classes may now be kind-polymorphic, and hence need
892 to be given kind arguments.
893
894 Example:
895 data T f a = MkT (f a) (T f a)
896 During kind-checking, we give T the kind T :: k1 -> k2 -> *
897 and figure out constraints on k1, k2 etc. Then we generalise
898 to get T :: forall k. (k->*) -> k -> *
899 So now the (T f a) in the RHS must be elaborated to (T k f a).
900
901 However, during tcTyClDecl of T (above) we will be in a recursive
902 "knot". So we aren't allowed to look at the TyCon T itself; we are only
903 allowed to put it (lazily) in the returned structures. But when
904 kind-checking the RHS of T's decl, we *do* need to know T's kind (so
905 that we can correctly elaboarate (T k f a). How can we get T's kind
906 without looking at T? Delicate answer: during tcTyClDecl, we extend
907
908 *Global* env with T -> ATyCon (the (not yet built) final TyCon for T)
909 *Local* env with T -> ATcTyCon (TcTyCon with the polymorphic kind of T)
910
911 Then:
912
913 * During TcHsType.tcTyVar we look in the *local* env, to get the
914 fully-known, not knot-tied TcTyCon for T.
915
916 * Then, in TcHsSyn.zonkTcTypeToType (and zonkTcTyCon in particular) we look in
917 the *global* env to get the TyCon.
918
919 This fancy footwork (with two bindings for T) is only necessary for the
920 TyCons or Classes of this recursive group. Earlier, finished groups,
921 live in the global env only.
922
923 See also Note [Kind checking recursive type and class declarations]
924
925 Note [Kind checking recursive type and class declarations]
926 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
927 Before we can type-check the decls, we must kind check them. This
928 is done by establishing an "initial kind", which is a rather uninformed
929 guess at a tycon's kind (by counting arguments, mainly) and then
930 using this initial kind for recursive occurrences.
931
932 The initial kind is stored in exactly the same way during kind-checking
933 as it is during type-checking (Note [Type checking recursive type and class
934 declarations]): in the *local* environment, with ATcTyCon. But we still
935 must store *something* in the *global* environment. Even though we
936 discard the result of kind-checking, we sometimes need to produce error
937 messages. These error messages will want to refer to the tycons being
938 checked, except that they don't exist yet, and it would be Terribly
939 Annoying to get the error messages to refer back to HsSyn. So we
940 create a TcTyCon and put it in the global env. This tycon can
941 print out its name and knows its kind,
942 but any other action taken on it will panic. Note
943 that TcTyCons are *not* knot-tied, unlike the rather valid but
944 knot-tied ones that occur during type-checking.
945
946 Note [Declarations for wired-in things]
947 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
948 For wired-in things we simply ignore the declaration
949 and take the wired-in information. That avoids complications.
950 e.g. the need to make the data constructor worker name for
951 a constraint tuple match the wired-in one
952 -}
953
954 tcTyClDecl :: RolesInfo -> LTyClDecl GhcRn -> TcM TyCon
955 tcTyClDecl roles_info (L loc decl)
956 | Just thing <- wiredInNameTyThing_maybe (tcdName decl)
957 = case thing of -- See Note [Declarations for wired-in things]
958 ATyCon tc -> return tc
959 _ -> pprPanic "tcTyClDecl" (ppr thing)
960
961 | otherwise
962 = setSrcSpan loc $ tcAddDeclCtxt decl $
963 do { traceTc "---- tcTyClDecl ---- {" (ppr decl)
964 ; tc <- tcTyClDecl1 Nothing roles_info decl
965 ; traceTc "---- tcTyClDecl end ---- }" (ppr tc)
966 ; return tc }
967
968 -- "type family" declarations
969 tcTyClDecl1 :: Maybe Class -> RolesInfo -> TyClDecl GhcRn -> TcM TyCon
970 tcTyClDecl1 parent _roles_info (FamDecl { tcdFam = fd })
971 = tcFamDecl1 parent fd
972
973 -- "type" synonym declaration
974 tcTyClDecl1 _parent roles_info
975 (SynDecl { tcdLName = L _ tc_name, tcdRhs = rhs })
976 = ASSERT( isNothing _parent )
977 tcTyClTyVars tc_name $ \ binders res_kind ->
978 tcTySynRhs roles_info tc_name binders res_kind rhs
979
980 -- "data/newtype" declaration
981 tcTyClDecl1 _parent roles_info
982 (DataDecl { tcdLName = L _ tc_name
983 , tcdDataDefn = defn })
984 = ASSERT( isNothing _parent )
985 tcTyClTyVars tc_name $ \ tycon_binders res_kind ->
986 tcDataDefn roles_info tc_name tycon_binders res_kind defn
987
988 tcTyClDecl1 _parent roles_info
989 (ClassDecl { tcdLName = L _ class_name
990 , tcdCtxt = ctxt, tcdMeths = meths
991 , tcdFDs = fundeps, tcdSigs = sigs
992 , tcdATs = ats, tcdATDefs = at_defs })
993 = ASSERT( isNothing _parent )
994 do { clas <- fixM $ \ clas ->
995 -- We need the knot because 'clas' is passed into tcClassATs
996 tcTyClTyVars class_name $ \ binders res_kind ->
997 do { MASSERT2( tcIsConstraintKind res_kind
998 , ppr class_name $$ ppr res_kind )
999 ; traceTc "tcClassDecl 1" (ppr class_name $$ ppr binders)
1000 ; let tycon_name = class_name -- We use the same name
1001 roles = roles_info tycon_name -- for TyCon and Class
1002
1003 ; ctxt' <- solveEqualities $ tcHsContext ctxt
1004 ; ctxt' <- zonkTcTypeToTypes emptyZonkEnv ctxt'
1005 -- Squeeze out any kind unification variables
1006 ; fds' <- mapM (addLocM tc_fundep) fundeps
1007 ; sig_stuff <- tcClassSigs class_name sigs meths
1008 ; at_stuff <- tcClassATs class_name clas ats at_defs
1009 ; mindef <- tcClassMinimalDef class_name sigs sig_stuff
1010 -- TODO: Allow us to distinguish between abstract class,
1011 -- and concrete class with no methods (maybe by
1012 -- specifying a trailing where or not
1013 ; sig_stuff' <- mapM zonkTcMethInfoToMethInfo sig_stuff
1014 -- this zonk is really just to squeeze out the TcTyCons
1015 -- and convert, e.g., Skolems to tyvars. We won't
1016 -- see any unfilled metavariables here.
1017
1018 ; is_boot <- tcIsHsBootOrSig
1019 ; let body | is_boot, null ctxt', null at_stuff, null sig_stuff
1020 = Nothing
1021 | otherwise
1022 = Just (ctxt', at_stuff, sig_stuff', mindef)
1023
1024 ; clas <- buildClass class_name binders roles fds' body
1025 ; traceTc "tcClassDecl" (ppr fundeps $$ ppr binders $$
1026 ppr fds')
1027 ; return clas }
1028
1029 ; return (classTyCon clas) }
1030 where
1031 tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM (tcLookupTyVar . unLoc) tvs1 ;
1032 ; tvs2' <- mapM (tcLookupTyVar . unLoc) tvs2 ;
1033 ; return (tvs1', tvs2') }
1034
1035 tcTyClDecl1 _ _ (XTyClDecl _) = panic "tcTyClDecl1"
1036
1037 tcFamDecl1 :: Maybe Class -> FamilyDecl GhcRn -> TcM TyCon
1038 tcFamDecl1 parent (FamilyDecl { fdInfo = fam_info, fdLName = tc_lname@(L _ tc_name)
1039 , fdResultSig = L _ sig, fdTyVars = user_tyvars
1040 , fdInjectivityAnn = inj })
1041 | DataFamily <- fam_info
1042 = tcTyClTyVars tc_name $ \ binders res_kind -> do
1043 { traceTc "data family:" (ppr tc_name)
1044 ; checkFamFlag tc_name
1045
1046 -- Check the kind signature, if any.
1047 -- Data families might have a variable return kind.
1048 -- See See Note [Arity of data families] in FamInstEnv.
1049 ; (extra_binders, final_res_kind) <- tcDataKindSig binders res_kind
1050 ; checkTc (tcIsLiftedTypeKind final_res_kind
1051 || isJust (tcGetCastedTyVar_maybe final_res_kind))
1052 (badKindSig False res_kind)
1053
1054 ; tc_rep_name <- newTyConRepName tc_name
1055 ; let tycon = mkFamilyTyCon tc_name (binders `chkAppend` extra_binders)
1056 final_res_kind
1057 (resultVariableName sig)
1058 (DataFamilyTyCon tc_rep_name)
1059 parent NotInjective
1060 ; return tycon }
1061
1062 | OpenTypeFamily <- fam_info
1063 = tcTyClTyVars tc_name $ \ binders res_kind -> do
1064 { traceTc "open type family:" (ppr tc_name)
1065 ; checkFamFlag tc_name
1066 ; inj' <- tcInjectivity binders inj
1067 ; let tycon = mkFamilyTyCon tc_name binders res_kind
1068 (resultVariableName sig) OpenSynFamilyTyCon
1069 parent inj'
1070 ; return tycon }
1071
1072 | ClosedTypeFamily mb_eqns <- fam_info
1073 = -- Closed type families are a little tricky, because they contain the definition
1074 -- of both the type family and the equations for a CoAxiom.
1075 do { traceTc "Closed type family:" (ppr tc_name)
1076 -- the variables in the header scope only over the injectivity
1077 -- declaration but this is not involved here
1078 ; (inj', binders, res_kind)
1079 <- tcTyClTyVars tc_name
1080 $ \ binders res_kind ->
1081 do { inj' <- tcInjectivity binders inj
1082 ; return (inj', binders, res_kind) }
1083
1084 ; checkFamFlag tc_name -- make sure we have -XTypeFamilies
1085
1086 -- If Nothing, this is an abstract family in a hs-boot file;
1087 -- but eqns might be empty in the Just case as well
1088 ; case mb_eqns of
1089 Nothing ->
1090 return $ mkFamilyTyCon tc_name binders res_kind
1091 (resultVariableName sig)
1092 AbstractClosedSynFamilyTyCon parent
1093 inj'
1094 Just eqns -> do {
1095
1096 -- Process the equations, creating CoAxBranches
1097 ; let tc_fam_tc = mkTcTyCon tc_name (ppr user_tyvars) binders res_kind
1098 [] ClosedTypeFamilyFlavour
1099
1100 ; branches <- mapAndReportM (tcTyFamInstEqn tc_fam_tc Nothing) eqns
1101 -- Do not attempt to drop equations dominated by earlier
1102 -- ones here; in the case of mutual recursion with a data
1103 -- type, we get a knot-tying failure. Instead we check
1104 -- for this afterwards, in TcValidity.checkValidCoAxiom
1105 -- Example: tc265
1106
1107 -- Create a CoAxiom, with the correct src location.
1108 ; co_ax_name <- newFamInstAxiomName tc_lname []
1109
1110 ; let mb_co_ax
1111 | null eqns = Nothing -- mkBranchedCoAxiom fails on empty list
1112 | otherwise = Just (mkBranchedCoAxiom co_ax_name fam_tc branches)
1113
1114 fam_tc = mkFamilyTyCon tc_name binders res_kind (resultVariableName sig)
1115 (ClosedSynFamilyTyCon mb_co_ax) parent inj'
1116
1117 -- We check for instance validity later, when doing validity
1118 -- checking for the tycon. Exception: checking equations
1119 -- overlap done by dropDominatedAxioms
1120 ; return fam_tc } }
1121
1122 | otherwise = panic "tcFamInst1" -- Silence pattern-exhaustiveness checker
1123 tcFamDecl1 _ (XFamilyDecl _) = panic "tcFamDecl1"
1124
1125 -- | Maybe return a list of Bools that say whether a type family was declared
1126 -- injective in the corresponding type arguments. Length of the list is equal to
1127 -- the number of arguments (including implicit kind/coercion arguments).
1128 -- True on position
1129 -- N means that a function is injective in its Nth argument. False means it is
1130 -- not.
1131 tcInjectivity :: [TyConBinder] -> Maybe (LInjectivityAnn GhcRn)
1132 -> TcM Injectivity
1133 tcInjectivity _ Nothing
1134 = return NotInjective
1135
1136 -- User provided an injectivity annotation, so for each tyvar argument we
1137 -- check whether a type family was declared injective in that argument. We
1138 -- return a list of Bools, where True means that corresponding type variable
1139 -- was mentioned in lInjNames (type family is injective in that argument) and
1140 -- False means that it was not mentioned in lInjNames (type family is not
1141 -- injective in that type variable). We also extend injectivity information to
1142 -- kind variables, so if a user declares:
1143 --
1144 -- type family F (a :: k1) (b :: k2) = (r :: k3) | r -> a
1145 --
1146 -- then we mark both `a` and `k1` as injective.
1147 -- NB: the return kind is considered to be *input* argument to a type family.
1148 -- Since injectivity allows to infer input arguments from the result in theory
1149 -- we should always mark the result kind variable (`k3` in this example) as
1150 -- injective. The reason is that result type has always an assigned kind and
1151 -- therefore we can always infer the result kind if we know the result type.
1152 -- But this does not seem to be useful in any way so we don't do it. (Another
1153 -- reason is that the implementation would not be straightforward.)
1154 tcInjectivity tcbs (Just (L loc (InjectivityAnn _ lInjNames)))
1155 = setSrcSpan loc $
1156 do { let tvs = binderVars tcbs
1157 ; dflags <- getDynFlags
1158 ; checkTc (xopt LangExt.TypeFamilyDependencies dflags)
1159 (text "Illegal injectivity annotation" $$
1160 text "Use TypeFamilyDependencies to allow this")
1161 ; inj_tvs <- mapM (tcLookupTyVar . unLoc) lInjNames
1162 ; inj_tvs <- mapM zonkTcTyVarToTyVar inj_tvs -- zonk the kinds
1163 ; let inj_ktvs = filterVarSet isTyVar $ -- no injective coercion vars
1164 closeOverKinds (mkVarSet inj_tvs)
1165 ; let inj_bools = map (`elemVarSet` inj_ktvs) tvs
1166 ; traceTc "tcInjectivity" (vcat [ ppr tvs, ppr lInjNames, ppr inj_tvs
1167 , ppr inj_ktvs, ppr inj_bools ])
1168 ; return $ Injective inj_bools }
1169
1170 tcTySynRhs :: RolesInfo
1171 -> Name
1172 -> [TyConBinder] -> Kind
1173 -> LHsType GhcRn -> TcM TyCon
1174 tcTySynRhs roles_info tc_name binders res_kind hs_ty
1175 = do { env <- getLclEnv
1176 ; traceTc "tc-syn" (ppr tc_name $$ ppr (tcl_env env))
1177 ; rhs_ty <- solveEqualities $ tcCheckLHsType hs_ty res_kind
1178 ; rhs_ty <- zonkTcTypeToType emptyZonkEnv rhs_ty
1179 ; let roles = roles_info tc_name
1180 tycon = buildSynTyCon tc_name binders res_kind roles rhs_ty
1181 ; return tycon }
1182
1183 tcDataDefn :: RolesInfo -> Name
1184 -> [TyConBinder] -> Kind
1185 -> HsDataDefn GhcRn -> TcM TyCon
1186 -- NB: not used for newtype/data instances (whether associated or not)
1187 tcDataDefn roles_info
1188 tc_name tycon_binders res_kind
1189 (HsDataDefn { dd_ND = new_or_data, dd_cType = cType
1190 , dd_ctxt = ctxt, dd_kindSig = mb_ksig
1191 , dd_cons = cons })
1192 = do { tcg_env <- getGblEnv
1193 ; let hsc_src = tcg_src tcg_env
1194 ; (extra_bndrs, final_res_kind) <- tcDataKindSig tycon_binders res_kind
1195 ; unless (mk_permissive_kind hsc_src cons) $
1196 checkTc (tcIsLiftedTypeKind final_res_kind) (badKindSig True res_kind)
1197
1198 ; let final_bndrs = tycon_binders `chkAppend` extra_bndrs
1199 roles = roles_info tc_name
1200
1201 ; stupid_tc_theta <- solveEqualities $ tcHsContext ctxt
1202 ; stupid_theta <- zonkTcTypeToTypes emptyZonkEnv
1203 stupid_tc_theta
1204 ; kind_signatures <- xoptM LangExt.KindSignatures
1205
1206 -- Check that we don't use kind signatures without Glasgow extensions
1207 ; when (isJust mb_ksig) $
1208 checkTc (kind_signatures) (badSigTyDecl tc_name)
1209
1210 ; gadt_syntax <- dataDeclChecks tc_name new_or_data stupid_theta cons
1211
1212 ; tycon <- fixM $ \ tycon -> do
1213 { let res_ty = mkTyConApp tycon (mkTyVarTys (binderVars final_bndrs))
1214 ; data_cons <- tcConDecls tycon (final_bndrs, res_ty) cons
1215 ; tc_rhs <- mk_tc_rhs hsc_src tycon data_cons
1216 ; tc_rep_nm <- newTyConRepName tc_name
1217 ; return (mkAlgTyCon tc_name
1218 final_bndrs
1219 final_res_kind
1220 roles
1221 (fmap unLoc cType)
1222 stupid_theta tc_rhs
1223 (VanillaAlgTyCon tc_rep_nm)
1224 gadt_syntax) }
1225 ; traceTc "tcDataDefn" (ppr tc_name $$ ppr tycon_binders $$ ppr extra_bndrs)
1226 ; return tycon }
1227 where
1228 -- Abstract data types in hsig files can have arbitrary kinds,
1229 -- because they may be implemented by type synonyms
1230 -- (which themselves can have arbitrary kinds, not just *)
1231 mk_permissive_kind HsigFile [] = True
1232 mk_permissive_kind _ _ = False
1233
1234 -- In hs-boot, a 'data' declaration with no constructors
1235 -- indicates a nominally distinct abstract data type.
1236 mk_tc_rhs HsBootFile _ []
1237 = return AbstractTyCon
1238
1239 mk_tc_rhs HsigFile _ [] -- ditto
1240 = return AbstractTyCon
1241
1242 mk_tc_rhs _ tycon data_cons
1243 = case new_or_data of
1244 DataType -> return (mkDataTyConRhs data_cons)
1245 NewType -> ASSERT( not (null data_cons) )
1246 mkNewTyConRhs tc_name tycon (head data_cons)
1247 tcDataDefn _ _ _ _ (XHsDataDefn _) = panic "tcDataDefn"
1248
1249 {-
1250 ************************************************************************
1251 * *
1252 Typechecking associated types (in class decls)
1253 (including the associated-type defaults)
1254 * *
1255 ************************************************************************
1256
1257 Note [Associated type defaults]
1258 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1259
1260 The following is an example of associated type defaults:
1261 class C a where
1262 data D a
1263
1264 type F a b :: *
1265 type F a b = [a] -- Default
1266
1267 Note that we can get default definitions only for type families, not data
1268 families.
1269 -}
1270
1271 tcClassATs :: Name -- The class name (not knot-tied)
1272 -> Class -- The class parent of this associated type
1273 -> [LFamilyDecl GhcRn] -- Associated types.
1274 -> [LTyFamDefltEqn GhcRn] -- Associated type defaults.
1275 -> TcM [ClassATItem]
1276 tcClassATs class_name cls ats at_defs
1277 = do { -- Complain about associated type defaults for non associated-types
1278 sequence_ [ failWithTc (badATErr class_name n)
1279 | n <- map at_def_tycon at_defs
1280 , not (n `elemNameSet` at_names) ]
1281 ; mapM tc_at ats }
1282 where
1283 at_def_tycon :: LTyFamDefltEqn GhcRn -> Name
1284 at_def_tycon (L _ eqn) = unLoc (feqn_tycon eqn)
1285
1286 at_fam_name :: LFamilyDecl GhcRn -> Name
1287 at_fam_name (L _ decl) = unLoc (fdLName decl)
1288
1289 at_names = mkNameSet (map at_fam_name ats)
1290
1291 at_defs_map :: NameEnv [LTyFamDefltEqn GhcRn]
1292 -- Maps an AT in 'ats' to a list of all its default defs in 'at_defs'
1293 at_defs_map = foldr (\at_def nenv -> extendNameEnv_C (++) nenv
1294 (at_def_tycon at_def) [at_def])
1295 emptyNameEnv at_defs
1296
1297 tc_at at = do { fam_tc <- addLocM (tcFamDecl1 (Just cls)) at
1298 ; let at_defs = lookupNameEnv at_defs_map (at_fam_name at)
1299 `orElse` []
1300 ; atd <- tcDefaultAssocDecl fam_tc at_defs
1301 ; return (ATI fam_tc atd) }
1302
1303 -------------------------
1304 tcDefaultAssocDecl :: TyCon -- ^ Family TyCon (not knot-tied)
1305 -> [LTyFamDefltEqn GhcRn] -- ^ Defaults
1306 -> TcM (Maybe (KnotTied Type, SrcSpan)) -- ^ Type checked RHS
1307 tcDefaultAssocDecl _ []
1308 = return Nothing -- No default declaration
1309
1310 tcDefaultAssocDecl _ (d1:_:_)
1311 = failWithTc (text "More than one default declaration for"
1312 <+> ppr (feqn_tycon (unLoc d1)))
1313
1314 tcDefaultAssocDecl fam_tc [L loc (FamEqn { feqn_tycon = L _ tc_name
1315 , feqn_pats = hs_tvs
1316 , feqn_rhs = rhs })]
1317 | HsQTvs { hsq_ext = HsQTvsRn { hsq_implicit = imp_vars}
1318 , hsq_explicit = exp_vars } <- hs_tvs
1319 = -- See Note [Type-checking default assoc decls]
1320 setSrcSpan loc $
1321 tcAddFamInstCtxt (text "default type instance") tc_name $
1322 do { traceTc "tcDefaultAssocDecl" (ppr tc_name)
1323 ; let fam_tc_name = tyConName fam_tc
1324 fam_arity = length (tyConVisibleTyVars fam_tc)
1325
1326 -- Kind of family check
1327 ; ASSERT( fam_tc_name == tc_name )
1328 checkTc (isTypeFamilyTyCon fam_tc) (wrongKindOfFamily fam_tc)
1329
1330 -- Arity check
1331 ; checkTc (exp_vars `lengthIs` fam_arity)
1332 (wrongNumberOfParmsErr fam_arity)
1333
1334 -- Typecheck RHS
1335 ; let all_vars = imp_vars ++ map hsLTyVarName exp_vars
1336 pats = map hsLTyVarBndrToType exp_vars
1337
1338 -- NB: Use tcFamTyPats, not tcTyClTyVars. The latter expects to get
1339 -- the LHsQTyVars used for declaring a tycon, but the names here
1340 -- are different.
1341
1342 -- You might think we should pass in some ClsInstInfo, as we're looking
1343 -- at an associated type. But this would be wrong, because an associated
1344 -- type default LHS can mention *different* type variables than the
1345 -- enclosing class. So it's treated more as a freestanding beast.
1346 ; (pats', rhs_ty)
1347 <- tcFamTyPats fam_tc Nothing all_vars pats
1348 (kcTyFamEqnRhs Nothing rhs) $
1349 \tvs pats rhs_kind ->
1350 do { rhs_ty <- solveEqualities $
1351 tcCheckLHsType rhs rhs_kind
1352
1353 -- Zonk the patterns etc into the Type world
1354 ; (ze, _) <- zonkTyBndrsX emptyZonkEnv tvs
1355 ; pats' <- zonkTcTypeToTypes ze pats
1356 ; rhs_ty' <- zonkTcTypeToType ze rhs_ty
1357 ; return (pats', rhs_ty') }
1358
1359 -- See Note [Type-checking default assoc decls]
1360 ; case tcMatchTys pats' (mkTyVarTys (tyConTyVars fam_tc)) of
1361 Just subst -> return (Just (substTyUnchecked subst rhs_ty, loc) )
1362 Nothing -> failWithTc (defaultAssocKindErr fam_tc)
1363 -- We check for well-formedness and validity later,
1364 -- in checkValidClass
1365 }
1366 tcDefaultAssocDecl _ [L _ (XFamEqn _)] = panic "tcDefaultAssocDecl"
1367 tcDefaultAssocDecl _ [L _ (FamEqn _ (L _ _) (XLHsQTyVars _) _ _)]
1368 = panic "tcDefaultAssocDecl"
1369
1370 {- Note [Type-checking default assoc decls]
1371 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1372 Consider this default declaration for an associated type
1373
1374 class C a where
1375 type F (a :: k) b :: *
1376 type F x y = Proxy x -> y
1377
1378 Note that the class variable 'a' doesn't scope over the default assoc
1379 decl (rather oddly I think), and (less oddly) neither does the second
1380 argument 'b' of the associated type 'F', or the kind variable 'k'.
1381 Instead, the default decl is treated more like a top-level type
1382 instance.
1383
1384 However we store the default rhs (Proxy x -> y) in F's TyCon, using
1385 F's own type variables, so we need to convert it to (Proxy a -> b).
1386 We do this by calling tcMatchTys to match them up. This also ensures
1387 that x's kind matches a's and similarly for y and b. The error
1388 message isn't great, mind you. (Trac #11361 was caused by not doing a
1389 proper tcMatchTys here.)
1390
1391 Recall also that the left-hand side of an associated type family
1392 default is always just variables -- no tycons here. Accordingly,
1393 the patterns used in the tcMatchTys won't actually be knot-tied,
1394 even though we're in the knot. This is too delicate for my taste,
1395 but it works.
1396
1397 -}
1398
1399 -------------------------
1400 kcTyFamInstEqn :: TcTyCon -> LTyFamInstEqn GhcRn -> TcM ()
1401 kcTyFamInstEqn tc_fam_tc
1402 (L loc (HsIB { hsib_ext = tv_names
1403 , hsib_body = FamEqn { feqn_tycon = L _ eqn_tc_name
1404 , feqn_pats = pats
1405 , feqn_rhs = hs_ty }}))
1406 = setSrcSpan loc $
1407 do { traceTc "kcTyFamInstEqn" (vcat
1408 [ text "tc_name =" <+> ppr eqn_tc_name
1409 , text "fam_tc =" <+> ppr tc_fam_tc <+> dcolon <+> ppr (tyConKind tc_fam_tc)
1410 , text "hsib_vars =" <+> ppr tv_names
1411 , text "feqn_pats =" <+> ppr pats ])
1412 ; checkTc (fam_name == eqn_tc_name)
1413 (wrongTyFamName fam_name eqn_tc_name)
1414 -- this check reports an arity error instead of a kind error; easier for user
1415 ; checkTc (pats `lengthIs` vis_arity) $
1416 wrongNumberOfParmsErr vis_arity
1417 ; kcFamTyPats tc_fam_tc tv_names pats $ \ rhs_kind ->
1418 discardResult $ kcTyFamEqnRhs Nothing hs_ty rhs_kind }
1419 where
1420 fam_name = tyConName tc_fam_tc
1421 vis_arity = length (tyConVisibleTyVars tc_fam_tc)
1422 kcTyFamInstEqn _ (L _ (XHsImplicitBndrs _)) = panic "kcTyFamInstEqn"
1423 kcTyFamInstEqn _ (L _ (HsIB _ (XFamEqn _))) = panic "kcTyFamInstEqn"
1424
1425 -- Infer the kind of the type on the RHS of a type family eqn. Then use
1426 -- this kind to check the kind of the LHS of the equation. This is useful
1427 -- as the callback to tcFamTyPats.
1428 kcTyFamEqnRhs :: Maybe ClsInstInfo
1429 -> LHsType GhcRn -- ^ Eqn RHS
1430 -> TcKind -- ^ Inferred kind of left-hand side
1431 -> TcM ([TcType], TcKind) -- ^ New pats, inst'ed kind of left-hand side
1432 kcTyFamEqnRhs mb_clsinfo rhs_hs_ty lhs_ki
1433 = do { -- It's still possible the lhs_ki has some foralls. Instantiate these away.
1434 (new_pats, insted_lhs_ki)
1435 <- instantiateTyUntilN mb_kind_env 0 lhs_ki
1436
1437 ; traceTc "kcTyFamEqnRhs" (vcat
1438 [ text "rhs_hs_ty =" <+> ppr rhs_hs_ty
1439 , text "lhs_ki =" <+> ppr lhs_ki
1440 , text "insted_lhs_ki =" <+> ppr insted_lhs_ki
1441 , text "new_pats =" <+> ppr new_pats
1442 ])
1443
1444 ; _ <- tcCheckLHsType rhs_hs_ty insted_lhs_ki
1445
1446 ; return (new_pats, insted_lhs_ki) }
1447 where
1448 mb_kind_env = thdOf3 <$> mb_clsinfo
1449
1450 tcTyFamInstEqn :: TcTyCon -> Maybe ClsInstInfo -> LTyFamInstEqn GhcRn
1451 -> TcM (KnotTied CoAxBranch)
1452 -- Needs to be here, not in TcInstDcls, because closed families
1453 -- (typechecked here) have TyFamInstEqns
1454 tcTyFamInstEqn fam_tc mb_clsinfo
1455 (L loc (HsIB { hsib_ext = tv_names
1456 , hsib_body = FamEqn { feqn_tycon = L _ eqn_tc_name
1457 , feqn_pats = pats
1458 , feqn_rhs = hs_ty }}))
1459 = ASSERT( getName fam_tc == eqn_tc_name )
1460 setSrcSpan loc $
1461 tcFamTyPats fam_tc mb_clsinfo tv_names pats
1462 (kcTyFamEqnRhs mb_clsinfo hs_ty) $
1463 \tvs pats res_kind ->
1464 do { rhs_ty <- solveEqualities $ tcCheckLHsType hs_ty res_kind
1465
1466 ; (ze, tvs') <- zonkTyBndrsX emptyZonkEnv tvs
1467 ; pats' <- zonkTcTypeToTypes ze pats
1468 ; rhs_ty' <- zonkTcTypeToType ze rhs_ty
1469 ; traceTc "tcTyFamInstEqn" (ppr fam_tc <+> pprTyVars tvs')
1470 ; return (mkCoAxBranch tvs' [] pats' rhs_ty'
1471 (map (const Nominal) tvs')
1472 loc) }
1473 tcTyFamInstEqn _ _ (L _ (XHsImplicitBndrs _)) = panic "tcTyFamInstEqn"
1474 tcTyFamInstEqn _ _ (L _ (HsIB _ (XFamEqn _))) = panic "tcTyFamInstEqn"
1475
1476 kcDataDefn :: Maybe (VarEnv Kind) -- ^ Possibly, instantiations for vars
1477 -- (associated types only)
1478 -> DataFamInstDecl GhcRn
1479 -> TcKind -- ^ the kind of the tycon applied to pats
1480 -> TcM ([TcType], TcKind)
1481 -- ^ the kind signature might force instantiation
1482 -- of the tycon; this returns any extra args and the inst'ed kind
1483 -- See Note [Instantiating a family tycon]
1484 -- Used for 'data instance' only
1485 -- Ordinary 'data' is handled by kcTyClDec
1486 kcDataDefn mb_kind_env
1487 (DataFamInstDecl { dfid_eqn = HsIB { hsib_body =
1488 FamEqn { feqn_tycon = fam_name
1489 , feqn_pats = pats
1490 , feqn_fixity = fixity
1491 , feqn_rhs = HsDataDefn { dd_ctxt = ctxt
1492 , dd_cons = cons
1493 , dd_kindSig = mb_kind } }}})
1494 res_k
1495 = do { _ <- tcHsContext ctxt
1496 ; checkNoErrs $ mapM_ (wrapLocM kcConDecl) cons
1497 -- See Note [Failing early in kcDataDefn]
1498 ; exp_res_kind <- case mb_kind of
1499 Nothing -> return liftedTypeKind
1500 Just k -> tcLHsKindSig (DataKindCtxt (unLoc fam_name)) k
1501
1502 -- The expected type might have a forall at the type. Normally, we
1503 -- can't skolemise in kinds because we don't have type-level lambda.
1504 -- But here, we're at the top-level of an instance declaration, so
1505 -- we actually have a place to put the regeneralised variables.
1506 -- Thus: skolemise away. cf. Inst.deeplySkolemise and TcUnify.tcSkolemise
1507 -- Examples in indexed-types/should_compile/T12369
1508 ; let (tvs_to_skolemise, inner_res_kind) = tcSplitForAllTys exp_res_kind
1509
1510 ; (skol_subst, tvs') <- tcInstSkolTyVars tvs_to_skolemise
1511 -- we don't need to do anything substantive with the tvs' because the
1512 -- quantifyTyVars in tcFamTyPats will catch them.
1513
1514 ; let inner_res_kind' = substTyAddInScope skol_subst inner_res_kind
1515 tv_prs = zip (map tyVarName tvs_to_skolemise) tvs'
1516 skol_info = SigSkol (InstDeclCtxt False) exp_res_kind tv_prs
1517
1518 ; (ev_binds, (_, new_args, co))
1519 <- solveEqualities $
1520 checkConstraints skol_info tvs' [] $
1521 checkExpectedKindX mb_kind_env pp_fam_app
1522 bogus_ty res_k inner_res_kind'
1523
1524 ; let Pair lhs_ki rhs_ki = tcCoercionKind co
1525
1526 ; when debugIsOn $
1527 do { (_, ev_binds) <- zonkTcEvBinds emptyZonkEnv ev_binds
1528 ; MASSERT( isEmptyTcEvBinds ev_binds )
1529 ; lhs_ki <- zonkTcType lhs_ki
1530 ; rhs_ki <- zonkTcType rhs_ki
1531 ; MASSERT( lhs_ki `tcEqType` rhs_ki ) }
1532
1533 ; return (new_args, lhs_ki) }
1534 where
1535 bogus_ty = pprPanic "kcDataDefn" (ppr fam_name <+> ppr pats)
1536 pp_fam_app = pprFamInstLHS fam_name pats fixity (unLoc ctxt) mb_kind
1537 kcDataDefn _ (DataFamInstDecl (XHsImplicitBndrs _)) _
1538 = panic "kcDataDefn"
1539 kcDataDefn _ (DataFamInstDecl (HsIB _ (FamEqn _ _ _ _ (XHsDataDefn _)))) _
1540 = panic "kcDataDefn"
1541 kcDataDefn _ (DataFamInstDecl (HsIB _ (XFamEqn _))) _
1542 = panic "kcDataDefn"
1543
1544 {-
1545 Kind check type patterns and kind annotate the embedded type variables.
1546 type instance F [a] = rhs
1547
1548 * Here we check that a type instance matches its kind signature, but we do
1549 not check whether there is a pattern for each type index; the latter
1550 check is only required for type synonym instances.
1551
1552 Note [Instantiating a family tycon]
1553 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1554 It's possible that kind-checking the result of a family tycon applied to
1555 its patterns will instantiate the tycon further. For example, we might
1556 have
1557
1558 type family F :: k where
1559 F = Int
1560 F = Maybe
1561
1562 After checking (F :: forall k. k) (with no visible patterns), we still need
1563 to instantiate the k. With data family instances, this problem can be even
1564 more intricate, due to Note [Arity of data families] in FamInstEnv. See
1565 indexed-types/should_compile/T12369 for an example.
1566
1567 So, the kind-checker must return both the new args (that is, Type
1568 (Type -> Type) for the equations above) and the instantiated kind.
1569
1570 Because we don't need this information in the kind-checking phase of
1571 checking closed type families, we don't require these extra pieces of
1572 information in tc_fam_ty_pats.
1573
1574 Note [Failing early in kcDataDefn]
1575 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1576 We need to use checkNoErrs when calling kcConDecl. This is because kcConDecl
1577 calls tcConDecl, which checks that the return type of a GADT-like constructor
1578 is actually an instance of the type head. Without the checkNoErrs, potentially
1579 two bad things could happen:
1580
1581 1) Duplicate error messages, because tcConDecl will be called again during
1582 *type* checking (as opposed to kind checking)
1583 2) If we just keep blindly forging forward after both kind checking and type
1584 checking, we can get a panic in rejigConRes. See Trac #8368.
1585 -}
1586
1587 -----------------
1588 kcFamTyPats :: TcTyCon
1589 -> [Name]
1590 -> HsTyPats GhcRn
1591 -> (TcKind -> TcM ())
1592 -> TcM ()
1593 kcFamTyPats tc_fam_tc tv_names arg_pats kind_checker
1594 = discardResult $
1595 kcImplicitTKBndrs tv_names $
1596 do { let name = tyConName tc_fam_tc
1597 loc = nameSrcSpan name
1598 lhs_fun = L loc (HsTyVar noExt NotPromoted (L loc name))
1599 -- lhs_fun is for error messages only
1600 no_fun = pprPanic "kcFamTyPats" (ppr name)
1601 fun_kind = tyConKind tc_fam_tc
1602
1603 ; (_, _, res_kind_out) <- tcInferApps typeLevelMode Nothing lhs_fun no_fun
1604 fun_kind arg_pats
1605 ; traceTc "kcFamTyPats" (vcat [ ppr tc_fam_tc, ppr arg_pats, ppr res_kind_out ])
1606 ; kind_checker res_kind_out }
1607
1608 tcFamTyPats :: TyCon
1609 -> Maybe ClsInstInfo
1610 -> [Name] -- Implicitly bound kind/type variable names
1611 -> HsTyPats GhcRn -- Type patterns
1612 -> (TcKind -> TcM ([TcType], TcKind))
1613 -- kind-checker for RHS
1614 -- See Note [Instantiating a family tycon]
1615 -> ( [TcTyVar] -- Kind and type variables
1616 -> [TcType] -- Kind and type arguments
1617 -> TcKind
1618 -> TcM a) -- NB: You can use solveEqualities here.
1619 -> TcM a
1620 -- Check the type patterns of a type or data family instance
1621 -- type instance F <pat1> <pat2> = <type>
1622 -- The 'tyvars' are the free type variables of pats
1623 --
1624 -- NB: The family instance declaration may be an associated one,
1625 -- nested inside an instance decl, thus
1626 -- instance C [a] where
1627 -- type F [a] = ...
1628 -- In that case, the type variable 'a' will *already be in scope*
1629 -- (and, if C is poly-kinded, so will its kind parameter).
1630 tcFamTyPats fam_tc mb_clsinfo
1631 tv_names arg_pats kind_checker thing_inside
1632 = do { -- First, check the arity.
1633 -- If we wait until validity checking, we'll get kind
1634 -- errors below when an arity error will be much easier to
1635 -- understand.
1636 let should_check_arity
1637 | DataFamilyFlavour _ <- flav = False
1638 -- why not check data families? See [Arity of data families] in FamInstEnv
1639 | otherwise = True
1640
1641 ; when should_check_arity $
1642 checkTc (arg_pats `lengthIs` vis_arity) $
1643 wrongNumberOfParmsErr vis_arity
1644 -- report only explicit arguments
1645
1646 ; (fam_used_tvs, (typats, (more_typats, res_kind)))
1647 <- solveEqualities $ -- See Note [Constraints in patterns]
1648 tcImplicitQTKBndrs FamInstSkol tv_names $
1649 -- See Note [Kind-checking tyvar binders for associated types]
1650 do { let loc = nameSrcSpan fam_name
1651 lhs_fun = L loc (HsTyVar noExt NotPromoted
1652 (L loc fam_name))
1653 fun_ty = mkTyConApp fam_tc []
1654 fun_kind = tyConKind fam_tc
1655 mb_kind_env = thdOf3 <$> mb_clsinfo
1656
1657 ; (_, args, res_kind_out)
1658 <- tcInferApps typeLevelMode mb_kind_env
1659 lhs_fun fun_ty fun_kind arg_pats
1660
1661 ; traceTc "tcFamTyPats 1" (vcat [ ppr fam_tc, ppr arg_pats, ppr res_kind_out ])
1662
1663 ; stuff <- kind_checker res_kind_out
1664 ; return (args, stuff) }
1665
1666 {- TODO (RAE): This should be cleverer. Consider this:
1667
1668 type family F a
1669
1670 data G a where
1671 MkG :: F a ~ Bool => G a
1672
1673 type family Foo (x :: G a) :: F a
1674 type instance Foo MkG = False
1675
1676 This should probably be accepted. Yet the solveEqualities
1677 will fail, unable to solve (F a ~ Bool)
1678 We want to quantify over that proof.
1679 But see Note [Constraints in patterns]
1680 below, which is missing this piece. -}
1681
1682
1683 -- Find free variables (after zonking) and turn
1684 -- them into skolems, so that we don't subsequently
1685 -- replace a meta kind var with (Any *)
1686 -- Very like kindGeneralize
1687 ; let all_pats = typats `chkAppend` more_typats
1688 ; vars <- zonkTcTypesAndSplitDepVars all_pats
1689 ; qtkvs <- quantifyTyVars emptyVarSet vars
1690
1691 ; when debugIsOn $
1692 do { all_pats <- mapM zonkTcType all_pats
1693 ; MASSERT2( isEmptyVarSet $ coVarsOfTypes all_pats, ppr all_pats ) }
1694 -- This should be the case, because otherwise the solveEqualities
1695 -- above would fail. TODO (RAE): Update once the solveEqualities
1696 -- bit is cleverer.
1697
1698 ; traceTc "tcFamTyPats" (ppr (getName fam_tc)
1699 $$ ppr all_pats $$ ppr qtkvs)
1700
1701 -- See Note [Free-floating kind vars] in TcHsType
1702 ; let all_mentioned_tvs = mkVarSet qtkvs
1703 -- qtkvs has all the tyvars bound by LHS
1704 -- type patterns
1705 unmentioned_tvs = filterOut (`elemVarSet` all_mentioned_tvs)
1706 fam_used_tvs
1707 -- If there are tyvars left over, we can
1708 -- assume they're free-floating, since they
1709 -- aren't bound by a type pattern
1710 ; checkNoErrs $ reportFloatingKvs fam_name flav
1711 qtkvs unmentioned_tvs
1712
1713 ; scopeTyVars FamInstSkol qtkvs $
1714 -- Extend envt with TcTyVars not TyVars, because the
1715 -- kind checking etc done by thing_inside does not expect
1716 -- to encounter TyVars; it expects TcTyVars
1717 thing_inside qtkvs all_pats res_kind }
1718 where
1719 fam_name = tyConName fam_tc
1720 flav = tyConFlavour fam_tc
1721 vis_arity = length (tyConVisibleTyVars fam_tc)
1722
1723
1724 {-
1725 Note [Constraints in patterns]
1726 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1727 NB: This isn't the whole story. See comment in tcFamTyPats.
1728
1729 At first glance, it seems there is a complicated story to tell in tcFamTyPats
1730 around constraint solving. After all, type family patterns can now do
1731 GADT pattern-matching, which is jolly complicated. But, there's a key fact
1732 which makes this all simple: everything is at top level! There cannot
1733 be untouchable type variables. There can't be weird interaction between
1734 case branches. There can't be global skolems.
1735
1736 This means that the semantics of type-level GADT matching is a little
1737 different than term level. If we have
1738
1739 data G a where
1740 MkGBool :: G Bool
1741
1742 And then
1743
1744 type family F (a :: G k) :: k
1745 type instance F MkGBool = True
1746
1747 we get
1748
1749 axF : F Bool (MkGBool <Bool>) ~ True
1750
1751 Simple! No casting on the RHS, because we can affect the kind parameter
1752 to F.
1753
1754 If we ever introduce local type families, this all gets a lot more
1755 complicated, and will end up looking awfully like term-level GADT
1756 pattern-matching.
1757
1758
1759 ** The new story **
1760
1761 Here is really what we want:
1762
1763 The matcher really can't deal with covars in arbitrary spots in coercions.
1764 But it can deal with covars that are arguments to GADT data constructors.
1765 So we somehow want to allow covars only in precisely those spots, then use
1766 them as givens when checking the RHS. TODO (RAE): Implement plan.
1767
1768
1769 Note [Quantifying over family patterns]
1770 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1771 We need to quantify over two different lots of kind variables:
1772
1773 First, the ones that come from the kinds of the tyvar args of
1774 tcTyVarBndrsKindGen, as usual
1775 data family Dist a
1776
1777 -- Proxy :: forall k. k -> *
1778 data instance Dist (Proxy a) = DP
1779 -- Generates data DistProxy = DP
1780 -- ax8 k (a::k) :: Dist * (Proxy k a) ~ DistProxy k a
1781 -- The 'k' comes from the tcTyVarBndrsKindGen (a::k)
1782
1783 Second, the ones that come from the kind argument of the type family
1784 which we pick up using the (tyCoVarsOfTypes typats) in the result of
1785 the thing_inside of tcHsTyvarBndrsGen.
1786 -- Any :: forall k. k
1787 data instance Dist Any = DA
1788 -- Generates data DistAny k = DA
1789 -- ax7 k :: Dist k (Any k) ~ DistAny k
1790 -- The 'k' comes from kindGeneralizeKinds (Any k)
1791
1792 Note [Quantified kind variables of a family pattern]
1793 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1794 Consider type family KindFam (p :: k1) (q :: k1)
1795 data T :: Maybe k1 -> k2 -> *
1796 type instance KindFam (a :: Maybe k) b = T a b -> Int
1797 The HsBSig for the family patterns will be ([k], [a])
1798
1799 Then in the family instance we want to
1800 * Bring into scope [ "k" -> k:*, "a" -> a:k ]
1801 * Kind-check the RHS
1802 * Quantify the type instance over k and k', as well as a,b, thus
1803 type instance [k, k', a:Maybe k, b:k']
1804 KindFam (Maybe k) k' a b = T k k' a b -> Int
1805
1806 Notice that in the third step we quantify over all the visibly-mentioned
1807 type variables (a,b), but also over the implicitly mentioned kind variables
1808 (k, k'). In this case one is bound explicitly but often there will be
1809 none. The role of the kind signature (a :: Maybe k) is to add a constraint
1810 that 'a' must have that kind, and to bring 'k' into scope.
1811
1812
1813
1814 ************************************************************************
1815 * *
1816 Data types
1817 * *
1818 ************************************************************************
1819 -}
1820
1821 dataDeclChecks :: Name -> NewOrData -> ThetaType -> [LConDecl GhcRn] -> TcM Bool
1822 dataDeclChecks tc_name new_or_data stupid_theta cons
1823 = do { -- Check that we don't use GADT syntax in H98 world
1824 gadtSyntax_ok <- xoptM LangExt.GADTSyntax
1825 ; let gadt_syntax = consUseGadtSyntax cons
1826 ; checkTc (gadtSyntax_ok || not gadt_syntax) (badGadtDecl tc_name)
1827
1828 -- Check that the stupid theta is empty for a GADT-style declaration
1829 ; checkTc (null stupid_theta || not gadt_syntax) (badStupidTheta tc_name)
1830
1831 -- Check that a newtype has exactly one constructor
1832 -- Do this before checking for empty data decls, so that
1833 -- we don't suggest -XEmptyDataDecls for newtypes
1834 ; checkTc (new_or_data == DataType || isSingleton cons)
1835 (newtypeConError tc_name (length cons))
1836
1837 -- Check that there's at least one condecl,
1838 -- or else we're reading an hs-boot file, or -XEmptyDataDecls
1839 ; empty_data_decls <- xoptM LangExt.EmptyDataDecls
1840 ; is_boot <- tcIsHsBootOrSig -- Are we compiling an hs-boot file?
1841 ; checkTc (not (null cons) || empty_data_decls || is_boot)
1842 (emptyConDeclsErr tc_name)
1843 ; return gadt_syntax }
1844
1845
1846 -----------------------------------
1847 consUseGadtSyntax :: [LConDecl a] -> Bool
1848 consUseGadtSyntax (L _ (ConDeclGADT { }) : _) = True
1849 consUseGadtSyntax _ = False
1850 -- All constructors have same shape
1851
1852 -----------------------------------
1853 tcConDecls :: KnotTied TyCon -> ([KnotTied TyConBinder], KnotTied Type)
1854 -> [LConDecl GhcRn] -> TcM [DataCon]
1855 -- Why both the tycon tyvars and binders? Because the tyvars
1856 -- have all the names and the binders have the visibilities.
1857 tcConDecls rep_tycon (tmpl_bndrs, res_tmpl)
1858 = concatMapM $ addLocM $
1859 tcConDecl rep_tycon (mkTyConTagMap rep_tycon) tmpl_bndrs res_tmpl
1860 -- It's important that we pay for tag allocation here, once per TyCon,
1861 -- See Note [Constructor tag allocation], fixes #14657
1862
1863 tcConDecl :: KnotTied TyCon -- Representation tycon. Knot-tied!
1864 -> NameEnv ConTag
1865 -> [KnotTied TyConBinder] -> KnotTied Type
1866 -- Return type template (with its template tyvars)
1867 -- (tvs, T tys), where T is the family TyCon
1868 -> ConDecl GhcRn
1869 -> TcM [DataCon]
1870
1871 tcConDecl rep_tycon tag_map tmpl_bndrs res_tmpl
1872 (ConDeclH98 { con_name = name
1873 , con_ex_tvs = explicit_tkv_nms
1874 , con_mb_cxt = hs_ctxt
1875 , con_args = hs_args })
1876 = addErrCtxt (dataConCtxtName [name]) $
1877 do { -- Get hold of the existential type variables
1878 -- e.g. data T a = forall k (b::k) f. MkT a (f b)
1879 -- Here tmpl_bndrs = {a}
1880 -- hs_qvars = HsQTvs { hsq_implicit = {k}
1881 -- , hsq_explicit = {f,b} }
1882
1883 ; traceTc "tcConDecl 1" (vcat [ ppr name, ppr explicit_tkv_nms ])
1884
1885 ; (exp_tvs, (ctxt, arg_tys, field_lbls, stricts))
1886 <- solveEqualities $
1887 tcExplicitTKBndrs skol_info explicit_tkv_nms $
1888 do { ctxt <- tcHsMbContext hs_ctxt
1889 ; btys <- tcConArgs hs_args
1890 ; field_lbls <- lookupConstructorFields (unLoc name)
1891 ; let (arg_tys, stricts) = unzip btys
1892 ; return (ctxt, arg_tys, field_lbls, stricts)
1893 }
1894
1895 -- exp_tvs have explicit, user-written binding sites
1896 -- the kvs below are those kind variables entirely unmentioned by the user
1897 -- and discovered only by generalization
1898
1899 ; kvs <- quantifyConDecl (mkVarSet (binderVars tmpl_bndrs))
1900 (mkSpecForAllTys exp_tvs $
1901 mkFunTys ctxt $
1902 mkFunTys arg_tys $
1903 unitTy)
1904 -- That type is a lie, of course. (It shouldn't end in ()!)
1905 -- And we could construct a proper result type from the info
1906 -- at hand. But the result would mention only the tmpl_tvs,
1907 -- and so it just creates more work to do it right. Really,
1908 -- we're doing this to get the right behavior around removing
1909 -- any vars bound in exp_binders.
1910
1911 -- Zonk to Types
1912 ; (ze, qkvs) <- zonkTyBndrsX emptyZonkEnv kvs
1913 ; (ze, user_qtvs) <- zonkTyBndrsX ze exp_tvs
1914 ; arg_tys <- zonkTcTypeToTypes ze arg_tys
1915 ; ctxt <- zonkTcTypeToTypes ze ctxt
1916
1917 ; fam_envs <- tcGetFamInstEnvs
1918
1919 -- Can't print univ_tvs, arg_tys etc, because we are inside the knot here
1920 ; traceTc "tcConDecl 2" (ppr name $$ ppr field_lbls)
1921 ; let
1922 univ_tvbs = tyConTyVarBinders tmpl_bndrs
1923 univ_tvs = binderVars univ_tvbs
1924 ex_tvbs = mkTyVarBinders Inferred qkvs ++
1925 mkTyVarBinders Specified user_qtvs
1926 ex_tvs = qkvs ++ user_qtvs
1927 -- For H98 datatypes, the user-written tyvar binders are precisely
1928 -- the universals followed by the existentials.
1929 -- See Note [DataCon user type variable binders] in DataCon.
1930 user_tvbs = univ_tvbs ++ ex_tvbs
1931 buildOneDataCon (L _ name) = do
1932 { is_infix <- tcConIsInfixH98 name hs_args
1933 ; rep_nm <- newTyConRepName name
1934
1935 ; buildDataCon fam_envs name is_infix rep_nm
1936 stricts Nothing field_lbls
1937 univ_tvs ex_tvs user_tvbs
1938 [{- no eq_preds -}] ctxt arg_tys
1939 res_tmpl rep_tycon tag_map
1940 -- NB: we put data_tc, the type constructor gotten from the
1941 -- constructor type signature into the data constructor;
1942 -- that way checkValidDataCon can complain if it's wrong.
1943 }
1944 ; traceTc "tcConDecl 2" (ppr name)
1945 ; mapM buildOneDataCon [name]
1946 }
1947 where
1948 skol_info = SigTypeSkol (ConArgCtxt (unLoc name))
1949
1950 tcConDecl rep_tycon tag_map tmpl_bndrs res_tmpl
1951 (ConDeclGADT { con_names = names
1952 , con_qvars = qtvs
1953 , con_mb_cxt = cxt, con_args = hs_args
1954 , con_res_ty = res_ty })
1955 | HsQTvs { hsq_ext = HsQTvsRn { hsq_implicit = implicit_tkv_nms }
1956 , hsq_explicit = explicit_tkv_nms } <- qtvs
1957 = addErrCtxt (dataConCtxtName names) $
1958 do { traceTc "tcConDecl 1" (ppr names)
1959 ; let (L _ name : _) = names
1960 skol_info = DataConSkol name
1961
1962 ; (imp_tvs, (exp_tvs, (ctxt, arg_tys, res_ty, field_lbls, stricts)))
1963 <- failIfEmitsConstraints $ -- we won't get another crack, and we don't
1964 -- want an error cascade
1965 tcImplicitTKBndrs skol_info implicit_tkv_nms $
1966 tcExplicitTKBndrs skol_info explicit_tkv_nms $
1967 do { ctxt <- tcHsMbContext cxt
1968 ; btys <- tcConArgs hs_args
1969 ; res_ty' <- tcHsLiftedType res_ty
1970 ; field_lbls <- lookupConstructorFields name
1971 ; let (arg_tys, stricts) = unzip btys
1972 ; return (ctxt, arg_tys, res_ty', field_lbls, stricts)
1973 }
1974 ; let user_tvs = imp_tvs ++ exp_tvs
1975
1976 ; tkvs <- quantifyConDecl emptyVarSet (mkSpecForAllTys user_tvs $
1977 mkFunTys ctxt $
1978 mkFunTys arg_tys $
1979 res_ty)
1980
1981 -- Zonk to Types
1982 ; (ze, tkvs) <- zonkTyBndrsX emptyZonkEnv tkvs
1983 ; (ze, user_tvs) <- zonkTyBndrsX ze user_tvs
1984 ; arg_tys <- zonkTcTypeToTypes ze arg_tys
1985 ; ctxt <- zonkTcTypeToTypes ze ctxt
1986 ; res_ty <- zonkTcTypeToType ze res_ty
1987
1988 ; let (univ_tvs, ex_tvs, tkvs', user_tvs', eq_preds, arg_subst)
1989 = rejigConRes tmpl_bndrs res_tmpl tkvs user_tvs res_ty
1990 -- NB: this is a /lazy/ binding, so we pass six thunks to
1991 -- buildDataCon without yet forcing the guards in rejigConRes
1992 -- See Note [Checking GADT return types]
1993
1994 -- Compute the user-written tyvar binders. These have the same
1995 -- tyvars as univ_tvs/ex_tvs, but perhaps in a different order.
1996 -- See Note [DataCon user type variable binders] in DataCon.
1997 tkv_bndrs = mkTyVarBinders Inferred tkvs'
1998 user_tv_bndrs = mkTyVarBinders Specified user_tvs'
1999 all_user_bndrs = tkv_bndrs ++ user_tv_bndrs
2000
2001 ctxt' = substTys arg_subst ctxt
2002 arg_tys' = substTys arg_subst arg_tys
2003 res_ty' = substTy arg_subst res_ty
2004
2005
2006 ; fam_envs <- tcGetFamInstEnvs
2007
2008 -- Can't print univ_tvs, arg_tys etc, because we are inside the knot here
2009 ; traceTc "tcConDecl 2" (ppr names $$ ppr field_lbls)
2010 ; let
2011 buildOneDataCon (L _ name) = do
2012 { is_infix <- tcConIsInfixGADT name hs_args
2013 ; rep_nm <- newTyConRepName name
2014
2015 ; buildDataCon fam_envs name is_infix
2016 rep_nm
2017 stricts Nothing field_lbls
2018 univ_tvs ex_tvs all_user_bndrs eq_preds
2019 ctxt' arg_tys' res_ty' rep_tycon tag_map
2020 -- NB: we put data_tc, the type constructor gotten from the
2021 -- constructor type signature into the data constructor;
2022 -- that way checkValidDataCon can complain if it's wrong.
2023 }
2024 ; traceTc "tcConDecl 2" (ppr names)
2025 ; mapM buildOneDataCon names
2026 }
2027 tcConDecl _ _ _ _ (ConDeclGADT _ _ _ (XLHsQTyVars _) _ _ _ _)
2028 = panic "tcConDecl"
2029 tcConDecl _ _ _ _ (XConDecl _) = panic "tcConDecl"
2030
2031 -- | Produce the telescope of kind variables that this datacon is
2032 -- implicitly quantified over. Incoming type need not be zonked.
2033 quantifyConDecl :: TcTyCoVarSet -- outer tvs, not to be quantified over; zonked
2034 -> TcType -> TcM [TcTyVar]
2035 quantifyConDecl gbl_tvs ty
2036 = do { ty <- zonkTcType ty
2037 ; let fvs = candidateQTyVarsOfType ty
2038 ; quantifyTyVars gbl_tvs fvs }
2039
2040 tcConIsInfixH98 :: Name
2041 -> HsConDetails (LHsType GhcRn) (Located [LConDeclField GhcRn])
2042 -> TcM Bool
2043 tcConIsInfixH98 _ details
2044 = case details of
2045 InfixCon {} -> return True
2046 _ -> return False
2047
2048 tcConIsInfixGADT :: Name
2049 -> HsConDetails (LHsType GhcRn) (Located [LConDeclField GhcRn])
2050 -> TcM Bool
2051 tcConIsInfixGADT con details
2052 = case details of
2053 InfixCon {} -> return True
2054 RecCon {} -> return False
2055 PrefixCon arg_tys -- See Note [Infix GADT constructors]
2056 | isSymOcc (getOccName con)
2057 , [_ty1,_ty2] <- arg_tys
2058 -> do { fix_env <- getFixityEnv
2059 ; return (con `elemNameEnv` fix_env) }
2060 | otherwise -> return False
2061
2062 tcConArgs :: HsConDeclDetails GhcRn
2063 -> TcM [(TcType, HsSrcBang)]
2064 tcConArgs (PrefixCon btys)
2065 = mapM tcConArg btys
2066 tcConArgs (InfixCon bty1 bty2)
2067 = do { bty1' <- tcConArg bty1
2068 ; bty2' <- tcConArg bty2
2069 ; return [bty1', bty2'] }
2070 tcConArgs (RecCon fields)
2071 = mapM tcConArg btys
2072 where
2073 -- We need a one-to-one mapping from field_names to btys
2074 combined = map (\(L _ f) -> (cd_fld_names f,cd_fld_type f)) (unLoc fields)
2075 explode (ns,ty) = zip ns (repeat ty)
2076 exploded = concatMap explode combined
2077 (_,btys) = unzip exploded
2078
2079
2080 tcConArg :: LHsType GhcRn -> TcM (TcType, HsSrcBang)
2081 tcConArg bty
2082 = do { traceTc "tcConArg 1" (ppr bty)
2083 ; arg_ty <- tcHsOpenType (getBangType bty)
2084 -- Newtypes can't have unboxed types, but we check
2085 -- that in checkValidDataCon; this tcConArg stuff
2086 -- doesn't happen for GADT-style declarations
2087 ; traceTc "tcConArg 2" (ppr bty)
2088 ; return (arg_ty, getBangStrictness bty) }
2089
2090 {-
2091 Note [Infix GADT constructors]
2092 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2093 We do not currently have syntax to declare an infix constructor in GADT syntax,
2094 but it makes a (small) difference to the Show instance. So as a slightly
2095 ad-hoc solution, we regard a GADT data constructor as infix if
2096 a) it is an operator symbol
2097 b) it has two arguments
2098 c) there is a fixity declaration for it
2099 For example:
2100 infix 6 (:--:)
2101 data T a where
2102 (:--:) :: t1 -> t2 -> T Int
2103
2104
2105 Note [Checking GADT return types]
2106 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2107 There is a delicacy around checking the return types of a datacon. The
2108 central problem is dealing with a declaration like
2109
2110 data T a where
2111 MkT :: T a -> Q a
2112
2113 Note that the return type of MkT is totally bogus. When creating the T
2114 tycon, we also need to create the MkT datacon, which must have a "rejigged"
2115 return type. That is, the MkT datacon's type must be transformed to have
2116 a uniform return type with explicit coercions for GADT-like type parameters.
2117 This rejigging is what rejigConRes does. The problem is, though, that checking
2118 that the return type is appropriate is much easier when done over *Type*,
2119 not *HsType*, and doing a call to tcMatchTy will loop because T isn't fully
2120 defined yet.
2121
2122 So, we want to make rejigConRes lazy and then check the validity of
2123 the return type in checkValidDataCon. To do this we /always/ return a
2124 6-tuple from rejigConRes (so that we can compute the return type from it, which
2125 checkValidDataCon needs), but the first three fields may be bogus if
2126 the return type isn't valid (the last equation for rejigConRes).
2127
2128 This is better than an earlier solution which reduced the number of
2129 errors reported in one pass. See Trac #7175, and #10836.
2130 -}
2131
2132 -- Example
2133 -- data instance T (b,c) where
2134 -- TI :: forall e. e -> T (e,e)
2135 --
2136 -- The representation tycon looks like this:
2137 -- data :R7T b c where
2138 -- TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
2139 -- In this case orig_res_ty = T (e,e)
2140
2141 rejigConRes :: [KnotTied TyConBinder] -> KnotTied Type -- Template for result type; e.g.
2142 -- data instance T [a] b c ...
2143 -- gives template ([a,b,c], T [a] b c)
2144 -- Type must be of kind *!
2145 -> [TyVar] -- The constructor's user-written, inferred
2146 -- type variables
2147 -> [TyVar] -- The constructor's user-written, specified
2148 -- type variables
2149 -> KnotTied Type -- res_ty type must be of kind *
2150 -> ([TyVar], -- Universal
2151 [TyVar], -- Existential (distinct OccNames from univs)
2152 [TyVar], -- The constructor's rejigged, user-written,
2153 -- inferred type variables
2154 [TyVar], -- The constructor's rejigged, user-written,
2155 -- specified type variables
2156 [EqSpec], -- Equality predicates
2157 TCvSubst) -- Substitution to apply to argument types
2158 -- We don't check that the TyCon given in the ResTy is
2159 -- the same as the parent tycon, because checkValidDataCon will do it
2160 -- NB: All arguments may potentially be knot-tied
2161 rejigConRes tmpl_bndrs res_tmpl dc_inferred_tvs dc_specified_tvs res_ty
2162 -- E.g. data T [a] b c where
2163 -- MkT :: forall x y z. T [(x,y)] z z
2164 -- The {a,b,c} are the tmpl_tvs, and the {x,y,z} are the dc_tvs
2165 -- (NB: unlike the H98 case, the dc_tvs are not all existential)
2166 -- Then we generate
2167 -- Univ tyvars Eq-spec
2168 -- a a~(x,y)
2169 -- b b~z
2170 -- z
2171 -- Existentials are the leftover type vars: [x,y]
2172 -- The user-written type variables are what is listed in the forall:
2173 -- [x, y, z] (all specified). We must rejig these as well.
2174 -- See Note [DataCon user type variable binders] in DataCon.
2175 -- So we return ( [a,b,z], [x,y]
2176 -- , [], [x,y,z]
2177 -- , [a~(x,y),b~z], <arg-subst> )
2178 | Just subst <- ASSERT( isLiftedTypeKind (typeKind res_ty) )
2179 ASSERT( isLiftedTypeKind (typeKind res_tmpl) )
2180 tcMatchTy res_tmpl res_ty
2181 = let (univ_tvs, raw_eqs, kind_subst) = mkGADTVars tmpl_tvs dc_tvs subst
2182 raw_ex_tvs = dc_tvs `minusList` univ_tvs
2183 (arg_subst, substed_ex_tvs) = substTyVarBndrs kind_subst raw_ex_tvs
2184
2185 -- After rejigging the existential tyvars, the resulting substitution
2186 -- gives us exactly what we need to rejig the user-written tyvars,
2187 -- since the dcUserTyVarBinders invariant guarantees that the
2188 -- substitution has *all* the tyvars in its domain.
2189 -- See Note [DataCon user type variable binders] in DataCon.
2190 subst_user_tvs = map (getTyVar "rejigConRes" . substTyVar arg_subst)
2191 substed_inferred_tvs = subst_user_tvs dc_inferred_tvs
2192 substed_specified_tvs = subst_user_tvs dc_specified_tvs
2193
2194 substed_eqs = map (substEqSpec arg_subst) raw_eqs
2195 in
2196 (univ_tvs, substed_ex_tvs, substed_inferred_tvs, substed_specified_tvs,
2197 substed_eqs, arg_subst)
2198
2199 | otherwise
2200 -- If the return type of the data constructor doesn't match the parent
2201 -- type constructor, or the arity is wrong, the tcMatchTy will fail
2202 -- e.g data T a b where
2203 -- T1 :: Maybe a -- Wrong tycon
2204 -- T2 :: T [a] -- Wrong arity
2205 -- We are detect that later, in checkValidDataCon, but meanwhile
2206 -- we must do *something*, not just crash. So we do something simple
2207 -- albeit bogus, relying on checkValidDataCon to check the
2208 -- bad-result-type error before seeing that the other fields look odd
2209 -- See Note [Checking GADT return types]
2210 = (tmpl_tvs, dc_tvs `minusList` tmpl_tvs, dc_inferred_tvs, dc_specified_tvs,
2211 [], emptyTCvSubst)
2212 where
2213 dc_tvs = dc_inferred_tvs ++ dc_specified_tvs
2214 tmpl_tvs = binderVars tmpl_bndrs
2215
2216 {- Note [mkGADTVars]
2217 ~~~~~~~~~~~~~~~~~~~~
2218 Running example:
2219
2220 data T (k1 :: *) (k2 :: *) (a :: k2) (b :: k2) where
2221 MkT :: forall (x1 : *) (y :: x1) (z :: *).
2222 T x1 * (Proxy (y :: x1), z) z
2223
2224 We need the rejigged type to be
2225
2226 MkT :: forall (x1 :: *) (k2 :: *) (a :: k2) (b :: k2).
2227 forall (y :: x1) (z :: *).
2228 (k2 ~ *, a ~ (Proxy x1 y, z), b ~ z)
2229 => T x1 k2 a b
2230
2231 You might naively expect that z should become a universal tyvar,
2232 not an existential. (After all, x1 becomes a universal tyvar.)
2233 But z has kind * while b has kind k2, so the return type
2234 T x1 k2 a z
2235 is ill-kinded. Another way to say it is this: the universal
2236 tyvars must have exactly the same kinds as the tyConTyVars.
2237
2238 So we need an existential tyvar and a heterogeneous equality
2239 constraint. (The b ~ z is a bit redundant with the k2 ~ * that
2240 comes before in that b ~ z implies k2 ~ *. I'm sure we could do
2241 some analysis that could eliminate k2 ~ *. But we don't do this
2242 yet.)
2243
2244 The data con signature has already been fully kind-checked.
2245 The return type
2246
2247 T x1 * (Proxy (y :: x1), z) z
2248 becomes
2249 qtkvs = [x1 :: *, y :: x1, z :: *]
2250 res_tmpl = T x1 * (Proxy x1 y, z) z
2251
2252 We start off by matching (T k1 k2 a b) with (T x1 * (Proxy x1 y, z) z). We
2253 know this match will succeed because of the validity check (actually done
2254 later, but laziness saves us -- see Note [Checking GADT return types]).
2255 Thus, we get
2256
2257 subst := { k1 |-> x1, k2 |-> *, a |-> (Proxy x1 y, z), b |-> z }
2258
2259 Now, we need to figure out what the GADT equalities should be. In this case,
2260 we *don't* want (k1 ~ x1) to be a GADT equality: it should just be a
2261 renaming. The others should be GADT equalities. We also need to make
2262 sure that the universally-quantified variables of the datacon match up
2263 with the tyvars of the tycon, as required for Core context well-formedness.
2264 (This last bit is why we have to rejig at all!)
2265
2266 `choose` walks down the tycon tyvars, figuring out what to do with each one.
2267 It carries two substitutions:
2268 - t_sub's domain is *template* or *tycon* tyvars, mapping them to variables
2269 mentioned in the datacon signature.
2270 - r_sub's domain is *result* tyvars, names written by the programmer in
2271 the datacon signature. The final rejigged type will use these names, but
2272 the subst is still needed because sometimes the printed name of these variables
2273 is different. (See choose_tv_name, below.)
2274
2275 Before explaining the details of `choose`, let's just look at its operation
2276 on our example:
2277
2278 choose [] [] {} {} [k1, k2, a, b]
2279 --> -- first branch of `case` statement
2280 choose
2281 univs: [x1 :: *]
2282 eq_spec: []
2283 t_sub: {k1 |-> x1}
2284 r_sub: {x1 |-> x1}
2285 t_tvs: [k2, a, b]
2286 --> -- second branch of `case` statement
2287 choose
2288 univs: [k2 :: *, x1 :: *]
2289 eq_spec: [k2 ~ *]
2290 t_sub: {k1 |-> x1, k2 |-> k2}
2291 r_sub: {x1 |-> x1}
2292 t_tvs: [a, b]
2293 --> -- second branch of `case` statement
2294 choose
2295 univs: [a :: k2, k2 :: *, x1 :: *]
2296 eq_spec: [ a ~ (Proxy x1 y, z)
2297 , k2 ~ * ]
2298 t_sub: {k1 |-> x1, k2 |-> k2, a |-> a}
2299 r_sub: {x1 |-> x1}
2300 t_tvs: [b]
2301 --> -- second branch of `case` statement
2302 choose
2303 univs: [b :: k2, a :: k2, k2 :: *, x1 :: *]
2304 eq_spec: [ b ~ z
2305 , a ~ (Proxy x1 y, z)
2306 , k2 ~ * ]
2307 t_sub: {k1 |-> x1, k2 |-> k2, a |-> a, b |-> z}
2308 r_sub: {x1 |-> x1}
2309 t_tvs: []
2310 --> -- end of recursion
2311 ( [x1 :: *, k2 :: *, a :: k2, b :: k2]
2312 , [k2 ~ *, a ~ (Proxy x1 y, z), b ~ z]
2313 , {x1 |-> x1} )
2314
2315 `choose` looks up each tycon tyvar in the matching (it *must* be matched!).
2316
2317 * If it finds a bare result tyvar (the first branch of the `case`
2318 statement), it checks to make sure that the result tyvar isn't yet
2319 in the list of univ_tvs. If it is in that list, then we have a
2320 repeated variable in the return type, and we in fact need a GADT
2321 equality.
2322
2323 * It then checks to make sure that the kind of the result tyvar
2324 matches the kind of the template tyvar. This check is what forces
2325 `z` to be existential, as it should be, explained above.
2326
2327 * Assuming no repeated variables or kind-changing, we wish to use the
2328 variable name given in the datacon signature (that is, `x1` not
2329 `k1`), not the tycon signature (which may have been made up by
2330 GHC). So, we add a mapping from the tycon tyvar to the result tyvar
2331 to t_sub.
2332
2333 * If we discover that a mapping in `subst` gives us a non-tyvar (the
2334 second branch of the `case` statement), then we have a GADT equality
2335 to create. We create a fresh equality, but we don't extend any
2336 substitutions. The template variable substitution is meant for use
2337 in universal tyvar kinds, and these shouldn't be affected by any
2338 GADT equalities.
2339
2340 This whole algorithm is quite delicate, indeed. I (Richard E.) see two ways
2341 of simplifying it:
2342
2343 1) The first branch of the `case` statement is really an optimization, used
2344 in order to get fewer GADT equalities. It might be possible to make a GADT
2345 equality for *every* univ. tyvar, even if the equality is trivial, and then
2346 either deal with the bigger type or somehow reduce it later.
2347
2348 2) This algorithm strives to use the names for type variables as specified
2349 by the user in the datacon signature. If we always used the tycon tyvar
2350 names, for example, this would be simplified. This change would almost
2351 certainly degrade error messages a bit, though.
2352 -}
2353
2354 -- ^ From information about a source datacon definition, extract out
2355 -- what the universal variables and the GADT equalities should be.
2356 -- See Note [mkGADTVars].
2357 mkGADTVars :: [TyVar] -- ^ The tycon vars
2358 -> [TyVar] -- ^ The datacon vars
2359 -> TCvSubst -- ^ The matching between the template result type
2360 -- and the actual result type
2361 -> ( [TyVar]
2362 , [EqSpec]
2363 , TCvSubst ) -- ^ The univ. variables, the GADT equalities,
2364 -- and a subst to apply to the GADT equalities
2365 -- and existentials.
2366 mkGADTVars tmpl_tvs dc_tvs subst
2367 = choose [] [] empty_subst empty_subst tmpl_tvs
2368 where
2369 in_scope = mkInScopeSet (mkVarSet tmpl_tvs `unionVarSet` mkVarSet dc_tvs)
2370 `unionInScope` getTCvInScope subst
2371 empty_subst = mkEmptyTCvSubst in_scope
2372
2373 choose :: [TyVar] -- accumulator of univ tvs, reversed
2374 -> [EqSpec] -- accumulator of GADT equalities, reversed
2375 -> TCvSubst -- template substitution
2376 -> TCvSubst -- res. substitution
2377 -> [TyVar] -- template tvs (the univ tvs passed in)
2378 -> ( [TyVar] -- the univ_tvs
2379 , [EqSpec] -- GADT equalities
2380 , TCvSubst ) -- a substitution to fix kinds in ex_tvs
2381
2382 choose univs eqs _t_sub r_sub []
2383 = (reverse univs, reverse eqs, r_sub)
2384 choose univs eqs t_sub r_sub (t_tv:t_tvs)
2385 | Just r_ty <- lookupTyVar subst t_tv
2386 = case getTyVar_maybe r_ty of
2387 Just r_tv
2388 | not (r_tv `elem` univs)
2389 , tyVarKind r_tv `eqType` (substTy t_sub (tyVarKind t_tv))
2390 -> -- simple, well-kinded variable substitution.
2391 choose (r_tv:univs) eqs
2392 (extendTvSubst t_sub t_tv r_ty')
2393 (extendTvSubst r_sub r_tv r_ty')
2394 t_tvs
2395 where
2396 r_tv1 = setTyVarName r_tv (choose_tv_name r_tv t_tv)
2397 r_ty' = mkTyVarTy r_tv1
2398
2399 -- Not a simple substitution: make an equality predicate
2400 _ -> choose (t_tv':univs) (mkEqSpec t_tv' r_ty : eqs)
2401 (extendTvSubst t_sub t_tv (mkTyVarTy t_tv'))
2402 -- We've updated the kind of t_tv,
2403 -- so add it to t_sub (Trac #14162)
2404 r_sub t_tvs
2405 where
2406 t_tv' = updateTyVarKind (substTy t_sub) t_tv
2407
2408 | otherwise
2409 = pprPanic "mkGADTVars" (ppr tmpl_tvs $$ ppr subst)
2410
2411 -- choose an appropriate name for a univ tyvar.
2412 -- This *must* preserve the Unique of the result tv, so that we
2413 -- can detect repeated variables. It prefers user-specified names
2414 -- over system names. A result variable with a system name can
2415 -- happen with GHC-generated implicit kind variables.
2416 choose_tv_name :: TyVar -> TyVar -> Name
2417 choose_tv_name r_tv t_tv
2418 | isSystemName r_tv_name
2419 = setNameUnique t_tv_name (getUnique r_tv_name)
2420
2421 | otherwise
2422 = r_tv_name
2423
2424 where
2425 r_tv_name = getName r_tv
2426 t_tv_name = getName t_tv
2427
2428 {-
2429 Note [Substitution in template variables kinds]
2430 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2431
2432 data G (a :: Maybe k) where
2433 MkG :: G Nothing
2434
2435 With explicit kind variables
2436
2437 data G k (a :: Maybe k) where
2438 MkG :: G k1 (Nothing k1)
2439
2440 Note how k1 is distinct from k. So, when we match the template
2441 `G k a` against `G k1 (Nothing k1)`, we get a subst
2442 [ k |-> k1, a |-> Nothing k1 ]. Even though this subst has two
2443 mappings, we surely don't want to add (k, k1) to the list of
2444 GADT equalities -- that would be overly complex and would create
2445 more untouchable variables than we need. So, when figuring out
2446 which tyvars are GADT-like and which aren't (the fundamental
2447 job of `choose`), we want to treat `k` as *not* GADT-like.
2448 Instead, we wish to substitute in `a`'s kind, to get (a :: Maybe k1)
2449 instead of (a :: Maybe k). This is the reason for dealing
2450 with a substitution in here.
2451
2452 However, we do not *always* want to substitute. Consider
2453
2454 data H (a :: k) where
2455 MkH :: H Int
2456
2457 With explicit kind variables:
2458
2459 data H k (a :: k) where
2460 MkH :: H * Int
2461
2462 Here, we have a kind-indexed GADT. The subst in question is
2463 [ k |-> *, a |-> Int ]. Now, we *don't* want to substitute in `a`'s
2464 kind, because that would give a constructor with the type
2465
2466 MkH :: forall (k :: *) (a :: *). (k ~ *) -> (a ~ Int) -> H k a
2467
2468 The problem here is that a's kind is wrong -- it needs to be k, not *!
2469 So, if the matching for a variable is anything but another bare variable,
2470 we drop the mapping from the substitution before proceeding. This
2471 was not an issue before kind-indexed GADTs because this case could
2472 never happen.
2473
2474 ************************************************************************
2475 * *
2476 Validity checking
2477 * *
2478 ************************************************************************
2479
2480 Validity checking is done once the mutually-recursive knot has been
2481 tied, so we can look at things freely.
2482 -}
2483
2484 checkValidTyCl :: TyCon -> TcM [TyCon]
2485 -- The returned list is either a singleton (if valid)
2486 -- or a list of "fake tycons" (if not); the fake tycons
2487 -- include any implicits, like promoted data constructors
2488 -- See Note [Recover from validity error]
2489 checkValidTyCl tc
2490 = setSrcSpan (getSrcSpan tc) $
2491 addTyConCtxt tc $
2492 recoverM recovery_code
2493 (do { traceTc "Starting validity for tycon" (ppr tc)
2494 ; checkValidTyCon tc
2495 ; traceTc "Done validity for tycon" (ppr tc)
2496 ; return [tc] })
2497 where
2498 recovery_code -- See Note [Recover from validity error]
2499 = do { traceTc "Aborted validity for tycon" (ppr tc)
2500 ; return (concatMap mk_fake_tc $
2501 ATyCon tc : implicitTyConThings tc) }
2502
2503 mk_fake_tc (ATyCon tc)
2504 | isClassTyCon tc = [tc] -- Ugh! Note [Recover from validity error]
2505 | otherwise = [makeRecoveryTyCon tc]
2506 mk_fake_tc (AConLike (RealDataCon dc))
2507 = [makeRecoveryTyCon (promoteDataCon dc)]
2508 mk_fake_tc _ = []
2509
2510 {- Note [Recover from validity error]
2511 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2512 We recover from a validity error in a type or class, which allows us
2513 to report multiple validity errors. In the failure case we return a
2514 TyCon of the right kind, but with no interesting behaviour
2515 (makeRecoveryTyCon). Why? Suppose we have
2516 type T a = Fun
2517 where Fun is a type family of arity 1. The RHS is invalid, but we
2518 want to go on checking validity of subsequent type declarations.
2519 So we replace T with an abstract TyCon which will do no harm.
2520 See indexed-types/should_fail/BadSock and Trac #10896
2521
2522 Some notes:
2523
2524 * We must make fakes for promoted DataCons too. Consider (Trac #15215)
2525 data T a = MkT ...
2526 data S a = ...T...MkT....
2527 If there is an error in the definition of 'T' we add a "fake type
2528 constructor" to the type environment, so that we can continue to
2529 typecheck 'S'. But we /were not/ adding a fake anything for 'MkT'
2530 and so there was an internal error when we met 'MkT' in the body of
2531 'S'.
2532
2533 * Painfully, we *don't* want to do this for classes.
2534 Consider tcfail041:
2535 class (?x::Int) => C a where ...
2536 instance C Int
2537 The class is invalid because of the superclass constraint. But
2538 we still want it to look like a /class/, else the instance bleats
2539 that the instance is mal-formed because it hasn't got a class in
2540 the head.
2541
2542 This is really bogus; now we have in scope a Class that is invalid
2543 in some way, with unknown downstream consequences. A better
2544 alterantive might be to make a fake class TyCon. A job for another day.
2545 -}
2546
2547 -------------------------
2548 -- For data types declared with record syntax, we require
2549 -- that each constructor that has a field 'f'
2550 -- (a) has the same result type
2551 -- (b) has the same type for 'f'
2552 -- module alpha conversion of the quantified type variables
2553 -- of the constructor.
2554 --
2555 -- Note that we allow existentials to match because the
2556 -- fields can never meet. E.g
2557 -- data T where
2558 -- T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
2559 -- T2 { f1 :: c, f2 :: c, f3 ::Int } :: T
2560 -- Here we do not complain about f1,f2 because they are existential
2561
2562 checkValidTyCon :: TyCon -> TcM ()
2563 checkValidTyCon tc
2564 | isPrimTyCon tc -- Happens when Haddock'ing GHC.Prim
2565 = return ()
2566
2567 | otherwise
2568 = do { traceTc "checkValidTyCon" (ppr tc $$ ppr (tyConClass_maybe tc))
2569 ; if | Just cl <- tyConClass_maybe tc
2570 -> checkValidClass cl
2571
2572 | Just syn_rhs <- synTyConRhs_maybe tc
2573 -> do { checkValidType syn_ctxt syn_rhs
2574 ; checkTySynRhs syn_ctxt syn_rhs }
2575
2576 | Just fam_flav <- famTyConFlav_maybe tc
2577 -> case fam_flav of
2578 { ClosedSynFamilyTyCon (Just ax)
2579 -> tcAddClosedTypeFamilyDeclCtxt tc $
2580 checkValidCoAxiom ax
2581 ; ClosedSynFamilyTyCon Nothing -> return ()
2582 ; AbstractClosedSynFamilyTyCon ->
2583 do { hsBoot <- tcIsHsBootOrSig
2584 ; checkTc hsBoot $
2585 text "You may define an abstract closed type family" $$
2586 text "only in a .hs-boot file" }
2587 ; DataFamilyTyCon {} -> return ()
2588 ; OpenSynFamilyTyCon -> return ()
2589 ; BuiltInSynFamTyCon _ -> return () }
2590
2591 | otherwise -> do
2592 { -- Check the context on the data decl
2593 traceTc "cvtc1" (ppr tc)
2594 ; checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
2595
2596 ; traceTc "cvtc2" (ppr tc)
2597
2598 ; dflags <- getDynFlags
2599 ; existential_ok <- xoptM LangExt.ExistentialQuantification
2600 ; gadt_ok <- xoptM LangExt.GADTs
2601 ; let ex_ok = existential_ok || gadt_ok
2602 -- Data cons can have existential context
2603 ; mapM_ (checkValidDataCon dflags ex_ok tc) data_cons
2604 ; mapM_ (checkPartialRecordField data_cons) (tyConFieldLabels tc)
2605
2606 -- Check that fields with the same name share a type
2607 ; mapM_ check_fields groups }}
2608 where
2609 syn_ctxt = TySynCtxt name
2610 name = tyConName tc
2611 data_cons = tyConDataCons tc
2612
2613 groups = equivClasses cmp_fld (concatMap get_fields data_cons)
2614 cmp_fld (f1,_) (f2,_) = flLabel f1 `compare` flLabel f2
2615 get_fields con = dataConFieldLabels con `zip` repeat con
2616 -- dataConFieldLabels may return the empty list, which is fine
2617
2618 -- See Note [GADT record selectors] in TcTyDecls
2619 -- We must check (a) that the named field has the same
2620 -- type in each constructor
2621 -- (b) that those constructors have the same result type
2622 --
2623 -- However, the constructors may have differently named type variable
2624 -- and (worse) we don't know how the correspond to each other. E.g.
2625 -- C1 :: forall a b. { f :: a, g :: b } -> T a b
2626 -- C2 :: forall d c. { f :: c, g :: c } -> T c d
2627 --
2628 -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
2629 -- result type against other candidates' types BOTH WAYS ROUND.
2630 -- If they magically agrees, take the substitution and
2631 -- apply them to the latter ones, and see if they match perfectly.
2632 check_fields ((label, con1) :| other_fields)
2633 -- These fields all have the same name, but are from
2634 -- different constructors in the data type
2635 = recoverM (return ()) $ mapM_ checkOne other_fields
2636 -- Check that all the fields in the group have the same type
2637 -- NB: this check assumes that all the constructors of a given
2638 -- data type use the same type variables
2639 where
2640 (_, _, _, res1) = dataConSig con1
2641 fty1 = dataConFieldType con1 lbl
2642 lbl = flLabel label
2643
2644 checkOne (_, con2) -- Do it both ways to ensure they are structurally identical
2645 = do { checkFieldCompat lbl con1 con2 res1 res2 fty1 fty2
2646 ; checkFieldCompat lbl con2 con1 res2 res1 fty2 fty1 }
2647 where
2648 (_, _, _, res2) = dataConSig con2
2649 fty2 = dataConFieldType con2 lbl
2650
2651 checkPartialRecordField :: [DataCon] -> FieldLabel -> TcM ()
2652 -- Checks the partial record field selector, and warns.
2653 -- See Note [Checking partial record field]
2654 checkPartialRecordField all_cons fld
2655 = setSrcSpan loc $
2656 warnIfFlag Opt_WarnPartialFields
2657 (not is_exhaustive && not (startsWithUnderscore occ_name))
2658 (sep [text "Use of partial record field selector" <> colon,
2659 nest 2 $ quotes (ppr occ_name)])
2660 where
2661 sel_name = flSelector fld
2662 loc = getSrcSpan sel_name
2663 occ_name = getOccName sel_name
2664
2665 (cons_with_field, cons_without_field) = partition has_field all_cons
2666 has_field con = fld `elem` (dataConFieldLabels con)
2667 is_exhaustive = all (dataConCannotMatch inst_tys) cons_without_field
2668
2669 con1 = ASSERT( not (null cons_with_field) ) head cons_with_field
2670 (univ_tvs, _, eq_spec, _, _, _) = dataConFullSig con1
2671 eq_subst = mkTvSubstPrs (map eqSpecPair eq_spec)
2672 inst_tys = substTyVars eq_subst univ_tvs
2673
2674 checkFieldCompat :: FieldLabelString -> DataCon -> DataCon
2675 -> Type -> Type -> Type -> Type -> TcM ()
2676 checkFieldCompat fld con1 con2 res1 res2 fty1 fty2
2677 = do { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
2678 ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
2679 where
2680 mb_subst1 = tcMatchTy res1 res2
2681 mb_subst2 = tcMatchTyX (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
2682
2683 -------------------------------
2684 checkValidDataCon :: DynFlags -> Bool -> TyCon -> DataCon -> TcM ()
2685 checkValidDataCon dflags existential_ok tc con
2686 = setSrcSpan (getSrcSpan con) $
2687 addErrCtxt (dataConCtxt con) $
2688 do { -- Check that the return type of the data constructor
2689 -- matches the type constructor; eg reject this:
2690 -- data T a where { MkT :: Bogus a }
2691 -- It's important to do this first:
2692 -- see Note [Checking GADT return types]
2693 -- and c.f. Note [Check role annotations in a second pass]
2694 let tc_tvs = tyConTyVars tc
2695 res_ty_tmpl = mkFamilyTyConApp tc (mkTyVarTys tc_tvs)
2696 orig_res_ty = dataConOrigResTy con
2697 ; traceTc "checkValidDataCon" (vcat
2698 [ ppr con, ppr tc, ppr tc_tvs
2699 , ppr res_ty_tmpl <+> dcolon <+> ppr (typeKind res_ty_tmpl)
2700 , ppr orig_res_ty <+> dcolon <+> ppr (typeKind orig_res_ty)])
2701
2702
2703 ; checkTc (isJust (tcMatchTy res_ty_tmpl
2704 orig_res_ty))
2705 (badDataConTyCon con res_ty_tmpl orig_res_ty)
2706 -- Note that checkTc aborts if it finds an error. This is
2707 -- critical to avoid panicking when we call dataConUserType
2708 -- on an un-rejiggable datacon!
2709
2710 ; traceTc "checkValidDataCon 2" (ppr (dataConUserType con))
2711
2712 -- Check that the result type is a *monotype*
2713 -- e.g. reject this: MkT :: T (forall a. a->a)
2714 -- Reason: it's really the argument of an equality constraint
2715 ; checkValidMonoType orig_res_ty
2716
2717 -- Check all argument types for validity
2718 ; checkValidType ctxt (dataConUserType con)
2719 ; mapM_ (checkForLevPoly empty)
2720 (dataConOrigArgTys con)
2721
2722 -- Extra checks for newtype data constructors
2723 ; when (isNewTyCon tc) (checkNewDataCon con)
2724
2725 -- Check that existentials are allowed if they are used
2726 ; checkTc (existential_ok || isVanillaDataCon con)
2727 (badExistential con)
2728
2729 -- Check that UNPACK pragmas and bangs work out
2730 -- E.g. reject data T = MkT {-# UNPACK #-} Int -- No "!"
2731 -- data T = MkT {-# UNPACK #-} !a -- Can't unpack
2732 ; zipWith3M_ check_bang (dataConSrcBangs con) (dataConImplBangs con) [1..]
2733
2734 -- Check the dcUserTyVarBinders invariant
2735 -- See Note [DataCon user type variable binders] in DataCon
2736 -- checked here because we sometimes build invalid DataCons before
2737 -- erroring above here
2738 ; when debugIsOn $
2739 do { let (univs, exs, eq_spec, _, _, _) = dataConFullSig con
2740 user_tvs = dataConUserTyVars con
2741 user_tvbs_invariant
2742 = Set.fromList (filterEqSpec eq_spec univs ++ exs)
2743 == Set.fromList user_tvs
2744 ; MASSERT2( user_tvbs_invariant
2745 , vcat ([ ppr con
2746 , ppr univs
2747 , ppr exs
2748 , ppr eq_spec
2749 , ppr user_tvs ])) }
2750
2751 ; traceTc "Done validity of data con" $
2752 vcat [ ppr con
2753 , text "Datacon user type:" <+> ppr (dataConUserType con)
2754 , text "Datacon rep type:" <+> ppr (dataConRepType con)
2755 , text "Rep typcon binders:" <+> ppr (tyConBinders (dataConTyCon con))
2756 , case tyConFamInst_maybe (dataConTyCon con) of
2757 Nothing -> text "not family"
2758 Just (f, _) -> ppr (tyConBinders f) ]
2759 }
2760 where
2761 ctxt = ConArgCtxt (dataConName con)
2762
2763 check_bang :: HsSrcBang -> HsImplBang -> Int -> TcM ()
2764 check_bang (HsSrcBang _ _ SrcLazy) _ n
2765 | not (xopt LangExt.StrictData dflags)
2766 = addErrTc
2767 (bad_bang n (text "Lazy annotation (~) without StrictData"))
2768 check_bang (HsSrcBang _ want_unpack strict_mark) rep_bang n
2769 | isSrcUnpacked want_unpack, not is_strict
2770 = addWarnTc NoReason (bad_bang n (text "UNPACK pragma lacks '!'"))
2771 | isSrcUnpacked want_unpack
2772 , case rep_bang of { HsUnpack {} -> False; _ -> True }
2773 -- If not optimising, we don't unpack (rep_bang is never
2774 -- HsUnpack), so don't complain! This happens, e.g., in Haddock.
2775 -- See dataConSrcToImplBang.
2776 , not (gopt Opt_OmitInterfacePragmas dflags)
2777 -- When typechecking an indefinite package in Backpack, we
2778 -- may attempt to UNPACK an abstract type. The test here will
2779 -- conclude that this is unusable, but it might become usable
2780 -- when we actually fill in the abstract type. As such, don't
2781 -- warn in this case (it gives users the wrong idea about whether
2782 -- or not UNPACK on abstract types is supported; it is!)
2783 , unitIdIsDefinite (thisPackage dflags)
2784 = addWarnTc NoReason (bad_bang n (text "Ignoring unusable UNPACK pragma"))
2785 where
2786 is_strict = case strict_mark of
2787 NoSrcStrict -> xopt LangExt.StrictData dflags
2788 bang -> isSrcStrict bang
2789
2790 check_bang _ _ _
2791 = return ()
2792
2793 bad_bang n herald
2794 = hang herald 2 (text "on the" <+> speakNth n
2795 <+> text "argument of" <+> quotes (ppr con))
2796 -------------------------------
2797 checkNewDataCon :: DataCon -> TcM ()
2798 -- Further checks for the data constructor of a newtype
2799 checkNewDataCon con
2800 = do { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
2801 -- One argument
2802
2803 ; checkTc (not (isUnliftedType arg_ty1)) $
2804 text "A newtype cannot have an unlifted argument type"
2805
2806 ; check_con (null eq_spec) $
2807 text "A newtype constructor must have a return type of form T a1 ... an"
2808 -- Return type is (T a b c)
2809
2810 ; check_con (null theta) $
2811 text "A newtype constructor cannot have a context in its type"
2812
2813 ; check_con (null ex_tvs) $
2814 text "A newtype constructor cannot have existential type variables"
2815 -- No existentials
2816
2817 ; checkTc (all ok_bang (dataConSrcBangs con))
2818 (newtypeStrictError con)
2819 -- No strictness annotations
2820 }
2821 where
2822 (_univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _res_ty)
2823 = dataConFullSig con
2824 check_con what msg
2825 = checkTc what (msg $$ ppr con <+> dcolon <+> ppr (dataConUserType con))
2826
2827 (arg_ty1 : _) = arg_tys
2828
2829 ok_bang (HsSrcBang _ _ SrcStrict) = False
2830 ok_bang (HsSrcBang _ _ SrcLazy) = False
2831 ok_bang _ = True
2832
2833 -------------------------------
2834 checkValidClass :: Class -> TcM ()
2835 checkValidClass cls
2836 = do { constrained_class_methods <- xoptM LangExt.ConstrainedClassMethods
2837 ; multi_param_type_classes <- xoptM LangExt.MultiParamTypeClasses
2838 ; nullary_type_classes <- xoptM LangExt.NullaryTypeClasses
2839 ; fundep_classes <- xoptM LangExt.FunctionalDependencies
2840 ; undecidable_super_classes <- xoptM LangExt.UndecidableSuperClasses
2841
2842 -- Check that the class is unary, unless multiparameter type classes
2843 -- are enabled; also recognize deprecated nullary type classes
2844 -- extension (subsumed by multiparameter type classes, Trac #8993)
2845 ; checkTc (multi_param_type_classes || cls_arity == 1 ||
2846 (nullary_type_classes && cls_arity == 0))
2847 (classArityErr cls_arity cls)
2848 ; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
2849
2850 -- Check the super-classes
2851 ; checkValidTheta (ClassSCCtxt (className cls)) theta
2852
2853 -- Now check for cyclic superclasses
2854 -- If there are superclass cycles, checkClassCycleErrs bails.
2855 ; unless undecidable_super_classes $
2856 case checkClassCycles cls of
2857 Just err -> setSrcSpan (getSrcSpan cls) $
2858 addErrTc err
2859 Nothing -> return ()
2860
2861 -- Check the class operations.
2862 -- But only if there have been no earlier errors
2863 -- See Note [Abort when superclass cycle is detected]
2864 ; whenNoErrs $
2865 mapM_ (check_op constrained_class_methods) op_stuff
2866
2867 -- Check the associated type defaults are well-formed and instantiated
2868 ; mapM_ check_at at_stuff }
2869 where
2870 (tyvars, fundeps, theta, _, at_stuff, op_stuff) = classExtraBigSig cls
2871 cls_arity = length (tyConVisibleTyVars (classTyCon cls))
2872 -- Ignore invisible variables
2873 cls_tv_set = mkVarSet tyvars
2874 mini_env = zipVarEnv tyvars (mkTyVarTys tyvars)
2875 mb_cls = Just (cls, tyvars, mini_env)
2876
2877 check_op constrained_class_methods (sel_id, dm)
2878 = setSrcSpan (getSrcSpan sel_id) $
2879 addErrCtxt (classOpCtxt sel_id op_ty) $ do
2880 { traceTc "class op type" (ppr op_ty)
2881 ; checkValidType ctxt op_ty
2882 -- This implements the ambiguity check, among other things
2883 -- Example: tc223
2884 -- class Error e => Game b mv e | b -> mv e where
2885 -- newBoard :: MonadState b m => m ()
2886 -- Here, MonadState has a fundep m->b, so newBoard is fine
2887
2888 -- a method cannot be levity polymorphic, as we have to store the
2889 -- method in a dictionary
2890 -- example of what this prevents:
2891 -- class BoundedX (a :: TYPE r) where minBound :: a
2892 -- See Note [Levity polymorphism checking] in DsMonad
2893 ; checkForLevPoly empty tau1
2894
2895 ; unless constrained_class_methods $
2896 mapM_ check_constraint (tail (cls_pred:op_theta))
2897
2898 ; check_dm ctxt sel_id cls_pred tau2 dm
2899 }
2900 where
2901 ctxt = FunSigCtxt op_name True -- Report redundant class constraints
2902 op_name = idName sel_id
2903 op_ty = idType sel_id
2904 (_,cls_pred,tau1) = tcSplitMethodTy op_ty
2905 -- See Note [Splitting nested sigma types in class type signatures]
2906 (_,op_theta,tau2) = tcSplitNestedSigmaTys tau1
2907
2908 check_constraint :: TcPredType -> TcM ()
2909 check_constraint pred -- See Note [Class method constraints]
2910 = when (not (isEmptyVarSet pred_tvs) &&
2911 pred_tvs `subVarSet` cls_tv_set)
2912 (addErrTc (badMethPred sel_id pred))
2913 where
2914 pred_tvs = tyCoVarsOfType pred
2915
2916 check_at (ATI fam_tc m_dflt_rhs)
2917 = do { checkTc (cls_arity == 0 || any (`elemVarSet` cls_tv_set) fam_tvs)
2918 (noClassTyVarErr cls fam_tc)
2919 -- Check that the associated type mentions at least
2920 -- one of the class type variables
2921 -- The check is disabled for nullary type classes,
2922 -- since there is no possible ambiguity (Trac #10020)
2923
2924 -- Check that any default declarations for associated types are valid
2925 ; whenIsJust m_dflt_rhs $ \ (rhs, loc) ->
2926 checkValidTyFamEqn mb_cls fam_tc
2927 fam_tvs [] (mkTyVarTys fam_tvs) rhs pp_lhs loc }
2928 where
2929 fam_tvs = tyConTyVars fam_tc
2930 pp_lhs = ppr (mkTyConApp fam_tc (mkTyVarTys fam_tvs))
2931
2932 check_dm :: UserTypeCtxt -> Id -> PredType -> Type -> DefMethInfo -> TcM ()
2933 -- Check validity of the /top-level/ generic-default type
2934 -- E.g for class C a where
2935 -- default op :: forall b. (a~b) => blah
2936 -- we do not want to do an ambiguity check on a type with
2937 -- a free TyVar 'a' (Trac #11608). See TcType
2938 -- Note [TyVars and TcTyVars during type checking] in TcType
2939 -- Hence the mkDefaultMethodType to close the type.
2940 check_dm ctxt sel_id vanilla_cls_pred vanilla_tau
2941 (Just (dm_name, dm_spec@(GenericDM dm_ty)))
2942 = setSrcSpan (getSrcSpan dm_name) $ do
2943 -- We have carefully set the SrcSpan on the generic
2944 -- default-method Name to be that of the generic
2945 -- default type signature
2946
2947 -- First, we check that that the method's default type signature
2948 -- aligns with the non-default type signature.
2949 -- See Note [Default method type signatures must align]
2950 let cls_pred = mkClassPred cls $ mkTyVarTys $ classTyVars cls
2951 -- Note that the second field of this tuple contains the context
2952 -- of the default type signature, making it apparent that we
2953 -- ignore method contexts completely when validity-checking
2954 -- default type signatures. See the end of
2955 -- Note [Default method type signatures must align]
2956 -- to learn why this is OK.
2957 --
2958 -- See also
2959 -- Note [Splitting nested sigma types in class type signatures]
2960 -- for an explanation of why we don't use tcSplitSigmaTy here.
2961 (_, _, dm_tau) = tcSplitNestedSigmaTys dm_ty
2962
2963 -- Given this class definition:
2964 --
2965 -- class C a b where
2966 -- op :: forall p q. (Ord a, D p q)
2967 -- => a -> b -> p -> (a, b)
2968 -- default op :: forall r s. E r
2969 -- => a -> b -> s -> (a, b)
2970 --
2971 -- We want to match up two types of the form:
2972 --
2973 -- Vanilla type sig: C aa bb => aa -> bb -> p -> (aa, bb)
2974 -- Default type sig: C a b => a -> b -> s -> (a, b)
2975 --
2976 -- Notice that the two type signatures can be quantified over
2977 -- different class type variables! Therefore, it's important that
2978 -- we include the class predicate parts to match up a with aa and
2979 -- b with bb.
2980 vanilla_phi_ty = mkPhiTy [vanilla_cls_pred] vanilla_tau
2981 dm_phi_ty = mkPhiTy [cls_pred] dm_tau
2982
2983 traceTc "check_dm" $ vcat
2984 [ text "vanilla_phi_ty" <+> ppr vanilla_phi_ty
2985 , text "dm_phi_ty" <+> ppr dm_phi_ty ]
2986
2987 -- Actually checking that the types align is done with a call to
2988 -- tcMatchTys. We need to get a match in both directions to rule
2989 -- out degenerate cases like these:
2990 --
2991 -- class Foo a where
2992 -- foo1 :: a -> b
2993 -- default foo1 :: a -> Int
2994 --
2995 -- foo2 :: a -> Int
2996 -- default foo2 :: a -> b
2997 unless (isJust $ tcMatchTys [dm_phi_ty, vanilla_phi_ty]
2998 [vanilla_phi_ty, dm_phi_ty]) $ addErrTc $
2999 hang (text "The default type signature for"
3000 <+> ppr sel_id <> colon)
3001 2 (ppr dm_ty)
3002 $$ (text "does not match its corresponding"
3003 <+> text "non-default type signature")
3004
3005 -- Now do an ambiguity check on the default type signature.
3006 checkValidType ctxt (mkDefaultMethodType cls sel_id dm_spec)
3007 check_dm _ _ _ _ _ = return ()
3008
3009 checkFamFlag :: Name -> TcM ()
3010 -- Check that we don't use families without -XTypeFamilies
3011 -- The parser won't even parse them, but I suppose a GHC API
3012 -- client might have a go!
3013 checkFamFlag tc_name
3014 = do { idx_tys <- xoptM LangExt.TypeFamilies
3015 ; checkTc idx_tys err_msg }
3016 where
3017 err_msg = hang (text "Illegal family declaration for" <+> quotes (ppr tc_name))
3018 2 (text "Enable TypeFamilies to allow indexed type families")
3019
3020 {- Note [Class method constraints]
3021 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3022 Haskell 2010 is supposed to reject
3023 class C a where
3024 op :: Eq a => a -> a
3025 where the method type constrains only the class variable(s). (The extension
3026 -XConstrainedClassMethods switches off this check.) But regardless
3027 we should not reject
3028 class C a where
3029 op :: (?x::Int) => a -> a
3030 as pointed out in Trac #11793. So the test here rejects the program if
3031 * -XConstrainedClassMethods is off
3032 * the tyvars of the constraint are non-empty
3033 * all the tyvars are class tyvars, none are locally quantified
3034
3035 Note [Abort when superclass cycle is detected]
3036 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3037 We must avoid doing the ambiguity check for the methods (in
3038 checkValidClass.check_op) when there are already errors accumulated.
3039 This is because one of the errors may be a superclass cycle, and
3040 superclass cycles cause canonicalization to loop. Here is a
3041 representative example:
3042
3043 class D a => C a where
3044 meth :: D a => ()
3045 class C a => D a
3046
3047 This fixes Trac #9415, #9739
3048
3049 Note [Default method type signatures must align]
3050 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3051 GHC enforces the invariant that a class method's default type signature
3052 must "align" with that of the method's non-default type signature, as per
3053 GHC Trac #12918. For instance, if you have:
3054
3055 class Foo a where
3056 bar :: forall b. Context => a -> b
3057
3058 Then a default type signature for bar must be alpha equivalent to
3059 (forall b. a -> b). That is, the types must be the same modulo differences in
3060 contexts. So the following would be acceptable default type signatures:
3061
3062 default bar :: forall b. Context1 => a -> b
3063 default bar :: forall x. Context2 => a -> x
3064
3065 But the following are NOT acceptable default type signatures:
3066
3067 default bar :: forall b. b -> a
3068 default bar :: forall x. x
3069 default bar :: a -> Int
3070
3071 Note that a is bound by the class declaration for Foo itself, so it is
3072 not allowed to differ in the default type signature.
3073
3074 The default type signature (default bar :: a -> Int) deserves special mention,
3075 since (a -> Int) is a straightforward instantiation of (forall b. a -> b). To
3076 write this, you need to declare the default type signature like so:
3077
3078 default bar :: forall b. (b ~ Int). a -> b
3079
3080 As noted in #12918, there are several reasons to do this:
3081
3082 1. It would make no sense to have a type that was flat-out incompatible with
3083 the non-default type signature. For instance, if you had:
3084
3085 class Foo a where
3086 bar :: a -> Int
3087 default bar :: a -> Bool
3088
3089 Then that would always fail in an instance declaration. So this check
3090 nips such cases in the bud before they have the chance to produce
3091 confusing error messages.
3092
3093 2. Internally, GHC uses TypeApplications to instantiate the default method in
3094 an instance. See Note [Default methods in instances] in TcInstDcls.
3095 Thus, GHC needs to know exactly what the universally quantified type
3096 variables are, and when instantiated that way, the default method's type
3097 must match the expected type.
3098
3099 3. Aesthetically, by only allowing the default type signature to differ in its
3100 context, we are making it more explicit the ways in which the default type
3101 signature is less polymorphic than the non-default type signature.
3102
3103 You might be wondering: why are the contexts allowed to be different, but not
3104 the rest of the type signature? That's because default implementations often
3105 rely on assumptions that the more general, non-default type signatures do not.
3106 For instance, in the Enum class declaration:
3107
3108 class Enum a where
3109 enum :: [a]
3110 default enum :: (Generic a, GEnum (Rep a)) => [a]
3111 enum = map to genum
3112
3113 class GEnum f where
3114 genum :: [f a]
3115
3116 The default implementation for enum only works for types that are instances of
3117 Generic, and for which their generic Rep type is an instance of GEnum. But
3118 clearly enum doesn't _have_ to use this implementation, so naturally, the
3119 context for enum is allowed to be different to accomodate this. As a result,
3120 when we validity-check default type signatures, we ignore contexts completely.
3121
3122 Note that when checking whether two type signatures match, we must take care to
3123 split as many foralls as it takes to retrieve the tau types we which to check.
3124 See Note [Splitting nested sigma types in class type signatures].
3125
3126 Note [Splitting nested sigma types in class type signatures]
3127 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3128 Consider this type synonym and class definition:
3129
3130 type Traversal s t a b = forall f. Applicative f => (a -> f b) -> s -> f t
3131
3132 class Each s t a b where
3133 each :: Traversal s t a b
3134 default each :: (Traversable g, s ~ g a, t ~ g b) => Traversal s t a b
3135
3136 It might seem obvious that the tau types in both type signatures for `each`
3137 are the same, but actually getting GHC to conclude this is surprisingly tricky.
3138 That is because in general, the form of a class method's non-default type
3139 signature is:
3140
3141 forall a. C a => forall d. D d => E a b
3142
3143 And the general form of a default type signature is:
3144
3145 forall f. F f => E a f -- The variable `a` comes from the class
3146
3147 So it you want to get the tau types in each type signature, you might find it
3148 reasonable to call tcSplitSigmaTy twice on the non-default type signature, and
3149 call it once on the default type signature. For most classes and methods, this
3150 will work, but Each is a bit of an exceptional case. The way `each` is written,
3151 it doesn't quantify any additional type variables besides those of the Each
3152 class itself, so the non-default type signature for `each` is actually this:
3153
3154 forall s t a b. Each s t a b => Traversal s t a b
3155
3156 Notice that there _appears_ to only be one forall. But there's actually another
3157 forall lurking in the Traversal type synonym, so if you call tcSplitSigmaTy
3158 twice, you'll also go under the forall in Traversal! That is, you'll end up
3159 with:
3160
3161 (a -> f b) -> s -> f t
3162
3163 A problem arises because you only call tcSplitSigmaTy once on the default type
3164 signature for `each`, which gives you
3165
3166 Traversal s t a b
3167
3168 Or, equivalently:
3169
3170 forall f. Applicative f => (a -> f b) -> s -> f t
3171
3172 This is _not_ the same thing as (a -> f b) -> s -> f t! So now tcMatchTy will
3173 say that the tau types for `each` are not equal.
3174
3175 A solution to this problem is to use tcSplitNestedSigmaTys instead of
3176 tcSplitSigmaTy. tcSplitNestedSigmaTys will always split any foralls that it
3177 sees until it can't go any further, so if you called it on the default type
3178 signature for `each`, it would return (a -> f b) -> s -> f t like we desired.
3179
3180 Note [Checking partial record field]
3181 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3182 This check checks the partial record field selector, and warns (Trac #7169).
3183
3184 For example:
3185
3186 data T a = A { m1 :: a, m2 :: a } | B { m1 :: a }
3187
3188 The function 'm2' is partial record field, and will fail when it is applied to
3189 'B'. The warning identifies such partial fields. The check is performed at the
3190 declaration of T, not at the call-sites of m2.
3191
3192 The warning can be suppressed by prefixing the field-name with an underscore.
3193 For example:
3194
3195 data T a = A { m1 :: a, _m2 :: a } | B { m1 :: a }
3196
3197 Note [checkValidDependency]
3198 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
3199 Consider
3200
3201 data Proxy k (a :: k)
3202 data Proxy2 k a = P (Proxy k a)
3203
3204 (This is test dependent/should_fail/InferDependency.) While it seems GHC can
3205 figure out the dependency between the arguments to Proxy2, this case errors.
3206 The problem is that when we build the initial kind (getInitialKind) for
3207 a tycon, we need to decide whether an argument is dependent or not. At first,
3208 I thought we could just assume that *all* arguments are dependent, and then
3209 patch it up later. However, this causes problems in error messages (where
3210 tycon's have mysterious kinds "forall (a :: k) -> blah") and in unification
3211 (where we try to unify kappa ~ forall (a :: k) -> blah, failing because the
3212 RHS is not a tau-type). Perhaps a cleverer algorithm could sort this out
3213 (say, by storing the dependency flag in a mutable cell and by avoiding
3214 these fancy kinds in error messages depending on the extension in effect)
3215 but it doesn't seem worth it.
3216
3217 So: we choose the dependency for each argument variable once and for all
3218 in getInitialKind. This means that any dependency must be lexically manifest.
3219
3220 checkValidDependency checks to make sure that no lexically non-dependent
3221 argument actually appears in a kind. Note the example above, where the k
3222 in Proxy2 is a dependent argument, but this fact is not lexically
3223 manifest. checkValidDependency will reject. This function must be called
3224 *before* kind generalization, because kind generalization works with
3225 the result of mkTyConKind, which will think that Proxy2's kind is
3226 Type -> k -> Type, where k is unbound. (It won't use a forall for a
3227 "non-dependent" argument k.)
3228 -}
3229
3230 -- | See Note [checkValidDependency]
3231 checkValidDependency :: [TyConBinder] -- zonked
3232 -> TcKind -- zonked (result kind)
3233 -> TcM ()
3234 checkValidDependency binders res_kind
3235 = go (tyCoVarsOfType res_kind) (reverse binders)
3236 where
3237 go :: TyCoVarSet -- fvs from scope
3238 -> [TyConBinder] -- binders, in reverse order
3239 -> TcM ()
3240 go _ [] = return () -- all set
3241 go fvs (tcb : tcbs)
3242 | not (isNamedTyConBinder tcb) && tcb_var `elemVarSet` fvs
3243 = do { setSrcSpan (getSrcSpan tcb_var) $
3244 addErrTc (vcat [ text "Type constructor argument" <+> quotes (ppr tcb_var) <+>
3245 text "is used dependently."
3246 , text "Any dependent arguments must be obviously so, not inferred"
3247 , text "by the type-checker."
3248 , hang (text "Inferred argument kinds:")
3249 2 (vcat (map pp_binder binders))
3250 , text "Suggestion: use" <+> quotes (ppr tcb_var) <+>
3251 text "in a kind to make the dependency clearer." ])
3252 ; go new_fvs tcbs }
3253
3254 | otherwise
3255 = go new_fvs tcbs
3256 where
3257 new_fvs = fvs `delVarSet` tcb_var
3258 `unionVarSet` tyCoVarsOfType tcb_kind
3259
3260 tcb_var = binderVar tcb
3261 tcb_kind = tyVarKind tcb_var
3262
3263 pp_binder binder = ppr (binderVar binder) <+> dcolon <+> ppr (binderKind binder)
3264
3265 {-
3266 ************************************************************************
3267 * *
3268 Checking role validity
3269 * *
3270 ************************************************************************
3271 -}
3272
3273 checkValidRoleAnnots :: RoleAnnotEnv -> TyCon -> TcM ()
3274 checkValidRoleAnnots role_annots tc
3275 | isTypeSynonymTyCon tc = check_no_roles
3276 | isFamilyTyCon tc = check_no_roles
3277 | isAlgTyCon tc = check_roles
3278 | otherwise = return ()
3279 where
3280 -- Role annotations are given only on *explicit* variables,
3281 -- but a tycon stores roles for all variables.
3282 -- So, we drop the implicit roles (which are all Nominal, anyway).
3283 name = tyConName tc
3284 tyvars = tyConTyVars tc
3285 roles = tyConRoles tc
3286 (vis_roles, vis_vars) = unzip $ snd $
3287 partitionInvisibles tc (mkTyVarTy . snd) $
3288 zip roles tyvars
3289 role_annot_decl_maybe = lookupRoleAnnot role_annots name
3290
3291 check_roles
3292 = whenIsJust role_annot_decl_maybe $
3293 \decl@(L loc (RoleAnnotDecl _ _ the_role_annots)) ->
3294 addRoleAnnotCtxt name $
3295 setSrcSpan loc $ do
3296 { role_annots_ok <- xoptM LangExt.RoleAnnotations
3297 ; checkTc role_annots_ok $ needXRoleAnnotations tc
3298 ; checkTc (vis_vars `equalLength` the_role_annots)
3299 (wrongNumberOfRoles vis_vars decl)
3300 ; _ <- zipWith3M checkRoleAnnot vis_vars the_role_annots vis_roles
3301 -- Representational or phantom roles for class parameters
3302 -- quickly lead to incoherence. So, we require
3303 -- IncoherentInstances to have them. See #8773, #14292
3304 ; incoherent_roles_ok <- xoptM LangExt.IncoherentInstances
3305 ; checkTc ( incoherent_roles_ok
3306 || (not $ isClassTyCon tc)
3307 || (all (== Nominal) vis_roles))
3308 incoherentRoles
3309
3310 ; lint <- goptM Opt_DoCoreLinting
3311 ; when lint $ checkValidRoles tc }
3312
3313 check_no_roles
3314 = whenIsJust role_annot_decl_maybe illegalRoleAnnotDecl
3315
3316 checkRoleAnnot :: TyVar -> Located (Maybe Role) -> Role -> TcM ()
3317 checkRoleAnnot _ (L _ Nothing) _ = return ()
3318 checkRoleAnnot tv (L _ (Just r1)) r2
3319 = when (r1 /= r2) $
3320 addErrTc $ badRoleAnnot (tyVarName tv) r1 r2
3321
3322 -- This is a double-check on the role inference algorithm. It is only run when
3323 -- -dcore-lint is enabled. See Note [Role inference] in TcTyDecls
3324 checkValidRoles :: TyCon -> TcM ()
3325 -- If you edit this function, you may need to update the GHC formalism
3326 -- See Note [GHC Formalism] in CoreLint
3327 checkValidRoles tc
3328 | isAlgTyCon tc
3329 -- tyConDataCons returns an empty list for data families
3330 = mapM_ check_dc_roles (tyConDataCons tc)
3331 | Just rhs <- synTyConRhs_maybe tc
3332 = check_ty_roles (zipVarEnv (tyConTyVars tc) (tyConRoles tc)) Representational rhs
3333 | otherwise
3334 = return ()
3335 where
3336 check_dc_roles datacon
3337 = do { traceTc "check_dc_roles" (ppr datacon <+> ppr (tyConRoles tc))
3338 ; mapM_ (check_ty_roles role_env Representational) $
3339 eqSpecPreds eq_spec ++ theta ++ arg_tys }
3340 -- See Note [Role-checking data constructor arguments] in TcTyDecls
3341 where
3342 (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _res_ty)
3343 = dataConFullSig datacon
3344 univ_roles = zipVarEnv univ_tvs (tyConRoles tc)
3345 -- zipVarEnv uses zipEqual, but we don't want that for ex_tvs
3346 ex_roles = mkVarEnv (map (, Nominal) ex_tvs)
3347 role_env = univ_roles `plusVarEnv` ex_roles
3348
3349 check_ty_roles env role ty
3350 | Just ty' <- coreView ty -- #14101
3351 = check_ty_roles env role ty'
3352
3353 check_ty_roles env role (TyVarTy tv)
3354 = case lookupVarEnv env tv of
3355 Just role' -> unless (role' `ltRole` role || role' == role) $
3356 report_error $ text "type variable" <+> quotes (ppr tv) <+>
3357 text "cannot have role" <+> ppr role <+>
3358 text "because it was assigned role" <+> ppr role'
3359 Nothing -> report_error $ text "type variable" <+> quotes (ppr tv) <+>
3360 text "missing in environment"
3361
3362 check_ty_roles env Representational (TyConApp tc tys)
3363 = let roles' = tyConRoles tc in
3364 zipWithM_ (maybe_check_ty_roles env) roles' tys
3365
3366 check_ty_roles env Nominal (TyConApp _ tys)
3367 = mapM_ (check_ty_roles env Nominal) tys
3368
3369 check_ty_roles _ Phantom ty@(TyConApp {})
3370 = pprPanic "check_ty_roles" (ppr ty)
3371
3372 check_ty_roles env role (AppTy ty1 ty2)
3373 = check_ty_roles env role ty1
3374 >> check_ty_roles env Nominal ty2
3375
3376 check_ty_roles env role (FunTy ty1 ty2)
3377 = check_ty_roles env role ty1
3378 >> check_ty_roles env role ty2
3379
3380 check_ty_roles env role (ForAllTy (TvBndr tv _) ty)
3381 = check_ty_roles env Nominal (tyVarKind tv)
3382 >> check_ty_roles (extendVarEnv env tv Nominal) role ty
3383
3384 check_ty_roles _ _ (LitTy {}) = return ()
3385
3386 check_ty_roles env role (CastTy t _)
3387 = check_ty_roles env role t
3388
3389 check_ty_roles _ role (CoercionTy co)
3390 = unless (role == Phantom) $
3391 report_error $ text "coercion" <+> ppr co <+> text "has bad role" <+> ppr role
3392
3393 maybe_check_ty_roles env role ty
3394 = when (role == Nominal || role == Representational) $
3395 check_ty_roles env role ty
3396
3397 report_error doc
3398 = addErrTc $ vcat [text "Internal error in role inference:",
3399 doc,
3400 text "Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug"]
3401
3402 {-
3403 ************************************************************************
3404 * *
3405 Error messages
3406 * *
3407 ************************************************************************
3408 -}
3409
3410 tcAddTyFamInstCtxt :: TyFamInstDecl GhcRn -> TcM a -> TcM a
3411 tcAddTyFamInstCtxt decl
3412 = tcAddFamInstCtxt (text "type instance") (tyFamInstDeclName decl)
3413
3414 tcMkDataFamInstCtxt :: DataFamInstDecl GhcRn -> SDoc
3415 tcMkDataFamInstCtxt decl@(DataFamInstDecl { dfid_eqn =
3416 HsIB { hsib_body = eqn }})
3417 = tcMkFamInstCtxt (pprDataFamInstFlavour decl <+> text "instance")
3418 (unLoc (feqn_tycon eqn))
3419 tcMkDataFamInstCtxt (DataFamInstDecl (XHsImplicitBndrs _))
3420 = panic "tcMkDataFamInstCtxt"
3421
3422 tcAddDataFamInstCtxt :: DataFamInstDecl GhcRn -> TcM a -> TcM a
3423 tcAddDataFamInstCtxt decl
3424 = addErrCtxt (tcMkDataFamInstCtxt decl)
3425
3426 tcMkFamInstCtxt :: SDoc -> Name -> SDoc
3427 tcMkFamInstCtxt flavour tycon
3428 = hsep [ text "In the" <+> flavour <+> text "declaration for"
3429 , quotes (ppr tycon) ]
3430
3431 tcAddFamInstCtxt :: SDoc -> Name -> TcM a -> TcM a
3432 tcAddFamInstCtxt flavour tycon thing_inside
3433 = addErrCtxt (tcMkFamInstCtxt flavour tycon) thing_inside
3434
3435 tcAddClosedTypeFamilyDeclCtxt :: TyCon -> TcM a -> TcM a
3436 tcAddClosedTypeFamilyDeclCtxt tc
3437 = addErrCtxt ctxt
3438 where
3439 ctxt = text "In the equations for closed type family" <+>
3440 quotes (ppr tc)
3441
3442 resultTypeMisMatch :: FieldLabelString -> DataCon -> DataCon -> SDoc
3443 resultTypeMisMatch field_name con1 con2
3444 = vcat [sep [text "Constructors" <+> ppr con1 <+> text "and" <+> ppr con2,
3445 text "have a common field" <+> quotes (ppr field_name) <> comma],
3446 nest 2 $ text "but have different result types"]
3447
3448 fieldTypeMisMatch :: FieldLabelString -> DataCon -> DataCon -> SDoc
3449 fieldTypeMisMatch field_name con1 con2
3450 = sep [text "Constructors" <+> ppr con1 <+> text "and" <+> ppr con2,
3451 text "give different types for field", quotes (ppr field_name)]
3452
3453 dataConCtxtName :: [Located Name] -> SDoc
3454 dataConCtxtName [con]
3455 = text "In the definition of data constructor" <+> quotes (ppr con)
3456 dataConCtxtName con
3457 = text "In the definition of data constructors" <+> interpp'SP con
3458
3459 dataConCtxt :: Outputable a => a -> SDoc
3460 dataConCtxt con = text "In the definition of data constructor" <+> quotes (ppr con)
3461
3462 classOpCtxt :: Var -> Type -> SDoc
3463 classOpCtxt sel_id tau = sep [text "When checking the class method:",
3464 nest 2 (pprPrefixOcc sel_id <+> dcolon <+> ppr tau)]
3465
3466 classArityErr :: Int -> Class -> SDoc
3467 classArityErr n cls
3468 | n == 0 = mkErr "No" "no-parameter"
3469 | otherwise = mkErr "Too many" "multi-parameter"
3470 where
3471 mkErr howMany allowWhat =
3472 vcat [text (howMany ++ " parameters for class") <+> quotes (ppr cls),
3473 parens (text ("Enable MultiParamTypeClasses to allow "
3474 ++ allowWhat ++ " classes"))]
3475
3476 classFunDepsErr :: Class -> SDoc
3477 classFunDepsErr cls
3478 = vcat [text "Fundeps in class" <+> quotes (ppr cls),
3479 parens (text "Enable FunctionalDependencies to allow fundeps")]
3480
3481 badMethPred :: Id -> TcPredType -> SDoc
3482 badMethPred sel_id pred
3483 = vcat [ hang (text "Constraint" <+> quotes (ppr pred)
3484 <+> text "in the type of" <+> quotes (ppr sel_id))
3485 2 (text "constrains only the class type variables")
3486 , text "Enable ConstrainedClassMethods to allow it" ]
3487
3488 noClassTyVarErr :: Class -> TyCon -> SDoc
3489 noClassTyVarErr clas fam_tc
3490 = sep [ text "The associated type" <+> quotes (ppr fam_tc)
3491 , text "mentions none of the type or kind variables of the class" <+>
3492 quotes (ppr clas <+> hsep (map ppr (classTyVars clas)))]
3493
3494 badDataConTyCon :: DataCon -> Type -> Type -> SDoc
3495 badDataConTyCon data_con res_ty_tmpl actual_res_ty
3496 | tcIsForAllTy actual_res_ty
3497 = nested_foralls_contexts_suggestion
3498 | isJust (tcSplitPredFunTy_maybe actual_res_ty)
3499 = nested_foralls_contexts_suggestion
3500 | otherwise
3501 = hang (text "Data constructor" <+> quotes (ppr data_con) <+>
3502 text "returns type" <+> quotes (ppr actual_res_ty))
3503 2 (text "instead of an instance of its parent type" <+> quotes (ppr res_ty_tmpl))
3504 where
3505 -- This suggestion is useful for suggesting how to correct code like what
3506 -- was reported in Trac #12087:
3507 --
3508 -- data F a where
3509 -- MkF :: Ord a => Eq a => a -> F a
3510 --
3511 -- Although nested foralls or contexts are allowed in function type
3512 -- signatures, it is much more difficult to engineer GADT constructor type
3513 -- signatures to allow something similar, so we error in the latter case.
3514 -- Nevertheless, we can at least suggest how a user might reshuffle their
3515 -- exotic GADT constructor type signature so that GHC will accept.
3516 nested_foralls_contexts_suggestion =
3517 text "GADT constructor type signature cannot contain nested"
3518 <+> quotes forAllLit <> text "s or contexts"
3519 $+$ hang (text "Suggestion: instead use this type signature:")
3520 2 (ppr (dataConName data_con) <+> dcolon <+> ppr suggested_ty)
3521
3522 -- To construct a type that GHC would accept (suggested_ty), we:
3523 --
3524 -- 1) Find the existentially quantified type variables and the class
3525 -- predicates from the datacon. (NB: We don't need the universally
3526 -- quantified type variables, since rejigConRes won't substitute them in
3527 -- the result type if it fails, as in this scenario.)
3528 -- 2) Split apart the return type (which is headed by a forall or a
3529 -- context) using tcSplitNestedSigmaTys, collecting the type variables
3530 -- and class predicates we find, as well as the rho type lurking
3531 -- underneath the nested foralls and contexts.
3532 -- 3) Smash together the type variables and class predicates from 1) and
3533 -- 2), and prepend them to the rho type from 2).
3534 actual_ex_tvs = dataConExTyVars data_con
3535 actual_theta = dataConTheta data_con
3536 (actual_res_tvs, actual_res_theta, actual_res_rho)
3537 = tcSplitNestedSigmaTys actual_res_ty
3538 suggested_ty = mkSpecForAllTys (actual_ex_tvs ++ actual_res_tvs) $
3539 mkFunTys (actual_theta ++ actual_res_theta)
3540 actual_res_rho
3541
3542 badGadtDecl :: Name -> SDoc
3543 badGadtDecl tc_name
3544 = vcat [ text "Illegal generalised algebraic data declaration for" <+> quotes (ppr tc_name)
3545 , nest 2 (parens $ text "Enable the GADTs extension to allow this") ]
3546
3547 badExistential :: DataCon -> SDoc
3548 badExistential con
3549 = hang (text "Data constructor" <+> quotes (ppr con) <+>
3550 text "has existential type variables, a context, or a specialised result type")
3551 2 (vcat [ ppr con <+> dcolon <+> ppr (dataConUserType con)
3552 , parens $ text "Enable ExistentialQuantification or GADTs to allow this" ])
3553
3554 badStupidTheta :: Name -> SDoc
3555 badStupidTheta tc_name
3556 = text "A data type declared in GADT style cannot have a context:" <+> quotes (ppr tc_name)
3557
3558 newtypeConError :: Name -> Int -> SDoc
3559 newtypeConError tycon n
3560 = sep [text "A newtype must have exactly one constructor,",
3561 nest 2 $ text "but" <+> quotes (ppr tycon) <+> text "has" <+> speakN n ]
3562
3563 newtypeStrictError :: DataCon -> SDoc
3564 newtypeStrictError con
3565 = sep [text "A newtype constructor cannot have a strictness annotation,",
3566 nest 2 $ text "but" <+> quotes (ppr con) <+> text "does"]
3567
3568 newtypeFieldErr :: DataCon -> Int -> SDoc
3569 newtypeFieldErr con_name n_flds
3570 = sep [text "The constructor of a newtype must have exactly one field",
3571 nest 2 $ text "but" <+> quotes (ppr con_name) <+> text "has" <+> speakN n_flds]
3572
3573 badSigTyDecl :: Name -> SDoc
3574 badSigTyDecl tc_name
3575 = vcat [ text "Illegal kind signature" <+>
3576 quotes (ppr tc_name)
3577 , nest 2 (parens $ text "Use KindSignatures to allow kind signatures") ]
3578
3579 emptyConDeclsErr :: Name -> SDoc
3580 emptyConDeclsErr tycon
3581 = sep [quotes (ppr tycon) <+> text "has no constructors",
3582 nest 2 $ text "(EmptyDataDecls permits this)"]
3583
3584 wrongKindOfFamily :: TyCon -> SDoc
3585 wrongKindOfFamily family
3586 = text "Wrong category of family instance; declaration was for a"
3587 <+> kindOfFamily
3588 where
3589 kindOfFamily | isTypeFamilyTyCon family = text "type family"
3590 | isDataFamilyTyCon family = text "data family"
3591 | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
3592
3593 wrongNumberOfParmsErr :: Arity -> SDoc
3594 wrongNumberOfParmsErr max_args
3595 = text "Number of parameters must match family declaration; expected"
3596 <+> ppr max_args
3597
3598 defaultAssocKindErr :: TyCon -> SDoc
3599 defaultAssocKindErr fam_tc
3600 = text "Kind mis-match on LHS of default declaration for"
3601 <+> quotes (ppr fam_tc)
3602
3603 wrongTyFamName :: Name -> Name -> SDoc
3604 wrongTyFamName fam_tc_name eqn_tc_name
3605 = hang (text "Mismatched type name in type family instance.")
3606 2 (vcat [ text "Expected:" <+> ppr fam_tc_name
3607 , text " Actual:" <+> ppr eqn_tc_name ])
3608
3609 badRoleAnnot :: Name -> Role -> Role -> SDoc
3610 badRoleAnnot var annot inferred
3611 = hang (text "Role mismatch on variable" <+> ppr var <> colon)
3612 2 (sep [ text "Annotation says", ppr annot
3613 , text "but role", ppr inferred
3614 , text "is required" ])
3615
3616 wrongNumberOfRoles :: [a] -> LRoleAnnotDecl GhcRn -> SDoc
3617 wrongNumberOfRoles tyvars d@(L _ (RoleAnnotDecl _ _ annots))
3618 = hang (text "Wrong number of roles listed in role annotation;" $$
3619 text "Expected" <+> (ppr $ length tyvars) <> comma <+>
3620 text "got" <+> (ppr $ length annots) <> colon)
3621 2 (ppr d)
3622 wrongNumberOfRoles _ (L _ (XRoleAnnotDecl _)) = panic "wrongNumberOfRoles"
3623
3624 illegalRoleAnnotDecl :: LRoleAnnotDecl GhcRn -> TcM ()
3625 illegalRoleAnnotDecl (L loc (RoleAnnotDecl _ tycon _))
3626 = setErrCtxt [] $
3627 setSrcSpan loc $
3628 addErrTc (text "Illegal role annotation for" <+> ppr tycon <> char ';' $$
3629 text "they are allowed only for datatypes and classes.")
3630 illegalRoleAnnotDecl (L _ (XRoleAnnotDecl _)) = panic "illegalRoleAnnotDecl"
3631
3632 needXRoleAnnotations :: TyCon -> SDoc
3633 needXRoleAnnotations tc
3634 = text "Illegal role annotation for" <+> ppr tc <> char ';' $$
3635 text "did you intend to use RoleAnnotations?"
3636
3637 incoherentRoles :: SDoc
3638 incoherentRoles = (text "Roles other than" <+> quotes (text "nominal") <+>
3639 text "for class parameters can lead to incoherence.") $$
3640 (text "Use IncoherentInstances to allow this; bad role found")
3641
3642 addTyConCtxt :: TyCon -> TcM a -> TcM a
3643 addTyConCtxt tc
3644 = addErrCtxt ctxt
3645 where
3646 name = getName tc
3647 flav = ppr (tyConFlavour tc)
3648 ctxt = hsep [ text "In the", flav
3649 , text "declaration for", quotes (ppr name) ]
3650
3651 addRoleAnnotCtxt :: Name -> TcM a -> TcM a
3652 addRoleAnnotCtxt name
3653 = addErrCtxt $
3654 text "while checking a role annotation for" <+> quotes (ppr name)