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