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