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