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