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