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