Check -XGADTs in (a) type family decls (b) pattern matches
[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 FunDeps
29 import Type
30 import Generics
31 import Class
32 import TyCon
33 import DataCon
34 import Id
35 import MkId             ( rEC_SEL_ERROR_ID )
36 import IdInfo
37 import Var
38 import VarSet
39 import Name
40 import OccName
41 import Outputable
42 import Maybes
43 import Monad
44 import Unify
45 import Util
46 import SrcLoc
47 import ListSetOps
48 import Digraph
49 import DynFlags
50 import FastString
51 import Unique           ( mkBuiltinUnique )
52 import BasicTypes
53
54 import Bag
55 import Data.List
56 import Control.Monad    ( mplus )
57 \end{code}
58
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection{Type checking for type and class declarations}
63 %*                                                                      *
64 %************************************************************************
65
66 Dealing with a group
67 ~~~~~~~~~~~~~~~~~~~~
68 Consider a mutually-recursive group, binding 
69 a type constructor T and a class C.
70
71 Step 1:         getInitialKind
72         Construct a KindEnv by binding T and C to a kind variable 
73
74 Step 2:         kcTyClDecl
75         In that environment, do a kind check
76
77 Step 3: Zonk the kinds
78
79 Step 4:         buildTyConOrClass
80         Construct an environment binding T to a TyCon and C to a Class.
81         a) Their kinds comes from zonking the relevant kind variable
82         b) Their arity (for synonyms) comes direct from the decl
83         c) The funcional dependencies come from the decl
84         d) The rest comes a knot-tied binding of T and C, returned from Step 4
85         e) The variances of the tycons in the group is calculated from 
86                 the knot-tied stuff
87
88 Step 5:         tcTyClDecl1
89         In this environment, walk over the decls, constructing the TyCons and Classes.
90         This uses in a strict way items (a)-(c) above, which is why they must
91         be constructed in Step 4. Feed the results back to Step 4.
92         For this step, pass the is-recursive flag as the wimp-out flag
93         to tcTyClDecl1.
94         
95
96 Step 6:         Extend environment
97         We extend the type environment with bindings not only for the TyCons and Classes,
98         but also for their "implicit Ids" like data constructors and class selectors
99
100 Step 7:         checkValidTyCl
101         For a recursive group only, check all the decls again, just
102         to check all the side conditions on validity.  We could not
103         do this before because we were in a mutually recursive knot.
104
105 Identification of recursive TyCons
106 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
107 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
108 @TyThing@s.
109
110 Identifying a TyCon as recursive serves two purposes
111
112 1.  Avoid infinite types.  Non-recursive newtypes are treated as
113 "transparent", like type synonyms, after the type checker.  If we did
114 this for all newtypes, we'd get infinite types.  So we figure out for
115 each newtype whether it is "recursive", and add a coercion if so.  In
116 effect, we are trying to "cut the loops" by identifying a loop-breaker.
117
118 2.  Avoid infinite unboxing.  This is nothing to do with newtypes.
119 Suppose we have
120         data T = MkT Int T
121         f (MkT x t) = f t
122 Well, this function diverges, but we don't want the strictness analyser
123 to diverge.  But the strictness analyser will diverge because it looks
124 deeper and deeper into the structure of T.   (I believe there are
125 examples where the function does something sane, and the strictness
126 analyser still diverges, but I can't see one now.)
127
128 Now, concerning (1), the FC2 branch currently adds a coercion for ALL
129 newtypes.  I did this as an experiment, to try to expose cases in which
130 the coercions got in the way of optimisations.  If it turns out that we
131 can indeed always use a coercion, then we don't risk recursive types,
132 and don't need to figure out what the loop breakers are.
133
134 For newtype *families* though, we will always have a coercion, so they
135 are always loop breakers!  So you can easily adjust the current
136 algorithm by simply treating all newtype families as loop breakers (and
137 indeed type families).  I think.
138
139 \begin{code}
140 tcTyAndClassDecls :: ModDetails -> [LTyClDecl Name]
141                    -> TcM (TcGblEnv,         -- Input env extended by types and classes 
142                                              -- and their implicit Ids,DataCons
143                            HsValBinds Name)  -- Renamed bindings for record selectors
144 -- Fails if there are any errors
145
146 tcTyAndClassDecls boot_details allDecls
147   = checkNoErrs $       -- The code recovers internally, but if anything gave rise to
148                         -- an error we'd better stop now, to avoid a cascade
149     do  {       -- Omit instances of type families; they are handled together
150                 -- with the *heads* of class instances
151         ; let decls = filter (not . isFamInstDecl . unLoc) allDecls
152
153                 -- First check for cyclic type synonysm or classes
154                 -- See notes with checkCycleErrs
155         ; checkCycleErrs decls
156         ; mod <- getModule
157         ; traceTc (text "tcTyAndCl" <+> ppr mod)
158         ; (syn_tycons, alg_tyclss) <- fixM (\ ~(_rec_syn_tycons, rec_alg_tyclss) ->
159           do    { let { -- Seperate ordinary synonyms from all other type and
160                         -- class declarations and add all associated type
161                         -- declarations from type classes.  The latter is
162                         -- required so that the temporary environment for the
163                         -- knot includes all associated family declarations.
164                       ; (syn_decls, alg_decls) = partition (isSynDecl . unLoc)
165                                                    decls
166                       ; alg_at_decls           = concatMap addATs alg_decls
167                       }
168                         -- Extend the global env with the knot-tied results
169                         -- for data types and classes
170                         -- 
171                         -- We must populate the environment with the loop-tied
172                         -- T's right away, because the kind checker may "fault
173                         -- in" some type  constructors that recursively
174                         -- mention T
175                 ; let gbl_things = mkGlobalThings alg_at_decls rec_alg_tyclss
176                 ; tcExtendRecEnv gbl_things $ do
177
178                         -- Kind-check the declarations
179                 { (kc_syn_decls, kc_alg_decls) <- kcTyClDecls syn_decls alg_decls
180
181                 ; let { -- Calculate rec-flag
182                       ; calc_rec  = calcRecFlags boot_details rec_alg_tyclss
183                       ; tc_decl   = addLocM (tcTyClDecl calc_rec) }
184
185                         -- Type-check the type synonyms, and extend the envt
186                 ; syn_tycons <- tcSynDecls kc_syn_decls
187                 ; tcExtendGlobalEnv syn_tycons $ do
188
189                         -- Type-check the data types and classes
190                 { alg_tyclss <- mapM tc_decl kc_alg_decls
191                 ; return (syn_tycons, concat alg_tyclss)
192             }}})
193         -- Finished with knot-tying now
194         -- Extend the environment with the finished things
195         ; tcExtendGlobalEnv (syn_tycons ++ alg_tyclss) $ do
196
197         -- Perform the validity check
198         { traceTc (text "ready for validity check")
199         ; mapM_ (addLocM checkValidTyCl) decls
200         ; traceTc (text "done")
201    
202         -- Add the implicit things;
203         -- we want them in the environment because 
204         -- they may be mentioned in interface files
205         -- NB: All associated types and their implicit things will be added a
206         --     second time here.  This doesn't matter as the definitions are
207         --     the same.
208         ; let { implicit_things = concatMap implicitTyThings alg_tyclss
209               ; aux_binds       = mkAuxBinds alg_tyclss }
210         ; traceTc ((text "Adding" <+> ppr alg_tyclss) 
211                    $$ (text "and" <+> ppr implicit_things))
212         ; env <- tcExtendGlobalEnv implicit_things getGblEnv
213         ; return (env, aux_binds) }
214     }
215   where
216     -- Pull associated types out of class declarations, to tie them into the
217     -- knot above.  
218     -- NB: We put them in the same place in the list as `tcTyClDecl' will
219     --     eventually put the matching `TyThing's.  That's crucial; otherwise,
220     --     the two argument lists of `mkGlobalThings' don't match up.
221     addATs decl@(L _ (ClassDecl {tcdATs = ats})) = decl : ats
222     addATs decl                                  = [decl]
223
224 mkGlobalThings :: [LTyClDecl Name]      -- The decls
225                -> [TyThing]             -- Knot-tied, in 1-1 correspondence with the decls
226                -> [(Name,TyThing)]
227 -- Driven by the Decls, and treating the TyThings lazily
228 -- make a TypeEnv for the new things
229 mkGlobalThings decls things
230   = map mk_thing (decls `zipLazy` things)
231   where
232     mk_thing (L _ (ClassDecl {tcdLName = L _ name}), ~(AClass cl))
233          = (name, AClass cl)
234     mk_thing (L _ decl, ~(ATyCon tc))
235          = (tcdName decl, ATyCon tc)
236 \end{code}
237
238
239 %************************************************************************
240 %*                                                                      *
241                Type checking family instances
242 %*                                                                      *
243 %************************************************************************
244
245 Family instances are somewhat of a hybrid.  They are processed together with
246 class instance heads, but can contain data constructors and hence they share a
247 lot of kinding and type checking code with ordinary algebraic data types (and
248 GADTs).
249
250 \begin{code}
251 tcFamInstDecl :: LTyClDecl Name -> TcM TyThing
252 tcFamInstDecl (L loc decl)
253   =     -- Prime error recovery, set source location
254     setSrcSpan loc                              $
255     tcAddDeclCtxt decl                          $
256     do { -- type families require -XTypeFamilies and can't be in an
257          -- hs-boot file
258        ; type_families <- doptM Opt_TypeFamilies
259        ; is_boot  <- tcIsHsBoot   -- Are we compiling an hs-boot file?
260        ; checkTc type_families $ badFamInstDecl (tcdLName decl)
261        ; checkTc (not is_boot) $ badBootFamInstDeclErr
262
263          -- Perform kind and type checking
264        ; tc <- tcFamInstDecl1 decl
265        ; checkValidTyCon tc     -- Remember to check validity;
266                                 -- no recursion to worry about here
267        ; return (ATyCon tc) }
268
269 tcFamInstDecl1 :: TyClDecl Name -> TcM TyCon
270
271   -- "type instance"
272 tcFamInstDecl1 (decl@TySynonym {tcdLName = L loc tc_name})
273   = kcIdxTyPats decl $ \k_tvs k_typats resKind family ->
274     do { -- check that the family declaration is for a synonym
275          unless (isSynTyCon family) $
276            addErr (wrongKindOfFamily family)
277
278        ; -- (1) kind check the right-hand side of the type equation
279        ; k_rhs <- kcCheckLHsType (tcdSynRhs decl) resKind
280
281          -- we need the exact same number of type parameters as the family
282          -- declaration 
283        ; let famArity = tyConArity family
284        ; checkTc (length k_typats == famArity) $ 
285            wrongNumberOfParmsErr famArity
286
287          -- (2) type check type equation
288        ; tcTyVarBndrs k_tvs $ \t_tvs -> do {  -- turn kinded into proper tyvars
289        ; t_typats <- mapM tcHsKindedType k_typats
290        ; t_rhs    <- tcHsKindedType k_rhs
291
292          -- (3) check the well-formedness of the instance
293        ; checkValidTypeInst t_typats t_rhs
294
295          -- (4) construct representation tycon
296        ; rep_tc_name <- newFamInstTyConName tc_name loc
297        ; buildSynTyCon rep_tc_name t_tvs (SynonymTyCon t_rhs) 
298                        (typeKind t_rhs) (Just (family, t_typats))
299        }}
300
301   -- "newtype instance" and "data instance"
302 tcFamInstDecl1 (decl@TyData {tcdND = new_or_data, tcdLName = L loc tc_name,
303                              tcdCons = cons})
304   = kcIdxTyPats decl $ \k_tvs k_typats resKind fam_tycon ->
305     do { -- check that the family declaration is for the right kind
306          unless (isAlgTyCon fam_tycon) $
307            addErr (wrongKindOfFamily fam_tycon)
308
309        ; -- (1) kind check the data declaration as usual
310        ; k_decl <- kcDataDecl decl k_tvs
311        ; let k_ctxt = tcdCtxt k_decl
312              k_cons = tcdCons k_decl
313
314          -- result kind must be '*' (otherwise, we have too few patterns)
315        ; checkTc (isLiftedTypeKind resKind) $ tooFewParmsErr (tyConArity fam_tycon)
316
317          -- (2) type check indexed data type declaration
318        ; tcTyVarBndrs k_tvs $ \t_tvs -> do {  -- turn kinded into proper tyvars
319        ; unbox_strict <- doptM Opt_UnboxStrictFields
320
321          -- kind check the type indexes and the context
322        ; t_typats     <- mapM tcHsKindedType k_typats
323        ; stupid_theta <- tcHsKindedContext k_ctxt
324
325          -- (3) Check that
326          --     (a) left-hand side contains no type family applications
327          --         (vanilla synonyms are fine, though, and we checked for
328          --         foralls earlier)
329        ; mapM_ checkTyFamFreeness t_typats
330
331          -- Check that we don't use GADT syntax in H98 world
332        ; gadt_ok <- doptM Opt_GADTs
333        ; checkTc (gadt_ok || consUseH98Syntax cons) (badGadtDecl tc_name)
334
335          --     (b) a newtype has exactly one constructor
336        ; checkTc (new_or_data == DataType || isSingleton k_cons) $
337                  newtypeConError tc_name (length k_cons)
338
339          -- (4) construct representation tycon
340        ; rep_tc_name <- newFamInstTyConName tc_name loc
341        ; let ex_ok = True       -- Existentials ok for type families!
342        ; fixM (\ rep_tycon -> do 
343              { let orig_res_ty = mkTyConApp fam_tycon t_typats
344              ; data_cons <- tcConDecls unbox_strict ex_ok rep_tycon
345                                        (t_tvs, orig_res_ty) k_cons
346              ; tc_rhs <-
347                  case new_or_data of
348                    DataType -> return (mkDataTyConRhs data_cons)
349                    NewType  -> ASSERT( not (null data_cons) )
350                                mkNewTyConRhs rep_tc_name rep_tycon (head data_cons)
351              ; buildAlgTyCon rep_tc_name t_tvs stupid_theta tc_rhs Recursive
352                              False h98_syntax (Just (fam_tycon, t_typats))
353                  -- We always assume that indexed types are recursive.  Why?
354                  -- (1) Due to their open nature, we can never be sure that a
355                  -- further instance might not introduce a new recursive
356                  -- dependency.  (2) They are always valid loop breakers as
357                  -- they involve a coercion.
358              })
359        }}
360        where
361          h98_syntax = case cons of      -- All constructors have same shape
362                         L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
363                         _ -> True
364
365 tcFamInstDecl1 d = pprPanic "tcFamInstDecl1" (ppr d)
366
367 -- Kind checking of indexed types
368 -- -
369
370 -- Kind check type patterns and kind annotate the embedded type variables.
371 --
372 -- * Here we check that a type instance matches its kind signature, but we do
373 --   not check whether there is a pattern for each type index; the latter
374 --   check is only required for type synonym instances.
375
376 kcIdxTyPats :: TyClDecl Name
377             -> ([LHsTyVarBndr Name] -> [LHsType Name] -> Kind -> TyCon -> TcM a)
378                -- ^^kinded tvs         ^^kinded ty pats  ^^res kind
379             -> TcM a
380 kcIdxTyPats decl thing_inside
381   = kcHsTyVars (tcdTyVars decl) $ \tvs -> 
382     do { fam_tycon <- tcLookupLocatedTyCon (tcdLName decl)
383        ; let { (kinds, resKind) = splitKindFunTys (tyConKind fam_tycon)
384              ; hs_typats        = fromJust $ tcdTyPats decl }
385
386          -- we may not have more parameters than the kind indicates
387        ; checkTc (length kinds >= length hs_typats) $
388            tooManyParmsErr (tcdLName decl)
389
390          -- type functions can have a higher-kinded result
391        ; let resultKind = mkArrowKinds (drop (length hs_typats) kinds) resKind
392        ; typats <- zipWithM kcCheckLHsType hs_typats kinds
393        ; thing_inside tvs typats resultKind fam_tycon
394        }
395   where
396 \end{code}
397
398
399 %************************************************************************
400 %*                                                                      *
401                 Kind checking
402 %*                                                                      *
403 %************************************************************************
404
405 We need to kind check all types in the mutually recursive group
406 before we know the kind of the type variables.  For example:
407
408 class C a where
409    op :: D b => a -> b -> b
410
411 class D c where
412    bop :: (Monad c) => ...
413
414 Here, the kind of the locally-polymorphic type variable "b"
415 depends on *all the uses of class D*.  For example, the use of
416 Monad c in bop's type signature means that D must have kind Type->Type.
417
418 However type synonyms work differently.  They can have kinds which don't
419 just involve (->) and *:
420         type R = Int#           -- Kind #
421         type S a = Array# a     -- Kind * -> #
422         type T a b = (# a,b #)  -- Kind * -> * -> (# a,b #)
423 So we must infer their kinds from their right-hand sides *first* and then
424 use them, whereas for the mutually recursive data types D we bring into
425 scope kind bindings D -> k, where k is a kind variable, and do inference.
426
427 Type families
428 ~~~~~~~~~~~~~
429 This treatment of type synonyms only applies to Haskell 98-style synonyms.
430 General type functions can be recursive, and hence, appear in `alg_decls'.
431
432 The kind of a type family is solely determinded by its kind signature;
433 hence, only kind signatures participate in the construction of the initial
434 kind environment (as constructed by `getInitialKind').  In fact, we ignore
435 instances of families altogether in the following.  However, we need to
436 include the kinds of associated families into the construction of the
437 initial kind environment.  (This is handled by `allDecls').
438
439 \begin{code}
440 kcTyClDecls :: [LTyClDecl Name] -> [Located (TyClDecl Name)]
441             -> TcM ([LTyClDecl Name], [Located (TyClDecl Name)])
442 kcTyClDecls syn_decls alg_decls
443   = do  {       -- First extend the kind env with each data type, class, and
444                 -- indexed type, mapping them to a type variable
445           let initialKindDecls = concat [allDecls decl | L _ decl <- alg_decls]
446         ; alg_kinds <- mapM getInitialKind initialKindDecls
447         ; tcExtendKindEnv alg_kinds $ do
448
449                 -- Now kind-check the type synonyms, in dependency order
450                 -- We do these differently to data type and classes,
451                 -- because a type synonym can be an unboxed type
452                 --      type Foo = Int#
453                 -- and a kind variable can't unify with UnboxedTypeKind
454                 -- So we infer their kinds in dependency order
455         { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
456         ; tcExtendKindEnv syn_kinds $  do
457
458                 -- Now kind-check the data type, class, and kind signatures,
459                 -- returning kind-annotated decls; we don't kind-check
460                 -- instances of indexed types yet, but leave this to
461                 -- `tcInstDecls1'
462         { kc_alg_decls <- mapM (wrapLocM kcTyClDecl)
463                             (filter (not . isFamInstDecl . unLoc) alg_decls)
464
465         ; return (kc_syn_decls, kc_alg_decls) }}}
466   where
467     -- get all declarations relevant for determining the initial kind
468     -- environment
469     allDecls (decl@ClassDecl {tcdATs = ats}) = decl : [ at 
470                                                       | L _ at <- ats
471                                                       , isFamilyDecl at]
472     allDecls decl | isFamInstDecl decl = []
473                   | otherwise          = [decl]
474
475 ------------------------------------------------------------------------
476 getInitialKind :: TyClDecl Name -> TcM (Name, TcKind)
477 -- Only for data type, class, and indexed type declarations
478 -- Get as much info as possible from the data, class, or indexed type decl,
479 -- so as to maximise usefulness of error messages
480 getInitialKind decl
481   = do  { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
482         ; res_kind  <- mk_res_kind decl
483         ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
484   where
485     mk_arg_kind (UserTyVar _)        = newKindVar
486     mk_arg_kind (KindedTyVar _ kind) = return kind
487
488     mk_res_kind (TyFamily { tcdKind    = Just kind }) = return kind
489     mk_res_kind (TyData   { tcdKindSig = Just kind }) = return kind
490         -- On GADT-style declarations we allow a kind signature
491         --      data T :: *->* where { ... }
492     mk_res_kind _ = return liftedTypeKind
493
494
495 ----------------
496 kcSynDecls :: [SCC (LTyClDecl Name)] 
497            -> TcM ([LTyClDecl Name],    -- Kind-annotated decls
498                    [(Name,TcKind)])     -- Kind bindings
499 kcSynDecls []
500   = return ([], [])
501 kcSynDecls (group : groups)
502   = do  { (decl,  nk)  <- kcSynDecl group
503         ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
504         ; return (decl:decls, nk:nks) }
505                         
506 ----------------
507 kcSynDecl :: SCC (LTyClDecl Name) 
508            -> TcM (LTyClDecl Name,      -- Kind-annotated decls
509                    (Name,TcKind))       -- Kind bindings
510 kcSynDecl (AcyclicSCC (L loc decl))
511   = tcAddDeclCtxt decl  $
512     kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
513     do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl)) 
514                         <+> brackets (ppr k_tvs))
515        ; (k_rhs, rhs_kind) <- kcLHsType (tcdSynRhs decl)
516        ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
517        ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
518        ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
519                  (unLoc (tcdLName decl), tc_kind)) })
520
521 kcSynDecl (CyclicSCC decls)
522   = do { recSynErr decls; failM }       -- Fail here to avoid error cascade
523                                         -- of out-of-scope tycons
524
525 kindedTyVarKind :: LHsTyVarBndr Name -> Kind
526 kindedTyVarKind (L _ (KindedTyVar _ k)) = k
527 kindedTyVarKind x = pprPanic "kindedTyVarKind" (ppr x)
528
529 ------------------------------------------------------------------------
530 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
531         -- Not used for type synonyms (see kcSynDecl)
532
533 kcTyClDecl decl@(TyData {})
534   = ASSERT( not . isFamInstDecl $ decl )   -- must not be a family instance
535     kcTyClDeclBody decl $
536       kcDataDecl decl
537
538 kcTyClDecl decl@(TyFamily {})
539   = kcFamilyDecl [] decl      -- the empty list signals a toplevel decl      
540
541 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs, tcdATs = ats})
542   = kcTyClDeclBody decl $ \ tvs' ->
543     do  { ctxt' <- kcHsContext ctxt     
544         ; ats'  <- mapM (wrapLocM (kcFamilyDecl tvs')) ats
545         ; sigs' <- mapM (wrapLocM kc_sig) sigs
546         ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs',
547                         tcdATs = ats'}) }
548   where
549     kc_sig (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
550                                    ; return (TypeSig nm op_ty') }
551     kc_sig other_sig          = return other_sig
552
553 kcTyClDecl decl@(ForeignType {})
554   = return decl
555
556 kcTyClDecl (TySynonym {}) = panic "kcTyClDecl TySynonym"
557
558 kcTyClDeclBody :: TyClDecl Name
559                -> ([LHsTyVarBndr Name] -> TcM a)
560                -> TcM a
561 -- getInitialKind has made a suitably-shaped kind for the type or class
562 -- Unpack it, and attribute those kinds to the type variables
563 -- Extend the env with bindings for the tyvars, taken from
564 -- the kind of the tycon/class.  Give it to the thing inside, and 
565 -- check the result kind matches
566 kcTyClDeclBody decl thing_inside
567   = tcAddDeclCtxt decl          $
568     do  { tc_ty_thing <- tcLookupLocated (tcdLName decl)
569         ; let tc_kind    = case tc_ty_thing of
570                            AThing k -> k
571                            _ -> pprPanic "kcTyClDeclBody" (ppr tc_ty_thing)
572               (kinds, _) = splitKindFunTys tc_kind
573               hs_tvs     = tcdTyVars decl
574               kinded_tvs = ASSERT( length kinds >= length hs_tvs )
575                            [ L loc (KindedTyVar (hsTyVarName tv) k)
576                            | (L loc tv, k) <- zip hs_tvs kinds]
577         ; tcExtendKindEnvTvs kinded_tvs (thing_inside kinded_tvs) }
578
579 -- Kind check a data declaration, assuming that we already extended the
580 -- kind environment with the type variables of the left-hand side (these
581 -- kinded type variables are also passed as the second parameter).
582 --
583 kcDataDecl :: TyClDecl Name -> [LHsTyVarBndr Name] -> TcM (TyClDecl Name)
584 kcDataDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
585            tvs
586   = do  { ctxt' <- kcHsContext ctxt     
587         ; cons' <- mapM (wrapLocM kc_con_decl) cons
588         ; return (decl {tcdTyVars = tvs, tcdCtxt = ctxt', tcdCons = cons'}) }
589   where
590     -- doc comments are typechecked to Nothing here
591     kc_con_decl (ConDecl name expl ex_tvs ex_ctxt details res _) 
592       = addErrCtxt (dataConCtxt name)   $ 
593         kcHsTyVars ex_tvs $ \ex_tvs' -> do
594         do { ex_ctxt' <- kcHsContext ex_ctxt
595            ; details' <- kc_con_details details 
596            ; res'     <- case res of
597                 ResTyH98 -> return ResTyH98
598                 ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
599            ; return (ConDecl name expl ex_tvs' ex_ctxt' details' res' Nothing) }
600
601     kc_con_details (PrefixCon btys) 
602         = do { btys' <- mapM kc_larg_ty btys 
603              ; return (PrefixCon btys') }
604     kc_con_details (InfixCon bty1 bty2) 
605         = do { bty1' <- kc_larg_ty bty1
606              ; bty2' <- kc_larg_ty bty2
607              ; return (InfixCon bty1' bty2') }
608     kc_con_details (RecCon fields) 
609         = do { fields' <- mapM kc_field fields
610              ; return (RecCon fields') }
611
612     kc_field (ConDeclField fld bty d) = do { bty' <- kc_larg_ty bty
613                                            ; return (ConDeclField fld bty' d) }
614
615     kc_larg_ty bty = case new_or_data of
616                         DataType -> kcHsSigType bty
617                         NewType  -> kcHsLiftedSigType bty
618         -- Can't allow an unlifted type for newtypes, because we're effectively
619         -- going to remove the constructor while coercing it to a lifted type.
620         -- And newtypes can't be bang'd
621 kcDataDecl d _ = pprPanic "kcDataDecl" (ppr d)
622
623 -- Kind check a family declaration or type family default declaration.
624 --
625 kcFamilyDecl :: [LHsTyVarBndr Name]  -- tyvars of enclosing class decl if any
626              -> TyClDecl Name -> TcM (TyClDecl Name)
627 kcFamilyDecl classTvs decl@(TyFamily {tcdKind = kind})
628   = kcTyClDeclBody decl $ \tvs' ->
629     do { mapM_ unifyClassParmKinds tvs'
630        ; return (decl {tcdTyVars = tvs', 
631                        tcdKind = kind `mplus` Just liftedTypeKind})
632                        -- default result kind is '*'
633        }
634   where
635     unifyClassParmKinds (L _ (KindedTyVar n k))
636       | Just classParmKind <- lookup n classTyKinds = unifyKind k classParmKind
637       | otherwise                                   = return ()
638     unifyClassParmKinds x = pprPanic "kcFamilyDecl/unifyClassParmKinds" (ppr x)
639     classTyKinds = [(n, k) | L _ (KindedTyVar n k) <- classTvs]
640 kcFamilyDecl _ (TySynonym {})              -- type family defaults
641   = panic "TcTyClsDecls.kcFamilyDecl: not implemented yet"
642 kcFamilyDecl _ d = pprPanic "kcFamilyDecl" (ppr d)
643 \end{code}
644
645
646 %************************************************************************
647 %*                                                                      *
648 \subsection{Type checking}
649 %*                                                                      *
650 %************************************************************************
651
652 \begin{code}
653 tcSynDecls :: [LTyClDecl Name] -> TcM [TyThing]
654 tcSynDecls [] = return []
655 tcSynDecls (decl : decls) 
656   = do { syn_tc <- addLocM tcSynDecl decl
657        ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls decls)
658        ; return (syn_tc : syn_tcs) }
659
660   -- "type"
661 tcSynDecl :: TyClDecl Name -> TcM TyThing
662 tcSynDecl
663   (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
664   = tcTyVarBndrs tvs            $ \ tvs' -> do 
665     { traceTc (text "tcd1" <+> ppr tc_name) 
666     ; rhs_ty' <- tcHsKindedType rhs_ty
667     ; tycon <- buildSynTyCon tc_name tvs' (SynonymTyCon rhs_ty') 
668                              (typeKind rhs_ty') Nothing
669     ; return (ATyCon tycon) 
670     }
671 tcSynDecl d = pprPanic "tcSynDecl" (ppr d)
672
673 --------------------
674 tcTyClDecl :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
675
676 tcTyClDecl calc_isrec decl
677   = tcAddDeclCtxt decl (tcTyClDecl1 calc_isrec decl)
678
679   -- "type family" declarations
680 tcTyClDecl1 :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
681 tcTyClDecl1 _calc_isrec 
682   (TyFamily {tcdFlavour = TypeFamily, 
683              tcdLName = L _ tc_name, tcdTyVars = tvs,
684              tcdKind = Just kind}) -- NB: kind at latest added during kind checking
685   = tcTyVarBndrs tvs  $ \ tvs' -> do 
686   { traceTc (text "type family: " <+> ppr tc_name) 
687
688         -- Check that we don't use families without -XTypeFamilies
689   ; idx_tys <- doptM Opt_TypeFamilies
690   ; checkTc idx_tys $ badFamInstDecl tc_name
691
692         -- Check for no type indices
693   ; checkTc (not (null tvs)) (noIndexTypes tc_name)
694
695   ; tycon <- buildSynTyCon tc_name tvs' (OpenSynTyCon kind Nothing) kind Nothing
696   ; return [ATyCon tycon]
697   }
698
699   -- "data family" declaration
700 tcTyClDecl1 _calc_isrec 
701   (TyFamily {tcdFlavour = DataFamily, 
702              tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = mb_kind})
703   = tcTyVarBndrs tvs  $ \ tvs' -> do 
704   { traceTc (text "data family: " <+> ppr tc_name) 
705   ; extra_tvs <- tcDataKindSig mb_kind
706   ; let final_tvs = tvs' ++ extra_tvs    -- we may not need these
707
708
709         -- Check that we don't use families without -XTypeFamilies
710   ; idx_tys <- doptM Opt_TypeFamilies
711   ; checkTc idx_tys $ badFamInstDecl tc_name
712
713         -- Check for no type indices
714   ; checkTc (not (null tvs)) (noIndexTypes tc_name)
715
716   ; tycon <- buildAlgTyCon tc_name final_tvs [] 
717                mkOpenDataTyConRhs Recursive False True Nothing
718   ; return [ATyCon tycon]
719   }
720
721   -- "newtype" and "data"
722   -- NB: not used for newtype/data instances (whether associated or not)
723 tcTyClDecl1 calc_isrec
724   (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
725            tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
726   = tcTyVarBndrs tvs    $ \ tvs' -> do 
727   { extra_tvs <- tcDataKindSig mb_ksig
728   ; let final_tvs = tvs' ++ extra_tvs
729   ; stupid_theta <- tcHsKindedContext ctxt
730   ; want_generic <- doptM Opt_Generics
731   ; unbox_strict <- doptM Opt_UnboxStrictFields
732   ; empty_data_decls <- doptM Opt_EmptyDataDecls
733   ; kind_signatures <- doptM Opt_KindSignatures
734   ; existential_ok <- doptM Opt_ExistentialQuantification
735   ; gadt_ok      <- doptM Opt_GADTs
736   ; is_boot      <- tcIsHsBoot  -- Are we compiling an hs-boot file?
737   ; let ex_ok = existential_ok || gadt_ok       -- Data cons can have existential context
738
739         -- Check that we don't use GADT syntax in H98 world
740   ; checkTc (gadt_ok || h98_syntax) (badGadtDecl tc_name)
741
742         -- Check that we don't use kind signatures without Glasgow extensions
743   ; checkTc (kind_signatures || isNothing mb_ksig) (badSigTyDecl tc_name)
744
745         -- Check that the stupid theta is empty for a GADT-style declaration
746   ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
747
748         -- Check that a newtype has exactly one constructor
749         -- Do this before checking for empty data decls, so that
750         -- we don't suggest -XEmptyDataDecls for newtypes
751   ; checkTc (new_or_data == DataType || isSingleton cons) 
752             (newtypeConError tc_name (length cons))
753
754         -- Check that there's at least one condecl,
755         -- or else we're reading an hs-boot file, or -XEmptyDataDecls
756   ; checkTc (not (null cons) || empty_data_decls || is_boot)
757             (emptyConDeclsErr tc_name)
758     
759   ; tycon <- fixM (\ tycon -> do 
760         { let res_ty = mkTyConApp tycon (mkTyVarTys final_tvs)
761         ; data_cons <- tcConDecls unbox_strict ex_ok 
762                                   tycon (final_tvs, res_ty) cons
763         ; tc_rhs <-
764             if null cons && is_boot     -- In a hs-boot file, empty cons means
765             then return AbstractTyCon   -- "don't know"; hence Abstract
766             else case new_or_data of
767                    DataType -> return (mkDataTyConRhs data_cons)
768                    NewType  -> ASSERT( not (null data_cons) )
769                                mkNewTyConRhs tc_name tycon (head data_cons)
770         ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
771             (want_generic && canDoGenerics data_cons) h98_syntax Nothing
772         })
773   ; return [ATyCon tycon]
774   }
775   where
776     is_rec   = calc_isrec tc_name
777     h98_syntax = consUseH98Syntax cons
778
779 tcTyClDecl1 calc_isrec 
780   (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs, 
781               tcdCtxt = ctxt, tcdMeths = meths,
782               tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
783   = tcTyVarBndrs tvs            $ \ tvs' -> do 
784   { ctxt' <- tcHsKindedContext ctxt
785   ; fds' <- mapM (addLocM tc_fundep) fundeps
786   ; atss <- mapM (addLocM (tcTyClDecl1 (const Recursive))) ats
787             -- NB: 'ats' only contains "type family" and "data family"
788             --     declarations as well as type family defaults
789   ; let ats' = map (setAssocFamilyPermutation tvs') (concat atss)
790   ; sig_stuff <- tcClassSigs class_name sigs meths
791   ; clas <- fixM (\ clas ->
792                 let     -- This little knot is just so we can get
793                         -- hold of the name of the class TyCon, which we
794                         -- need to look up its recursiveness
795                     tycon_name = tyConName (classTyCon clas)
796                     tc_isrec = calc_isrec tycon_name
797                 in
798                 buildClass False {- Must include unfoldings for selectors -}
799                            class_name tvs' ctxt' fds' ats'
800                            sig_stuff tc_isrec)
801   ; return (AClass clas : ats')
802       -- NB: Order is important due to the call to `mkGlobalThings' when
803       --     tying the the type and class declaration type checking knot.
804   }
805   where
806     tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM tcLookupTyVar tvs1 ;
807                                 ; tvs2' <- mapM tcLookupTyVar tvs2 ;
808                                 ; return (tvs1', tvs2') }
809
810 tcTyClDecl1 _
811   (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
812   = return [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
813
814 tcTyClDecl1 _ d = pprPanic "tcTyClDecl1" (ppr d)
815
816 -----------------------------------
817 tcConDecls :: Bool -> Bool -> TyCon -> ([TyVar], Type)
818            -> [LConDecl Name] -> TcM [DataCon]
819 tcConDecls unbox ex_ok rep_tycon res_tmpl cons
820   = mapM (addLocM (tcConDecl unbox ex_ok rep_tycon res_tmpl)) cons
821
822 tcConDecl :: Bool               -- True <=> -funbox-strict_fields
823           -> Bool               -- True <=> -XExistentialQuantificaton or -XGADTs
824           -> TyCon              -- Representation tycon
825           -> ([TyVar], Type)    -- Return type template (with its template tyvars)
826           -> ConDecl Name 
827           -> TcM DataCon
828
829 tcConDecl unbox_strict existential_ok rep_tycon res_tmpl        -- Data types
830           (ConDecl name _ tvs ctxt details res_ty _)
831   = addErrCtxt (dataConCtxt name)       $ 
832     tcTyVarBndrs tvs                    $ \ tvs' -> do 
833     { ctxt' <- tcHsKindedContext ctxt
834     ; checkTc (existential_ok || (null tvs && null (unLoc ctxt)))
835               (badExistential name)
836     ; (univ_tvs, ex_tvs, eq_preds, res_ty') <- tcResultType res_tmpl tvs' res_ty
837     ; let 
838         tc_datacon is_infix field_lbls btys
839           = do { (arg_tys, stricts) <- mapAndUnzipM (tcConArg unbox_strict) btys
840                ; buildDataCon (unLoc name) is_infix
841                     stricts field_lbls
842                     univ_tvs ex_tvs eq_preds ctxt' arg_tys
843                     res_ty' rep_tycon }
844                 -- NB:  we put data_tc, the type constructor gotten from the
845                 --      constructor type signature into the data constructor;
846                 --      that way checkValidDataCon can complain if it's wrong.
847
848     ; case details of
849         PrefixCon btys     -> tc_datacon False [] btys
850         InfixCon bty1 bty2 -> tc_datacon True  [] [bty1,bty2]
851         RecCon fields      -> tc_datacon False field_names btys
852                            where
853                               field_names = map (unLoc . cd_fld_name) fields
854                               btys        = map cd_fld_type fields
855     }
856
857 -- Example
858 --   data instance T (b,c) where 
859 --      TI :: forall e. e -> T (e,e)
860 --
861 -- The representation tycon looks like this:
862 --   data :R7T b c where 
863 --      TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
864 -- In this case orig_res_ty = T (e,e)
865
866 tcResultType :: ([TyVar], Type) -- Template for result type; e.g.
867                                 -- data instance T [a] b c = ...  
868                                 --      gives template ([a,b,c], T [a] b c)
869              -> [TyVar]         -- where MkT :: forall x y z. ...
870              -> ResType Name
871              -> TcM ([TyVar],           -- Universal
872                      [TyVar],           -- Existential (distinct OccNames from univs)
873                      [(TyVar,Type)],    -- Equality predicates
874                      Type)              -- Typechecked return type
875         -- We don't check that the TyCon given in the ResTy is
876         -- the same as the parent tycon, becuase we are in the middle
877         -- of a recursive knot; so it's postponed until checkValidDataCon
878
879 tcResultType (tmpl_tvs, res_ty) dc_tvs ResTyH98
880   = return (tmpl_tvs, dc_tvs, [], res_ty)
881         -- In H98 syntax the dc_tvs are the existential ones
882         --      data T a b c = forall d e. MkT ...
883         -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
884
885 tcResultType (tmpl_tvs, res_tmpl) dc_tvs (ResTyGADT res_ty)
886         -- E.g.  data T [a] b c where
887         --         MkT :: forall x y z. T [(x,y)] z z
888         -- Then we generate
889         --      Univ tyvars     Eq-spec
890         --          a              a~(x,y)
891         --          b              b~z
892         --          z              
893         -- Existentials are the leftover type vars: [x,y]
894         -- So we return ([a,b,z], [x,y], [a~(x,y),b~z], T [(x,y)] z z)
895   = do  { res_ty' <- tcHsKindedType res_ty
896         ; let Just subst = tcMatchTy (mkVarSet tmpl_tvs) res_tmpl res_ty'
897
898                 -- /Lazily/ figure out the univ_tvs etc
899                 -- Each univ_tv is either a dc_tv or a tmpl_tv
900               (univ_tvs, eq_spec) = foldr choose ([], []) tidy_tmpl_tvs
901               choose tmpl (univs, eqs)
902                 | Just ty <- lookupTyVar subst tmpl 
903                 = case tcGetTyVar_maybe ty of
904                     Just tv | not (tv `elem` univs)
905                             -> (tv:univs,   eqs)
906                     _other  -> (tmpl:univs, (tmpl,ty):eqs)
907                 | otherwise = pprPanic "tcResultType" (ppr res_ty)
908               ex_tvs = dc_tvs `minusList` univ_tvs
909
910         ; return (univ_tvs, ex_tvs, eq_spec, res_ty') }
911   where
912         -- NB: tmpl_tvs and dc_tvs are distinct, but
913         -- we want them to be *visibly* distinct, both for
914         -- interface files and general confusion.  So rename
915         -- the tc_tvs, since they are not used yet (no 
916         -- consequential renaming needed)
917     (_, tidy_tmpl_tvs) = mapAccumL tidy_one init_occ_env tmpl_tvs
918     init_occ_env       = initTidyOccEnv (map getOccName dc_tvs)
919     tidy_one env tv    = (env', setTyVarName tv (tidyNameOcc name occ'))
920               where
921                  name = tyVarName tv
922                  (env', occ') = tidyOccName env (getOccName name) 
923
924 consUseH98Syntax :: [LConDecl a] -> Bool
925 consUseH98Syntax (L _ (ConDecl { con_res = ResTyGADT _ }) : _) = False
926 consUseH98Syntax _                                             = True
927                  -- All constructors have same shape
928
929 -------------------
930 tcConArg :: Bool                -- True <=> -funbox-strict_fields
931            -> LHsType Name
932            -> TcM (TcType, StrictnessMark)
933 tcConArg unbox_strict bty
934   = do  { arg_ty <- tcHsBangType bty
935         ; let bang = getBangStrictness bty
936         ; return (arg_ty, chooseBoxingStrategy unbox_strict arg_ty bang) }
937
938 -- We attempt to unbox/unpack a strict field when either:
939 --   (i)  The field is marked '!!', or
940 --   (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
941 --
942 -- We have turned off unboxing of newtypes because coercions make unboxing 
943 -- and reboxing more complicated
944 chooseBoxingStrategy :: Bool -> TcType -> HsBang -> StrictnessMark
945 chooseBoxingStrategy unbox_strict_fields arg_ty bang
946   = case bang of
947         HsNoBang                                    -> NotMarkedStrict
948         HsStrict | unbox_strict_fields 
949                    && can_unbox arg_ty              -> MarkedUnboxed
950         HsUnbox  | can_unbox arg_ty                 -> MarkedUnboxed
951         _                                           -> MarkedStrict
952   where
953     -- we can unbox if the type is a chain of newtypes with a product tycon
954     -- at the end
955     can_unbox arg_ty = case splitTyConApp_maybe arg_ty of
956                    Nothing                      -> False
957                    Just (arg_tycon, tycon_args) -> 
958                        not (isRecursiveTyCon arg_tycon) &&      -- Note [Recusive unboxing]
959                        isProductTyCon arg_tycon &&
960                        (if isNewTyCon arg_tycon then 
961                             can_unbox (newTyConInstRhs arg_tycon tycon_args)
962                         else True)
963 \end{code}
964
965 Note [Recursive unboxing]
966 ~~~~~~~~~~~~~~~~~~~~~~~~~
967 Be careful not to try to unbox this!
968         data T = MkT !T Int
969 But it's the *argument* type that matters. This is fine:
970         data S = MkS S !Int
971 because Int is non-recursive.
972
973
974 %************************************************************************
975 %*                                                                      *
976                 Validity checking
977 %*                                                                      *
978 %************************************************************************
979
980 Validity checking is done once the mutually-recursive knot has been
981 tied, so we can look at things freely.
982
983 \begin{code}
984 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
985 checkCycleErrs tyclss
986   | null cls_cycles
987   = return ()
988   | otherwise
989   = do  { mapM_ recClsErr cls_cycles
990         ; failM }       -- Give up now, because later checkValidTyCl
991                         -- will loop if the synonym is recursive
992   where
993     cls_cycles = calcClassCycles tyclss
994
995 checkValidTyCl :: TyClDecl Name -> TcM ()
996 -- We do the validity check over declarations, rather than TyThings
997 -- only so that we can add a nice context with tcAddDeclCtxt
998 checkValidTyCl decl
999   = tcAddDeclCtxt decl $
1000     do  { thing <- tcLookupLocatedGlobal (tcdLName decl)
1001         ; traceTc (text "Validity of" <+> ppr thing)    
1002         ; case thing of
1003             ATyCon tc -> checkValidTyCon tc
1004             AClass cl -> checkValidClass cl 
1005             _ -> panic "checkValidTyCl"
1006         ; traceTc (text "Done validity of" <+> ppr thing)       
1007         }
1008
1009 -------------------------
1010 -- For data types declared with record syntax, we require
1011 -- that each constructor that has a field 'f' 
1012 --      (a) has the same result type
1013 --      (b) has the same type for 'f'
1014 -- module alpha conversion of the quantified type variables
1015 -- of the constructor.
1016 --
1017 -- Note that we allow existentials to match becuase the
1018 -- fields can never meet. E.g
1019 --      data T where
1020 --        T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
1021 --        T2 { f1 :: c, f2 :: c, f3 ::Int } :: T  
1022 -- Here we do not complain about f1,f2 because they are existential
1023
1024 checkValidTyCon :: TyCon -> TcM ()
1025 checkValidTyCon tc 
1026   | isSynTyCon tc 
1027   = case synTyConRhs tc of
1028       OpenSynTyCon _ _ -> return ()
1029       SynonymTyCon ty  -> checkValidType syn_ctxt ty
1030   | otherwise
1031   = do  -- Check the context on the data decl
1032     checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
1033         
1034         -- Check arg types of data constructors
1035     mapM_ (checkValidDataCon tc) data_cons
1036
1037         -- Check that fields with the same name share a type
1038     mapM_ check_fields groups
1039
1040   where
1041     syn_ctxt  = TySynCtxt name
1042     name      = tyConName tc
1043     data_cons = tyConDataCons tc
1044
1045     groups = equivClasses cmp_fld (concatMap get_fields data_cons)
1046     cmp_fld (f1,_) (f2,_) = f1 `compare` f2
1047     get_fields con = dataConFieldLabels con `zip` repeat con
1048         -- dataConFieldLabels may return the empty list, which is fine
1049
1050     -- See Note [GADT record selectors] in MkId.lhs
1051     -- We must check (a) that the named field has the same 
1052     --                   type in each constructor
1053     --               (b) that those constructors have the same result type
1054     --
1055     -- However, the constructors may have differently named type variable
1056     -- and (worse) we don't know how the correspond to each other.  E.g.
1057     --     C1 :: forall a b. { f :: a, g :: b } -> T a b
1058     --     C2 :: forall d c. { f :: c, g :: c } -> T c d
1059     -- 
1060     -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
1061     -- result type against other candidates' types BOTH WAYS ROUND.
1062     -- If they magically agrees, take the substitution and
1063     -- apply them to the latter ones, and see if they match perfectly.
1064     check_fields ((label, con1) : other_fields)
1065         -- These fields all have the same name, but are from
1066         -- different constructors in the data type
1067         = recoverM (return ()) $ mapM_ checkOne other_fields
1068                 -- Check that all the fields in the group have the same type
1069                 -- NB: this check assumes that all the constructors of a given
1070                 -- data type use the same type variables
1071         where
1072         (tvs1, _, _, res1) = dataConSig con1
1073         ts1 = mkVarSet tvs1
1074         fty1 = dataConFieldType con1 label
1075
1076         checkOne (_, con2)    -- Do it bothways to ensure they are structurally identical
1077             = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
1078                  ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
1079             where        
1080                 (tvs2, _, _, res2) = dataConSig con2
1081                 ts2 = mkVarSet tvs2
1082                 fty2 = dataConFieldType con2 label
1083     check_fields [] = panic "checkValidTyCon/check_fields []"
1084
1085 checkFieldCompat :: Name -> DataCon -> DataCon -> TyVarSet
1086                  -> Type -> Type -> Type -> Type -> TcM ()
1087 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
1088   = do  { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
1089         ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
1090   where
1091     mb_subst1 = tcMatchTy tvs1 res1 res2
1092     mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
1093
1094 -------------------------------
1095 checkValidDataCon :: TyCon -> DataCon -> TcM ()
1096 checkValidDataCon tc con
1097   = setSrcSpan (srcLocSpan (getSrcLoc con))     $
1098     addErrCtxt (dataConCtxt con)                $ 
1099     do  { 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 = grow 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 wrongKindOfFamily :: TyCon -> SDoc
1521 wrongKindOfFamily family =
1522   ptext (sLit "Wrong category of family instance; declaration was for a") <+>
1523   kindOfFamily
1524   where
1525     kindOfFamily | isSynTyCon family = ptext (sLit "type synonym")
1526                  | isAlgTyCon family = ptext (sLit "data type")
1527                  | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1528
1529 emptyConDeclsErr :: Name -> SDoc
1530 emptyConDeclsErr tycon
1531   = sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
1532          nest 2 $ ptext (sLit "(-XEmptyDataDecls permits this)")]
1533 \end{code}