Add an extra print to -ddump-tc-trace
[ghc-hetmet.git] / compiler / typecheck / TcTyClsDecls.lhs
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 \begin{code}
9 module TcTyClsDecls (
10         tcTyAndClassDecls, tcFamInstDecl, mkAuxBinds
11     ) where
12
13 #include "HsVersions.h"
14
15 import HsSyn
16 import HsTypes
17 import HscTypes
18 import BuildTyCl
19 import TcUnify
20 import TcRnMonad
21 import TcEnv
22 import TcTyDecls
23 import TcClassDcl
24 import TcHsType
25 import TcMType
26 import TcType
27 import TysWiredIn       ( unitTy )
28 import Type
29 import Generics
30 import Class
31 import TyCon
32 import DataCon
33 import Id
34 import MkId             ( rEC_SEL_ERROR_ID )
35 import IdInfo
36 import Var
37 import VarSet
38 import Name
39 import OccName
40 import Outputable
41 import Maybes
42 import Monad
43 import Unify
44 import Util
45 import SrcLoc
46 import ListSetOps
47 import Digraph
48 import DynFlags
49 import FastString
50 import Unique           ( mkBuiltinUnique )
51 import BasicTypes
52
53 import Bag
54 import Data.List
55 import Control.Monad    ( mplus )
56 \end{code}
57
58
59 %************************************************************************
60 %*                                                                      *
61 \subsection{Type checking for type and class declarations}
62 %*                                                                      *
63 %************************************************************************
64
65 Dealing with a group
66 ~~~~~~~~~~~~~~~~~~~~
67 Consider a mutually-recursive group, binding 
68 a type constructor T and a class C.
69
70 Step 1:         getInitialKind
71         Construct a KindEnv by binding T and C to a kind variable 
72
73 Step 2:         kcTyClDecl
74         In that environment, do a kind check
75
76 Step 3: Zonk the kinds
77
78 Step 4:         buildTyConOrClass
79         Construct an environment binding T to a TyCon and C to a Class.
80         a) Their kinds comes from zonking the relevant kind variable
81         b) Their arity (for synonyms) comes direct from the decl
82         c) The funcional dependencies come from the decl
83         d) The rest comes a knot-tied binding of T and C, returned from Step 4
84         e) The variances of the tycons in the group is calculated from 
85                 the knot-tied stuff
86
87 Step 5:         tcTyClDecl1
88         In this environment, walk over the decls, constructing the TyCons and Classes.
89         This uses in a strict way items (a)-(c) above, which is why they must
90         be constructed in Step 4. Feed the results back to Step 4.
91         For this step, pass the is-recursive flag as the wimp-out flag
92         to tcTyClDecl1.
93         
94
95 Step 6:         Extend environment
96         We extend the type environment with bindings not only for the TyCons and Classes,
97         but also for their "implicit Ids" like data constructors and class selectors
98
99 Step 7:         checkValidTyCl
100         For a recursive group only, check all the decls again, just
101         to check all the side conditions on validity.  We could not
102         do this before because we were in a mutually recursive knot.
103
104 Identification of recursive TyCons
105 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
106 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
107 @TyThing@s.
108
109 Identifying a TyCon as recursive serves two purposes
110
111 1.  Avoid infinite types.  Non-recursive newtypes are treated as
112 "transparent", like type synonyms, after the type checker.  If we did
113 this for all newtypes, we'd get infinite types.  So we figure out for
114 each newtype whether it is "recursive", and add a coercion if so.  In
115 effect, we are trying to "cut the loops" by identifying a loop-breaker.
116
117 2.  Avoid infinite unboxing.  This is nothing to do with newtypes.
118 Suppose we have
119         data T = MkT Int T
120         f (MkT x t) = f t
121 Well, this function diverges, but we don't want the strictness analyser
122 to diverge.  But the strictness analyser will diverge because it looks
123 deeper and deeper into the structure of T.   (I believe there are
124 examples where the function does something sane, and the strictness
125 analyser still diverges, but I can't see one now.)
126
127 Now, concerning (1), the FC2 branch currently adds a coercion for ALL
128 newtypes.  I did this as an experiment, to try to expose cases in which
129 the coercions got in the way of optimisations.  If it turns out that we
130 can indeed always use a coercion, then we don't risk recursive types,
131 and don't need to figure out what the loop breakers are.
132
133 For newtype *families* though, we will always have a coercion, so they
134 are always loop breakers!  So you can easily adjust the current
135 algorithm by simply treating all newtype families as loop breakers (and
136 indeed type families).  I think.
137
138 \begin{code}
139 tcTyAndClassDecls :: ModDetails -> [LTyClDecl Name]
140                    -> TcM (TcGblEnv,         -- Input env extended by types and classes 
141                                              -- and their implicit Ids,DataCons
142                            HsValBinds Name)  -- Renamed bindings for record selectors
143 -- Fails if there are any errors
144
145 tcTyAndClassDecls boot_details allDecls
146   = checkNoErrs $       -- The code recovers internally, but if anything gave rise to
147                         -- an error we'd better stop now, to avoid a cascade
148     do  {       -- Omit instances of type families; they are handled together
149                 -- with the *heads* of class instances
150         ; let decls = filter (not . isFamInstDecl . unLoc) allDecls
151
152                 -- First check for cyclic type synonysm or classes
153                 -- See notes with checkCycleErrs
154         ; checkCycleErrs decls
155         ; mod <- getModule
156         ; traceTc (text "tcTyAndCl" <+> ppr mod)
157         ; (syn_tycons, alg_tyclss) <- fixM (\ ~(_rec_syn_tycons, rec_alg_tyclss) ->
158           do    { let { -- Seperate ordinary synonyms from all other type and
159                         -- class declarations and add all associated type
160                         -- declarations from type classes.  The latter is
161                         -- required so that the temporary environment for the
162                         -- knot includes all associated family declarations.
163                       ; (syn_decls, alg_decls) = partition (isSynDecl . unLoc)
164                                                    decls
165                       ; alg_at_decls           = concatMap addATs alg_decls
166                       }
167                         -- Extend the global env with the knot-tied results
168                         -- for data types and classes
169                         -- 
170                         -- We must populate the environment with the loop-tied
171                         -- T's right away, because the kind checker may "fault
172                         -- in" some type  constructors that recursively
173                         -- mention T
174                 ; let gbl_things = mkGlobalThings alg_at_decls rec_alg_tyclss
175                 ; tcExtendRecEnv gbl_things $ do
176
177                         -- Kind-check the declarations
178                 { (kc_syn_decls, kc_alg_decls) <- kcTyClDecls syn_decls alg_decls
179
180                 ; let { -- Calculate rec-flag
181                       ; calc_rec  = calcRecFlags boot_details rec_alg_tyclss
182                       ; tc_decl   = addLocM (tcTyClDecl calc_rec) }
183
184                         -- Type-check the type synonyms, and extend the envt
185                 ; syn_tycons <- tcSynDecls kc_syn_decls
186                 ; tcExtendGlobalEnv syn_tycons $ do
187
188                         -- Type-check the data types and classes
189                 { alg_tyclss <- mapM tc_decl kc_alg_decls
190                 ; return (syn_tycons, concat alg_tyclss)
191             }}})
192         -- Finished with knot-tying now
193         -- Extend the environment with the finished things
194         ; tcExtendGlobalEnv (syn_tycons ++ alg_tyclss) $ do
195
196         -- Perform the validity check
197         { traceTc (text "ready for validity check")
198         ; mapM_ (addLocM checkValidTyCl) decls
199         ; traceTc (text "done")
200    
201         -- Add the implicit things;
202         -- we want them in the environment because 
203         -- they may be mentioned in interface files
204         -- NB: All associated types and their implicit things will be added a
205         --     second time here.  This doesn't matter as the definitions are
206         --     the same.
207         ; let { implicit_things = concatMap implicitTyThings alg_tyclss
208               ; aux_binds       = mkAuxBinds alg_tyclss }
209         ; traceTc ((text "Adding" <+> ppr alg_tyclss) 
210                    $$ (text "and" <+> ppr implicit_things))
211         ; env <- tcExtendGlobalEnv implicit_things getGblEnv
212         ; return (env, aux_binds) }
213     }
214   where
215     -- Pull associated types out of class declarations, to tie them into the
216     -- knot above.  
217     -- NB: We put them in the same place in the list as `tcTyClDecl' will
218     --     eventually put the matching `TyThing's.  That's crucial; otherwise,
219     --     the two argument lists of `mkGlobalThings' don't match up.
220     addATs decl@(L _ (ClassDecl {tcdATs = ats})) = decl : ats
221     addATs decl                                  = [decl]
222
223 mkGlobalThings :: [LTyClDecl Name]      -- The decls
224                -> [TyThing]             -- Knot-tied, in 1-1 correspondence with the decls
225                -> [(Name,TyThing)]
226 -- Driven by the Decls, and treating the TyThings lazily
227 -- make a TypeEnv for the new things
228 mkGlobalThings decls things
229   = map mk_thing (decls `zipLazy` things)
230   where
231     mk_thing (L _ (ClassDecl {tcdLName = L _ name}), ~(AClass cl))
232          = (name, AClass cl)
233     mk_thing (L _ decl, ~(ATyCon tc))
234          = (tcdName decl, ATyCon tc)
235 \end{code}
236
237
238 %************************************************************************
239 %*                                                                      *
240                Type checking family instances
241 %*                                                                      *
242 %************************************************************************
243
244 Family instances are somewhat of a hybrid.  They are processed together with
245 class instance heads, but can contain data constructors and hence they share a
246 lot of kinding and type checking code with ordinary algebraic data types (and
247 GADTs).
248
249 \begin{code}
250 tcFamInstDecl :: LTyClDecl Name -> TcM TyThing
251 tcFamInstDecl (L loc decl)
252   =     -- Prime error recovery, set source location
253     setSrcSpan loc                              $
254     tcAddDeclCtxt decl                          $
255     do { -- type families require -XTypeFamilies and can't be in an
256          -- hs-boot file
257        ; type_families <- doptM Opt_TypeFamilies
258        ; is_boot  <- tcIsHsBoot   -- Are we compiling an hs-boot file?
259        ; checkTc type_families $ badFamInstDecl (tcdLName decl)
260        ; checkTc (not is_boot) $ badBootFamInstDeclErr
261
262          -- Perform kind and type checking
263        ; tc <- tcFamInstDecl1 decl
264        ; checkValidTyCon tc     -- Remember to check validity;
265                                 -- no recursion to worry about here
266        ; return (ATyCon tc) }
267
268 tcFamInstDecl1 :: TyClDecl Name -> TcM TyCon
269
270   -- "type instance"
271 tcFamInstDecl1 (decl@TySynonym {tcdLName = L loc tc_name})
272   = kcIdxTyPats decl $ \k_tvs k_typats resKind family ->
273     do { -- check that the family declaration is for a synonym
274          checkTc (isOpenTyCon family) (notFamily family)
275        ; checkTc (isSynTyCon family) (wrongKindOfFamily family)
276
277        ; -- (1) kind check the right-hand side of the type equation
278        ; k_rhs <- kcCheckLHsType (tcdSynRhs decl) resKind
279
280          -- we need the exact same number of type parameters as the family
281          -- declaration 
282        ; let famArity = tyConArity family
283        ; checkTc (length k_typats == famArity) $ 
284            wrongNumberOfParmsErr famArity
285
286          -- (2) type check type equation
287        ; tcTyVarBndrs k_tvs $ \t_tvs -> do {  -- turn kinded into proper tyvars
288        ; t_typats <- mapM tcHsKindedType k_typats
289        ; t_rhs    <- tcHsKindedType k_rhs
290
291          -- (3) check the well-formedness of the instance
292        ; checkValidTypeInst t_typats t_rhs
293
294          -- (4) construct representation tycon
295        ; rep_tc_name <- newFamInstTyConName tc_name loc
296        ; buildSynTyCon rep_tc_name t_tvs (SynonymTyCon t_rhs) 
297                        (typeKind t_rhs) (Just (family, t_typats))
298        }}
299
300   -- "newtype instance" and "data instance"
301 tcFamInstDecl1 (decl@TyData {tcdND = new_or_data, tcdLName = L loc tc_name,
302                              tcdCons = cons})
303   = kcIdxTyPats decl $ \k_tvs k_typats resKind fam_tycon ->
304     do { -- check that the family declaration is for the right kind
305          checkTc (isOpenTyCon fam_tycon) (notFamily fam_tycon)
306        ; checkTc (isAlgTyCon fam_tycon) (wrongKindOfFamily fam_tycon)
307
308        ; -- (1) kind check the data declaration as usual
309        ; k_decl <- kcDataDecl decl k_tvs
310        ; let k_ctxt = tcdCtxt k_decl
311              k_cons = tcdCons k_decl
312
313          -- result kind must be '*' (otherwise, we have too few patterns)
314        ; checkTc (isLiftedTypeKind resKind) $ tooFewParmsErr (tyConArity fam_tycon)
315
316          -- (2) type check indexed data type declaration
317        ; tcTyVarBndrs k_tvs $ \t_tvs -> do {  -- turn kinded into proper tyvars
318        ; unbox_strict <- doptM Opt_UnboxStrictFields
319
320          -- kind check the type indexes and the context
321        ; t_typats     <- mapM tcHsKindedType k_typats
322        ; stupid_theta <- tcHsKindedContext k_ctxt
323
324          -- (3) Check that
325          --     (a) left-hand side contains no type family applications
326          --         (vanilla synonyms are fine, though, and we checked for
327          --         foralls earlier)
328        ; mapM_ checkTyFamFreeness t_typats
329
330          -- Check that we don't use GADT syntax in H98 world
331        ; gadt_ok <- doptM Opt_GADTs
332        ; checkTc (gadt_ok || consUseH98Syntax cons) (badGadtDecl tc_name)
333
334          --     (b) a newtype has exactly one constructor
335        ; checkTc (new_or_data == DataType || isSingleton k_cons) $
336                  newtypeConError tc_name (length k_cons)
337
338          -- (4) construct representation tycon
339        ; rep_tc_name <- newFamInstTyConName tc_name loc
340        ; let ex_ok = True       -- Existentials ok for type families!
341        ; fixM (\ rep_tycon -> do 
342              { let orig_res_ty = mkTyConApp fam_tycon t_typats
343              ; data_cons <- tcConDecls unbox_strict ex_ok rep_tycon
344                                        (t_tvs, orig_res_ty) k_cons
345              ; tc_rhs <-
346                  case new_or_data of
347                    DataType -> return (mkDataTyConRhs data_cons)
348                    NewType  -> ASSERT( not (null data_cons) )
349                                mkNewTyConRhs rep_tc_name rep_tycon (head data_cons)
350              ; buildAlgTyCon rep_tc_name t_tvs stupid_theta tc_rhs Recursive
351                              False h98_syntax (Just (fam_tycon, t_typats))
352                  -- We always assume that indexed types are recursive.  Why?
353                  -- (1) Due to their open nature, we can never be sure that a
354                  -- further instance might not introduce a new recursive
355                  -- dependency.  (2) They are always valid loop breakers as
356                  -- they involve a coercion.
357              })
358        }}
359        where
360          h98_syntax = case cons of      -- All constructors have same shape
361                         L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
362                         _ -> True
363
364 tcFamInstDecl1 d = pprPanic "tcFamInstDecl1" (ppr d)
365
366 -- Kind checking of indexed types
367 -- -
368
369 -- Kind check type patterns and kind annotate the embedded type variables.
370 --
371 -- * Here we check that a type instance matches its kind signature, but we do
372 --   not check whether there is a pattern for each type index; the latter
373 --   check is only required for type synonym instances.
374
375 kcIdxTyPats :: TyClDecl Name
376             -> ([LHsTyVarBndr Name] -> [LHsType Name] -> Kind -> TyCon -> TcM a)
377                -- ^^kinded tvs         ^^kinded ty pats  ^^res kind
378             -> TcM a
379 kcIdxTyPats decl thing_inside
380   = kcHsTyVars (tcdTyVars decl) $ \tvs -> 
381     do { fam_tycon <- tcLookupLocatedTyCon (tcdLName decl)
382        ; let { (kinds, resKind) = splitKindFunTys (tyConKind fam_tycon)
383              ; hs_typats        = fromJust $ tcdTyPats decl }
384
385          -- we may not have more parameters than the kind indicates
386        ; checkTc (length kinds >= length hs_typats) $
387            tooManyParmsErr (tcdLName decl)
388
389          -- type functions can have a higher-kinded result
390        ; let resultKind = mkArrowKinds (drop (length hs_typats) kinds) resKind
391        ; typats <- zipWithM kcCheckLHsType hs_typats kinds
392        ; thing_inside tvs typats resultKind fam_tycon
393        }
394   where
395 \end{code}
396
397
398 %************************************************************************
399 %*                                                                      *
400                 Kind checking
401 %*                                                                      *
402 %************************************************************************
403
404 We need to kind check all types in the mutually recursive group
405 before we know the kind of the type variables.  For example:
406
407 class C a where
408    op :: D b => a -> b -> b
409
410 class D c where
411    bop :: (Monad c) => ...
412
413 Here, the kind of the locally-polymorphic type variable "b"
414 depends on *all the uses of class D*.  For example, the use of
415 Monad c in bop's type signature means that D must have kind Type->Type.
416
417 However type synonyms work differently.  They can have kinds which don't
418 just involve (->) and *:
419         type R = Int#           -- Kind #
420         type S a = Array# a     -- Kind * -> #
421         type T a b = (# a,b #)  -- Kind * -> * -> (# a,b #)
422 So we must infer their kinds from their right-hand sides *first* and then
423 use them, whereas for the mutually recursive data types D we bring into
424 scope kind bindings D -> k, where k is a kind variable, and do inference.
425
426 Type families
427 ~~~~~~~~~~~~~
428 This treatment of type synonyms only applies to Haskell 98-style synonyms.
429 General type functions can be recursive, and hence, appear in `alg_decls'.
430
431 The kind of a type family is solely determinded by its kind signature;
432 hence, only kind signatures participate in the construction of the initial
433 kind environment (as constructed by `getInitialKind').  In fact, we ignore
434 instances of families altogether in the following.  However, we need to
435 include the kinds of associated families into the construction of the
436 initial kind environment.  (This is handled by `allDecls').
437
438 \begin{code}
439 kcTyClDecls :: [LTyClDecl Name] -> [Located (TyClDecl Name)]
440             -> TcM ([LTyClDecl Name], [Located (TyClDecl Name)])
441 kcTyClDecls syn_decls alg_decls
442   = do  {       -- First extend the kind env with each data type, class, and
443                 -- indexed type, mapping them to a type variable
444           let initialKindDecls = concat [allDecls decl | L _ decl <- alg_decls]
445         ; alg_kinds <- mapM getInitialKind initialKindDecls
446         ; tcExtendKindEnv alg_kinds $ do
447
448                 -- Now kind-check the type synonyms, in dependency order
449                 -- We do these differently to data type and classes,
450                 -- because a type synonym can be an unboxed type
451                 --      type Foo = Int#
452                 -- and a kind variable can't unify with UnboxedTypeKind
453                 -- So we infer their kinds in dependency order
454         { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
455         ; tcExtendKindEnv syn_kinds $  do
456
457                 -- Now kind-check the data type, class, and kind signatures,
458                 -- returning kind-annotated decls; we don't kind-check
459                 -- instances of indexed types yet, but leave this to
460                 -- `tcInstDecls1'
461         { kc_alg_decls <- mapM (wrapLocM kcTyClDecl)
462                             (filter (not . isFamInstDecl . unLoc) alg_decls)
463
464         ; return (kc_syn_decls, kc_alg_decls) }}}
465   where
466     -- get all declarations relevant for determining the initial kind
467     -- environment
468     allDecls (decl@ClassDecl {tcdATs = ats}) = decl : [ at 
469                                                       | L _ at <- ats
470                                                       , isFamilyDecl at]
471     allDecls decl | isFamInstDecl decl = []
472                   | otherwise          = [decl]
473
474 ------------------------------------------------------------------------
475 getInitialKind :: TyClDecl Name -> TcM (Name, TcKind)
476 -- Only for data type, class, and indexed type declarations
477 -- Get as much info as possible from the data, class, or indexed type decl,
478 -- so as to maximise usefulness of error messages
479 getInitialKind decl
480   = do  { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
481         ; res_kind  <- mk_res_kind decl
482         ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
483   where
484     mk_arg_kind (UserTyVar _)        = newKindVar
485     mk_arg_kind (KindedTyVar _ kind) = return kind
486
487     mk_res_kind (TyFamily { tcdKind    = Just kind }) = return kind
488     mk_res_kind (TyData   { tcdKindSig = Just kind }) = return kind
489         -- On GADT-style declarations we allow a kind signature
490         --      data T :: *->* where { ... }
491     mk_res_kind _ = return liftedTypeKind
492
493
494 ----------------
495 kcSynDecls :: [SCC (LTyClDecl Name)] 
496            -> TcM ([LTyClDecl Name],    -- Kind-annotated decls
497                    [(Name,TcKind)])     -- Kind bindings
498 kcSynDecls []
499   = return ([], [])
500 kcSynDecls (group : groups)
501   = do  { (decl,  nk)  <- kcSynDecl group
502         ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
503         ; return (decl:decls, nk:nks) }
504                         
505 ----------------
506 kcSynDecl :: SCC (LTyClDecl Name) 
507            -> TcM (LTyClDecl Name,      -- Kind-annotated decls
508                    (Name,TcKind))       -- Kind bindings
509 kcSynDecl (AcyclicSCC (L loc decl))
510   = tcAddDeclCtxt decl  $
511     kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
512     do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl)) 
513                         <+> brackets (ppr k_tvs))
514        ; (k_rhs, rhs_kind) <- kcLHsType (tcdSynRhs decl)
515        ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
516        ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
517        ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
518                  (unLoc (tcdLName decl), tc_kind)) })
519
520 kcSynDecl (CyclicSCC decls)
521   = do { recSynErr decls; failM }       -- Fail here to avoid error cascade
522                                         -- of out-of-scope tycons
523
524 kindedTyVarKind :: LHsTyVarBndr Name -> Kind
525 kindedTyVarKind (L _ (KindedTyVar _ k)) = k
526 kindedTyVarKind x = pprPanic "kindedTyVarKind" (ppr x)
527
528 ------------------------------------------------------------------------
529 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
530         -- Not used for type synonyms (see kcSynDecl)
531
532 kcTyClDecl decl@(TyData {})
533   = ASSERT( not . isFamInstDecl $ decl )   -- must not be a family instance
534     kcTyClDeclBody decl $
535       kcDataDecl decl
536
537 kcTyClDecl decl@(TyFamily {})
538   = kcFamilyDecl [] decl      -- the empty list signals a toplevel decl      
539
540 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs, tcdATs = ats})
541   = kcTyClDeclBody decl $ \ tvs' ->
542     do  { ctxt' <- kcHsContext ctxt     
543         ; ats'  <- mapM (wrapLocM (kcFamilyDecl tvs')) ats
544         ; sigs' <- mapM (wrapLocM kc_sig) sigs
545         ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs',
546                         tcdATs = ats'}) }
547   where
548     kc_sig (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
549                                    ; return (TypeSig nm op_ty') }
550     kc_sig other_sig          = return other_sig
551
552 kcTyClDecl decl@(ForeignType {})
553   = return decl
554
555 kcTyClDecl (TySynonym {}) = panic "kcTyClDecl TySynonym"
556
557 kcTyClDeclBody :: TyClDecl Name
558                -> ([LHsTyVarBndr Name] -> TcM a)
559                -> TcM a
560 -- getInitialKind has made a suitably-shaped kind for the type or class
561 -- Unpack it, and attribute those kinds to the type variables
562 -- Extend the env with bindings for the tyvars, taken from
563 -- the kind of the tycon/class.  Give it to the thing inside, and 
564 -- check the result kind matches
565 kcTyClDeclBody decl thing_inside
566   = tcAddDeclCtxt decl          $
567     do  { tc_ty_thing <- tcLookupLocated (tcdLName decl)
568         ; let tc_kind    = case tc_ty_thing of
569                            AThing k -> k
570                            _ -> pprPanic "kcTyClDeclBody" (ppr tc_ty_thing)
571               (kinds, _) = splitKindFunTys tc_kind
572               hs_tvs     = tcdTyVars decl
573               kinded_tvs = ASSERT( length kinds >= length hs_tvs )
574                            [ L loc (KindedTyVar (hsTyVarName tv) k)
575                            | (L loc tv, k) <- zip hs_tvs kinds]
576         ; tcExtendKindEnvTvs kinded_tvs (thing_inside kinded_tvs) }
577
578 -- Kind check a data declaration, assuming that we already extended the
579 -- kind environment with the type variables of the left-hand side (these
580 -- kinded type variables are also passed as the second parameter).
581 --
582 kcDataDecl :: TyClDecl Name -> [LHsTyVarBndr Name] -> TcM (TyClDecl Name)
583 kcDataDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
584            tvs
585   = do  { ctxt' <- kcHsContext ctxt     
586         ; cons' <- mapM (wrapLocM kc_con_decl) cons
587         ; return (decl {tcdTyVars = tvs, tcdCtxt = ctxt', tcdCons = cons'}) }
588   where
589     -- doc comments are typechecked to Nothing here
590     kc_con_decl (ConDecl name expl ex_tvs ex_ctxt details res _) 
591       = addErrCtxt (dataConCtxt name)   $ 
592         kcHsTyVars ex_tvs $ \ex_tvs' -> do
593         do { ex_ctxt' <- kcHsContext ex_ctxt
594            ; details' <- kc_con_details details 
595            ; res'     <- case res of
596                 ResTyH98 -> return ResTyH98
597                 ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
598            ; return (ConDecl name expl ex_tvs' ex_ctxt' details' res' Nothing) }
599
600     kc_con_details (PrefixCon btys) 
601         = do { btys' <- mapM kc_larg_ty btys 
602              ; return (PrefixCon btys') }
603     kc_con_details (InfixCon bty1 bty2) 
604         = do { bty1' <- kc_larg_ty bty1
605              ; bty2' <- kc_larg_ty bty2
606              ; return (InfixCon bty1' bty2') }
607     kc_con_details (RecCon fields) 
608         = do { fields' <- mapM kc_field fields
609              ; return (RecCon fields') }
610
611     kc_field (ConDeclField fld bty d) = do { bty' <- kc_larg_ty bty
612                                            ; return (ConDeclField fld bty' d) }
613
614     kc_larg_ty bty = case new_or_data of
615                         DataType -> kcHsSigType bty
616                         NewType  -> kcHsLiftedSigType bty
617         -- Can't allow an unlifted type for newtypes, because we're effectively
618         -- going to remove the constructor while coercing it to a lifted type.
619         -- And newtypes can't be bang'd
620 kcDataDecl d _ = pprPanic "kcDataDecl" (ppr d)
621
622 -- Kind check a family declaration or type family default declaration.
623 --
624 kcFamilyDecl :: [LHsTyVarBndr Name]  -- tyvars of enclosing class decl if any
625              -> TyClDecl Name -> TcM (TyClDecl Name)
626 kcFamilyDecl classTvs decl@(TyFamily {tcdKind = kind})
627   = kcTyClDeclBody decl $ \tvs' ->
628     do { mapM_ unifyClassParmKinds tvs'
629        ; return (decl {tcdTyVars = tvs', 
630                        tcdKind = kind `mplus` Just liftedTypeKind})
631                        -- default result kind is '*'
632        }
633   where
634     unifyClassParmKinds (L _ (KindedTyVar n k))
635       | Just classParmKind <- lookup n classTyKinds = unifyKind k classParmKind
636       | otherwise                                   = return ()
637     unifyClassParmKinds x = pprPanic "kcFamilyDecl/unifyClassParmKinds" (ppr x)
638     classTyKinds = [(n, k) | L _ (KindedTyVar n k) <- classTvs]
639 kcFamilyDecl _ (TySynonym {})              -- type family defaults
640   = panic "TcTyClsDecls.kcFamilyDecl: not implemented yet"
641 kcFamilyDecl _ d = pprPanic "kcFamilyDecl" (ppr d)
642 \end{code}
643
644
645 %************************************************************************
646 %*                                                                      *
647 \subsection{Type checking}
648 %*                                                                      *
649 %************************************************************************
650
651 \begin{code}
652 tcSynDecls :: [LTyClDecl Name] -> TcM [TyThing]
653 tcSynDecls [] = return []
654 tcSynDecls (decl : decls) 
655   = do { syn_tc <- addLocM tcSynDecl decl
656        ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls decls)
657        ; return (syn_tc : syn_tcs) }
658
659   -- "type"
660 tcSynDecl :: TyClDecl Name -> TcM TyThing
661 tcSynDecl
662   (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
663   = tcTyVarBndrs tvs            $ \ tvs' -> do 
664     { traceTc (text "tcd1" <+> ppr tc_name) 
665     ; rhs_ty' <- tcHsKindedType rhs_ty
666     ; tycon <- buildSynTyCon tc_name tvs' (SynonymTyCon rhs_ty') 
667                              (typeKind rhs_ty') Nothing
668     ; return (ATyCon tycon) 
669     }
670 tcSynDecl d = pprPanic "tcSynDecl" (ppr d)
671
672 --------------------
673 tcTyClDecl :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
674
675 tcTyClDecl calc_isrec decl
676   = tcAddDeclCtxt decl (tcTyClDecl1 calc_isrec decl)
677
678   -- "type family" declarations
679 tcTyClDecl1 :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
680 tcTyClDecl1 _calc_isrec 
681   (TyFamily {tcdFlavour = TypeFamily, 
682              tcdLName = L _ tc_name, tcdTyVars = tvs,
683              tcdKind = Just kind}) -- NB: kind at latest added during kind checking
684   = tcTyVarBndrs tvs  $ \ tvs' -> do 
685   { traceTc (text "type family: " <+> ppr tc_name) 
686
687         -- Check that we don't use families without -XTypeFamilies
688   ; idx_tys <- doptM Opt_TypeFamilies
689   ; checkTc idx_tys $ badFamInstDecl tc_name
690
691         -- Check for no type indices
692   ; checkTc (not (null tvs)) (noIndexTypes tc_name)
693
694   ; tycon <- buildSynTyCon tc_name tvs' (OpenSynTyCon kind Nothing) kind Nothing
695   ; return [ATyCon tycon]
696   }
697
698   -- "data family" declaration
699 tcTyClDecl1 _calc_isrec 
700   (TyFamily {tcdFlavour = DataFamily, 
701              tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = mb_kind})
702   = tcTyVarBndrs tvs  $ \ tvs' -> do 
703   { traceTc (text "data family: " <+> ppr tc_name) 
704   ; extra_tvs <- tcDataKindSig mb_kind
705   ; let final_tvs = tvs' ++ extra_tvs    -- we may not need these
706
707
708         -- Check that we don't use families without -XTypeFamilies
709   ; idx_tys <- doptM Opt_TypeFamilies
710   ; checkTc idx_tys $ badFamInstDecl tc_name
711
712         -- Check for no type indices
713   ; checkTc (not (null tvs)) (noIndexTypes tc_name)
714
715   ; tycon <- buildAlgTyCon tc_name final_tvs [] 
716                mkOpenDataTyConRhs Recursive False True Nothing
717   ; return [ATyCon tycon]
718   }
719
720   -- "newtype" and "data"
721   -- NB: not used for newtype/data instances (whether associated or not)
722 tcTyClDecl1 calc_isrec
723   (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
724            tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
725   = tcTyVarBndrs tvs    $ \ tvs' -> do 
726   { extra_tvs <- tcDataKindSig mb_ksig
727   ; let final_tvs = tvs' ++ extra_tvs
728   ; stupid_theta <- tcHsKindedContext ctxt
729   ; want_generic <- doptM Opt_Generics
730   ; unbox_strict <- doptM Opt_UnboxStrictFields
731   ; empty_data_decls <- doptM Opt_EmptyDataDecls
732   ; kind_signatures <- doptM Opt_KindSignatures
733   ; existential_ok <- doptM Opt_ExistentialQuantification
734   ; gadt_ok      <- doptM Opt_GADTs
735   ; is_boot      <- tcIsHsBoot  -- Are we compiling an hs-boot file?
736   ; let ex_ok = existential_ok || gadt_ok       -- Data cons can have existential context
737
738         -- Check that we don't use GADT syntax in H98 world
739   ; checkTc (gadt_ok || h98_syntax) (badGadtDecl tc_name)
740
741         -- Check that we don't use kind signatures without Glasgow extensions
742   ; checkTc (kind_signatures || isNothing mb_ksig) (badSigTyDecl tc_name)
743
744         -- Check that the stupid theta is empty for a GADT-style declaration
745   ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
746
747         -- Check that a newtype has exactly one constructor
748         -- Do this before checking for empty data decls, so that
749         -- we don't suggest -XEmptyDataDecls for newtypes
750   ; checkTc (new_or_data == DataType || isSingleton cons) 
751             (newtypeConError tc_name (length cons))
752
753         -- Check that there's at least one condecl,
754         -- or else we're reading an hs-boot file, or -XEmptyDataDecls
755   ; checkTc (not (null cons) || empty_data_decls || is_boot)
756             (emptyConDeclsErr tc_name)
757     
758   ; tycon <- fixM (\ tycon -> do 
759         { let res_ty = mkTyConApp tycon (mkTyVarTys final_tvs)
760         ; data_cons <- tcConDecls unbox_strict ex_ok 
761                                   tycon (final_tvs, res_ty) cons
762         ; tc_rhs <-
763             if null cons && is_boot     -- In a hs-boot file, empty cons means
764             then return AbstractTyCon   -- "don't know"; hence Abstract
765             else case new_or_data of
766                    DataType -> return (mkDataTyConRhs data_cons)
767                    NewType  -> ASSERT( not (null data_cons) )
768                                mkNewTyConRhs tc_name tycon (head data_cons)
769         ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
770             (want_generic && canDoGenerics data_cons) h98_syntax Nothing
771         })
772   ; return [ATyCon tycon]
773   }
774   where
775     is_rec   = calc_isrec tc_name
776     h98_syntax = consUseH98Syntax cons
777
778 tcTyClDecl1 calc_isrec 
779   (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs, 
780               tcdCtxt = ctxt, tcdMeths = meths,
781               tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
782   = tcTyVarBndrs tvs            $ \ tvs' -> do 
783   { ctxt' <- tcHsKindedContext ctxt
784   ; fds' <- mapM (addLocM tc_fundep) fundeps
785   ; atss <- mapM (addLocM (tcTyClDecl1 (const Recursive))) ats
786             -- NB: 'ats' only contains "type family" and "data family"
787             --     declarations as well as type family defaults
788   ; let ats' = map (setAssocFamilyPermutation tvs') (concat atss)
789   ; sig_stuff <- tcClassSigs class_name sigs meths
790   ; clas <- fixM (\ clas ->
791                 let     -- This little knot is just so we can get
792                         -- hold of the name of the class TyCon, which we
793                         -- need to look up its recursiveness
794                     tycon_name = tyConName (classTyCon clas)
795                     tc_isrec = calc_isrec tycon_name
796                 in
797                 buildClass False {- Must include unfoldings for selectors -}
798                            class_name tvs' ctxt' fds' ats'
799                            sig_stuff tc_isrec)
800   ; return (AClass clas : ats')
801       -- NB: Order is important due to the call to `mkGlobalThings' when
802       --     tying the the type and class declaration type checking knot.
803   }
804   where
805     tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM tcLookupTyVar tvs1 ;
806                                 ; tvs2' <- mapM tcLookupTyVar tvs2 ;
807                                 ; return (tvs1', tvs2') }
808
809 tcTyClDecl1 _
810   (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
811   = return [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
812
813 tcTyClDecl1 _ d = pprPanic "tcTyClDecl1" (ppr d)
814
815 -----------------------------------
816 tcConDecls :: Bool -> Bool -> TyCon -> ([TyVar], Type)
817            -> [LConDecl Name] -> TcM [DataCon]
818 tcConDecls unbox ex_ok rep_tycon res_tmpl cons
819   = mapM (addLocM (tcConDecl unbox ex_ok rep_tycon res_tmpl)) cons
820
821 tcConDecl :: Bool               -- True <=> -funbox-strict_fields
822           -> Bool               -- True <=> -XExistentialQuantificaton or -XGADTs
823           -> TyCon              -- Representation tycon
824           -> ([TyVar], Type)    -- Return type template (with its template tyvars)
825           -> ConDecl Name 
826           -> TcM DataCon
827
828 tcConDecl unbox_strict existential_ok rep_tycon res_tmpl        -- Data types
829           (ConDecl name _ tvs ctxt details res_ty _)
830   = addErrCtxt (dataConCtxt name)       $ 
831     tcTyVarBndrs tvs                    $ \ tvs' -> do 
832     { ctxt' <- tcHsKindedContext ctxt
833     ; checkTc (existential_ok || (null tvs && null (unLoc ctxt)))
834               (badExistential name)
835     ; (univ_tvs, ex_tvs, eq_preds, res_ty') <- tcResultType res_tmpl tvs' res_ty
836     ; let 
837         tc_datacon is_infix field_lbls btys
838           = do { (arg_tys, stricts) <- mapAndUnzipM (tcConArg unbox_strict) btys
839                ; buildDataCon (unLoc name) is_infix
840                     stricts field_lbls
841                     univ_tvs ex_tvs eq_preds ctxt' arg_tys
842                     res_ty' rep_tycon }
843                 -- NB:  we put data_tc, the type constructor gotten from the
844                 --      constructor type signature into the data constructor;
845                 --      that way checkValidDataCon can complain if it's wrong.
846
847     ; case details of
848         PrefixCon btys     -> tc_datacon False [] btys
849         InfixCon bty1 bty2 -> tc_datacon True  [] [bty1,bty2]
850         RecCon fields      -> tc_datacon False field_names btys
851                            where
852                               field_names = map (unLoc . cd_fld_name) fields
853                               btys        = map cd_fld_type fields
854     }
855
856 -- Example
857 --   data instance T (b,c) where 
858 --      TI :: forall e. e -> T (e,e)
859 --
860 -- The representation tycon looks like this:
861 --   data :R7T b c where 
862 --      TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
863 -- In this case orig_res_ty = T (e,e)
864
865 tcResultType :: ([TyVar], Type) -- Template for result type; e.g.
866                                 -- data instance T [a] b c = ...  
867                                 --      gives template ([a,b,c], T [a] b c)
868              -> [TyVar]         -- where MkT :: forall x y z. ...
869              -> ResType Name
870              -> TcM ([TyVar],           -- Universal
871                      [TyVar],           -- Existential (distinct OccNames from univs)
872                      [(TyVar,Type)],    -- Equality predicates
873                      Type)              -- Typechecked return type
874         -- We don't check that the TyCon given in the ResTy is
875         -- the same as the parent tycon, becuase we are in the middle
876         -- of a recursive knot; so it's postponed until checkValidDataCon
877
878 tcResultType (tmpl_tvs, res_ty) dc_tvs ResTyH98
879   = return (tmpl_tvs, dc_tvs, [], res_ty)
880         -- In H98 syntax the dc_tvs are the existential ones
881         --      data T a b c = forall d e. MkT ...
882         -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
883
884 tcResultType (tmpl_tvs, res_tmpl) dc_tvs (ResTyGADT res_ty)
885         -- E.g.  data T [a] b c where
886         --         MkT :: forall x y z. T [(x,y)] z z
887         -- Then we generate
888         --      Univ tyvars     Eq-spec
889         --          a              a~(x,y)
890         --          b              b~z
891         --          z              
892         -- Existentials are the leftover type vars: [x,y]
893         -- So we return ([a,b,z], [x,y], [a~(x,y),b~z], T [(x,y)] z z)
894   = do  { res_ty' <- tcHsKindedType res_ty
895         ; let Just subst = tcMatchTy (mkVarSet tmpl_tvs) res_tmpl res_ty'
896
897                 -- /Lazily/ figure out the univ_tvs etc
898                 -- Each univ_tv is either a dc_tv or a tmpl_tv
899               (univ_tvs, eq_spec) = foldr choose ([], []) tidy_tmpl_tvs
900               choose tmpl (univs, eqs)
901                 | Just ty <- lookupTyVar subst tmpl 
902                 = case tcGetTyVar_maybe ty of
903                     Just tv | not (tv `elem` univs)
904                             -> (tv:univs,   eqs)
905                     _other  -> (tmpl:univs, (tmpl,ty):eqs)
906                 | otherwise = pprPanic "tcResultType" (ppr res_ty)
907               ex_tvs = dc_tvs `minusList` univ_tvs
908
909         ; return (univ_tvs, ex_tvs, eq_spec, res_ty') }
910   where
911         -- NB: tmpl_tvs and dc_tvs are distinct, but
912         -- we want them to be *visibly* distinct, both for
913         -- interface files and general confusion.  So rename
914         -- the tc_tvs, since they are not used yet (no 
915         -- consequential renaming needed)
916     (_, tidy_tmpl_tvs) = mapAccumL tidy_one init_occ_env tmpl_tvs
917     init_occ_env       = initTidyOccEnv (map getOccName dc_tvs)
918     tidy_one env tv    = (env', setTyVarName tv (tidyNameOcc name occ'))
919               where
920                  name = tyVarName tv
921                  (env', occ') = tidyOccName env (getOccName name) 
922
923 consUseH98Syntax :: [LConDecl a] -> Bool
924 consUseH98Syntax (L _ (ConDecl { con_res = ResTyGADT _ }) : _) = False
925 consUseH98Syntax _                                             = True
926                  -- All constructors have same shape
927
928 -------------------
929 tcConArg :: Bool                -- True <=> -funbox-strict_fields
930            -> LHsType Name
931            -> TcM (TcType, StrictnessMark)
932 tcConArg unbox_strict bty
933   = do  { arg_ty <- tcHsBangType bty
934         ; let bang = getBangStrictness bty
935         ; return (arg_ty, chooseBoxingStrategy unbox_strict arg_ty bang) }
936
937 -- We attempt to unbox/unpack a strict field when either:
938 --   (i)  The field is marked '!!', or
939 --   (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
940 --
941 -- We have turned off unboxing of newtypes because coercions make unboxing 
942 -- and reboxing more complicated
943 chooseBoxingStrategy :: Bool -> TcType -> HsBang -> StrictnessMark
944 chooseBoxingStrategy unbox_strict_fields arg_ty bang
945   = case bang of
946         HsNoBang                                    -> NotMarkedStrict
947         HsStrict | unbox_strict_fields 
948                    && can_unbox arg_ty              -> MarkedUnboxed
949         HsUnbox  | can_unbox arg_ty                 -> MarkedUnboxed
950         _                                           -> MarkedStrict
951   where
952     -- we can unbox if the type is a chain of newtypes with a product tycon
953     -- at the end
954     can_unbox arg_ty = case splitTyConApp_maybe arg_ty of
955                    Nothing                      -> False
956                    Just (arg_tycon, tycon_args) -> 
957                        not (isRecursiveTyCon arg_tycon) &&      -- Note [Recusive unboxing]
958                        isProductTyCon arg_tycon &&
959                        (if isNewTyCon arg_tycon then 
960                             can_unbox (newTyConInstRhs arg_tycon tycon_args)
961                         else True)
962 \end{code}
963
964 Note [Recursive unboxing]
965 ~~~~~~~~~~~~~~~~~~~~~~~~~
966 Be careful not to try to unbox this!
967         data T = MkT !T Int
968 But it's the *argument* type that matters. This is fine:
969         data S = MkS S !Int
970 because Int is non-recursive.
971
972
973 %************************************************************************
974 %*                                                                      *
975                 Validity checking
976 %*                                                                      *
977 %************************************************************************
978
979 Validity checking is done once the mutually-recursive knot has been
980 tied, so we can look at things freely.
981
982 \begin{code}
983 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
984 checkCycleErrs tyclss
985   | null cls_cycles
986   = return ()
987   | otherwise
988   = do  { mapM_ recClsErr cls_cycles
989         ; failM }       -- Give up now, because later checkValidTyCl
990                         -- will loop if the synonym is recursive
991   where
992     cls_cycles = calcClassCycles tyclss
993
994 checkValidTyCl :: TyClDecl Name -> TcM ()
995 -- We do the validity check over declarations, rather than TyThings
996 -- only so that we can add a nice context with tcAddDeclCtxt
997 checkValidTyCl decl
998   = tcAddDeclCtxt decl $
999     do  { thing <- tcLookupLocatedGlobal (tcdLName decl)
1000         ; traceTc (text "Validity of" <+> ppr thing)    
1001         ; case thing of
1002             ATyCon tc -> checkValidTyCon tc
1003             AClass cl -> checkValidClass cl 
1004             _ -> panic "checkValidTyCl"
1005         ; traceTc (text "Done validity of" <+> ppr thing)       
1006         }
1007
1008 -------------------------
1009 -- For data types declared with record syntax, we require
1010 -- that each constructor that has a field 'f' 
1011 --      (a) has the same result type
1012 --      (b) has the same type for 'f'
1013 -- module alpha conversion of the quantified type variables
1014 -- of the constructor.
1015 --
1016 -- Note that we allow existentials to match becuase the
1017 -- fields can never meet. E.g
1018 --      data T where
1019 --        T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
1020 --        T2 { f1 :: c, f2 :: c, f3 ::Int } :: T  
1021 -- Here we do not complain about f1,f2 because they are existential
1022
1023 checkValidTyCon :: TyCon -> TcM ()
1024 checkValidTyCon tc 
1025   | isSynTyCon tc 
1026   = case synTyConRhs tc of
1027       OpenSynTyCon _ _ -> return ()
1028       SynonymTyCon ty  -> checkValidType syn_ctxt ty
1029   | otherwise
1030   = do  -- Check the context on the data decl
1031     checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
1032         
1033         -- Check arg types of data constructors
1034     mapM_ (checkValidDataCon tc) data_cons
1035
1036         -- Check that fields with the same name share a type
1037     mapM_ check_fields groups
1038
1039   where
1040     syn_ctxt  = TySynCtxt name
1041     name      = tyConName tc
1042     data_cons = tyConDataCons tc
1043
1044     groups = equivClasses cmp_fld (concatMap get_fields data_cons)
1045     cmp_fld (f1,_) (f2,_) = f1 `compare` f2
1046     get_fields con = dataConFieldLabels con `zip` repeat con
1047         -- dataConFieldLabels may return the empty list, which is fine
1048
1049     -- See Note [GADT record selectors] in MkId.lhs
1050     -- We must check (a) that the named field has the same 
1051     --                   type in each constructor
1052     --               (b) that those constructors have the same result type
1053     --
1054     -- However, the constructors may have differently named type variable
1055     -- and (worse) we don't know how the correspond to each other.  E.g.
1056     --     C1 :: forall a b. { f :: a, g :: b } -> T a b
1057     --     C2 :: forall d c. { f :: c, g :: c } -> T c d
1058     -- 
1059     -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
1060     -- result type against other candidates' types BOTH WAYS ROUND.
1061     -- If they magically agrees, take the substitution and
1062     -- apply them to the latter ones, and see if they match perfectly.
1063     check_fields ((label, con1) : other_fields)
1064         -- These fields all have the same name, but are from
1065         -- different constructors in the data type
1066         = recoverM (return ()) $ mapM_ checkOne other_fields
1067                 -- Check that all the fields in the group have the same type
1068                 -- NB: this check assumes that all the constructors of a given
1069                 -- data type use the same type variables
1070         where
1071         (tvs1, _, _, res1) = dataConSig con1
1072         ts1 = mkVarSet tvs1
1073         fty1 = dataConFieldType con1 label
1074
1075         checkOne (_, con2)    -- Do it bothways to ensure they are structurally identical
1076             = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
1077                  ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
1078             where        
1079                 (tvs2, _, _, res2) = dataConSig con2
1080                 ts2 = mkVarSet tvs2
1081                 fty2 = dataConFieldType con2 label
1082     check_fields [] = panic "checkValidTyCon/check_fields []"
1083
1084 checkFieldCompat :: Name -> DataCon -> DataCon -> TyVarSet
1085                  -> Type -> Type -> Type -> Type -> TcM ()
1086 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
1087   = do  { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
1088         ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
1089   where
1090     mb_subst1 = tcMatchTy tvs1 res1 res2
1091     mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
1092
1093 -------------------------------
1094 checkValidDataCon :: TyCon -> DataCon -> TcM ()
1095 checkValidDataCon tc con
1096   = setSrcSpan (srcLocSpan (getSrcLoc con))     $
1097     addErrCtxt (dataConCtxt con)                $ 
1098     do  { traceTc (ptext (sLit "Validity of data con") <+> ppr con)
1099         ; let tc_tvs = tyConTyVars tc
1100               res_ty_tmpl = mkFamilyTyConApp tc (mkTyVarTys tc_tvs)
1101               actual_res_ty = dataConOrigResTy con
1102         ; checkTc (isJust (tcMatchTy (mkVarSet tc_tvs)
1103                                 res_ty_tmpl
1104                                 actual_res_ty))
1105                   (badDataConTyCon con res_ty_tmpl actual_res_ty)
1106         ; checkValidMonoType (dataConOrigResTy con)
1107                 -- Disallow MkT :: T (forall a. a->a)
1108                 -- Reason: it's really the argument of an equality constraint
1109         ; checkValidType ctxt (dataConUserType con)
1110         ; when (isNewTyCon tc) (checkNewDataCon con)
1111     }
1112   where
1113     ctxt = ConArgCtxt (dataConName con) 
1114
1115 -------------------------------
1116 checkNewDataCon :: DataCon -> TcM ()
1117 -- Checks for the data constructor of a newtype
1118 checkNewDataCon con
1119   = do  { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
1120                 -- One argument
1121         ; checkTc (null eq_spec) (newtypePredError con)
1122                 -- Return type is (T a b c)
1123         ; checkTc (null ex_tvs && null eq_theta && null dict_theta) (newtypeExError con)
1124                 -- No existentials
1125         ; checkTc (not (any isMarkedStrict (dataConStrictMarks con))) 
1126                   (newtypeStrictError con)
1127                 -- No strictness
1128     }
1129   where
1130     (_univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _res_ty) = dataConFullSig con
1131
1132 -------------------------------
1133 checkValidClass :: Class -> TcM ()
1134 checkValidClass cls
1135   = do  { constrained_class_methods <- doptM Opt_ConstrainedClassMethods
1136         ; multi_param_type_classes <- doptM Opt_MultiParamTypeClasses
1137         ; fundep_classes <- doptM Opt_FunctionalDependencies
1138
1139         -- Check that the class is unary, unless GlaExs
1140         ; checkTc (notNull tyvars) (nullaryClassErr cls)
1141         ; checkTc (multi_param_type_classes || unary) (classArityErr cls)
1142         ; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
1143
1144         -- Check the super-classes
1145         ; checkValidTheta (ClassSCCtxt (className cls)) theta
1146
1147         -- Check the class operations
1148         ; mapM_ (check_op constrained_class_methods) op_stuff
1149
1150         -- Check that if the class has generic methods, then the
1151         -- class has only one parameter.  We can't do generic
1152         -- multi-parameter type classes!
1153         ; checkTc (unary || no_generics) (genericMultiParamErr cls)
1154         }
1155   where
1156     (tyvars, fundeps, theta, _, _, op_stuff) = classExtraBigSig cls
1157     unary       = isSingleton tyvars
1158     no_generics = null [() | (_, GenDefMeth) <- op_stuff]
1159
1160     check_op constrained_class_methods (sel_id, dm) 
1161       = addErrCtxt (classOpCtxt sel_id tau) $ do
1162         { checkValidTheta SigmaCtxt (tail theta)
1163                 -- The 'tail' removes the initial (C a) from the
1164                 -- class itself, leaving just the method type
1165
1166         ; traceTc (text "class op type" <+> ppr op_ty <+> ppr tau)
1167         ; checkValidType (FunSigCtxt op_name) tau
1168
1169                 -- Check that the type mentions at least one of
1170                 -- the class type variables...or at least one reachable
1171                 -- from one of the class variables.  Example: tc223
1172                 --   class Error e => Game b mv e | b -> mv e where
1173                 --      newBoard :: MonadState b m => m ()
1174                 -- Here, MonadState has a fundep m->b, so newBoard is fine
1175         ; let grown_tyvars = growThetaTyVars theta (mkVarSet tyvars)
1176         ; checkTc (tyVarsOfType tau `intersectsVarSet` grown_tyvars)
1177                   (noClassTyVarErr cls sel_id)
1178
1179                 -- Check that for a generic method, the type of 
1180                 -- the method is sufficiently simple
1181         ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
1182                   (badGenericMethodType op_name op_ty)
1183         }
1184         where
1185           op_name = idName sel_id
1186           op_ty   = idType sel_id
1187           (_,theta1,tau1) = tcSplitSigmaTy op_ty
1188           (_,theta2,tau2)  = tcSplitSigmaTy tau1
1189           (theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
1190                       | otherwise = (theta1, mkPhiTy (tail theta1) tau1)
1191                 -- Ugh!  The function might have a type like
1192                 --      op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
1193                 -- With -XConstrainedClassMethods, we want to allow this, even though the inner 
1194                 -- forall has an (Eq a) constraint.  Whereas in general, each constraint 
1195                 -- in the context of a for-all must mention at least one quantified
1196                 -- type variable.  What a mess!
1197 \end{code}
1198
1199
1200 %************************************************************************
1201 %*                                                                      *
1202                 Building record selectors
1203 %*                                                                      *
1204 %************************************************************************
1205
1206 \begin{code}
1207 mkAuxBinds :: [TyThing] -> HsValBinds Name
1208 mkAuxBinds ty_things
1209   = ValBindsOut [(NonRecursive, b) | b <- binds] sigs
1210   where
1211     (sigs, binds) = unzip rec_sels
1212     rec_sels = map mkRecSelBind [ (tc,fld) 
1213                                 | ATyCon tc <- ty_things 
1214                                 , fld <- tyConFields tc ]
1215
1216
1217 mkRecSelBind :: (TyCon, FieldLabel) -> (LSig Name, LHsBinds Name)
1218 mkRecSelBind (tycon, sel_name)
1219   = (L loc (IdSig sel_id), unitBag (L loc sel_bind))
1220   where
1221     loc = getSrcSpan tycon    
1222     sel_id = Var.mkLocalVar rec_details sel_name sel_ty vanillaIdInfo
1223     rec_details = RecSelId { sel_tycon = tycon, sel_naughty = is_naughty }
1224
1225     -- Find a representative constructor, con1
1226     all_cons = tyConDataCons tycon 
1227     cons_w_field = [ con | con <- all_cons
1228                    , sel_name `elem` dataConFieldLabels con ] 
1229     con1 = ASSERT( not (null cons_w_field) ) head cons_w_field
1230
1231     -- Selector type; Note [Polymorphic selectors]
1232     field_ty = dataConFieldType con1 sel_name
1233     (field_tvs, field_theta, field_tau) 
1234        | is_naughty = ([], [], unitTy)
1235        | otherwise  = tcSplitSigmaTy field_ty
1236     data_ty    = dataConOrigResTy con1
1237     data_tvs   = tyVarsOfType data_ty
1238     is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tvs)  
1239     sel_ty = mkForAllTys (varSetElems data_tvs ++ field_tvs) $ 
1240              mkPhiTy (dataConStupidTheta con1)  $       -- Urgh!
1241              mkPhiTy field_theta                $       -- Urgh!
1242              mkFunTy data_ty field_tau
1243
1244     -- Make the binding: sel (C2 { fld = x }) = x
1245     --                   sel (C7 { fld = x }) = x
1246     --    where cons_w_field = [C2,C7]
1247     sel_bind     = mkFunBind sel_lname (map mk_match cons_w_field ++ deflt)
1248     mk_match con = mkSimpleMatch [L loc (mk_sel_pat con)] 
1249                                  (L loc match_body)
1250     mk_sel_pat con = ConPatIn (L loc (getName con)) (RecCon rec_fields)
1251     rec_fields = HsRecFields { rec_flds = [rec_field], rec_dotdot = Nothing }
1252     rec_field  = HsRecField { hsRecFieldId = sel_lname
1253                             , hsRecFieldArg = nlVarPat field_var
1254                             , hsRecPun = False }
1255     match_body | is_naughty = ExplicitTuple [] Boxed
1256                | otherwise  = HsVar field_var
1257     sel_lname = L loc sel_name
1258     field_var = mkInternalName (mkBuiltinUnique 1) (getOccName sel_name) loc
1259
1260     -- Add catch-all default case unless the case is exhaustive
1261     -- We do this explicitly so that we get a nice error message that
1262     -- mentions this particular record selector
1263     deflt | length cons_w_field == length all_cons = []
1264           | otherwise = [mkSimpleMatch [nlWildPat] 
1265                             (nlHsApp (nlHsVar (getName rEC_SEL_ERROR_ID))
1266                                      (nlHsLit msg_lit))]
1267     msg_lit = HsStringPrim $ mkFastString $ 
1268               occNameString (getOccName sel_name)
1269
1270 ---------------
1271 tyConFields :: TyCon -> [FieldLabel]
1272 tyConFields tc 
1273   | isAlgTyCon tc = nub (concatMap dataConFieldLabels (tyConDataCons tc))
1274   | otherwise     = []
1275 \end{code}
1276
1277 Note [Polymorphic selectors]
1278 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1279 When a record has a polymorphic field, we pull the foralls out to the front.
1280    data T = MkT { f :: forall a. [a] -> a }
1281 Then f :: forall a. T -> [a] -> a
1282 NOT  f :: T -> forall a. [a] -> a
1283
1284 This is horrid.  It's only needed in deeply obscure cases, which I hate.
1285 The only case I know is test tc163, which is worth looking at.  It's far
1286 from clear that this test should succeed at all!
1287
1288 Note [Naughty record selectors]
1289 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1290 A "naughty" field is one for which we can't define a record 
1291 selector, because an existential type variable would escape.  For example:
1292         data T = forall a. MkT { x,y::a }
1293 We obviously can't define       
1294         x (MkT v _) = v
1295 Nevertheless we *do* put a RecSelId into the type environment
1296 so that if the user tries to use 'x' as a selector we can bleat
1297 helpfully, rather than saying unhelpfully that 'x' is not in scope.
1298 Hence the sel_naughty flag, to identify record selectors that don't really exist.
1299
1300 In general, a field is naughty if its type mentions a type variable that
1301 isn't in the result type of the constructor.
1302
1303 We make a dummy binding for naughty selectors, so that they can be treated
1304 uniformly, apart from their sel_naughty field.  The function is never called.
1305
1306 Note [GADT record selectors]
1307 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1308 For GADTs, we require that all constructors with a common field 'f' have the same
1309 result type (modulo alpha conversion).  [Checked in TcTyClsDecls.checkValidTyCon]
1310 E.g. 
1311         data T where
1312           T1 { f :: Maybe a } :: T [a]
1313           T2 { f :: Maybe a, y :: b  } :: T [a]
1314
1315 and now the selector takes that result type as its argument:
1316    f :: forall a. T [a] -> Maybe a
1317
1318 Details: the "real" types of T1,T2 are:
1319    T1 :: forall r a.   (r~[a]) => a -> T r
1320    T2 :: forall r a b. (r~[a]) => a -> b -> T r
1321
1322 So the selector loooks like this:
1323    f :: forall a. T [a] -> Maybe a
1324    f (a:*) (t:T [a])
1325      = case t of
1326          T1 c   (g:[a]~[c]) (v:Maybe c)       -> v `cast` Maybe (right (sym g))
1327          T2 c d (g:[a]~[c]) (v:Maybe c) (w:d) -> v `cast` Maybe (right (sym g))
1328
1329 Note the forall'd tyvars of the selector are just the free tyvars
1330 of the result type; there may be other tyvars in the constructor's
1331 type (e.g. 'b' in T2).
1332
1333 Note the need for casts in the result!
1334
1335 Note [Selector running example]
1336 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1337 It's OK to combine GADTs and type families.  Here's a running example:
1338
1339         data instance T [a] where 
1340           T1 { fld :: b } :: T [Maybe b]
1341
1342 The representation type looks like this
1343         data :R7T a where
1344           T1 { fld :: b } :: :R7T (Maybe b)
1345
1346 and there's coercion from the family type to the representation type
1347         :CoR7T a :: T [a] ~ :R7T a
1348
1349 The selector we want for fld looks like this:
1350
1351         fld :: forall b. T [Maybe b] -> b
1352         fld = /\b. \(d::T [Maybe b]).
1353               case d `cast` :CoR7T (Maybe b) of 
1354                 T1 (x::b) -> x
1355
1356 The scrutinee of the case has type :R7T (Maybe b), which can be
1357 gotten by appying the eq_spec to the univ_tvs of the data con.
1358
1359 %************************************************************************
1360 %*                                                                      *
1361                 Error messages
1362 %*                                                                      *
1363 %************************************************************************
1364
1365 \begin{code}
1366 resultTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1367 resultTypeMisMatch field_name con1 con2
1368   = vcat [sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2, 
1369                 ptext (sLit "have a common field") <+> quotes (ppr field_name) <> comma],
1370           nest 2 $ ptext (sLit "but have different result types")]
1371
1372 fieldTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1373 fieldTypeMisMatch field_name con1 con2
1374   = sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2, 
1375          ptext (sLit "give different types for field"), quotes (ppr field_name)]
1376
1377 dataConCtxt :: Outputable a => a -> SDoc
1378 dataConCtxt con = ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
1379
1380 classOpCtxt :: Var -> Type -> SDoc
1381 classOpCtxt sel_id tau = sep [ptext (sLit "When checking the class method:"),
1382                               nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
1383
1384 nullaryClassErr :: Class -> SDoc
1385 nullaryClassErr cls
1386   = ptext (sLit "No parameters for class")  <+> quotes (ppr cls)
1387
1388 classArityErr :: Class -> SDoc
1389 classArityErr cls
1390   = vcat [ptext (sLit "Too many parameters for class") <+> quotes (ppr cls),
1391           parens (ptext (sLit "Use -XMultiParamTypeClasses to allow multi-parameter classes"))]
1392
1393 classFunDepsErr :: Class -> SDoc
1394 classFunDepsErr cls
1395   = vcat [ptext (sLit "Fundeps in class") <+> quotes (ppr cls),
1396           parens (ptext (sLit "Use -XFunctionalDependencies to allow fundeps"))]
1397
1398 noClassTyVarErr :: Class -> Var -> SDoc
1399 noClassTyVarErr clas op
1400   = sep [ptext (sLit "The class method") <+> quotes (ppr op),
1401          ptext (sLit "mentions none of the type variables of the class") <+> 
1402                 ppr clas <+> hsep (map ppr (classTyVars clas))]
1403
1404 genericMultiParamErr :: Class -> SDoc
1405 genericMultiParamErr clas
1406   = ptext (sLit "The multi-parameter class") <+> quotes (ppr clas) <+> 
1407     ptext (sLit "cannot have generic methods")
1408
1409 badGenericMethodType :: Name -> Kind -> SDoc
1410 badGenericMethodType op op_ty
1411   = hang (ptext (sLit "Generic method type is too complex"))
1412        4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
1413                 ptext (sLit "You can only use type variables, arrows, lists, and tuples")])
1414
1415 recSynErr :: [LTyClDecl Name] -> TcRn ()
1416 recSynErr syn_decls
1417   = setSrcSpan (getLoc (head sorted_decls)) $
1418     addErr (sep [ptext (sLit "Cycle in type synonym declarations:"),
1419                  nest 2 (vcat (map ppr_decl sorted_decls))])
1420   where
1421     sorted_decls = sortLocated syn_decls
1422     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
1423
1424 recClsErr :: [Located (TyClDecl Name)] -> TcRn ()
1425 recClsErr cls_decls
1426   = setSrcSpan (getLoc (head sorted_decls)) $
1427     addErr (sep [ptext (sLit "Cycle in class declarations (via superclasses):"),
1428                  nest 2 (vcat (map ppr_decl sorted_decls))])
1429   where
1430     sorted_decls = sortLocated cls_decls
1431     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
1432
1433 sortLocated :: [Located a] -> [Located a]
1434 sortLocated things = sortLe le things
1435   where
1436     le (L l1 _) (L l2 _) = l1 <= l2
1437
1438 badDataConTyCon :: DataCon -> Type -> Type -> SDoc
1439 badDataConTyCon data_con res_ty_tmpl actual_res_ty
1440   = hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con) <+>
1441                 ptext (sLit "returns type") <+> quotes (ppr actual_res_ty))
1442        2 (ptext (sLit "instead of an instance of its parent type") <+> quotes (ppr res_ty_tmpl))
1443
1444 badGadtDecl :: Name -> SDoc
1445 badGadtDecl tc_name
1446   = vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
1447          , nest 2 (parens $ ptext (sLit "Use -XGADTs to allow GADTs")) ]
1448
1449 badExistential :: Located Name -> SDoc
1450 badExistential con_name
1451   = hang (ptext (sLit "Data constructor") <+> quotes (ppr con_name) <+>
1452                 ptext (sLit "has existential type variables, or a context"))
1453        2 (parens $ ptext (sLit "Use -XExistentialQuantification or -XGADTs to allow this"))
1454
1455 badStupidTheta :: Name -> SDoc
1456 badStupidTheta tc_name
1457   = ptext (sLit "A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
1458
1459 newtypeConError :: Name -> Int -> SDoc
1460 newtypeConError tycon n
1461   = sep [ptext (sLit "A newtype must have exactly one constructor,"),
1462          nest 2 $ ptext (sLit "but") <+> quotes (ppr tycon) <+> ptext (sLit "has") <+> speakN n ]
1463
1464 newtypeExError :: DataCon -> SDoc
1465 newtypeExError con
1466   = sep [ptext (sLit "A newtype constructor cannot have an existential context,"),
1467          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1468
1469 newtypeStrictError :: DataCon -> SDoc
1470 newtypeStrictError con
1471   = sep [ptext (sLit "A newtype constructor cannot have a strictness annotation,"),
1472          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1473
1474 newtypePredError :: DataCon -> SDoc
1475 newtypePredError con
1476   = sep [ptext (sLit "A newtype constructor must have a return type of form T a1 ... an"),
1477          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does not")]
1478
1479 newtypeFieldErr :: DataCon -> Int -> SDoc
1480 newtypeFieldErr con_name n_flds
1481   = sep [ptext (sLit "The constructor of a newtype must have exactly one field"), 
1482          nest 2 $ ptext (sLit "but") <+> quotes (ppr con_name) <+> ptext (sLit "has") <+> speakN n_flds]
1483
1484 badSigTyDecl :: Name -> SDoc
1485 badSigTyDecl tc_name
1486   = vcat [ ptext (sLit "Illegal kind signature") <+>
1487            quotes (ppr tc_name)
1488          , nest 2 (parens $ ptext (sLit "Use -XKindSignatures to allow kind signatures")) ]
1489
1490 noIndexTypes :: Name -> SDoc
1491 noIndexTypes tc_name
1492   = ptext (sLit "Type family constructor") <+> quotes (ppr tc_name)
1493     <+> ptext (sLit "must have at least one type index parameter")
1494
1495 badFamInstDecl :: Outputable a => a -> SDoc
1496 badFamInstDecl tc_name
1497   = vcat [ ptext (sLit "Illegal family instance for") <+>
1498            quotes (ppr tc_name)
1499          , nest 2 (parens $ ptext (sLit "Use -XTypeFamilies to allow indexed type families")) ]
1500
1501 tooManyParmsErr :: Located Name -> SDoc
1502 tooManyParmsErr tc_name
1503   = ptext (sLit "Family instance has too many parameters:") <+> 
1504     quotes (ppr tc_name)
1505
1506 tooFewParmsErr :: Arity -> SDoc
1507 tooFewParmsErr arity
1508   = ptext (sLit "Family instance has too few parameters; expected") <+> 
1509     ppr arity
1510
1511 wrongNumberOfParmsErr :: Arity -> SDoc
1512 wrongNumberOfParmsErr exp_arity
1513   = ptext (sLit "Number of parameters must match family declaration; expected")
1514     <+> ppr exp_arity
1515
1516 badBootFamInstDeclErr :: SDoc
1517 badBootFamInstDeclErr
1518   = ptext (sLit "Illegal family instance in hs-boot file")
1519
1520 notFamily :: TyCon -> SDoc
1521 notFamily tycon
1522   = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tycon)
1523          , nest 2 $ parens (ppr tycon <+> ptext (sLit "is not an indexed type family"))]
1524   
1525 wrongKindOfFamily :: TyCon -> SDoc
1526 wrongKindOfFamily family
1527   = ptext (sLit "Wrong category of family instance; declaration was for a")
1528     <+> kindOfFamily
1529   where
1530     kindOfFamily | isSynTyCon family = ptext (sLit "type synonym")
1531                  | isAlgTyCon family = ptext (sLit "data type")
1532                  | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1533
1534 emptyConDeclsErr :: Name -> SDoc
1535 emptyConDeclsErr tycon
1536   = sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
1537          nest 2 $ ptext (sLit "(-XEmptyDataDecls permits this)")]
1538 \end{code}