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