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