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