Avoid nasty name clash with associated data types (fixes Trac #2888)
[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 \end{code}
229
230
231 %************************************************************************
232 %*                                                                      *
233 \subsection{Type checking family instances}
234 %*                                                                      *
235 %************************************************************************
236
237 Family instances are somewhat of a hybrid.  They are processed together with
238 class instance heads, but can contain data constructors and hence they share a
239 lot of kinding and type checking code with ordinary algebraic data types (and
240 GADTs).
241
242 \begin{code}
243 tcFamInstDecl :: LTyClDecl Name -> TcM TyThing
244 tcFamInstDecl (L loc decl)
245   =     -- Prime error recovery, set source location
246     setSrcSpan loc                              $
247     tcAddDeclCtxt decl                          $
248     do { -- type families require -XTypeFamilies and can't be in an
249          -- hs-boot file
250        ; type_families <- doptM Opt_TypeFamilies
251        ; is_boot  <- tcIsHsBoot   -- Are we compiling an hs-boot file?
252        ; checkTc type_families $ badFamInstDecl (tcdLName decl)
253        ; checkTc (not is_boot) $ badBootFamInstDeclErr
254
255          -- Perform kind and type checking
256        ; tc <- tcFamInstDecl1 decl
257        ; checkValidTyCon tc     -- Remember to check validity;
258                                 -- no recursion to worry about here
259        ; return (ATyCon tc) }
260
261 tcFamInstDecl1 :: TyClDecl Name -> TcM TyCon
262
263   -- "type instance"
264 tcFamInstDecl1 (decl@TySynonym {tcdLName = L loc tc_name})
265   = kcIdxTyPats decl $ \k_tvs k_typats resKind family ->
266     do { -- check that the family declaration is for a synonym
267          unless (isSynTyCon family) $
268            addErr (wrongKindOfFamily family)
269
270        ; -- (1) kind check the right-hand side of the type equation
271        ; k_rhs <- kcCheckHsType (tcdSynRhs decl) resKind
272
273          -- we need the exact same number of type parameters as the family
274          -- declaration 
275        ; let famArity = tyConArity family
276        ; checkTc (length k_typats == famArity) $ 
277            wrongNumberOfParmsErr famArity
278
279          -- (2) type check type equation
280        ; tcTyVarBndrs k_tvs $ \t_tvs -> do {  -- turn kinded into proper tyvars
281        ; t_typats <- mapM tcHsKindedType k_typats
282        ; t_rhs    <- tcHsKindedType k_rhs
283
284          -- (3) check the well-formedness of the instance
285        ; checkValidTypeInst t_typats t_rhs
286
287          -- (4) construct representation tycon
288        ; rep_tc_name <- newFamInstTyConName tc_name loc
289        ; buildSynTyCon rep_tc_name t_tvs (SynonymTyCon t_rhs) 
290                        (typeKind t_rhs) (Just (family, t_typats))
291        }}
292
293   -- "newtype instance" and "data instance"
294 tcFamInstDecl1 (decl@TyData {tcdND = new_or_data, tcdLName = L loc tc_name,
295                              tcdCons = cons})
296   = kcIdxTyPats decl $ \k_tvs k_typats resKind fam_tycon ->
297     do { -- check that the family declaration is for the right kind
298          unless (isAlgTyCon fam_tycon) $
299            addErr (wrongKindOfFamily fam_tycon)
300
301        ; -- (1) kind check the data declaration as usual
302        ; k_decl <- kcDataDecl decl k_tvs
303        ; let k_ctxt = tcdCtxt k_decl
304              k_cons = tcdCons k_decl
305
306          -- result kind must be '*' (otherwise, we have too few patterns)
307        ; checkTc (isLiftedTypeKind resKind) $ tooFewParmsErr (tyConArity fam_tycon)
308
309          -- (2) type check indexed data type declaration
310        ; tcTyVarBndrs k_tvs $ \t_tvs -> do {  -- turn kinded into proper tyvars
311        ; unbox_strict <- doptM Opt_UnboxStrictFields
312
313          -- kind check the type indexes and the context
314        ; t_typats     <- mapM tcHsKindedType k_typats
315        ; stupid_theta <- tcHsKindedContext k_ctxt
316
317          -- (3) Check that
318          --     (a) left-hand side contains no type family applications
319          --         (vanilla synonyms are fine, though, and we checked for
320          --         foralls earlier)
321        ; mapM_ checkTyFamFreeness t_typats
322
323          --     (b) a newtype has exactly one constructor
324        ; checkTc (new_or_data == DataType || isSingleton k_cons) $
325                  newtypeConError tc_name (length k_cons)
326
327          -- (4) construct representation tycon
328        ; rep_tc_name <- newFamInstTyConName tc_name loc
329        ; let ex_ok = True       -- Existentials ok for type families!
330        ; fixM (\ rep_tycon -> do 
331              { let orig_res_ty = mkTyConApp fam_tycon t_typats
332              ; data_cons <- tcConDecls unbox_strict ex_ok rep_tycon
333                                        (t_tvs, orig_res_ty) k_cons
334              ; tc_rhs <-
335                  case new_or_data of
336                    DataType -> return (mkDataTyConRhs data_cons)
337                    NewType  -> ASSERT( not (null data_cons) )
338                                mkNewTyConRhs rep_tc_name rep_tycon (head data_cons)
339              ; buildAlgTyCon rep_tc_name t_tvs stupid_theta tc_rhs Recursive
340                              False h98_syntax (Just (fam_tycon, t_typats))
341                  -- We always assume that indexed types are recursive.  Why?
342                  -- (1) Due to their open nature, we can never be sure that a
343                  -- further instance might not introduce a new recursive
344                  -- dependency.  (2) They are always valid loop breakers as
345                  -- they involve a coercion.
346              })
347        }}
348        where
349          h98_syntax = case cons of      -- All constructors have same shape
350                         L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
351                         _ -> True
352
353 tcFamInstDecl1 d = pprPanic "tcFamInstDecl1" (ppr d)
354
355 -- Kind checking of indexed types
356 -- -
357
358 -- Kind check type patterns and kind annotate the embedded type variables.
359 --
360 -- * Here we check that a type instance matches its kind signature, but we do
361 --   not check whether there is a pattern for each type index; the latter
362 --   check is only required for type synonym instances.
363 --
364 kcIdxTyPats :: TyClDecl Name
365             -> ([LHsTyVarBndr Name] -> [LHsType Name] -> Kind -> TyCon -> TcM a)
366                -- ^^kinded tvs         ^^kinded ty pats  ^^res kind
367             -> TcM a
368 kcIdxTyPats decl thing_inside
369   = kcHsTyVars (tcdTyVars decl) $ \tvs -> 
370     do { fam_tycon <- tcLookupLocatedTyCon (tcdLName decl)
371        ; let { (kinds, resKind) = splitKindFunTys (tyConKind fam_tycon)
372              ; hs_typats        = fromJust $ tcdTyPats decl }
373
374          -- we may not have more parameters than the kind indicates
375        ; checkTc (length kinds >= length hs_typats) $
376            tooManyParmsErr (tcdLName decl)
377
378          -- type functions can have a higher-kinded result
379        ; let resultKind = mkArrowKinds (drop (length hs_typats) kinds) resKind
380        ; typats <- zipWithM kcCheckHsType hs_typats kinds
381        ; thing_inside tvs typats resultKind fam_tycon
382        }
383   where
384 \end{code}
385
386
387 %************************************************************************
388 %*                                                                      *
389                 Kind checking
390 %*                                                                      *
391 %************************************************************************
392
393 We need to kind check all types in the mutually recursive group
394 before we know the kind of the type variables.  For example:
395
396 class C a where
397    op :: D b => a -> b -> b
398
399 class D c where
400    bop :: (Monad c) => ...
401
402 Here, the kind of the locally-polymorphic type variable "b"
403 depends on *all the uses of class D*.  For example, the use of
404 Monad c in bop's type signature means that D must have kind Type->Type.
405
406 However type synonyms work differently.  They can have kinds which don't
407 just involve (->) and *:
408         type R = Int#           -- Kind #
409         type S a = Array# a     -- Kind * -> #
410         type T a b = (# a,b #)  -- Kind * -> * -> (# a,b #)
411 So we must infer their kinds from their right-hand sides *first* and then
412 use them, whereas for the mutually recursive data types D we bring into
413 scope kind bindings D -> k, where k is a kind variable, and do inference.
414
415 Type families
416 ~~~~~~~~~~~~~
417 This treatment of type synonyms only applies to Haskell 98-style synonyms.
418 General type functions can be recursive, and hence, appear in `alg_decls'.
419
420 The kind of a type family is solely determinded by its kind signature;
421 hence, only kind signatures participate in the construction of the initial
422 kind environment (as constructed by `getInitialKind').  In fact, we ignore
423 instances of families altogether in the following.  However, we need to
424 include the kinds of associated families into the construction of the
425 initial kind environment.  (This is handled by `allDecls').
426
427 \begin{code}
428 kcTyClDecls :: [LTyClDecl Name] -> [Located (TyClDecl Name)]
429             -> TcM ([LTyClDecl Name], [Located (TyClDecl Name)])
430 kcTyClDecls syn_decls alg_decls
431   = do  {       -- First extend the kind env with each data type, class, and
432                 -- indexed type, mapping them to a type variable
433           let initialKindDecls = concat [allDecls decl | L _ decl <- alg_decls]
434         ; alg_kinds <- mapM getInitialKind initialKindDecls
435         ; tcExtendKindEnv alg_kinds $ do
436
437                 -- Now kind-check the type synonyms, in dependency order
438                 -- We do these differently to data type and classes,
439                 -- because a type synonym can be an unboxed type
440                 --      type Foo = Int#
441                 -- and a kind variable can't unify with UnboxedTypeKind
442                 -- So we infer their kinds in dependency order
443         { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
444         ; tcExtendKindEnv syn_kinds $  do
445
446                 -- Now kind-check the data type, class, and kind signatures,
447                 -- returning kind-annotated decls; we don't kind-check
448                 -- instances of indexed types yet, but leave this to
449                 -- `tcInstDecls1'
450         { kc_alg_decls <- mapM (wrapLocM kcTyClDecl)
451                             (filter (not . isFamInstDecl . unLoc) alg_decls)
452
453         ; return (kc_syn_decls, kc_alg_decls) }}}
454   where
455     -- get all declarations relevant for determining the initial kind
456     -- environment
457     allDecls (decl@ClassDecl {tcdATs = ats}) = decl : [ at 
458                                                       | L _ at <- ats
459                                                       , isFamilyDecl at]
460     allDecls decl | isFamInstDecl decl = []
461                   | otherwise          = [decl]
462
463 ------------------------------------------------------------------------
464 getInitialKind :: TyClDecl Name -> TcM (Name, TcKind)
465 -- Only for data type, class, and indexed type declarations
466 -- Get as much info as possible from the data, class, or indexed type decl,
467 -- so as to maximise usefulness of error messages
468 getInitialKind decl
469   = do  { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
470         ; res_kind  <- mk_res_kind decl
471         ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
472   where
473     mk_arg_kind (UserTyVar _)        = newKindVar
474     mk_arg_kind (KindedTyVar _ kind) = return kind
475
476     mk_res_kind (TyFamily { tcdKind    = Just kind }) = return kind
477     mk_res_kind (TyData   { tcdKindSig = Just kind }) = return kind
478         -- On GADT-style declarations we allow a kind signature
479         --      data T :: *->* where { ... }
480     mk_res_kind _ = return liftedTypeKind
481
482
483 ----------------
484 kcSynDecls :: [SCC (LTyClDecl Name)] 
485            -> TcM ([LTyClDecl Name],    -- Kind-annotated decls
486                    [(Name,TcKind)])     -- Kind bindings
487 kcSynDecls []
488   = return ([], [])
489 kcSynDecls (group : groups)
490   = do  { (decl,  nk)  <- kcSynDecl group
491         ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
492         ; return (decl:decls, nk:nks) }
493                         
494 ----------------
495 kcSynDecl :: SCC (LTyClDecl Name) 
496            -> TcM (LTyClDecl Name,      -- Kind-annotated decls
497                    (Name,TcKind))       -- Kind bindings
498 kcSynDecl (AcyclicSCC (L loc decl))
499   = tcAddDeclCtxt decl  $
500     kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
501     do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl)) 
502                         <+> brackets (ppr k_tvs))
503        ; (k_rhs, rhs_kind) <- kcHsType (tcdSynRhs decl)
504        ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
505        ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
506        ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
507                  (unLoc (tcdLName decl), tc_kind)) })
508
509 kcSynDecl (CyclicSCC decls)
510   = do { recSynErr decls; failM }       -- Fail here to avoid error cascade
511                                         -- of out-of-scope tycons
512
513 kindedTyVarKind :: LHsTyVarBndr Name -> Kind
514 kindedTyVarKind (L _ (KindedTyVar _ k)) = k
515 kindedTyVarKind x = pprPanic "kindedTyVarKind" (ppr x)
516
517 ------------------------------------------------------------------------
518 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
519         -- Not used for type synonyms (see kcSynDecl)
520
521 kcTyClDecl decl@(TyData {})
522   = ASSERT( not . isFamInstDecl $ decl )   -- must not be a family instance
523     kcTyClDeclBody decl $
524       kcDataDecl decl
525
526 kcTyClDecl decl@(TyFamily {})
527   = kcFamilyDecl [] decl      -- the empty list signals a toplevel decl      
528
529 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs, tcdATs = ats})
530   = kcTyClDeclBody decl $ \ tvs' ->
531     do  { ctxt' <- kcHsContext ctxt     
532         ; ats'  <- mapM (wrapLocM (kcFamilyDecl tvs')) ats
533         ; sigs' <- mapM (wrapLocM kc_sig) sigs
534         ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs',
535                         tcdATs = ats'}) }
536   where
537     kc_sig (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
538                                    ; return (TypeSig nm op_ty') }
539     kc_sig other_sig          = return other_sig
540
541 kcTyClDecl decl@(ForeignType {})
542   = return decl
543
544 kcTyClDecl (TySynonym {}) = panic "kcTyClDecl TySynonym"
545
546 kcTyClDeclBody :: TyClDecl Name
547                -> ([LHsTyVarBndr Name] -> TcM a)
548                -> TcM a
549 -- getInitialKind has made a suitably-shaped kind for the type or class
550 -- Unpack it, and attribute those kinds to the type variables
551 -- Extend the env with bindings for the tyvars, taken from
552 -- the kind of the tycon/class.  Give it to the thing inside, and 
553 -- check the result kind matches
554 kcTyClDeclBody decl thing_inside
555   = tcAddDeclCtxt decl          $
556     do  { tc_ty_thing <- tcLookupLocated (tcdLName decl)
557         ; let tc_kind    = case tc_ty_thing of
558                            AThing k -> k
559                            _ -> pprPanic "kcTyClDeclBody" (ppr tc_ty_thing)
560               (kinds, _) = splitKindFunTys tc_kind
561               hs_tvs     = tcdTyVars decl
562               kinded_tvs = ASSERT( length kinds >= length hs_tvs )
563                            [ L loc (KindedTyVar (hsTyVarName tv) k)
564                            | (L loc tv, k) <- zip hs_tvs kinds]
565         ; tcExtendKindEnvTvs kinded_tvs (thing_inside kinded_tvs) }
566
567 -- Kind check a data declaration, assuming that we already extended the
568 -- kind environment with the type variables of the left-hand side (these
569 -- kinded type variables are also passed as the second parameter).
570 --
571 kcDataDecl :: TyClDecl Name -> [LHsTyVarBndr Name] -> TcM (TyClDecl Name)
572 kcDataDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
573            tvs
574   = do  { ctxt' <- kcHsContext ctxt     
575         ; cons' <- mapM (wrapLocM kc_con_decl) cons
576         ; return (decl {tcdTyVars = tvs, tcdCtxt = ctxt', tcdCons = cons'}) }
577   where
578     -- doc comments are typechecked to Nothing here
579     kc_con_decl (ConDecl name expl ex_tvs ex_ctxt details res _) = do
580       kcHsTyVars ex_tvs $ \ex_tvs' -> do
581         ex_ctxt' <- kcHsContext ex_ctxt
582         details' <- kc_con_details details 
583         res'     <- case res of
584           ResTyH98 -> return ResTyH98
585           ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
586         return (ConDecl name expl ex_tvs' ex_ctxt' details' res' Nothing)
587
588     kc_con_details (PrefixCon btys) 
589         = do { btys' <- mapM kc_larg_ty btys 
590              ; return (PrefixCon btys') }
591     kc_con_details (InfixCon bty1 bty2) 
592         = do { bty1' <- kc_larg_ty bty1
593              ; bty2' <- kc_larg_ty bty2
594              ; return (InfixCon bty1' bty2') }
595     kc_con_details (RecCon fields) 
596         = do { fields' <- mapM kc_field fields
597              ; return (RecCon fields') }
598
599     kc_field (ConDeclField fld bty d) = do { bty' <- kc_larg_ty bty
600                                            ; return (ConDeclField fld bty' d) }
601
602     kc_larg_ty bty = case new_or_data of
603                         DataType -> kcHsSigType bty
604                         NewType  -> kcHsLiftedSigType bty
605         -- Can't allow an unlifted type for newtypes, because we're effectively
606         -- going to remove the constructor while coercing it to a lifted type.
607         -- And newtypes can't be bang'd
608 kcDataDecl d _ = pprPanic "kcDataDecl" (ppr d)
609
610 -- Kind check a family declaration or type family default declaration.
611 --
612 kcFamilyDecl :: [LHsTyVarBndr Name]  -- tyvars of enclosing class decl if any
613              -> TyClDecl Name -> TcM (TyClDecl Name)
614 kcFamilyDecl classTvs decl@(TyFamily {tcdKind = kind})
615   = kcTyClDeclBody decl $ \tvs' ->
616     do { mapM_ unifyClassParmKinds tvs'
617        ; return (decl {tcdTyVars = tvs', 
618                        tcdKind = kind `mplus` Just liftedTypeKind})
619                        -- default result kind is '*'
620        }
621   where
622     unifyClassParmKinds (L _ (KindedTyVar n k))
623       | Just classParmKind <- lookup n classTyKinds = unifyKind k classParmKind
624       | otherwise                                   = return ()
625     unifyClassParmKinds x = pprPanic "kcFamilyDecl/unifyClassParmKinds" (ppr x)
626     classTyKinds = [(n, k) | L _ (KindedTyVar n k) <- classTvs]
627 kcFamilyDecl _ (TySynonym {})              -- type family defaults
628   = panic "TcTyClsDecls.kcFamilyDecl: not implemented yet"
629 kcFamilyDecl _ d = pprPanic "kcFamilyDecl" (ppr d)
630 \end{code}
631
632
633 %************************************************************************
634 %*                                                                      *
635 \subsection{Type checking}
636 %*                                                                      *
637 %************************************************************************
638
639 \begin{code}
640 tcSynDecls :: [LTyClDecl Name] -> TcM [TyThing]
641 tcSynDecls [] = return []
642 tcSynDecls (decl : decls) 
643   = do { syn_tc <- addLocM tcSynDecl decl
644        ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls decls)
645        ; return (syn_tc : syn_tcs) }
646
647   -- "type"
648 tcSynDecl :: TyClDecl Name -> TcM TyThing
649 tcSynDecl
650   (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
651   = tcTyVarBndrs tvs            $ \ tvs' -> do 
652     { traceTc (text "tcd1" <+> ppr tc_name) 
653     ; rhs_ty' <- tcHsKindedType rhs_ty
654     ; tycon <- buildSynTyCon tc_name tvs' (SynonymTyCon rhs_ty') 
655                              (typeKind rhs_ty') Nothing
656     ; return (ATyCon tycon) 
657     }
658 tcSynDecl d = pprPanic "tcSynDecl" (ppr d)
659
660 --------------------
661 tcTyClDecl :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
662
663 tcTyClDecl calc_isrec decl
664   = tcAddDeclCtxt decl (tcTyClDecl1 calc_isrec decl)
665
666   -- "type family" declarations
667 tcTyClDecl1 :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
668 tcTyClDecl1 _calc_isrec 
669   (TyFamily {tcdFlavour = TypeFamily, 
670              tcdLName = L _ tc_name, tcdTyVars = tvs,
671              tcdKind = Just kind}) -- NB: kind at latest added during kind checking
672   = tcTyVarBndrs tvs  $ \ tvs' -> do 
673   { traceTc (text "type family: " <+> ppr tc_name) 
674
675         -- Check that we don't use families without -XTypeFamilies
676   ; idx_tys <- doptM Opt_TypeFamilies
677   ; checkTc idx_tys $ badFamInstDecl tc_name
678
679         -- Check for no type indices
680   ; checkTc (not (null tvs)) (noIndexTypes tc_name)
681
682   ; tycon <- buildSynTyCon tc_name tvs' (OpenSynTyCon kind Nothing) kind Nothing
683   ; return [ATyCon tycon]
684   }
685
686   -- "data family" declaration
687 tcTyClDecl1 _calc_isrec 
688   (TyFamily {tcdFlavour = DataFamily, 
689              tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = mb_kind})
690   = tcTyVarBndrs tvs  $ \ tvs' -> do 
691   { traceTc (text "data family: " <+> ppr tc_name) 
692   ; extra_tvs <- tcDataKindSig mb_kind
693   ; let final_tvs = tvs' ++ extra_tvs    -- we may not need these
694
695
696         -- Check that we don't use families without -XTypeFamilies
697   ; idx_tys <- doptM Opt_TypeFamilies
698   ; checkTc idx_tys $ badFamInstDecl tc_name
699
700         -- Check for no type indices
701   ; checkTc (not (null tvs)) (noIndexTypes 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' = map (setAssocFamilyPermutation tvs') (concat atss)
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 tcTyClDecl1 _
800   (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
801   = return [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
802
803 tcTyClDecl1 _ d = pprPanic "tcTyClDecl1" (ppr d)
804
805 -----------------------------------
806 tcConDecls :: Bool -> Bool -> TyCon -> ([TyVar], Type)
807            -> [LConDecl Name] -> TcM [DataCon]
808 tcConDecls unbox ex_ok rep_tycon res_tmpl cons
809   = mapM (addLocM (tcConDecl unbox ex_ok rep_tycon res_tmpl)) cons
810
811 tcConDecl :: Bool               -- True <=> -funbox-strict_fields
812           -> Bool               -- True <=> -XExistentialQuantificaton or -XGADTs
813           -> TyCon              -- Representation tycon
814           -> ([TyVar], Type)    -- Return type template (with its template tyvars)
815           -> ConDecl Name 
816           -> TcM DataCon
817
818 tcConDecl unbox_strict existential_ok rep_tycon res_tmpl        -- Data types
819           (ConDecl name _ tvs ctxt details res_ty _)
820   = addErrCtxt (dataConCtxt name)       $ 
821     tcTyVarBndrs tvs                    $ \ tvs' -> do 
822     { ctxt' <- tcHsKindedContext ctxt
823     ; checkTc (existential_ok || (null tvs && null (unLoc ctxt)))
824               (badExistential name)
825     ; (univ_tvs, ex_tvs, eq_preds, res_ty') <- tcResultType res_tmpl tvs' res_ty
826     ; let 
827         tc_datacon is_infix field_lbls btys
828           = do { (arg_tys, stricts) <- mapAndUnzipM (tcConArg unbox_strict) btys
829                ; buildDataCon (unLoc name) is_infix
830                     stricts field_lbls
831                     univ_tvs ex_tvs eq_preds ctxt' arg_tys
832                     res_ty' rep_tycon }
833                 -- NB:  we put data_tc, the type constructor gotten from the
834                 --      constructor type signature into the data constructor;
835                 --      that way checkValidDataCon can complain if it's wrong.
836
837     ; case details of
838         PrefixCon btys     -> tc_datacon False [] btys
839         InfixCon bty1 bty2 -> tc_datacon True  [] [bty1,bty2]
840         RecCon fields      -> tc_datacon False field_names btys
841                            where
842                               field_names = map (unLoc . cd_fld_name) fields
843                               btys        = map cd_fld_type fields
844     }
845
846 -- Example
847 --   data instance T (b,c) where 
848 --      TI :: forall e. e -> T (e,e)
849 --
850 -- The representation tycon looks like this:
851 --   data :R7T b c where 
852 --      TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
853 -- In this case orig_res_ty = T (e,e)
854
855 tcResultType :: ([TyVar], Type) -- Template for result type; e.g.
856                                 -- data T a b c = ...  gives ([a,b,c], T a b)
857              -> [TyVar]         -- where MkT :: forall a b c. ...
858              -> ResType Name
859              -> TcM ([TyVar],           -- Universal
860                      [TyVar],           -- Existential (distinct OccNames from univs)
861                      [(TyVar,Type)],    -- Equality predicates
862                      Type)              -- Typechecked return type
863         -- We don't check that the TyCon given in the ResTy is
864         -- the same as the parent tycon, becuase we are in the middle
865         -- of a recursive knot; so it's postponed until checkValidDataCon
866
867 tcResultType (tmpl_tvs, res_ty) dc_tvs ResTyH98
868   = return (tmpl_tvs, dc_tvs, [], res_ty)
869         -- In H98 syntax the dc_tvs are the existential ones
870         --      data T a b c = forall d e. MkT ...
871         -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
872
873 tcResultType (tmpl_tvs, res_tmpl) dc_tvs (ResTyGADT res_ty)
874         -- E.g.  data T [a] b c where
875         --         MkT :: forall x y z. T [(x,y)] z z
876         -- Then we generate
877         --      Univ tyvars     Eq-spec
878         --          a              a~(x,y)
879         --          b              b~z
880         --          z              
881         -- Existentials are the leftover type vars: [x,y]
882   = do  { res_ty' <- tcHsKindedType res_ty
883         ; let Just subst = tcMatchTy (mkVarSet tmpl_tvs) res_tmpl res_ty'
884
885                 -- /Lazily/ figure out the univ_tvs etc
886                 -- Each univ_tv is either a dc_tv or a tmpl_tv
887               (univ_tvs, eq_spec) = foldr choose ([], []) tidy_tmpl_tvs
888               choose tmpl (univs, eqs)
889                 | Just ty <- lookupTyVar subst tmpl 
890                 = case tcGetTyVar_maybe ty of
891                     Just tv | not (tv `elem` univs)
892                             -> (tv:univs,   eqs)
893                     _other  -> (tmpl:univs, (tmpl,ty):eqs)
894                 | otherwise = pprPanic "tcResultType" (ppr res_ty)
895               ex_tvs = dc_tvs `minusList` univ_tvs
896
897         ; return (univ_tvs, ex_tvs, eq_spec, res_ty') }
898   where
899         -- NB: tmpl_tvs and dc_tvs are distinct, but
900         -- we want them to be *visibly* distinct, both for
901         -- interface files and general confusion.  So rename
902         -- the tc_tvs, since they are not used yet (no 
903         -- consequential renaming needed)
904     (_, tidy_tmpl_tvs) = mapAccumL tidy_one init_occ_env tmpl_tvs
905     init_occ_env       = initTidyOccEnv (map getOccName dc_tvs)
906     tidy_one env tv    = (env', setTyVarName tv (tidyNameOcc name occ'))
907               where
908                  name = tyVarName tv
909                  (env', occ') = tidyOccName env (getOccName name) 
910
911 -------------------
912 tcConArg :: Bool                -- True <=> -funbox-strict_fields
913            -> LHsType Name
914            -> TcM (TcType, StrictnessMark)
915 tcConArg unbox_strict bty
916   = do  { arg_ty <- tcHsBangType bty
917         ; let bang = getBangStrictness bty
918         ; return (arg_ty, chooseBoxingStrategy unbox_strict arg_ty bang) }
919
920 -- We attempt to unbox/unpack a strict field when either:
921 --   (i)  The field is marked '!!', or
922 --   (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
923 --
924 -- We have turned off unboxing of newtypes because coercions make unboxing 
925 -- and reboxing more complicated
926 chooseBoxingStrategy :: Bool -> TcType -> HsBang -> StrictnessMark
927 chooseBoxingStrategy unbox_strict_fields arg_ty bang
928   = case bang of
929         HsNoBang                                    -> NotMarkedStrict
930         HsStrict | unbox_strict_fields 
931                    && can_unbox arg_ty              -> MarkedUnboxed
932         HsUnbox  | can_unbox arg_ty                 -> MarkedUnboxed
933         _                                           -> MarkedStrict
934   where
935     -- we can unbox if the type is a chain of newtypes with a product tycon
936     -- at the end
937     can_unbox arg_ty = case splitTyConApp_maybe arg_ty of
938                    Nothing                      -> False
939                    Just (arg_tycon, tycon_args) -> 
940                        not (isRecursiveTyCon arg_tycon) &&      -- Note [Recusive unboxing]
941                        isProductTyCon arg_tycon &&
942                        (if isNewTyCon arg_tycon then 
943                             can_unbox (newTyConInstRhs arg_tycon tycon_args)
944                         else True)
945 \end{code}
946
947 Note [Recursive unboxing]
948 ~~~~~~~~~~~~~~~~~~~~~~~~~
949 Be careful not to try to unbox this!
950         data T = MkT !T Int
951 But it's the *argument* type that matters. This is fine:
952         data S = MkS S !Int
953 because Int is non-recursive.
954
955 %************************************************************************
956 %*                                                                      *
957 \subsection{Dependency analysis}
958 %*                                                                      *
959 %************************************************************************
960
961 Validity checking is done once the mutually-recursive knot has been
962 tied, so we can look at things freely.
963
964 \begin{code}
965 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
966 checkCycleErrs tyclss
967   | null cls_cycles
968   = return ()
969   | otherwise
970   = do  { mapM_ recClsErr cls_cycles
971         ; failM }       -- Give up now, because later checkValidTyCl
972                         -- will loop if the synonym is recursive
973   where
974     cls_cycles = calcClassCycles tyclss
975
976 checkValidTyCl :: TyClDecl Name -> TcM ()
977 -- We do the validity check over declarations, rather than TyThings
978 -- only so that we can add a nice context with tcAddDeclCtxt
979 checkValidTyCl decl
980   = tcAddDeclCtxt decl $
981     do  { thing <- tcLookupLocatedGlobal (tcdLName decl)
982         ; traceTc (text "Validity of" <+> ppr thing)    
983         ; case thing of
984             ATyCon tc -> checkValidTyCon tc
985             AClass cl -> checkValidClass cl 
986             _ -> panic "checkValidTyCl"
987         ; traceTc (text "Done validity of" <+> ppr thing)       
988         }
989
990 -------------------------
991 -- For data types declared with record syntax, we require
992 -- that each constructor that has a field 'f' 
993 --      (a) has the same result type
994 --      (b) has the same type for 'f'
995 -- module alpha conversion of the quantified type variables
996 -- of the constructor.
997 --
998 -- Note that we allow existentials to match becuase the
999 -- fields can never meet. E.g
1000 --      data T where
1001 --        T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
1002 --        T2 { f1 :: c, f2 :: c, f3 ::Int } :: T  
1003 -- Here we do not complain about f1,f2 because they are existential
1004
1005 checkValidTyCon :: TyCon -> TcM ()
1006 checkValidTyCon tc 
1007   | isSynTyCon tc 
1008   = case synTyConRhs tc of
1009       OpenSynTyCon _ _ -> return ()
1010       SynonymTyCon ty  -> checkValidType syn_ctxt ty
1011   | otherwise
1012   = do  -- Check the context on the data decl
1013     checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
1014         
1015         -- Check arg types of data constructors
1016     mapM_ (checkValidDataCon tc) data_cons
1017
1018         -- Check that fields with the same name share a type
1019     mapM_ check_fields groups
1020
1021   where
1022     syn_ctxt  = TySynCtxt name
1023     name      = tyConName tc
1024     data_cons = tyConDataCons tc
1025
1026     groups = equivClasses cmp_fld (concatMap get_fields data_cons)
1027     cmp_fld (f1,_) (f2,_) = f1 `compare` f2
1028     get_fields con = dataConFieldLabels con `zip` repeat con
1029         -- dataConFieldLabels may return the empty list, which is fine
1030
1031     -- See Note [GADT record selectors] in MkId.lhs
1032     -- We must check (a) that the named field has the same 
1033     --                   type in each constructor
1034     --               (b) that those constructors have the same result type
1035     --
1036     -- However, the constructors may have differently named type variable
1037     -- and (worse) we don't know how the correspond to each other.  E.g.
1038     --     C1 :: forall a b. { f :: a, g :: b } -> T a b
1039     --     C2 :: forall d c. { f :: c, g :: c } -> T c d
1040     -- 
1041     -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
1042     -- result type against other candidates' types BOTH WAYS ROUND.
1043     -- If they magically agrees, take the substitution and
1044     -- apply them to the latter ones, and see if they match perfectly.
1045     check_fields ((label, con1) : other_fields)
1046         -- These fields all have the same name, but are from
1047         -- different constructors in the data type
1048         = recoverM (return ()) $ mapM_ checkOne other_fields
1049                 -- Check that all the fields in the group have the same type
1050                 -- NB: this check assumes that all the constructors of a given
1051                 -- data type use the same type variables
1052         where
1053         (tvs1, _, _, res1) = dataConSig con1
1054         ts1 = mkVarSet tvs1
1055         fty1 = dataConFieldType con1 label
1056
1057         checkOne (_, con2)    -- Do it bothways to ensure they are structurally identical
1058             = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
1059                  ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
1060             where        
1061                 (tvs2, _, _, res2) = dataConSig con2
1062                 ts2 = mkVarSet tvs2
1063                 fty2 = dataConFieldType con2 label
1064     check_fields [] = panic "checkValidTyCon/check_fields []"
1065
1066 checkFieldCompat :: Name -> DataCon -> DataCon -> TyVarSet
1067                  -> Type -> Type -> Type -> Type -> TcM ()
1068 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
1069   = do  { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
1070         ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
1071   where
1072     mb_subst1 = tcMatchTy tvs1 res1 res2
1073     mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
1074
1075 -------------------------------
1076 checkValidDataCon :: TyCon -> DataCon -> TcM ()
1077 checkValidDataCon tc con
1078   = setSrcSpan (srcLocSpan (getSrcLoc con))     $
1079     addErrCtxt (dataConCtxt con)                $ 
1080     do  { let tc_tvs = tyConTyVars tc
1081               res_ty_tmpl = mkFamilyTyConApp tc (mkTyVarTys tc_tvs)
1082               actual_res_ty = dataConOrigResTy con
1083         ; checkTc (isJust (tcMatchTy (mkVarSet tc_tvs)
1084                                 res_ty_tmpl
1085                                 actual_res_ty))
1086                   (badDataConTyCon con res_ty_tmpl actual_res_ty)
1087         ; checkValidMonoType (dataConOrigResTy con)
1088                 -- Disallow MkT :: T (forall a. a->a)
1089                 -- Reason: it's really the argument of an equality constraint
1090         ; checkValidType ctxt (dataConUserType con)
1091         ; when (isNewTyCon tc) (checkNewDataCon con)
1092     }
1093   where
1094     ctxt = ConArgCtxt (dataConName con) 
1095
1096 -------------------------------
1097 checkNewDataCon :: DataCon -> TcM ()
1098 -- Checks for the data constructor of a newtype
1099 checkNewDataCon con
1100   = do  { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
1101                 -- One argument
1102         ; checkTc (null eq_spec) (newtypePredError con)
1103                 -- Return type is (T a b c)
1104         ; checkTc (null ex_tvs && null eq_theta && null dict_theta) (newtypeExError con)
1105                 -- No existentials
1106         ; checkTc (not (any isMarkedStrict (dataConStrictMarks con))) 
1107                   (newtypeStrictError con)
1108                 -- No strictness
1109     }
1110   where
1111     (_univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _res_ty) = dataConFullSig con
1112
1113 -------------------------------
1114 checkValidClass :: Class -> TcM ()
1115 checkValidClass cls
1116   = do  { constrained_class_methods <- doptM Opt_ConstrainedClassMethods
1117         ; multi_param_type_classes <- doptM Opt_MultiParamTypeClasses
1118         ; fundep_classes <- doptM Opt_FunctionalDependencies
1119
1120         -- Check that the class is unary, unless GlaExs
1121         ; checkTc (notNull tyvars) (nullaryClassErr cls)
1122         ; checkTc (multi_param_type_classes || unary) (classArityErr cls)
1123         ; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
1124
1125         -- Check the super-classes
1126         ; checkValidTheta (ClassSCCtxt (className cls)) theta
1127
1128         -- Check the class operations
1129         ; mapM_ (check_op constrained_class_methods) op_stuff
1130
1131         -- Check that if the class has generic methods, then the
1132         -- class has only one parameter.  We can't do generic
1133         -- multi-parameter type classes!
1134         ; checkTc (unary || no_generics) (genericMultiParamErr cls)
1135         }
1136   where
1137     (tyvars, fundeps, theta, _, _, op_stuff) = classExtraBigSig cls
1138     unary       = isSingleton tyvars
1139     no_generics = null [() | (_, GenDefMeth) <- op_stuff]
1140
1141     check_op constrained_class_methods (sel_id, dm) 
1142       = addErrCtxt (classOpCtxt sel_id tau) $ do
1143         { checkValidTheta SigmaCtxt (tail theta)
1144                 -- The 'tail' removes the initial (C a) from the
1145                 -- class itself, leaving just the method type
1146
1147         ; traceTc (text "class op type" <+> ppr op_ty <+> ppr tau)
1148         ; checkValidType (FunSigCtxt op_name) tau
1149
1150                 -- Check that the type mentions at least one of
1151                 -- the class type variables...or at least one reachable
1152                 -- from one of the class variables.  Example: tc223
1153                 --   class Error e => Game b mv e | b -> mv e where
1154                 --      newBoard :: MonadState b m => m ()
1155                 -- Here, MonadState has a fundep m->b, so newBoard is fine
1156         ; let grown_tyvars = grow theta (mkVarSet tyvars)
1157         ; checkTc (tyVarsOfType tau `intersectsVarSet` grown_tyvars)
1158                   (noClassTyVarErr cls sel_id)
1159
1160                 -- Check that for a generic method, the type of 
1161                 -- the method is sufficiently simple
1162         ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
1163                   (badGenericMethodType op_name op_ty)
1164         }
1165         where
1166           op_name = idName sel_id
1167           op_ty   = idType sel_id
1168           (_,theta1,tau1) = tcSplitSigmaTy op_ty
1169           (_,theta2,tau2)  = tcSplitSigmaTy tau1
1170           (theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
1171                       | otherwise = (theta1, mkPhiTy (tail theta1) tau1)
1172                 -- Ugh!  The function might have a type like
1173                 --      op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
1174                 -- With -XConstrainedClassMethods, we want to allow this, even though the inner 
1175                 -- forall has an (Eq a) constraint.  Whereas in general, each constraint 
1176                 -- in the context of a for-all must mention at least one quantified
1177                 -- type variable.  What a mess!
1178
1179
1180 ---------------------------------------------------------------------
1181 resultTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1182 resultTypeMisMatch field_name con1 con2
1183   = vcat [sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2, 
1184                 ptext (sLit "have a common field") <+> quotes (ppr field_name) <> comma],
1185           nest 2 $ ptext (sLit "but have different result types")]
1186
1187 fieldTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1188 fieldTypeMisMatch field_name con1 con2
1189   = sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2, 
1190          ptext (sLit "give different types for field"), quotes (ppr field_name)]
1191
1192 dataConCtxt :: Outputable a => a -> SDoc
1193 dataConCtxt con = ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
1194
1195 classOpCtxt :: Var -> Type -> SDoc
1196 classOpCtxt sel_id tau = sep [ptext (sLit "When checking the class method:"),
1197                               nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
1198
1199 nullaryClassErr :: Class -> SDoc
1200 nullaryClassErr cls
1201   = ptext (sLit "No parameters for class")  <+> quotes (ppr cls)
1202
1203 classArityErr :: Class -> SDoc
1204 classArityErr cls
1205   = vcat [ptext (sLit "Too many parameters for class") <+> quotes (ppr cls),
1206           parens (ptext (sLit "Use -XMultiParamTypeClasses to allow multi-parameter classes"))]
1207
1208 classFunDepsErr :: Class -> SDoc
1209 classFunDepsErr cls
1210   = vcat [ptext (sLit "Fundeps in class") <+> quotes (ppr cls),
1211           parens (ptext (sLit "Use -XFunctionalDependencies to allow fundeps"))]
1212
1213 noClassTyVarErr :: Class -> Var -> SDoc
1214 noClassTyVarErr clas op
1215   = sep [ptext (sLit "The class method") <+> quotes (ppr op),
1216          ptext (sLit "mentions none of the type variables of the class") <+> 
1217                 ppr clas <+> hsep (map ppr (classTyVars clas))]
1218
1219 genericMultiParamErr :: Class -> SDoc
1220 genericMultiParamErr clas
1221   = ptext (sLit "The multi-parameter class") <+> quotes (ppr clas) <+> 
1222     ptext (sLit "cannot have generic methods")
1223
1224 badGenericMethodType :: Name -> Kind -> SDoc
1225 badGenericMethodType op op_ty
1226   = hang (ptext (sLit "Generic method type is too complex"))
1227        4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
1228                 ptext (sLit "You can only use type variables, arrows, lists, and tuples")])
1229
1230 recSynErr :: [LTyClDecl Name] -> TcRn ()
1231 recSynErr syn_decls
1232   = setSrcSpan (getLoc (head sorted_decls)) $
1233     addErr (sep [ptext (sLit "Cycle in type synonym declarations:"),
1234                  nest 2 (vcat (map ppr_decl sorted_decls))])
1235   where
1236     sorted_decls = sortLocated syn_decls
1237     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
1238
1239 recClsErr :: [Located (TyClDecl Name)] -> TcRn ()
1240 recClsErr cls_decls
1241   = setSrcSpan (getLoc (head sorted_decls)) $
1242     addErr (sep [ptext (sLit "Cycle in class declarations (via superclasses):"),
1243                  nest 2 (vcat (map ppr_decl sorted_decls))])
1244   where
1245     sorted_decls = sortLocated cls_decls
1246     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
1247
1248 sortLocated :: [Located a] -> [Located a]
1249 sortLocated things = sortLe le things
1250   where
1251     le (L l1 _) (L l2 _) = l1 <= l2
1252
1253 badDataConTyCon :: DataCon -> Type -> Type -> SDoc
1254 badDataConTyCon data_con res_ty_tmpl actual_res_ty
1255   = hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con) <+>
1256                 ptext (sLit "returns type") <+> quotes (ppr actual_res_ty))
1257        2 (ptext (sLit "instead of an instance of its parent type") <+> quotes (ppr res_ty_tmpl))
1258
1259 badGadtDecl :: Name -> SDoc
1260 badGadtDecl tc_name
1261   = vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
1262          , nest 2 (parens $ ptext (sLit "Use -XGADTs to allow GADTs")) ]
1263
1264 badExistential :: Located Name -> SDoc
1265 badExistential con_name
1266   = hang (ptext (sLit "Data constructor") <+> quotes (ppr con_name) <+>
1267                 ptext (sLit "has existential type variables, or a context"))
1268        2 (parens $ ptext (sLit "Use -XExistentialQuantification or -XGADTs to allow this"))
1269
1270 badStupidTheta :: Name -> SDoc
1271 badStupidTheta tc_name
1272   = ptext (sLit "A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
1273
1274 newtypeConError :: Name -> Int -> SDoc
1275 newtypeConError tycon n
1276   = sep [ptext (sLit "A newtype must have exactly one constructor,"),
1277          nest 2 $ ptext (sLit "but") <+> quotes (ppr tycon) <+> ptext (sLit "has") <+> speakN n ]
1278
1279 newtypeExError :: DataCon -> SDoc
1280 newtypeExError con
1281   = sep [ptext (sLit "A newtype constructor cannot have an existential context,"),
1282          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1283
1284 newtypeStrictError :: DataCon -> SDoc
1285 newtypeStrictError con
1286   = sep [ptext (sLit "A newtype constructor cannot have a strictness annotation,"),
1287          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1288
1289 newtypePredError :: DataCon -> SDoc
1290 newtypePredError con
1291   = sep [ptext (sLit "A newtype constructor must have a return type of form T a1 ... an"),
1292          nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does not")]
1293
1294 newtypeFieldErr :: DataCon -> Int -> SDoc
1295 newtypeFieldErr con_name n_flds
1296   = sep [ptext (sLit "The constructor of a newtype must have exactly one field"), 
1297          nest 2 $ ptext (sLit "but") <+> quotes (ppr con_name) <+> ptext (sLit "has") <+> speakN n_flds]
1298
1299 badSigTyDecl :: Name -> SDoc
1300 badSigTyDecl tc_name
1301   = vcat [ ptext (sLit "Illegal kind signature") <+>
1302            quotes (ppr tc_name)
1303          , nest 2 (parens $ ptext (sLit "Use -XKindSignatures to allow kind signatures")) ]
1304
1305 noIndexTypes :: Name -> SDoc
1306 noIndexTypes tc_name
1307   = ptext (sLit "Type family constructor") <+> quotes (ppr tc_name)
1308     <+> ptext (sLit "must have at least one type index parameter")
1309
1310 badFamInstDecl :: Outputable a => a -> SDoc
1311 badFamInstDecl tc_name
1312   = vcat [ ptext (sLit "Illegal family instance for") <+>
1313            quotes (ppr tc_name)
1314          , nest 2 (parens $ ptext (sLit "Use -XTypeFamilies to allow indexed type families")) ]
1315
1316 {-
1317 badGadtIdxTyDecl :: Name -> SDoc
1318 badGadtIdxTyDecl tc_name
1319   = vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+>
1320            quotes (ppr tc_name)
1321          , nest 2 (parens $ ptext (sLit "Family instances can not yet use GADT declarations")) ]
1322 -}
1323 tooManyParmsErr :: Located Name -> SDoc
1324 tooManyParmsErr tc_name
1325   = ptext (sLit "Family instance has too many parameters:") <+> 
1326     quotes (ppr tc_name)
1327
1328 tooFewParmsErr :: Arity -> SDoc
1329 tooFewParmsErr arity
1330   = ptext (sLit "Family instance has too few parameters; expected") <+> 
1331     ppr arity
1332
1333 wrongNumberOfParmsErr :: Arity -> SDoc
1334 wrongNumberOfParmsErr exp_arity
1335   = ptext (sLit "Number of parameters must match family declaration; expected")
1336     <+> ppr exp_arity
1337
1338 badBootFamInstDeclErr :: SDoc
1339 badBootFamInstDeclErr = 
1340   ptext (sLit "Illegal family instance in hs-boot file")
1341
1342 wrongKindOfFamily :: TyCon -> SDoc
1343 wrongKindOfFamily family =
1344   ptext (sLit "Wrong category of family instance; declaration was for a") <+>
1345   kindOfFamily
1346   where
1347     kindOfFamily | isSynTyCon family = ptext (sLit "type synonym")
1348                  | isAlgTyCon family = ptext (sLit "data type")
1349                  | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1350
1351 emptyConDeclsErr :: Name -> SDoc
1352 emptyConDeclsErr tycon
1353   = sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
1354          nest 2 $ ptext (sLit "(-XEmptyDataDecls permits this)")]
1355 \end{code}