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