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