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