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