Improve error reporting for kind errors (fix Trac #1633)
[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 (ConDecl name expl ex_tvs ex_ctxt details res _) 
594       = addErrCtxt (dataConCtxt name)   $ 
595         kcHsTyVars ex_tvs $ \ex_tvs' -> do
596         do { ex_ctxt' <- kcHsContext ex_ctxt
597            ; details' <- kc_con_details details 
598            ; res'     <- case res of
599                 ResTyH98 -> return ResTyH98
600                 ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
601            ; return (ConDecl name expl ex_tvs' ex_ctxt' details' res' Nothing) }
602
603     kc_con_details (PrefixCon btys) 
604         = do { btys' <- mapM kc_larg_ty btys 
605              ; return (PrefixCon btys') }
606     kc_con_details (InfixCon bty1 bty2) 
607         = do { bty1' <- kc_larg_ty bty1
608              ; bty2' <- kc_larg_ty bty2
609              ; return (InfixCon bty1' bty2') }
610     kc_con_details (RecCon fields) 
611         = do { fields' <- mapM kc_field fields
612              ; return (RecCon fields') }
613
614     kc_field (ConDeclField fld bty d) = do { bty' <- kc_larg_ty bty
615                                            ; return (ConDeclField fld bty' d) }
616
617     kc_larg_ty bty = case new_or_data of
618                         DataType -> kcHsSigType bty
619                         NewType  -> kcHsLiftedSigType bty
620         -- Can't allow an unlifted type for newtypes, because we're effectively
621         -- going to remove the constructor while coercing it to a lifted type.
622         -- And newtypes can't be bang'd
623 kcDataDecl d _ = pprPanic "kcDataDecl" (ppr d)
624
625 -- Kind check a family declaration or type family default declaration.
626 --
627 kcFamilyDecl :: [LHsTyVarBndr Name]  -- tyvars of enclosing class decl if any
628              -> TyClDecl Name -> TcM (TyClDecl Name)
629 kcFamilyDecl classTvs decl@(TyFamily {tcdKind = kind})
630   = kcTyClDeclBody decl $ \tvs' ->
631     do { mapM_ unifyClassParmKinds tvs'
632        ; return (decl {tcdTyVars = tvs', 
633                        tcdKind = kind `mplus` Just liftedTypeKind})
634                        -- default result kind is '*'
635        }
636   where
637     unifyClassParmKinds (L _ (KindedTyVar n k))
638       | Just classParmKind <- lookup n classTyKinds = unifyKind k classParmKind
639       | otherwise                                   = return ()
640     unifyClassParmKinds x = pprPanic "kcFamilyDecl/unifyClassParmKinds" (ppr x)
641     classTyKinds = [(n, k) | L _ (KindedTyVar n k) <- classTvs]
642 kcFamilyDecl _ (TySynonym {})              -- type family defaults
643   = panic "TcTyClsDecls.kcFamilyDecl: not implemented yet"
644 kcFamilyDecl _ d = pprPanic "kcFamilyDecl" (ppr d)
645 \end{code}
646
647
648 %************************************************************************
649 %*                                                                      *
650 \subsection{Type checking}
651 %*                                                                      *
652 %************************************************************************
653
654 \begin{code}
655 tcSynDecls :: [LTyClDecl Name] -> TcM [TyThing]
656 tcSynDecls [] = return []
657 tcSynDecls (decl : decls) 
658   = do { syn_tc <- addLocM tcSynDecl decl
659        ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls decls)
660        ; return (syn_tc : syn_tcs) }
661
662   -- "type"
663 tcSynDecl :: TyClDecl Name -> TcM TyThing
664 tcSynDecl
665   (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
666   = tcTyVarBndrs tvs            $ \ tvs' -> do 
667     { traceTc (text "tcd1" <+> ppr tc_name) 
668     ; rhs_ty' <- tcHsKindedType rhs_ty
669     ; tycon <- buildSynTyCon tc_name tvs' (SynonymTyCon rhs_ty') 
670                              (typeKind rhs_ty') Nothing
671     ; return (ATyCon tycon) 
672     }
673 tcSynDecl d = pprPanic "tcSynDecl" (ppr d)
674
675 --------------------
676 tcTyClDecl :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
677
678 tcTyClDecl calc_isrec decl
679   = tcAddDeclCtxt decl (tcTyClDecl1 calc_isrec decl)
680
681   -- "type family" declarations
682 tcTyClDecl1 :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
683 tcTyClDecl1 _calc_isrec 
684   (TyFamily {tcdFlavour = TypeFamily, 
685              tcdLName = L _ tc_name, tcdTyVars = tvs,
686              tcdKind = Just kind}) -- NB: kind at latest added during kind checking
687   = tcTyVarBndrs tvs  $ \ tvs' -> do 
688   { traceTc (text "type family: " <+> ppr tc_name) 
689
690         -- Check that we don't use families without -XTypeFamilies
691   ; idx_tys <- doptM Opt_TypeFamilies
692   ; checkTc idx_tys $ badFamInstDecl tc_name
693
694         -- Check for no type indices
695   ; checkTc (not (null tvs)) (noIndexTypes tc_name)
696
697   ; tycon <- buildSynTyCon tc_name tvs' (OpenSynTyCon kind Nothing) kind Nothing
698   ; return [ATyCon tycon]
699   }
700
701   -- "data family" declaration
702 tcTyClDecl1 _calc_isrec 
703   (TyFamily {tcdFlavour = DataFamily, 
704              tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = mb_kind})
705   = tcTyVarBndrs tvs  $ \ tvs' -> do 
706   { traceTc (text "data family: " <+> ppr tc_name) 
707   ; extra_tvs <- tcDataKindSig mb_kind
708   ; let final_tvs = tvs' ++ extra_tvs    -- we may not need these
709
710
711         -- Check that we don't use families without -XTypeFamilies
712   ; idx_tys <- doptM Opt_TypeFamilies
713   ; checkTc idx_tys $ badFamInstDecl tc_name
714
715         -- Check for no type indices
716   ; checkTc (not (null tvs)) (noIndexTypes tc_name)
717
718   ; tycon <- buildAlgTyCon tc_name final_tvs [] 
719                mkOpenDataTyConRhs Recursive False True Nothing
720   ; return [ATyCon tycon]
721   }
722
723   -- "newtype" and "data"
724   -- NB: not used for newtype/data instances (whether associated or not)
725 tcTyClDecl1 calc_isrec
726   (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
727            tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
728   = tcTyVarBndrs tvs    $ \ tvs' -> do 
729   { extra_tvs <- tcDataKindSig mb_ksig
730   ; let final_tvs = tvs' ++ extra_tvs
731   ; stupid_theta <- tcHsKindedContext ctxt
732   ; want_generic <- doptM Opt_Generics
733   ; unbox_strict <- doptM Opt_UnboxStrictFields
734   ; empty_data_decls <- doptM Opt_EmptyDataDecls
735   ; kind_signatures <- doptM Opt_KindSignatures
736   ; existential_ok <- doptM Opt_ExistentialQuantification
737   ; gadt_ok      <- doptM Opt_GADTs
738   ; is_boot      <- tcIsHsBoot  -- Are we compiling an hs-boot file?
739   ; let ex_ok = existential_ok || gadt_ok       -- Data cons can have existential context
740
741         -- Check that we don't use GADT syntax in H98 world
742   ; checkTc (gadt_ok || h98_syntax) (badGadtDecl tc_name)
743
744         -- Check that we don't use kind signatures without Glasgow extensions
745   ; checkTc (kind_signatures || isNothing mb_ksig) (badSigTyDecl tc_name)
746
747         -- Check that the stupid theta is empty for a GADT-style declaration
748   ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
749
750         -- Check that a newtype has exactly one constructor
751         -- Do this before checking for empty data decls, so that
752         -- we don't suggest -XEmptyDataDecls for newtypes
753   ; checkTc (new_or_data == DataType || isSingleton cons) 
754             (newtypeConError tc_name (length cons))
755
756         -- Check that there's at least one condecl,
757         -- or else we're reading an hs-boot file, or -XEmptyDataDecls
758   ; checkTc (not (null cons) || empty_data_decls || is_boot)
759             (emptyConDeclsErr tc_name)
760     
761   ; tycon <- fixM (\ tycon -> do 
762         { let res_ty = mkTyConApp tycon (mkTyVarTys final_tvs)
763         ; data_cons <- tcConDecls unbox_strict ex_ok 
764                                   tycon (final_tvs, res_ty) cons
765         ; tc_rhs <-
766             if null cons && is_boot     -- In a hs-boot file, empty cons means
767             then return AbstractTyCon   -- "don't know"; hence Abstract
768             else case new_or_data of
769                    DataType -> return (mkDataTyConRhs data_cons)
770                    NewType  -> ASSERT( not (null data_cons) )
771                                mkNewTyConRhs tc_name tycon (head data_cons)
772         ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
773             (want_generic && canDoGenerics data_cons) h98_syntax Nothing
774         })
775   ; return [ATyCon tycon]
776   }
777   where
778     is_rec   = calc_isrec tc_name
779     h98_syntax = consUseH98Syntax cons
780
781 tcTyClDecl1 calc_isrec 
782   (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs, 
783               tcdCtxt = ctxt, tcdMeths = meths,
784               tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
785   = tcTyVarBndrs tvs            $ \ tvs' -> do 
786   { ctxt' <- tcHsKindedContext ctxt
787   ; fds' <- mapM (addLocM tc_fundep) fundeps
788   ; atss <- mapM (addLocM (tcTyClDecl1 (const Recursive))) ats
789             -- NB: 'ats' only contains "type family" and "data family"
790             --     declarations as well as type family defaults
791   ; let ats' = map (setAssocFamilyPermutation tvs') (concat atss)
792   ; sig_stuff <- tcClassSigs class_name sigs meths
793   ; clas <- fixM (\ clas ->
794                 let     -- This little knot is just so we can get
795                         -- hold of the name of the class TyCon, which we
796                         -- need to look up its recursiveness
797                     tycon_name = tyConName (classTyCon clas)
798                     tc_isrec = calc_isrec tycon_name
799                 in
800                 buildClass False {- Must include unfoldings for selectors -}
801                            class_name tvs' ctxt' fds' ats'
802                            sig_stuff tc_isrec)
803   ; return (AClass clas : ats')
804       -- NB: Order is important due to the call to `mkGlobalThings' when
805       --     tying the the type and class declaration type checking knot.
806   }
807   where
808     tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM tcLookupTyVar tvs1 ;
809                                 ; tvs2' <- mapM tcLookupTyVar tvs2 ;
810                                 ; return (tvs1', tvs2') }
811
812 tcTyClDecl1 _
813   (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
814   = return [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
815
816 tcTyClDecl1 _ d = pprPanic "tcTyClDecl1" (ppr d)
817
818 -----------------------------------
819 tcConDecls :: Bool -> Bool -> TyCon -> ([TyVar], Type)
820            -> [LConDecl Name] -> TcM [DataCon]
821 tcConDecls unbox ex_ok rep_tycon res_tmpl cons
822   = mapM (addLocM (tcConDecl unbox ex_ok rep_tycon res_tmpl)) cons
823
824 tcConDecl :: Bool               -- True <=> -funbox-strict_fields
825           -> Bool               -- True <=> -XExistentialQuantificaton or -XGADTs
826           -> TyCon              -- Representation tycon
827           -> ([TyVar], Type)    -- Return type template (with its template tyvars)
828           -> ConDecl Name 
829           -> TcM DataCon
830
831 tcConDecl unbox_strict existential_ok rep_tycon res_tmpl        -- Data types
832           (ConDecl name _ tvs ctxt details res_ty _)
833   = addErrCtxt (dataConCtxt name)       $ 
834     tcTyVarBndrs tvs                    $ \ tvs' -> do 
835     { ctxt' <- tcHsKindedContext ctxt
836     ; checkTc (existential_ok || (null tvs && null (unLoc ctxt)))
837               (badExistential name)
838     ; (univ_tvs, ex_tvs, eq_preds, res_ty') <- tcResultType res_tmpl tvs' res_ty
839     ; let 
840         tc_datacon is_infix field_lbls btys
841           = do { (arg_tys, stricts) <- mapAndUnzipM (tcConArg unbox_strict) btys
842                ; buildDataCon (unLoc name) is_infix
843                     stricts field_lbls
844                     univ_tvs ex_tvs eq_preds ctxt' arg_tys
845                     res_ty' rep_tycon }
846                 -- NB:  we put data_tc, the type constructor gotten from the
847                 --      constructor type signature into the data constructor;
848                 --      that way checkValidDataCon can complain if it's wrong.
849
850     ; case details of
851         PrefixCon btys     -> tc_datacon False [] btys
852         InfixCon bty1 bty2 -> tc_datacon True  [] [bty1,bty2]
853         RecCon fields      -> tc_datacon False field_names btys
854                            where
855                               field_names = map (unLoc . cd_fld_name) fields
856                               btys        = map cd_fld_type fields
857     }
858
859 -- Example
860 --   data instance T (b,c) where 
861 --      TI :: forall e. e -> T (e,e)
862 --
863 -- The representation tycon looks like this:
864 --   data :R7T b c where 
865 --      TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
866 -- In this case orig_res_ty = T (e,e)
867
868 tcResultType :: ([TyVar], Type) -- Template for result type; e.g.
869                                 -- data instance T [a] b c = ...  
870                                 --      gives template ([a,b,c], T [a] b c)
871              -> [TyVar]         -- where MkT :: forall x y z. ...
872              -> ResType Name
873              -> TcM ([TyVar],           -- Universal
874                      [TyVar],           -- Existential (distinct OccNames from univs)
875                      [(TyVar,Type)],    -- Equality predicates
876                      Type)              -- Typechecked return type
877         -- We don't check that the TyCon given in the ResTy is
878         -- the same as the parent tycon, becuase we are in the middle
879         -- of a recursive knot; so it's postponed until checkValidDataCon
880
881 tcResultType (tmpl_tvs, res_ty) dc_tvs ResTyH98
882   = return (tmpl_tvs, dc_tvs, [], res_ty)
883         -- In H98 syntax the dc_tvs are the existential ones
884         --      data T a b c = forall d e. MkT ...
885         -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
886
887 tcResultType (tmpl_tvs, res_tmpl) dc_tvs (ResTyGADT res_ty)
888         -- E.g.  data T [a] b c where
889         --         MkT :: forall x y z. T [(x,y)] z z
890         -- Then we generate
891         --      Univ tyvars     Eq-spec
892         --          a              a~(x,y)
893         --          b              b~z
894         --          z              
895         -- Existentials are the leftover type vars: [x,y]
896         -- So we return ([a,b,z], [x,y], [a~(x,y),b~z], T [(x,y)] z z)
897   = do  { res_ty' <- tcHsKindedType res_ty
898         ; let Just subst = tcMatchTy (mkVarSet tmpl_tvs) res_tmpl res_ty'
899
900                 -- /Lazily/ figure out the univ_tvs etc
901                 -- Each univ_tv is either a dc_tv or a tmpl_tv
902               (univ_tvs, eq_spec) = foldr choose ([], []) tidy_tmpl_tvs
903               choose tmpl (univs, eqs)
904                 | Just ty <- lookupTyVar subst tmpl 
905                 = case tcGetTyVar_maybe ty of
906                     Just tv | not (tv `elem` univs)
907                             -> (tv:univs,   eqs)
908                     _other  -> (tmpl:univs, (tmpl,ty):eqs)
909                 | otherwise = pprPanic "tcResultType" (ppr res_ty)
910               ex_tvs = dc_tvs `minusList` univ_tvs
911
912         ; return (univ_tvs, ex_tvs, eq_spec, res_ty') }
913   where
914         -- NB: tmpl_tvs and dc_tvs are distinct, but
915         -- we want them to be *visibly* distinct, both for
916         -- interface files and general confusion.  So rename
917         -- the tc_tvs, since they are not used yet (no 
918         -- consequential renaming needed)
919     (_, tidy_tmpl_tvs) = mapAccumL tidy_one init_occ_env tmpl_tvs
920     init_occ_env       = initTidyOccEnv (map getOccName dc_tvs)
921     tidy_one env tv    = (env', setTyVarName tv (tidyNameOcc name occ'))
922               where
923                  name = tyVarName tv
924                  (env', occ') = tidyOccName env (getOccName name) 
925
926 consUseH98Syntax :: [LConDecl a] -> Bool
927 consUseH98Syntax (L _ (ConDecl { con_res = ResTyGADT _ }) : _) = False
928 consUseH98Syntax _                                             = True
929                  -- All constructors have same shape
930
931 -------------------
932 tcConArg :: Bool                -- True <=> -funbox-strict_fields
933            -> LHsType Name
934            -> TcM (TcType, StrictnessMark)
935 tcConArg unbox_strict bty
936   = do  { arg_ty <- tcHsBangType bty
937         ; let bang = getBangStrictness bty
938         ; return (arg_ty, chooseBoxingStrategy unbox_strict arg_ty bang) }
939
940 -- We attempt to unbox/unpack a strict field when either:
941 --   (i)  The field is marked '!!', or
942 --   (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
943 --
944 -- We have turned off unboxing of newtypes because coercions make unboxing 
945 -- and reboxing more complicated
946 chooseBoxingStrategy :: Bool -> TcType -> HsBang -> StrictnessMark
947 chooseBoxingStrategy unbox_strict_fields arg_ty bang
948   = case bang of
949         HsNoBang                                    -> NotMarkedStrict
950         HsStrict | unbox_strict_fields 
951                    && can_unbox arg_ty              -> MarkedUnboxed
952         HsUnbox  | can_unbox arg_ty                 -> MarkedUnboxed
953         _                                           -> MarkedStrict
954   where
955     -- we can unbox if the type is a chain of newtypes with a product tycon
956     -- at the end
957     can_unbox arg_ty = case splitTyConApp_maybe arg_ty of
958                    Nothing                      -> False
959                    Just (arg_tycon, tycon_args) -> 
960                        not (isRecursiveTyCon arg_tycon) &&      -- Note [Recusive unboxing]
961                        isProductTyCon arg_tycon &&
962                        (if isNewTyCon arg_tycon then 
963                             can_unbox (newTyConInstRhs arg_tycon tycon_args)
964                         else True)
965 \end{code}
966
967 Note [Recursive unboxing]
968 ~~~~~~~~~~~~~~~~~~~~~~~~~
969 Be careful not to try to unbox this!
970         data T = MkT !T Int
971 But it's the *argument* type that matters. This is fine:
972         data S = MkS S !Int
973 because Int is non-recursive.
974
975
976 %************************************************************************
977 %*                                                                      *
978                 Validity checking
979 %*                                                                      *
980 %************************************************************************
981
982 Validity checking is done once the mutually-recursive knot has been
983 tied, so we can look at things freely.
984
985 \begin{code}
986 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
987 checkCycleErrs tyclss
988   | null cls_cycles
989   = return ()
990   | otherwise
991   = do  { mapM_ recClsErr cls_cycles
992         ; failM }       -- Give up now, because later checkValidTyCl
993                         -- will loop if the synonym is recursive
994   where
995     cls_cycles = calcClassCycles tyclss
996
997 checkValidTyCl :: TyClDecl Name -> TcM ()
998 -- We do the validity check over declarations, rather than TyThings
999 -- only so that we can add a nice context with tcAddDeclCtxt
1000 checkValidTyCl decl
1001   = tcAddDeclCtxt decl $
1002     do  { thing <- tcLookupLocatedGlobal (tcdLName decl)
1003         ; traceTc (text "Validity of" <+> ppr thing)    
1004         ; case thing of
1005             ATyCon tc -> checkValidTyCon tc
1006             AClass cl -> checkValidClass cl 
1007             _ -> panic "checkValidTyCl"
1008         ; traceTc (text "Done validity of" <+> ppr thing)       
1009         }
1010
1011 -------------------------
1012 -- For data types declared with record syntax, we require
1013 -- that each constructor that has a field 'f' 
1014 --      (a) has the same result type
1015 --      (b) has the same type for 'f'
1016 -- module alpha conversion of the quantified type variables
1017 -- of the constructor.
1018 --
1019 -- Note that we allow existentials to match becuase the
1020 -- fields can never meet. E.g
1021 --      data T where
1022 --        T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
1023 --        T2 { f1 :: c, f2 :: c, f3 ::Int } :: T  
1024 -- Here we do not complain about f1,f2 because they are existential
1025
1026 checkValidTyCon :: TyCon -> TcM ()
1027 checkValidTyCon tc 
1028   | isSynTyCon tc 
1029   = case synTyConRhs tc of
1030       OpenSynTyCon _ _ -> return ()
1031       SynonymTyCon ty  -> checkValidType syn_ctxt ty
1032   | otherwise
1033   = do  -- Check the context on the data decl
1034     checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
1035         
1036         -- Check arg types of data constructors
1037     mapM_ (checkValidDataCon tc) data_cons
1038
1039         -- Check that fields with the same name share a type
1040     mapM_ check_fields groups
1041
1042   where
1043     syn_ctxt  = TySynCtxt name
1044     name      = tyConName tc
1045     data_cons = tyConDataCons tc
1046
1047     groups = equivClasses cmp_fld (concatMap get_fields data_cons)
1048     cmp_fld (f1,_) (f2,_) = f1 `compare` f2
1049     get_fields con = dataConFieldLabels con `zip` repeat con
1050         -- dataConFieldLabels may return the empty list, which is fine
1051
1052     -- See Note [GADT record selectors] in MkId.lhs
1053     -- We must check (a) that the named field has the same 
1054     --                   type in each constructor
1055     --               (b) that those constructors have the same result type
1056     --
1057     -- However, the constructors may have differently named type variable
1058     -- and (worse) we don't know how the correspond to each other.  E.g.
1059     --     C1 :: forall a b. { f :: a, g :: b } -> T a b
1060     --     C2 :: forall d c. { f :: c, g :: c } -> T c d
1061     -- 
1062     -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
1063     -- result type against other candidates' types BOTH WAYS ROUND.
1064     -- If they magically agrees, take the substitution and
1065     -- apply them to the latter ones, and see if they match perfectly.
1066     check_fields ((label, con1) : other_fields)
1067         -- These fields all have the same name, but are from
1068         -- different constructors in the data type
1069         = recoverM (return ()) $ mapM_ checkOne other_fields
1070                 -- Check that all the fields in the group have the same type
1071                 -- NB: this check assumes that all the constructors of a given
1072                 -- data type use the same type variables
1073         where
1074         (tvs1, _, _, res1) = dataConSig con1
1075         ts1 = mkVarSet tvs1
1076         fty1 = dataConFieldType con1 label
1077
1078         checkOne (_, con2)    -- Do it bothways to ensure they are structurally identical
1079             = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
1080                  ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
1081             where        
1082                 (tvs2, _, _, res2) = dataConSig con2
1083                 ts2 = mkVarSet tvs2
1084                 fty2 = dataConFieldType con2 label
1085     check_fields [] = panic "checkValidTyCon/check_fields []"
1086
1087 checkFieldCompat :: Name -> DataCon -> DataCon -> TyVarSet
1088                  -> Type -> Type -> Type -> Type -> TcM ()
1089 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
1090   = do  { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
1091         ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
1092   where
1093     mb_subst1 = tcMatchTy tvs1 res1 res2
1094     mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
1095
1096 -------------------------------
1097 checkValidDataCon :: TyCon -> DataCon -> TcM ()
1098 checkValidDataCon tc con
1099   = setSrcSpan (srcLocSpan (getSrcLoc con))     $
1100     addErrCtxt (dataConCtxt con)                $ 
1101     do  { traceTc (ptext (sLit "Validity of data con") <+> ppr con)
1102         ; let tc_tvs = tyConTyVars tc
1103               res_ty_tmpl = mkFamilyTyConApp tc (mkTyVarTys tc_tvs)
1104               actual_res_ty = dataConOrigResTy con
1105         ; checkTc (isJust (tcMatchTy (mkVarSet tc_tvs)
1106                                 res_ty_tmpl
1107                                 actual_res_ty))
1108                   (badDataConTyCon con res_ty_tmpl actual_res_ty)
1109         ; checkValidMonoType (dataConOrigResTy con)
1110                 -- Disallow MkT :: T (forall a. a->a)
1111                 -- Reason: it's really the argument of an equality constraint
1112         ; checkValidType ctxt (dataConUserType con)
1113         ; when (isNewTyCon tc) (checkNewDataCon con)
1114     }
1115   where
1116     ctxt = ConArgCtxt (dataConName con) 
1117
1118 -------------------------------
1119 checkNewDataCon :: DataCon -> TcM ()
1120 -- Checks for the data constructor of a newtype
1121 checkNewDataCon con
1122   = do  { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
1123                 -- One argument
1124         ; checkTc (null eq_spec) (newtypePredError con)
1125                 -- Return type is (T a b c)
1126         ; checkTc (null ex_tvs && null eq_theta && null dict_theta) (newtypeExError con)
1127                 -- No existentials
1128         ; checkTc (not (any isMarkedStrict (dataConStrictMarks con))) 
1129                   (newtypeStrictError con)
1130                 -- No strictness
1131     }
1132   where
1133     (_univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _res_ty) = dataConFullSig con
1134
1135 -------------------------------
1136 checkValidClass :: Class -> TcM ()
1137 checkValidClass cls
1138   = do  { constrained_class_methods <- doptM Opt_ConstrainedClassMethods
1139         ; multi_param_type_classes <- doptM Opt_MultiParamTypeClasses
1140         ; fundep_classes <- doptM Opt_FunctionalDependencies
1141
1142         -- Check that the class is unary, unless GlaExs
1143         ; checkTc (notNull tyvars) (nullaryClassErr cls)
1144         ; checkTc (multi_param_type_classes || unary) (classArityErr cls)
1145         ; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
1146
1147         -- Check the super-classes
1148         ; checkValidTheta (ClassSCCtxt (className cls)) theta
1149
1150         -- Check the class operations
1151         ; mapM_ (check_op constrained_class_methods) op_stuff
1152
1153         -- Check that if the class has generic methods, then the
1154         -- class has only one parameter.  We can't do generic
1155         -- multi-parameter type classes!
1156         ; checkTc (unary || no_generics) (genericMultiParamErr cls)
1157         }
1158   where
1159     (tyvars, fundeps, theta, _, _, op_stuff) = classExtraBigSig cls
1160     unary       = isSingleton tyvars
1161     no_generics = null [() | (_, GenDefMeth) <- op_stuff]
1162
1163     check_op constrained_class_methods (sel_id, dm) 
1164       = addErrCtxt (classOpCtxt sel_id tau) $ do
1165         { checkValidTheta SigmaCtxt (tail theta)
1166                 -- The 'tail' removes the initial (C a) from the
1167                 -- class itself, leaving just the method type
1168
1169         ; traceTc (text "class op type" <+> ppr op_ty <+> ppr tau)
1170         ; checkValidType (FunSigCtxt op_name) tau
1171
1172                 -- Check that the type mentions at least one of
1173                 -- the class type variables...or at least one reachable
1174                 -- from one of the class variables.  Example: tc223
1175                 --   class Error e => Game b mv e | b -> mv e where
1176                 --      newBoard :: MonadState b m => m ()
1177                 -- Here, MonadState has a fundep m->b, so newBoard is fine
1178         ; let grown_tyvars = growThetaTyVars theta (mkVarSet tyvars)
1179         ; checkTc (tyVarsOfType tau `intersectsVarSet` grown_tyvars)
1180                   (noClassTyVarErr cls sel_id)
1181
1182                 -- Check that for a generic method, the type of 
1183                 -- the method is sufficiently simple
1184         ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
1185                   (badGenericMethodType op_name op_ty)
1186         }
1187         where
1188           op_name = idName sel_id
1189           op_ty   = idType sel_id
1190           (_,theta1,tau1) = tcSplitSigmaTy op_ty
1191           (_,theta2,tau2)  = tcSplitSigmaTy tau1
1192           (theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
1193                       | otherwise = (theta1, mkPhiTy (tail theta1) tau1)
1194                 -- Ugh!  The function might have a type like
1195                 --      op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
1196                 -- With -XConstrainedClassMethods, we want to allow this, even though the inner 
1197                 -- forall has an (Eq a) constraint.  Whereas in general, each constraint 
1198                 -- in the context of a for-all must mention at least one quantified
1199                 -- type variable.  What a mess!
1200 \end{code}
1201
1202
1203 %************************************************************************
1204 %*                                                                      *
1205                 Building record selectors
1206 %*                                                                      *
1207 %************************************************************************
1208
1209 \begin{code}
1210 mkAuxBinds :: [TyThing] -> HsValBinds Name
1211 -- NB We produce *un-typechecked* bindings, rather like 'deriving'
1212 --    This makes life easier, because the later type checking will add
1213 --    all necessary type abstractions and applications
1214 mkAuxBinds ty_things
1215   = ValBindsOut [(NonRecursive, b) | b <- binds] sigs
1216   where
1217     (sigs, binds) = unzip rec_sels
1218     rec_sels = map mkRecSelBind [ (tc,fld) 
1219                                 | ATyCon tc <- ty_things 
1220                                 , fld <- tyConFields tc ]
1221
1222 mkRecSelBind :: (TyCon, FieldLabel) -> (LSig Name, LHsBinds Name)
1223 mkRecSelBind (tycon, sel_name)
1224   = (L loc (IdSig sel_id), unitBag (L loc sel_bind))
1225   where
1226     loc         = getSrcSpan tycon    
1227     sel_id      = Var.mkLocalVar rec_details sel_name sel_ty vanillaIdInfo
1228     rec_details = RecSelId { sel_tycon = tycon, sel_naughty = is_naughty }
1229
1230     -- Find a representative constructor, con1
1231     all_cons     = tyConDataCons tycon 
1232     cons_w_field = [ con | con <- all_cons
1233                    , sel_name `elem` dataConFieldLabels con ] 
1234     con1 = ASSERT( not (null cons_w_field) ) head cons_w_field
1235
1236     -- Selector type; Note [Polymorphic selectors]
1237     field_ty   = dataConFieldType con1 sel_name
1238     data_ty    = dataConOrigResTy con1
1239     data_tvs   = tyVarsOfType data_ty
1240     is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tvs)  
1241     (field_tvs, field_theta, field_tau) = tcSplitSigmaTy field_ty
1242     sel_ty | is_naughty = unitTy
1243            | otherwise  = mkForAllTys (varSetElems data_tvs ++ field_tvs) $ 
1244                           mkPhiTy (dataConStupidTheta con1) $   -- Urgh!
1245                           mkPhiTy field_theta               $   -- Urgh!
1246                           mkFunTy data_ty field_tau
1247
1248     -- Make the binding: sel (C2 { fld = x }) = x
1249     --                   sel (C7 { fld = x }) = x
1250     --    where cons_w_field = [C2,C7]
1251     sel_bind | is_naughty = mkFunBind sel_lname [mkSimpleMatch [] unit_rhs]
1252              | otherwise  = mkFunBind sel_lname (map mk_match cons_w_field ++ deflt)
1253     mk_match con = mkSimpleMatch [L loc (mk_sel_pat con)] 
1254                                  (L loc (HsVar field_var))
1255     mk_sel_pat con = ConPatIn (L loc (getName con)) (RecCon rec_fields)
1256     rec_fields = HsRecFields { rec_flds = [rec_field], rec_dotdot = Nothing }
1257     rec_field  = HsRecField { hsRecFieldId = sel_lname
1258                             , hsRecFieldArg = nlVarPat field_var
1259                             , hsRecPun = False }
1260     sel_lname = L loc sel_name
1261     field_var = mkInternalName (mkBuiltinUnique 1) (getOccName sel_name) loc
1262
1263     -- Add catch-all default case unless the case is exhaustive
1264     -- We do this explicitly so that we get a nice error message that
1265     -- mentions this particular record selector
1266     deflt | length cons_w_field == length all_cons = []
1267           | otherwise = [mkSimpleMatch [nlWildPat] 
1268                             (nlHsApp (nlHsVar (getName rEC_SEL_ERROR_ID))
1269                                      (nlHsLit msg_lit))]
1270
1271     unit_rhs = L loc $ ExplicitTuple [] Boxed
1272     msg_lit = HsStringPrim $ mkFastString $ 
1273               occNameString (getOccName sel_name)
1274
1275 ---------------
1276 tyConFields :: TyCon -> [FieldLabel]
1277 tyConFields tc 
1278   | isAlgTyCon tc = nub (concatMap dataConFieldLabels (tyConDataCons tc))
1279   | otherwise     = []
1280 \end{code}
1281
1282 Note [Polymorphic selectors]
1283 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1284 When a record has a polymorphic field, we pull the foralls out to the front.
1285    data T = MkT { f :: forall a. [a] -> a }
1286 Then f :: forall a. T -> [a] -> a
1287 NOT  f :: T -> forall a. [a] -> a
1288
1289 This is horrid.  It's only needed in deeply obscure cases, which I hate.
1290 The only case I know is test tc163, which is worth looking at.  It's far
1291 from clear that this test should succeed at all!
1292
1293 Note [Naughty record selectors]
1294 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1295 A "naughty" field is one for which we can't define a record 
1296 selector, because an existential type variable would escape.  For example:
1297         data T = forall a. MkT { x,y::a }
1298 We obviously can't define       
1299         x (MkT v _) = v
1300 Nevertheless we *do* put a RecSelId into the type environment
1301 so that if the user tries to use 'x' as a selector we can bleat
1302 helpfully, rather than saying unhelpfully that 'x' is not in scope.
1303 Hence the sel_naughty flag, to identify record selectors that don't really exist.
1304
1305 In general, a field is naughty if its type mentions a type variable that
1306 isn't in the result type of the constructor.
1307
1308 We make a dummy binding 
1309    sel = ()
1310 for naughty selectors, so that the later type-check will add them to the
1311 environment, and they'll be exported.  The function is never called, because
1312 the tyepchecker spots the sel_naughty field.
1313
1314 Note [GADT record selectors]
1315 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1316 For GADTs, we require that all constructors with a common field 'f' have the same
1317 result type (modulo alpha conversion).  [Checked in TcTyClsDecls.checkValidTyCon]
1318 E.g. 
1319         data T where
1320           T1 { f :: Maybe a } :: T [a]
1321           T2 { f :: Maybe a, y :: b  } :: T [a]
1322
1323 and now the selector takes that result type as its argument:
1324    f :: forall a. T [a] -> Maybe a
1325
1326 Details: the "real" types of T1,T2 are:
1327    T1 :: forall r a.   (r~[a]) => a -> T r
1328    T2 :: forall r a b. (r~[a]) => a -> b -> T r
1329
1330 So the selector loooks like this:
1331    f :: forall a. T [a] -> Maybe a
1332    f (a:*) (t:T [a])
1333      = case t of
1334          T1 c   (g:[a]~[c]) (v:Maybe c)       -> v `cast` Maybe (right (sym g))
1335          T2 c d (g:[a]~[c]) (v:Maybe c) (w:d) -> v `cast` Maybe (right (sym g))
1336
1337 Note the forall'd tyvars of the selector are just the free tyvars
1338 of the result type; there may be other tyvars in the constructor's
1339 type (e.g. 'b' in T2).
1340
1341 Note the need for casts in the result!
1342
1343 Note [Selector running example]
1344 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1345 It's OK to combine GADTs and type families.  Here's a running example:
1346
1347         data instance T [a] where 
1348           T1 { fld :: b } :: T [Maybe b]
1349
1350 The representation type looks like this
1351         data :R7T a where
1352           T1 { fld :: b } :: :R7T (Maybe b)
1353
1354 and there's coercion from the family type to the representation type
1355         :CoR7T a :: T [a] ~ :R7T a
1356
1357 The selector we want for fld looks like this:
1358
1359         fld :: forall b. T [Maybe b] -> b
1360         fld = /\b. \(d::T [Maybe b]).
1361               case d `cast` :CoR7T (Maybe b) of 
1362                 T1 (x::b) -> x
1363
1364 The scrutinee of the case has type :R7T (Maybe b), which can be
1365 gotten by appying the eq_spec to the univ_tvs of the data con.
1366
1367 %************************************************************************
1368 %*                                                                      *
1369                 Error messages
1370 %*                                                                      *
1371 %************************************************************************
1372
1373 \begin{code}
1374 resultTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1375 resultTypeMisMatch field_name con1 con2
1376   = vcat [sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2, 
1377                 ptext (sLit "have a common field") <+> quotes (ppr field_name) <> comma],
1378           nest 2 $ ptext (sLit "but have different result types")]
1379
1380 fieldTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1381 fieldTypeMisMatch field_name con1 con2
1382   = sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2, 
1383          ptext (sLit "give different types for field"), quotes (ppr field_name)]
1384
1385 dataConCtxt :: Outputable a => a -> SDoc
1386 dataConCtxt con = ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
1387
1388 classOpCtxt :: Var -> Type -> SDoc
1389 classOpCtxt sel_id tau = sep [ptext (sLit "When checking the class method:"),
1390                               nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
1391
1392 nullaryClassErr :: Class -> SDoc
1393 nullaryClassErr cls
1394   = ptext (sLit "No parameters for class")  <+> quotes (ppr cls)
1395
1396 classArityErr :: Class -> SDoc
1397 classArityErr cls
1398   = vcat [ptext (sLit "Too many parameters for class") <+> quotes (ppr cls),
1399           parens (ptext (sLit "Use -XMultiParamTypeClasses to allow multi-parameter classes"))]
1400
1401 classFunDepsErr :: Class -> SDoc
1402 classFunDepsErr cls
1403   = vcat [ptext (sLit "Fundeps in class") <+> quotes (ppr cls),
1404           parens (ptext (sLit "Use -XFunctionalDependencies to allow fundeps"))]
1405
1406 noClassTyVarErr :: Class -> Var -> SDoc
1407 noClassTyVarErr clas op
1408   = sep [ptext (sLit "The class method") <+> quotes (ppr op),
1409          ptext (sLit "mentions none of the type variables of the class") <+> 
1410                 ppr clas <+> hsep (map ppr (classTyVars clas))]
1411
1412 genericMultiParamErr :: Class -> SDoc
1413 genericMultiParamErr clas
1414   = ptext (sLit "The multi-parameter class") <+> quotes (ppr clas) <+> 
1415     ptext (sLit "cannot have generic methods")
1416
1417 badGenericMethodType :: Name -> Kind -> SDoc
1418 badGenericMethodType op op_ty
1419   = hang (ptext (sLit "Generic method type is too complex"))
1420        4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
1421                 ptext (sLit "You can only use type variables, arrows, lists, and tuples")])
1422
1423 recSynErr :: [LTyClDecl Name] -> TcRn ()
1424 recSynErr syn_decls
1425   = setSrcSpan (getLoc (head sorted_decls)) $
1426     addErr (sep [ptext (sLit "Cycle in type synonym declarations:"),
1427                  nest 2 (vcat (map ppr_decl sorted_decls))])
1428   where
1429     sorted_decls = sortLocated syn_decls
1430     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
1431
1432 recClsErr :: [Located (TyClDecl Name)] -> TcRn ()
1433 recClsErr cls_decls
1434   = setSrcSpan (getLoc (head sorted_decls)) $
1435     addErr (sep [ptext (sLit "Cycle in class declarations (via superclasses):"),
1436                  nest 2 (vcat (map ppr_decl sorted_decls))])
1437   where
1438     sorted_decls = sortLocated cls_decls
1439     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
1440
1441 sortLocated :: [Located a] -> [Located a]
1442 sortLocated things = sortLe le things
1443   where
1444     le (L l1 _) (L l2 _) = l1 <= l2
1445
1446 badDataConTyCon :: DataCon -> Type -> Type -> SDoc
1447 badDataConTyCon data_con res_ty_tmpl actual_res_ty
1448   = hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con) <+>
1449                 ptext (sLit "returns type") <+> quotes (ppr actual_res_ty))
1450        2 (ptext (sLit "instead of an instance of its parent type") <+> quotes (ppr res_ty_tmpl))
1451
1452 badGadtDecl :: Name -> SDoc
1453 badGadtDecl tc_name
1454   = vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
1455          , nest 2 (parens $ ptext (sLit "Use -XGADTs to allow GADTs")) ]
1456
1457 badExistential :: Located Name -> SDoc
1458 badExistential con_name
1459   = hang (ptext (sLit "Data constructor") <+> quotes (ppr con_name) <+>
1460                 ptext (sLit "has existential type variables, or a context"))
1461        2 (parens $ ptext (sLit "Use -XExistentialQuantification or -XGADTs to allow this"))
1462
1463 badStupidTheta :: Name -> SDoc
1464 badStupidTheta tc_name
1465   = ptext (sLit "A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
1466
1467 newtypeConError :: Name -> Int -> SDoc
1468 newtypeConError tycon n
1469   = sep [ptext (sLit "A newtype must have exactly one constructor,"),
1470          nest 2 $ ptext (sLit "but") <+> quotes (ppr tycon) <+> ptext (sLit "has") <+> speakN n ]
1471
1472 newtypeExError :: DataCon -> SDoc
1473 newtypeExError con
1474   = sep [ptext (sLit "A newtype constructor cannot have an existential context,"),
1475          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1476
1477 newtypeStrictError :: DataCon -> SDoc
1478 newtypeStrictError con
1479   = sep [ptext (sLit "A newtype constructor cannot have a strictness annotation,"),
1480          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1481
1482 newtypePredError :: DataCon -> SDoc
1483 newtypePredError con
1484   = sep [ptext (sLit "A newtype constructor must have a return type of form T a1 ... an"),
1485          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does not")]
1486
1487 newtypeFieldErr :: DataCon -> Int -> SDoc
1488 newtypeFieldErr con_name n_flds
1489   = sep [ptext (sLit "The constructor of a newtype must have exactly one field"), 
1490          nest 2 $ ptext (sLit "but") <+> quotes (ppr con_name) <+> ptext (sLit "has") <+> speakN n_flds]
1491
1492 badSigTyDecl :: Name -> SDoc
1493 badSigTyDecl tc_name
1494   = vcat [ ptext (sLit "Illegal kind signature") <+>
1495            quotes (ppr tc_name)
1496          , nest 2 (parens $ ptext (sLit "Use -XKindSignatures to allow kind signatures")) ]
1497
1498 noIndexTypes :: Name -> SDoc
1499 noIndexTypes tc_name
1500   = ptext (sLit "Type family constructor") <+> quotes (ppr tc_name)
1501     <+> ptext (sLit "must have at least one type index parameter")
1502
1503 badFamInstDecl :: Outputable a => a -> SDoc
1504 badFamInstDecl tc_name
1505   = vcat [ ptext (sLit "Illegal family instance for") <+>
1506            quotes (ppr tc_name)
1507          , nest 2 (parens $ ptext (sLit "Use -XTypeFamilies to allow indexed type families")) ]
1508
1509 tooManyParmsErr :: Located Name -> SDoc
1510 tooManyParmsErr tc_name
1511   = ptext (sLit "Family instance has too many parameters:") <+> 
1512     quotes (ppr tc_name)
1513
1514 tooFewParmsErr :: Arity -> SDoc
1515 tooFewParmsErr arity
1516   = ptext (sLit "Family instance has too few parameters; expected") <+> 
1517     ppr arity
1518
1519 wrongNumberOfParmsErr :: Arity -> SDoc
1520 wrongNumberOfParmsErr exp_arity
1521   = ptext (sLit "Number of parameters must match family declaration; expected")
1522     <+> ppr exp_arity
1523
1524 badBootFamInstDeclErr :: SDoc
1525 badBootFamInstDeclErr
1526   = ptext (sLit "Illegal family instance in hs-boot file")
1527
1528 notFamily :: TyCon -> SDoc
1529 notFamily tycon
1530   = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tycon)
1531          , nest 2 $ parens (ppr tycon <+> ptext (sLit "is not an indexed type family"))]
1532   
1533 wrongKindOfFamily :: TyCon -> SDoc
1534 wrongKindOfFamily family
1535   = ptext (sLit "Wrong category of family instance; declaration was for a")
1536     <+> kindOfFamily
1537   where
1538     kindOfFamily | isSynTyCon family = ptext (sLit "type synonym")
1539                  | isAlgTyCon family = ptext (sLit "data type")
1540                  | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1541
1542 emptyConDeclsErr :: Name -> SDoc
1543 emptyConDeclsErr tycon
1544   = sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
1545          nest 2 $ ptext (sLit "(-XEmptyDataDecls permits this)")]
1546 \end{code}