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