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