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