Type synonym families may be nullary
[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) (EK resKind EkUnk)
279                   -- ToDo: the ExpKind could be better
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          checkTc (isOpenTyCon fam_tycon) (notFamily fam_tycon)
307        ; checkTc (isAlgTyCon fam_tycon) (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 { let tc_name = tcdLName decl
383        ; fam_tycon <- tcLookupLocatedTyCon tc_name
384        ; let { (kinds, resKind) = splitKindFunTys (tyConKind fam_tycon)
385              ; hs_typats        = fromJust $ tcdTyPats decl }
386
387          -- we may not have more parameters than the kind indicates
388        ; checkTc (length kinds >= length hs_typats) $
389            tooManyParmsErr (tcdLName decl)
390
391          -- type functions can have a higher-kinded result
392        ; let resultKind = mkArrowKinds (drop (length hs_typats) kinds) resKind
393        ; typats <- zipWithM kcCheckLHsType hs_typats 
394                             [ EK kind (EkArg (ppr tc_name) n) 
395                             | (kind,n) <- kinds `zip` [1..]]
396        ; thing_inside tvs typats resultKind fam_tycon
397        }
398 \end{code}
399
400
401 %************************************************************************
402 %*                                                                      *
403                 Kind checking
404 %*                                                                      *
405 %************************************************************************
406
407 We need to kind check all types in the mutually recursive group
408 before we know the kind of the type variables.  For example:
409
410 class C a where
411    op :: D b => a -> b -> b
412
413 class D c where
414    bop :: (Monad c) => ...
415
416 Here, the kind of the locally-polymorphic type variable "b"
417 depends on *all the uses of class D*.  For example, the use of
418 Monad c in bop's type signature means that D must have kind Type->Type.
419
420 However type synonyms work differently.  They can have kinds which don't
421 just involve (->) and *:
422         type R = Int#           -- Kind #
423         type S a = Array# a     -- Kind * -> #
424         type T a b = (# a,b #)  -- Kind * -> * -> (# a,b #)
425 So we must infer their kinds from their right-hand sides *first* and then
426 use them, whereas for the mutually recursive data types D we bring into
427 scope kind bindings D -> k, where k is a kind variable, and do inference.
428
429 Type families
430 ~~~~~~~~~~~~~
431 This treatment of type synonyms only applies to Haskell 98-style synonyms.
432 General type functions can be recursive, and hence, appear in `alg_decls'.
433
434 The kind of a type family is solely determinded by its kind signature;
435 hence, only kind signatures participate in the construction of the initial
436 kind environment (as constructed by `getInitialKind').  In fact, we ignore
437 instances of families altogether in the following.  However, we need to
438 include the kinds of associated families into the construction of the
439 initial kind environment.  (This is handled by `allDecls').
440
441 \begin{code}
442 kcTyClDecls :: [LTyClDecl Name] -> [Located (TyClDecl Name)]
443             -> TcM ([LTyClDecl Name], [Located (TyClDecl Name)])
444 kcTyClDecls syn_decls alg_decls
445   = do  {       -- First extend the kind env with each data type, class, and
446                 -- indexed type, mapping them to a type variable
447           let initialKindDecls = concat [allDecls decl | L _ decl <- alg_decls]
448         ; alg_kinds <- mapM getInitialKind initialKindDecls
449         ; tcExtendKindEnv alg_kinds $ do
450
451                 -- Now kind-check the type synonyms, in dependency order
452                 -- We do these differently to data type and classes,
453                 -- because a type synonym can be an unboxed type
454                 --      type Foo = Int#
455                 -- and a kind variable can't unify with UnboxedTypeKind
456                 -- So we infer their kinds in dependency order
457         { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
458         ; tcExtendKindEnv syn_kinds $  do
459
460                 -- Now kind-check the data type, class, and kind signatures,
461                 -- returning kind-annotated decls; we don't kind-check
462                 -- instances of indexed types yet, but leave this to
463                 -- `tcInstDecls1'
464         { kc_alg_decls <- mapM (wrapLocM kcTyClDecl)
465                             (filter (not . isFamInstDecl . unLoc) alg_decls)
466
467         ; return (kc_syn_decls, kc_alg_decls) }}}
468   where
469     -- get all declarations relevant for determining the initial kind
470     -- environment
471     allDecls (decl@ClassDecl {tcdATs = ats}) = decl : [ at 
472                                                       | L _ at <- ats
473                                                       , isFamilyDecl at]
474     allDecls decl | isFamInstDecl decl = []
475                   | otherwise          = [decl]
476
477 ------------------------------------------------------------------------
478 getInitialKind :: TyClDecl Name -> TcM (Name, TcKind)
479 -- Only for data type, class, and indexed type declarations
480 -- Get as much info as possible from the data, class, or indexed type decl,
481 -- so as to maximise usefulness of error messages
482 getInitialKind decl
483   = do  { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
484         ; res_kind  <- mk_res_kind decl
485         ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
486   where
487     mk_arg_kind (UserTyVar _)        = newKindVar
488     mk_arg_kind (KindedTyVar _ kind) = return kind
489
490     mk_res_kind (TyFamily { tcdKind    = Just kind }) = return kind
491     mk_res_kind (TyData   { tcdKindSig = Just kind }) = return kind
492         -- On GADT-style declarations we allow a kind signature
493         --      data T :: *->* where { ... }
494     mk_res_kind _ = return liftedTypeKind
495
496
497 ----------------
498 kcSynDecls :: [SCC (LTyClDecl Name)] 
499            -> TcM ([LTyClDecl Name],    -- Kind-annotated decls
500                    [(Name,TcKind)])     -- Kind bindings
501 kcSynDecls []
502   = return ([], [])
503 kcSynDecls (group : groups)
504   = do  { (decl,  nk)  <- kcSynDecl group
505         ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
506         ; return (decl:decls, nk:nks) }
507                         
508 ----------------
509 kcSynDecl :: SCC (LTyClDecl Name) 
510            -> TcM (LTyClDecl Name,      -- Kind-annotated decls
511                    (Name,TcKind))       -- Kind bindings
512 kcSynDecl (AcyclicSCC (L loc decl))
513   = tcAddDeclCtxt decl  $
514     kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
515     do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl)) 
516                         <+> brackets (ppr k_tvs))
517        ; (k_rhs, rhs_kind) <- kcLHsType (tcdSynRhs decl)
518        ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
519        ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
520        ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
521                  (unLoc (tcdLName decl), tc_kind)) })
522
523 kcSynDecl (CyclicSCC decls)
524   = do { recSynErr decls; failM }       -- Fail here to avoid error cascade
525                                         -- of out-of-scope tycons
526
527 kindedTyVarKind :: LHsTyVarBndr Name -> Kind
528 kindedTyVarKind (L _ (KindedTyVar _ k)) = k
529 kindedTyVarKind x = pprPanic "kindedTyVarKind" (ppr x)
530
531 ------------------------------------------------------------------------
532 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
533         -- Not used for type synonyms (see kcSynDecl)
534
535 kcTyClDecl decl@(TyData {})
536   = ASSERT( not . isFamInstDecl $ decl )   -- must not be a family instance
537     kcTyClDeclBody decl $
538       kcDataDecl decl
539
540 kcTyClDecl decl@(TyFamily {})
541   = kcFamilyDecl [] decl      -- the empty list signals a toplevel decl      
542
543 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs, tcdATs = ats})
544   = kcTyClDeclBody decl $ \ tvs' ->
545     do  { ctxt' <- kcHsContext ctxt     
546         ; ats'  <- mapM (wrapLocM (kcFamilyDecl tvs')) ats
547         ; sigs' <- mapM (wrapLocM kc_sig) sigs
548         ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs',
549                         tcdATs = ats'}) }
550   where
551     kc_sig (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
552                                    ; return (TypeSig nm op_ty') }
553     kc_sig other_sig          = return other_sig
554
555 kcTyClDecl decl@(ForeignType {})
556   = return decl
557
558 kcTyClDecl (TySynonym {}) = panic "kcTyClDecl TySynonym"
559
560 kcTyClDeclBody :: TyClDecl Name
561                -> ([LHsTyVarBndr Name] -> TcM a)
562                -> TcM a
563 -- getInitialKind has made a suitably-shaped kind for the type or class
564 -- Unpack it, and attribute those kinds to the type variables
565 -- Extend the env with bindings for the tyvars, taken from
566 -- the kind of the tycon/class.  Give it to the thing inside, and 
567 -- check the result kind matches
568 kcTyClDeclBody decl thing_inside
569   = tcAddDeclCtxt decl          $
570     do  { tc_ty_thing <- tcLookupLocated (tcdLName decl)
571         ; let tc_kind    = case tc_ty_thing of
572                            AThing k -> k
573                            _ -> pprPanic "kcTyClDeclBody" (ppr tc_ty_thing)
574               (kinds, _) = splitKindFunTys tc_kind
575               hs_tvs     = tcdTyVars decl
576               kinded_tvs = ASSERT( length kinds >= length hs_tvs )
577                            [ L loc (KindedTyVar (hsTyVarName tv) k)
578                            | (L loc tv, k) <- zip hs_tvs kinds]
579         ; tcExtendKindEnvTvs kinded_tvs (thing_inside kinded_tvs) }
580
581 -- Kind check a data declaration, assuming that we already extended the
582 -- kind environment with the type variables of the left-hand side (these
583 -- kinded type variables are also passed as the second parameter).
584 --
585 kcDataDecl :: TyClDecl Name -> [LHsTyVarBndr Name] -> TcM (TyClDecl Name)
586 kcDataDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
587            tvs
588   = do  { ctxt' <- kcHsContext ctxt     
589         ; cons' <- mapM (wrapLocM kc_con_decl) cons
590         ; return (decl {tcdTyVars = tvs, tcdCtxt = ctxt', tcdCons = cons'}) }
591   where
592     -- doc comments are typechecked to Nothing here
593     kc_con_decl con_decl@(ConDecl { con_name = name, con_qvars = ex_tvs
594                                   , con_cxt = ex_ctxt, con_details = details, con_res = res })
595       = addErrCtxt (dataConCtxt name)   $ 
596         kcHsTyVars ex_tvs $ \ex_tvs' -> do
597         do { ex_ctxt' <- kcHsContext ex_ctxt
598            ; details' <- kc_con_details details 
599            ; res'     <- case res of
600                 ResTyH98 -> return ResTyH98
601                 ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
602            ; return (con_decl { con_qvars = ex_tvs', con_cxt = ex_ctxt'
603                               , con_details = details', con_res = res' }) }
604
605     kc_con_details (PrefixCon btys) 
606         = do { btys' <- mapM kc_larg_ty btys 
607              ; return (PrefixCon btys') }
608     kc_con_details (InfixCon bty1 bty2) 
609         = do { bty1' <- kc_larg_ty bty1
610              ; bty2' <- kc_larg_ty bty2
611              ; return (InfixCon bty1' bty2') }
612     kc_con_details (RecCon fields) 
613         = do { fields' <- mapM kc_field fields
614              ; return (RecCon fields') }
615
616     kc_field (ConDeclField fld bty d) = do { bty' <- kc_larg_ty bty
617                                            ; return (ConDeclField fld bty' d) }
618
619     kc_larg_ty bty = case new_or_data of
620                         DataType -> kcHsSigType bty
621                         NewType  -> kcHsLiftedSigType bty
622         -- Can't allow an unlifted type for newtypes, because we're effectively
623         -- going to remove the constructor while coercing it to a lifted type.
624         -- And newtypes can't be bang'd
625 kcDataDecl d _ = pprPanic "kcDataDecl" (ppr d)
626
627 -- Kind check a family declaration or type family default declaration.
628 --
629 kcFamilyDecl :: [LHsTyVarBndr Name]  -- tyvars of enclosing class decl if any
630              -> TyClDecl Name -> TcM (TyClDecl Name)
631 kcFamilyDecl classTvs decl@(TyFamily {tcdKind = kind})
632   = kcTyClDeclBody decl $ \tvs' ->
633     do { mapM_ unifyClassParmKinds tvs'
634        ; return (decl {tcdTyVars = tvs', 
635                        tcdKind = kind `mplus` Just liftedTypeKind})
636                        -- default result kind is '*'
637        }
638   where
639     unifyClassParmKinds (L _ (KindedTyVar n k))
640       | Just classParmKind <- lookup n classTyKinds = unifyKind k classParmKind
641       | otherwise                                   = return ()
642     unifyClassParmKinds x = pprPanic "kcFamilyDecl/unifyClassParmKinds" (ppr x)
643     classTyKinds = [(n, k) | L _ (KindedTyVar n k) <- classTvs]
644 kcFamilyDecl _ (TySynonym {})              -- type family defaults
645   = panic "TcTyClsDecls.kcFamilyDecl: not implemented yet"
646 kcFamilyDecl _ d = pprPanic "kcFamilyDecl" (ppr d)
647 \end{code}
648
649
650 %************************************************************************
651 %*                                                                      *
652 \subsection{Type checking}
653 %*                                                                      *
654 %************************************************************************
655
656 \begin{code}
657 tcSynDecls :: [LTyClDecl Name] -> TcM [TyThing]
658 tcSynDecls [] = return []
659 tcSynDecls (decl : decls) 
660   = do { syn_tc <- addLocM tcSynDecl decl
661        ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls decls)
662        ; return (syn_tc : syn_tcs) }
663
664   -- "type"
665 tcSynDecl :: TyClDecl Name -> TcM TyThing
666 tcSynDecl
667   (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
668   = tcTyVarBndrs tvs            $ \ tvs' -> do 
669     { traceTc (text "tcd1" <+> ppr tc_name) 
670     ; rhs_ty' <- tcHsKindedType rhs_ty
671     ; tycon <- buildSynTyCon tc_name tvs' (SynonymTyCon rhs_ty') 
672                              (typeKind rhs_ty') Nothing
673     ; return (ATyCon tycon) 
674     }
675 tcSynDecl d = pprPanic "tcSynDecl" (ppr d)
676
677 --------------------
678 tcTyClDecl :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
679
680 tcTyClDecl calc_isrec decl
681   = tcAddDeclCtxt decl (tcTyClDecl1 calc_isrec decl)
682
683   -- "type family" declarations
684 tcTyClDecl1 :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
685 tcTyClDecl1 _calc_isrec 
686   (TyFamily {tcdFlavour = TypeFamily, 
687              tcdLName = L _ tc_name, tcdTyVars = tvs,
688              tcdKind = Just kind}) -- NB: kind at latest added during kind checking
689   = tcTyVarBndrs tvs  $ \ tvs' -> do 
690   { traceTc (text "type family: " <+> ppr tc_name) 
691
692         -- Check that we don't use families without -XTypeFamilies
693   ; idx_tys <- doptM Opt_TypeFamilies
694   ; checkTc idx_tys $ badFamInstDecl tc_name
695
696   ; tycon <- buildSynTyCon tc_name tvs' (OpenSynTyCon kind Nothing) kind Nothing
697   ; return [ATyCon tycon]
698   }
699
700   -- "data family" declaration
701 tcTyClDecl1 _calc_isrec 
702   (TyFamily {tcdFlavour = DataFamily, 
703              tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = mb_kind})
704   = tcTyVarBndrs tvs  $ \ tvs' -> do 
705   { traceTc (text "data family: " <+> ppr tc_name) 
706   ; extra_tvs <- tcDataKindSig mb_kind
707   ; let final_tvs = tvs' ++ extra_tvs    -- we may not need these
708
709
710         -- Check that we don't use families without -XTypeFamilies
711   ; idx_tys <- doptM Opt_TypeFamilies
712   ; checkTc idx_tys $ badFamInstDecl tc_name
713
714   ; tycon <- buildAlgTyCon tc_name final_tvs [] 
715                mkOpenDataTyConRhs Recursive False True Nothing
716   ; return [ATyCon tycon]
717   }
718
719   -- "newtype" and "data"
720   -- NB: not used for newtype/data instances (whether associated or not)
721 tcTyClDecl1 calc_isrec
722   (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
723            tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
724   = tcTyVarBndrs tvs    $ \ tvs' -> do 
725   { extra_tvs <- tcDataKindSig mb_ksig
726   ; let final_tvs = tvs' ++ extra_tvs
727   ; stupid_theta <- tcHsKindedContext ctxt
728   ; want_generic <- doptM Opt_Generics
729   ; unbox_strict <- doptM Opt_UnboxStrictFields
730   ; empty_data_decls <- doptM Opt_EmptyDataDecls
731   ; kind_signatures <- doptM Opt_KindSignatures
732   ; existential_ok <- doptM Opt_ExistentialQuantification
733   ; gadt_ok      <- doptM Opt_GADTs
734   ; is_boot      <- tcIsHsBoot  -- Are we compiling an hs-boot file?
735   ; let ex_ok = existential_ok || gadt_ok       -- Data cons can have existential context
736
737         -- Check that we don't use GADT syntax in H98 world
738   ; checkTc (gadt_ok || h98_syntax) (badGadtDecl tc_name)
739
740         -- Check that we don't use kind signatures without Glasgow extensions
741   ; checkTc (kind_signatures || isNothing mb_ksig) (badSigTyDecl tc_name)
742
743         -- Check that the stupid theta is empty for a GADT-style declaration
744   ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
745
746         -- Check that a newtype has exactly one constructor
747         -- Do this before checking for empty data decls, so that
748         -- we don't suggest -XEmptyDataDecls for newtypes
749   ; checkTc (new_or_data == DataType || isSingleton cons) 
750             (newtypeConError tc_name (length cons))
751
752         -- Check that there's at least one condecl,
753         -- or else we're reading an hs-boot file, or -XEmptyDataDecls
754   ; checkTc (not (null cons) || empty_data_decls || is_boot)
755             (emptyConDeclsErr tc_name)
756     
757   ; tycon <- fixM (\ tycon -> do 
758         { let res_ty = mkTyConApp tycon (mkTyVarTys final_tvs)
759         ; data_cons <- tcConDecls unbox_strict ex_ok 
760                                   tycon (final_tvs, res_ty) cons
761         ; tc_rhs <-
762             if null cons && is_boot     -- In a hs-boot file, empty cons means
763             then return AbstractTyCon   -- "don't know"; hence Abstract
764             else case new_or_data of
765                    DataType -> return (mkDataTyConRhs data_cons)
766                    NewType  -> ASSERT( not (null data_cons) )
767                                mkNewTyConRhs tc_name tycon (head data_cons)
768         ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
769             (want_generic && canDoGenerics data_cons) h98_syntax Nothing
770         })
771   ; return [ATyCon tycon]
772   }
773   where
774     is_rec   = calc_isrec tc_name
775     h98_syntax = consUseH98Syntax cons
776
777 tcTyClDecl1 calc_isrec 
778   (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs, 
779               tcdCtxt = ctxt, tcdMeths = meths,
780               tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
781   = tcTyVarBndrs tvs            $ \ tvs' -> do 
782   { ctxt' <- tcHsKindedContext ctxt
783   ; fds' <- mapM (addLocM tc_fundep) fundeps
784   ; atss <- mapM (addLocM (tcTyClDecl1 (const Recursive))) ats
785             -- NB: 'ats' only contains "type family" and "data family"
786             --     declarations as well as type family defaults
787   ; let ats' = map (setAssocFamilyPermutation tvs') (concat atss)
788   ; sig_stuff <- tcClassSigs class_name sigs meths
789   ; clas <- fixM (\ clas ->
790                 let     -- This little knot is just so we can get
791                         -- hold of the name of the class TyCon, which we
792                         -- need to look up its recursiveness
793                     tycon_name = tyConName (classTyCon clas)
794                     tc_isrec = calc_isrec tycon_name
795                 in
796                 buildClass False {- Must include unfoldings for selectors -}
797                            class_name tvs' ctxt' fds' ats'
798                            sig_stuff tc_isrec)
799   ; return (AClass clas : ats')
800       -- NB: Order is important due to the call to `mkGlobalThings' when
801       --     tying the the type and class declaration type checking knot.
802   }
803   where
804     tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM tcLookupTyVar tvs1 ;
805                                 ; tvs2' <- mapM tcLookupTyVar tvs2 ;
806                                 ; return (tvs1', tvs2') }
807
808 tcTyClDecl1 _
809   (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
810   = return [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
811
812 tcTyClDecl1 _ d = pprPanic "tcTyClDecl1" (ppr d)
813
814 -----------------------------------
815 tcConDecls :: Bool -> Bool -> TyCon -> ([TyVar], Type)
816            -> [LConDecl Name] -> TcM [DataCon]
817 tcConDecls unbox ex_ok rep_tycon res_tmpl cons
818   = mapM (addLocM (tcConDecl unbox ex_ok rep_tycon res_tmpl)) cons
819
820 tcConDecl :: Bool               -- True <=> -funbox-strict_fields
821           -> Bool               -- True <=> -XExistentialQuantificaton or -XGADTs
822           -> TyCon              -- Representation tycon
823           -> ([TyVar], Type)    -- Return type template (with its template tyvars)
824           -> ConDecl Name 
825           -> TcM DataCon
826
827 tcConDecl unbox_strict existential_ok rep_tycon res_tmpl        -- Data types
828           (ConDecl {con_name =name, con_qvars = tvs, con_cxt = ctxt
829                    , con_details = details, con_res = 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 -- NB We produce *un-typechecked* bindings, rather like 'deriving'
1209 --    This makes life easier, because the later type checking will add
1210 --    all necessary type abstractions and applications
1211 mkAuxBinds ty_things
1212   = ValBindsOut [(NonRecursive, b) | b <- binds] sigs
1213   where
1214     (sigs, binds) = unzip rec_sels
1215     rec_sels = map mkRecSelBind [ (tc,fld) 
1216                                 | ATyCon tc <- ty_things 
1217                                 , fld <- tyConFields tc ]
1218
1219 mkRecSelBind :: (TyCon, FieldLabel) -> (LSig Name, LHsBinds Name)
1220 mkRecSelBind (tycon, sel_name)
1221   = (L loc (IdSig sel_id), unitBag (L loc sel_bind))
1222   where
1223     loc         = getSrcSpan tycon    
1224     sel_id      = Var.mkLocalVar rec_details sel_name sel_ty vanillaIdInfo
1225     rec_details = RecSelId { sel_tycon = tycon, sel_naughty = is_naughty }
1226
1227     -- Find a representative constructor, con1
1228     all_cons     = tyConDataCons tycon 
1229     cons_w_field = [ con | con <- all_cons
1230                    , sel_name `elem` dataConFieldLabels con ] 
1231     con1 = ASSERT( not (null cons_w_field) ) head cons_w_field
1232
1233     -- Selector type; Note [Polymorphic selectors]
1234     field_ty   = dataConFieldType con1 sel_name
1235     data_ty    = dataConOrigResTy con1
1236     data_tvs   = tyVarsOfType data_ty
1237     is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tvs)  
1238     (field_tvs, field_theta, field_tau) = tcSplitSigmaTy field_ty
1239     sel_ty | is_naughty = unitTy  -- See Note [Naughty record selectors]
1240            | otherwise  = mkForAllTys (varSetElems data_tvs ++ field_tvs) $ 
1241                           mkPhiTy (dataConStupidTheta con1) $   -- Urgh!
1242                           mkPhiTy field_theta               $   -- Urgh!
1243                           mkFunTy data_ty field_tau
1244
1245     -- Make the binding: sel (C2 { fld = x }) = x
1246     --                   sel (C7 { fld = x }) = x
1247     --    where cons_w_field = [C2,C7]
1248     sel_bind | is_naughty = mkFunBind sel_lname [mkSimpleMatch [] unit_rhs]
1249              | otherwise  = mkFunBind sel_lname (map mk_match cons_w_field ++ deflt)
1250     mk_match con = mkSimpleMatch [L loc (mk_sel_pat con)] 
1251                                  (L loc (HsVar field_var))
1252     mk_sel_pat con = ConPatIn (L loc (getName con)) (RecCon rec_fields)
1253     rec_fields = HsRecFields { rec_flds = [rec_field], rec_dotdot = Nothing }
1254     rec_field  = HsRecField { hsRecFieldId = sel_lname
1255                             , hsRecFieldArg = nlVarPat field_var
1256                             , hsRecPun = False }
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
1268     unit_rhs = L loc $ ExplicitTuple [] Boxed
1269     msg_lit = HsStringPrim $ mkFastString $ 
1270               occNameString (getOccName sel_name)
1271
1272 ---------------
1273 tyConFields :: TyCon -> [FieldLabel]
1274 tyConFields tc 
1275   | isAlgTyCon tc = nub (concatMap dataConFieldLabels (tyConDataCons tc))
1276   | otherwise     = []
1277 \end{code}
1278
1279 Note [Polymorphic selectors]
1280 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1281 When a record has a polymorphic field, we pull the foralls out to the front.
1282    data T = MkT { f :: forall a. [a] -> a }
1283 Then f :: forall a. T -> [a] -> a
1284 NOT  f :: T -> forall a. [a] -> a
1285
1286 This is horrid.  It's only needed in deeply obscure cases, which I hate.
1287 The only case I know is test tc163, which is worth looking at.  It's far
1288 from clear that this test should succeed at all!
1289
1290 Note [Naughty record selectors]
1291 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1292 A "naughty" field is one for which we can't define a record 
1293 selector, because an existential type variable would escape.  For example:
1294         data T = forall a. MkT { x,y::a }
1295 We obviously can't define       
1296         x (MkT v _) = v
1297 Nevertheless we *do* put a RecSelId into the type environment
1298 so that if the user tries to use 'x' as a selector we can bleat
1299 helpfully, rather than saying unhelpfully that 'x' is not in scope.
1300 Hence the sel_naughty flag, to identify record selectors that don't really exist.
1301
1302 In general, a field is "naughty" if its type mentions a type variable that
1303 isn't in the result type of the constructor.  Note that this *allows*
1304 GADT record selectors (Note [GADT record selectors]) whose types may look 
1305 like     sel :: T [a] -> a
1306
1307 For naughty selectors we make a dummy binding 
1308    sel = ()
1309 for naughty selectors, so that the later type-check will add them to the
1310 environment, and they'll be exported.  The function is never called, because
1311 the tyepchecker spots the sel_naughty field.
1312
1313 Note [GADT record selectors]
1314 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1315 For GADTs, we require that all constructors with a common field 'f' have the same
1316 result type (modulo alpha conversion).  [Checked in TcTyClsDecls.checkValidTyCon]
1317 E.g. 
1318         data T where
1319           T1 { f :: Maybe a } :: T [a]
1320           T2 { f :: Maybe a, y :: b  } :: T [a]
1321
1322 and now the selector takes that result type as its argument:
1323    f :: forall a. T [a] -> Maybe a
1324
1325 Details: the "real" types of T1,T2 are:
1326    T1 :: forall r a.   (r~[a]) => a -> T r
1327    T2 :: forall r a b. (r~[a]) => a -> b -> T r
1328
1329 So the selector loooks like this:
1330    f :: forall a. T [a] -> Maybe a
1331    f (a:*) (t:T [a])
1332      = case t of
1333          T1 c   (g:[a]~[c]) (v:Maybe c)       -> v `cast` Maybe (right (sym g))
1334          T2 c d (g:[a]~[c]) (v:Maybe c) (w:d) -> v `cast` Maybe (right (sym g))
1335
1336 Note the forall'd tyvars of the selector are just the free tyvars
1337 of the result type; there may be other tyvars in the constructor's
1338 type (e.g. 'b' in T2).
1339
1340 Note the need for casts in the result!
1341
1342 Note [Selector running example]
1343 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1344 It's OK to combine GADTs and type families.  Here's a running example:
1345
1346         data instance T [a] where 
1347           T1 { fld :: b } :: T [Maybe b]
1348
1349 The representation type looks like this
1350         data :R7T a where
1351           T1 { fld :: b } :: :R7T (Maybe b)
1352
1353 and there's coercion from the family type to the representation type
1354         :CoR7T a :: T [a] ~ :R7T a
1355
1356 The selector we want for fld looks like this:
1357
1358         fld :: forall b. T [Maybe b] -> b
1359         fld = /\b. \(d::T [Maybe b]).
1360               case d `cast` :CoR7T (Maybe b) of 
1361                 T1 (x::b) -> x
1362
1363 The scrutinee of the case has type :R7T (Maybe b), which can be
1364 gotten by appying the eq_spec to the univ_tvs of the data con.
1365
1366 %************************************************************************
1367 %*                                                                      *
1368                 Error messages
1369 %*                                                                      *
1370 %************************************************************************
1371
1372 \begin{code}
1373 resultTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1374 resultTypeMisMatch field_name con1 con2
1375   = vcat [sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2, 
1376                 ptext (sLit "have a common field") <+> quotes (ppr field_name) <> comma],
1377           nest 2 $ ptext (sLit "but have different result types")]
1378
1379 fieldTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1380 fieldTypeMisMatch field_name con1 con2
1381   = sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2, 
1382          ptext (sLit "give different types for field"), quotes (ppr field_name)]
1383
1384 dataConCtxt :: Outputable a => a -> SDoc
1385 dataConCtxt con = ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
1386
1387 classOpCtxt :: Var -> Type -> SDoc
1388 classOpCtxt sel_id tau = sep [ptext (sLit "When checking the class method:"),
1389                               nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
1390
1391 nullaryClassErr :: Class -> SDoc
1392 nullaryClassErr cls
1393   = ptext (sLit "No parameters for class")  <+> quotes (ppr cls)
1394
1395 classArityErr :: Class -> SDoc
1396 classArityErr cls
1397   = vcat [ptext (sLit "Too many parameters for class") <+> quotes (ppr cls),
1398           parens (ptext (sLit "Use -XMultiParamTypeClasses to allow multi-parameter classes"))]
1399
1400 classFunDepsErr :: Class -> SDoc
1401 classFunDepsErr cls
1402   = vcat [ptext (sLit "Fundeps in class") <+> quotes (ppr cls),
1403           parens (ptext (sLit "Use -XFunctionalDependencies to allow fundeps"))]
1404
1405 noClassTyVarErr :: Class -> Var -> SDoc
1406 noClassTyVarErr clas op
1407   = sep [ptext (sLit "The class method") <+> quotes (ppr op),
1408          ptext (sLit "mentions none of the type variables of the class") <+> 
1409                 ppr clas <+> hsep (map ppr (classTyVars clas))]
1410
1411 genericMultiParamErr :: Class -> SDoc
1412 genericMultiParamErr clas
1413   = ptext (sLit "The multi-parameter class") <+> quotes (ppr clas) <+> 
1414     ptext (sLit "cannot have generic methods")
1415
1416 badGenericMethodType :: Name -> Kind -> SDoc
1417 badGenericMethodType op op_ty
1418   = hang (ptext (sLit "Generic method type is too complex"))
1419        4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
1420                 ptext (sLit "You can only use type variables, arrows, lists, and tuples")])
1421
1422 recSynErr :: [LTyClDecl Name] -> TcRn ()
1423 recSynErr syn_decls
1424   = setSrcSpan (getLoc (head sorted_decls)) $
1425     addErr (sep [ptext (sLit "Cycle in type synonym declarations:"),
1426                  nest 2 (vcat (map ppr_decl sorted_decls))])
1427   where
1428     sorted_decls = sortLocated syn_decls
1429     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
1430
1431 recClsErr :: [Located (TyClDecl Name)] -> TcRn ()
1432 recClsErr cls_decls
1433   = setSrcSpan (getLoc (head sorted_decls)) $
1434     addErr (sep [ptext (sLit "Cycle in class declarations (via superclasses):"),
1435                  nest 2 (vcat (map ppr_decl sorted_decls))])
1436   where
1437     sorted_decls = sortLocated cls_decls
1438     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
1439
1440 sortLocated :: [Located a] -> [Located a]
1441 sortLocated things = sortLe le things
1442   where
1443     le (L l1 _) (L l2 _) = l1 <= l2
1444
1445 badDataConTyCon :: DataCon -> Type -> Type -> SDoc
1446 badDataConTyCon data_con res_ty_tmpl actual_res_ty
1447   = hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con) <+>
1448                 ptext (sLit "returns type") <+> quotes (ppr actual_res_ty))
1449        2 (ptext (sLit "instead of an instance of its parent type") <+> quotes (ppr res_ty_tmpl))
1450
1451 badGadtDecl :: Name -> SDoc
1452 badGadtDecl tc_name
1453   = vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
1454          , nest 2 (parens $ ptext (sLit "Use -XGADTs to allow GADTs")) ]
1455
1456 badExistential :: Located Name -> SDoc
1457 badExistential con_name
1458   = hang (ptext (sLit "Data constructor") <+> quotes (ppr con_name) <+>
1459                 ptext (sLit "has existential type variables, or a context"))
1460        2 (parens $ ptext (sLit "Use -XExistentialQuantification or -XGADTs to allow this"))
1461
1462 badStupidTheta :: Name -> SDoc
1463 badStupidTheta tc_name
1464   = ptext (sLit "A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
1465
1466 newtypeConError :: Name -> Int -> SDoc
1467 newtypeConError tycon n
1468   = sep [ptext (sLit "A newtype must have exactly one constructor,"),
1469          nest 2 $ ptext (sLit "but") <+> quotes (ppr tycon) <+> ptext (sLit "has") <+> speakN n ]
1470
1471 newtypeExError :: DataCon -> SDoc
1472 newtypeExError con
1473   = sep [ptext (sLit "A newtype constructor cannot have an existential context,"),
1474          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1475
1476 newtypeStrictError :: DataCon -> SDoc
1477 newtypeStrictError con
1478   = sep [ptext (sLit "A newtype constructor cannot have a strictness annotation,"),
1479          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1480
1481 newtypePredError :: DataCon -> SDoc
1482 newtypePredError con
1483   = sep [ptext (sLit "A newtype constructor must have a return type of form T a1 ... an"),
1484          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does not")]
1485
1486 newtypeFieldErr :: DataCon -> Int -> SDoc
1487 newtypeFieldErr con_name n_flds
1488   = sep [ptext (sLit "The constructor of a newtype must have exactly one field"), 
1489          nest 2 $ ptext (sLit "but") <+> quotes (ppr con_name) <+> ptext (sLit "has") <+> speakN n_flds]
1490
1491 badSigTyDecl :: Name -> SDoc
1492 badSigTyDecl tc_name
1493   = vcat [ ptext (sLit "Illegal kind signature") <+>
1494            quotes (ppr tc_name)
1495          , nest 2 (parens $ ptext (sLit "Use -XKindSignatures to allow kind signatures")) ]
1496
1497 badFamInstDecl :: Outputable a => a -> SDoc
1498 badFamInstDecl tc_name
1499   = vcat [ ptext (sLit "Illegal family instance for") <+>
1500            quotes (ppr tc_name)
1501          , nest 2 (parens $ ptext (sLit "Use -XTypeFamilies to allow indexed type families")) ]
1502
1503 tooManyParmsErr :: Located Name -> SDoc
1504 tooManyParmsErr tc_name
1505   = ptext (sLit "Family instance has too many parameters:") <+> 
1506     quotes (ppr tc_name)
1507
1508 tooFewParmsErr :: Arity -> SDoc
1509 tooFewParmsErr arity
1510   = ptext (sLit "Family instance has too few parameters; expected") <+> 
1511     ppr arity
1512
1513 wrongNumberOfParmsErr :: Arity -> SDoc
1514 wrongNumberOfParmsErr exp_arity
1515   = ptext (sLit "Number of parameters must match family declaration; expected")
1516     <+> ppr exp_arity
1517
1518 badBootFamInstDeclErr :: SDoc
1519 badBootFamInstDeclErr
1520   = ptext (sLit "Illegal family instance in hs-boot file")
1521
1522 notFamily :: TyCon -> SDoc
1523 notFamily tycon
1524   = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tycon)
1525          , nest 2 $ parens (ppr tycon <+> ptext (sLit "is not an indexed type family"))]
1526   
1527 wrongKindOfFamily :: TyCon -> SDoc
1528 wrongKindOfFamily family
1529   = ptext (sLit "Wrong category of family instance; declaration was for a")
1530     <+> kindOfFamily
1531   where
1532     kindOfFamily | isSynTyCon family = ptext (sLit "type synonym")
1533                  | isAlgTyCon family = ptext (sLit "data type")
1534                  | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1535
1536 emptyConDeclsErr :: Name -> SDoc
1537 emptyConDeclsErr tycon
1538   = sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
1539          nest 2 $ ptext (sLit "(-XEmptyDataDecls permits this)")]
1540 \end{code}