Slightly improved comments 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
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 -XTypeFamilies 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 -XTypeFamilies
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   -- "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 -XTypeFamilies
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   -- NB: not used for newtype/data instances (whether associated or not)
697 tcTyClDecl1 calc_isrec
698   (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
699            tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
700   = tcTyVarBndrs tvs    $ \ tvs' -> do 
701   { extra_tvs <- tcDataKindSig mb_ksig
702   ; let final_tvs = tvs' ++ extra_tvs
703   ; stupid_theta <- tcHsKindedContext ctxt
704   ; want_generic <- doptM Opt_Generics
705   ; unbox_strict <- doptM Opt_UnboxStrictFields
706   ; empty_data_decls <- doptM Opt_EmptyDataDecls
707   ; kind_signatures <- doptM Opt_KindSignatures
708   ; gadt_ok      <- doptM Opt_GADTs
709   ; is_boot      <- tcIsHsBoot  -- Are we compiling an hs-boot file?
710
711         -- Check that we don't use GADT syntax in H98 world
712   ; checkTc (gadt_ok || h98_syntax) (badGadtDecl tc_name)
713
714         -- Check that we don't use kind signatures without Glasgow extensions
715   ; checkTc (kind_signatures || isNothing mb_ksig) (badSigTyDecl tc_name)
716
717         -- Check that the stupid theta is empty for a GADT-style declaration
718   ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
719
720         -- Check that there's at least one condecl,
721         -- or else we're reading an hs-boot file, or -XEmptyDataDecls
722   ; checkTc (not (null cons) || empty_data_decls || is_boot)
723             (emptyConDeclsErr tc_name)
724     
725         -- Check that a newtype has exactly one constructor
726   ; checkTc (new_or_data == DataType || isSingleton cons) 
727             (newtypeConError tc_name (length cons))
728
729   ; tycon <- fixM (\ tycon -> do 
730         { data_cons <- mappM (addLocM (tcConDecl unbox_strict tycon final_tvs)) 
731                              cons
732         ; tc_rhs <-
733             if null cons && is_boot     -- In a hs-boot file, empty cons means
734             then return AbstractTyCon   -- "don't know"; hence Abstract
735             else case new_or_data of
736                    DataType -> return (mkDataTyConRhs data_cons)
737                    NewType  -> 
738                        ASSERT( not (null data_cons) )
739                        mkNewTyConRhs tc_name tycon (head data_cons)
740         ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
741             (want_generic && canDoGenerics data_cons) h98_syntax Nothing
742         })
743   ; return [ATyCon tycon]
744   }
745   where
746     is_rec   = calc_isrec tc_name
747     h98_syntax = case cons of   -- All constructors have same shape
748                         L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
749                         other -> True
750
751 tcTyClDecl1 calc_isrec 
752   (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs, 
753               tcdCtxt = ctxt, tcdMeths = meths,
754               tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
755   = tcTyVarBndrs tvs            $ \ tvs' -> do 
756   { ctxt' <- tcHsKindedContext ctxt
757   ; fds' <- mappM (addLocM tc_fundep) fundeps
758   ; atss <- mappM (addLocM (tcTyClDecl1 (const Recursive))) ats
759             -- NB: 'ats' only contains "type family" and "data family"
760             --     declarations as well as type family defaults
761   ; let ats' = zipWith setTyThingPoss atss (map (tcdTyVars . unLoc) ats)
762   ; sig_stuff <- tcClassSigs class_name sigs meths
763   ; clas <- fixM (\ clas ->
764                 let     -- This little knot is just so we can get
765                         -- hold of the name of the class TyCon, which we
766                         -- need to look up its recursiveness
767                     tycon_name = tyConName (classTyCon clas)
768                     tc_isrec = calc_isrec tycon_name
769                 in
770                 buildClass class_name tvs' ctxt' fds' ats'
771                            sig_stuff tc_isrec)
772   ; return (AClass clas : ats')
773       -- NB: Order is important due to the call to `mkGlobalThings' when
774       --     tying the the type and class declaration type checking knot.
775   }
776   where
777     tc_fundep (tvs1, tvs2) = do { tvs1' <- mappM tcLookupTyVar tvs1 ;
778                                 ; tvs2' <- mappM tcLookupTyVar tvs2 ;
779                                 ; return (tvs1', tvs2') }
780
781     -- For each AT argument compute the position of the corresponding class
782     -- parameter in the class head.  This will later serve as a permutation
783     -- vector when checking the validity of instance declarations.
784     setTyThingPoss [ATyCon tycon] atTyVars = 
785       let classTyVars = hsLTyVarNames tvs
786           poss        =   catMaybes 
787                         . map (`elemIndex` classTyVars) 
788                         . hsLTyVarNames 
789                         $ atTyVars
790                      -- There will be no Nothing, as we already passed renaming
791       in 
792       ATyCon (setTyConArgPoss tycon poss)
793     setTyThingPoss _              _ = panic "TcTyClsDecls.setTyThingPoss"
794
795 tcTyClDecl1 calc_isrec 
796   (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
797   = returnM [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
798
799 -----------------------------------
800 tcConDecl :: Bool               -- True <=> -funbox-strict_fields
801           -> TyCon -> [TyVar] 
802           -> ConDecl Name 
803           -> TcM DataCon
804
805 tcConDecl unbox_strict tycon tc_tvs     -- Data types
806           (ConDecl name _ tvs ctxt details res_ty _)
807   = tcTyVarBndrs tvs            $ \ tvs' -> do 
808     { ctxt' <- tcHsKindedContext ctxt
809     ; (univ_tvs, ex_tvs, eq_preds, data_tc) <- tcResultType tycon tc_tvs tvs' res_ty
810     ; let 
811         -- Tiresome: tidy the tyvar binders, since tc_tvs and tvs' may have the same OccNames
812         tc_datacon is_infix field_lbls btys
813           = do { let bangs = map getBangStrictness btys
814                ; arg_tys <- mappM tcHsBangType btys
815                ; buildDataCon (unLoc name) is_infix
816                     (argStrictness unbox_strict bangs arg_tys)
817                     (map unLoc field_lbls)
818                     univ_tvs ex_tvs eq_preds ctxt' arg_tys
819                     data_tc }
820                 -- NB:  we put data_tc, the type constructor gotten from the
821                 --      constructor type signature into the data constructor;
822                 --      that way checkValidDataCon can complain if it's wrong.
823
824     ; case details of
825         PrefixCon btys     -> tc_datacon False [] btys
826         InfixCon bty1 bty2 -> tc_datacon True  [] [bty1,bty2]
827         RecCon fields      -> tc_datacon False field_names btys
828                            where
829                               field_names = map cd_fld_name fields
830                               btys        = map cd_fld_type fields
831     }
832
833 tcResultType :: TyCon
834              -> [TyVar]         -- data T a b c = ...
835              -> [TyVar]         -- where MkT :: forall a b c. ...
836              -> ResType Name
837              -> TcM ([TyVar],           -- Universal
838                      [TyVar],           -- Existential (distinct OccNames from univs)
839                      [(TyVar,Type)],    -- Equality predicates
840                      TyCon)             -- TyCon given in the ResTy
841         -- We don't check that the TyCon given in the ResTy is
842         -- the same as the parent tycon, becuase we are in the middle
843         -- of a recursive knot; so it's postponed until checkValidDataCon
844
845 tcResultType decl_tycon tc_tvs dc_tvs ResTyH98
846   = return (tc_tvs, dc_tvs, [], decl_tycon)
847         -- In H98 syntax the dc_tvs are the existential ones
848         --      data T a b c = forall d e. MkT ...
849         -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
850
851 tcResultType _ tc_tvs dc_tvs (ResTyGADT res_ty)
852         -- E.g.  data T a b c where
853         --         MkT :: forall x y z. T (x,y) z z
854         -- Then we generate
855         --      ([a,z,c], [x,y], [a:=:(x,y), c:=:z], T)
856
857   = do  { (dc_tycon, res_tys) <- tcLHsConResTy res_ty
858
859         ; let univ_tvs = choose_univs [] tidy_tc_tvs res_tys
860                 -- Each univ_tv is either a dc_tv or a tc_tv
861               ex_tvs = dc_tvs `minusList` univ_tvs
862               eq_spec = [ (tv, ty) | (tv,ty) <- univ_tvs `zip` res_tys, 
863                                       tv `elem` tc_tvs]
864         ; return (univ_tvs, ex_tvs, eq_spec, dc_tycon) }
865   where
866         -- choose_univs uses the res_ty itself if it's a type variable
867         -- and hasn't already been used; otherwise it uses one of the tc_tvs
868     choose_univs used tc_tvs []
869         = ASSERT( null tc_tvs ) []
870     choose_univs used (tc_tv:tc_tvs) (res_ty:res_tys) 
871         | Just tv <- tcGetTyVar_maybe res_ty, not (tv `elem` used)
872         = tv    : choose_univs (tv:used) tc_tvs res_tys
873         | otherwise
874         = tc_tv : choose_univs used tc_tvs res_tys
875
876         -- NB: tc_tvs and dc_tvs are distinct, but
877         -- we want them to be *visibly* distinct, both for
878         -- interface files and general confusion.  So rename
879         -- the tc_tvs, since they are not used yet (no 
880         -- consequential renaming needed)
881     init_occ_env     = initTidyOccEnv (map getOccName dc_tvs)
882     (_, tidy_tc_tvs) = mapAccumL tidy_one init_occ_env tc_tvs
883     tidy_one env tv  = (env', setTyVarName tv (tidyNameOcc name occ'))
884               where
885                  name = tyVarName tv
886                  (env', occ') = tidyOccName env (getOccName name) 
887
888               -------------------
889 argStrictness :: Bool           -- True <=> -funbox-strict_fields
890               -> [HsBang]
891               -> [TcType] -> [StrictnessMark]
892 argStrictness unbox_strict bangs arg_tys
893  = ASSERT( length bangs == length arg_tys )
894    zipWith (chooseBoxingStrategy unbox_strict) arg_tys bangs
895
896 -- We attempt to unbox/unpack a strict field when either:
897 --   (i)  The field is marked '!!', or
898 --   (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
899 --
900 -- We have turned off unboxing of newtypes because coercions make unboxing 
901 -- and reboxing more complicated
902 chooseBoxingStrategy :: Bool -> TcType -> HsBang -> StrictnessMark
903 chooseBoxingStrategy unbox_strict_fields arg_ty bang
904   = case bang of
905         HsNoBang                                    -> NotMarkedStrict
906         HsStrict | unbox_strict_fields 
907                    && can_unbox arg_ty              -> MarkedUnboxed
908         HsUnbox  | can_unbox arg_ty                 -> MarkedUnboxed
909         other                                       -> MarkedStrict
910   where
911     -- we can unbox if the type is a chain of newtypes with a product tycon
912     -- at the end
913     can_unbox arg_ty = case splitTyConApp_maybe arg_ty of
914                    Nothing                      -> False
915                    Just (arg_tycon, tycon_args) -> 
916                        not (isRecursiveTyCon arg_tycon) &&      -- Note [Recusive unboxing]
917                        isProductTyCon arg_tycon &&
918                        (if isNewTyCon arg_tycon then 
919                             can_unbox (newTyConInstRhs arg_tycon tycon_args)
920                         else True)
921 \end{code}
922
923 Note [Recursive unboxing]
924 ~~~~~~~~~~~~~~~~~~~~~~~~~
925 Be careful not to try to unbox this!
926         data T = MkT !T Int
927 But it's the *argument* type that matters. This is fine:
928         data S = MkS S !Int
929 because Int is non-recursive.
930
931 %************************************************************************
932 %*                                                                      *
933 \subsection{Dependency analysis}
934 %*                                                                      *
935 %************************************************************************
936
937 Validity checking is done once the mutually-recursive knot has been
938 tied, so we can look at things freely.
939
940 \begin{code}
941 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
942 checkCycleErrs tyclss
943   | null cls_cycles
944   = return ()
945   | otherwise
946   = do  { mappM_ recClsErr cls_cycles
947         ; failM }       -- Give up now, because later checkValidTyCl
948                         -- will loop if the synonym is recursive
949   where
950     cls_cycles = calcClassCycles tyclss
951
952 checkValidTyCl :: TyClDecl Name -> TcM ()
953 -- We do the validity check over declarations, rather than TyThings
954 -- only so that we can add a nice context with tcAddDeclCtxt
955 checkValidTyCl decl
956   = tcAddDeclCtxt decl $
957     do  { thing <- tcLookupLocatedGlobal (tcdLName decl)
958         ; traceTc (text "Validity of" <+> ppr thing)    
959         ; case thing of
960             ATyCon tc -> checkValidTyCon tc
961             AClass cl -> checkValidClass cl 
962         ; traceTc (text "Done validity of" <+> ppr thing)       
963         }
964
965 -------------------------
966 -- For data types declared with record syntax, we require
967 -- that each constructor that has a field 'f' 
968 --      (a) has the same result type
969 --      (b) has the same type for 'f'
970 -- module alpha conversion of the quantified type variables
971 -- of the constructor.
972
973 checkValidTyCon :: TyCon -> TcM ()
974 checkValidTyCon tc 
975   | isSynTyCon tc 
976   = case synTyConRhs tc of
977       OpenSynTyCon _ _ -> return ()
978       SynonymTyCon ty  -> checkValidType syn_ctxt ty
979   | otherwise
980   =     -- Check the context on the data decl
981     checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)     `thenM_` 
982         
983         -- Check arg types of data constructors
984     mappM_ (checkValidDataCon tc) data_cons                     `thenM_`
985
986         -- Check that fields with the same name share a type
987     mappM_ check_fields groups
988
989   where
990     syn_ctxt  = TySynCtxt name
991     name      = tyConName tc
992     data_cons = tyConDataCons tc
993
994     groups = equivClasses cmp_fld (concatMap get_fields data_cons)
995     cmp_fld (f1,_) (f2,_) = f1 `compare` f2
996     get_fields con = dataConFieldLabels con `zip` repeat con
997         -- dataConFieldLabels may return the empty list, which is fine
998
999     -- See Note [GADT record selectors] in MkId.lhs
1000     -- We must check (a) that the named field has the same 
1001     --                   type in each constructor
1002     --               (b) that those constructors have the same result type
1003     --
1004     -- However, the constructors may have differently named type variable
1005     -- and (worse) we don't know how the correspond to each other.  E.g.
1006     --     C1 :: forall a b. { f :: a, g :: b } -> T a b
1007     --     C2 :: forall d c. { f :: c, g :: c } -> T c d
1008     -- 
1009     -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
1010     -- result type against other candidates' types BOTH WAYS ROUND.
1011     -- If they magically agrees, take the substitution and
1012     -- apply them to the latter ones, and see if they match perfectly.
1013     check_fields fields@((label, con1) : other_fields)
1014         -- These fields all have the same name, but are from
1015         -- different constructors in the data type
1016         = recoverM (return ()) $ mapM_ checkOne other_fields
1017                 -- Check that all the fields in the group have the same type
1018                 -- NB: this check assumes that all the constructors of a given
1019                 -- data type use the same type variables
1020         where
1021         (tvs1, _, _, res1) = dataConSig con1
1022         ts1 = mkVarSet tvs1
1023         fty1 = dataConFieldType con1 label
1024
1025         checkOne (_, con2)    -- Do it bothways to ensure they are structurally identical
1026             = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
1027                  ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
1028             where        
1029                 (tvs2, _, _, res2) = dataConSig con2
1030                 ts2 = mkVarSet tvs2
1031                 fty2 = dataConFieldType con2 label
1032
1033 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
1034   = do  { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
1035         ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
1036   where
1037     mb_subst1 = tcMatchTy tvs1 res1 res2
1038     mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
1039
1040 -------------------------------
1041 checkValidDataCon :: TyCon -> DataCon -> TcM ()
1042 checkValidDataCon tc con
1043   = setSrcSpan (srcLocSpan (getSrcLoc con))     $
1044     addErrCtxt (dataConCtxt con)                $ 
1045     do  { checkTc (dataConTyCon con == tc) (badDataConTyCon con)
1046         ; checkValidType ctxt (dataConUserType con)
1047         ; ifM (isNewTyCon tc) (checkNewDataCon con)
1048     }
1049   where
1050     ctxt = ConArgCtxt (dataConName con) 
1051
1052 -------------------------------
1053 checkNewDataCon :: DataCon -> TcM ()
1054 -- Checks for the data constructor of a newtype
1055 checkNewDataCon con
1056   = do  { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
1057                 -- One argument
1058         ; checkTc (null eq_spec) (newtypePredError con)
1059                 -- Return type is (T a b c)
1060         ; checkTc (null ex_tvs && null eq_theta && null dict_theta) (newtypeExError con)
1061                 -- No existentials
1062         ; checkTc (not (any isMarkedStrict (dataConStrictMarks con))) 
1063                   (newtypeStrictError con)
1064                 -- No strictness
1065     }
1066   where
1067     (_univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _res_ty) = dataConFullSig con
1068
1069 -------------------------------
1070 checkValidClass :: Class -> TcM ()
1071 checkValidClass cls
1072   = do  { constrained_class_methods <- doptM Opt_ConstrainedClassMethods
1073         ; multi_param_type_classes <- doptM Opt_MultiParamTypeClasses
1074         ; fundep_classes <- doptM Opt_FunctionalDependencies
1075
1076         -- Check that the class is unary, unless GlaExs
1077         ; checkTc (notNull tyvars) (nullaryClassErr cls)
1078         ; checkTc (multi_param_type_classes || unary) (classArityErr cls)
1079         ; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
1080
1081         -- Check the super-classes
1082         ; checkValidTheta (ClassSCCtxt (className cls)) theta
1083
1084         -- Check the class operations
1085         ; mappM_ (check_op constrained_class_methods) op_stuff
1086
1087         -- Check that if the class has generic methods, then the
1088         -- class has only one parameter.  We can't do generic
1089         -- multi-parameter type classes!
1090         ; checkTc (unary || no_generics) (genericMultiParamErr cls)
1091         }
1092   where
1093     (tyvars, fundeps, theta, _, _, op_stuff) = classExtraBigSig cls
1094     unary       = isSingleton tyvars
1095     no_generics = null [() | (_, GenDefMeth) <- op_stuff]
1096
1097     check_op constrained_class_methods (sel_id, dm) 
1098       = addErrCtxt (classOpCtxt sel_id tau) $ do
1099         { checkValidTheta SigmaCtxt (tail theta)
1100                 -- The 'tail' removes the initial (C a) from the
1101                 -- class itself, leaving just the method type
1102
1103         ; traceTc (text "class op type" <+> ppr op_ty <+> ppr tau)
1104         ; checkValidType (FunSigCtxt op_name) tau
1105
1106                 -- Check that the type mentions at least one of
1107                 -- the class type variables...or at least one reachable
1108                 -- from one of the class variables.  Example: tc223
1109                 --   class Error e => Game b mv e | b -> mv e where
1110                 --      newBoard :: MonadState b m => m ()
1111                 -- Here, MonadState has a fundep m->b, so newBoard is fine
1112         ; let grown_tyvars = grow theta (mkVarSet tyvars)
1113         ; checkTc (tyVarsOfType tau `intersectsVarSet` grown_tyvars)
1114                   (noClassTyVarErr cls sel_id)
1115
1116                 -- Check that for a generic method, the type of 
1117                 -- the method is sufficiently simple
1118         ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
1119                   (badGenericMethodType op_name op_ty)
1120         }
1121         where
1122           op_name = idName sel_id
1123           op_ty   = idType sel_id
1124           (_,theta1,tau1) = tcSplitSigmaTy op_ty
1125           (_,theta2,tau2)  = tcSplitSigmaTy tau1
1126           (theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
1127                       | otherwise = (theta1, mkPhiTy (tail theta1) tau1)
1128                 -- Ugh!  The function might have a type like
1129                 --      op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
1130                 -- With -XConstrainedClassMethods, we want to allow this, even though the inner 
1131                 -- forall has an (Eq a) constraint.  Whereas in general, each constraint 
1132                 -- in the context of a for-all must mention at least one quantified
1133                 -- type variable.  What a mess!
1134
1135
1136 ---------------------------------------------------------------------
1137 resultTypeMisMatch field_name con1 con2
1138   = vcat [sep [ptext SLIT("Constructors") <+> ppr con1 <+> ptext SLIT("and") <+> ppr con2, 
1139                 ptext SLIT("have a common field") <+> quotes (ppr field_name) <> comma],
1140           nest 2 $ ptext SLIT("but have different result types")]
1141 fieldTypeMisMatch field_name con1 con2
1142   = sep [ptext SLIT("Constructors") <+> ppr con1 <+> ptext SLIT("and") <+> ppr con2, 
1143          ptext SLIT("give different types for field"), quotes (ppr field_name)]
1144
1145 dataConCtxt con = ptext SLIT("In the definition of data constructor") <+> quotes (ppr con)
1146
1147 classOpCtxt sel_id tau = sep [ptext SLIT("When checking the class method:"),
1148                               nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
1149
1150 nullaryClassErr cls
1151   = ptext SLIT("No parameters for class")  <+> quotes (ppr cls)
1152
1153 classArityErr cls
1154   = vcat [ptext SLIT("Too many parameters for class") <+> quotes (ppr cls),
1155           parens (ptext SLIT("Use -XMultiParamTypeClasses to allow multi-parameter classes"))]
1156
1157 classFunDepsErr cls
1158   = vcat [ptext SLIT("Fundeps in class") <+> quotes (ppr cls),
1159           parens (ptext SLIT("Use -XFunctionalDependencies to allow fundeps"))]
1160
1161 noClassTyVarErr clas op
1162   = sep [ptext SLIT("The class method") <+> quotes (ppr op),
1163          ptext SLIT("mentions none of the type variables of the class") <+> 
1164                 ppr clas <+> hsep (map ppr (classTyVars clas))]
1165
1166 genericMultiParamErr clas
1167   = ptext SLIT("The multi-parameter class") <+> quotes (ppr clas) <+> 
1168     ptext SLIT("cannot have generic methods")
1169
1170 badGenericMethodType op op_ty
1171   = hang (ptext SLIT("Generic method type is too complex"))
1172        4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
1173                 ptext SLIT("You can only use type variables, arrows, lists, and tuples")])
1174
1175 recSynErr syn_decls
1176   = setSrcSpan (getLoc (head sorted_decls)) $
1177     addErr (sep [ptext SLIT("Cycle in type synonym declarations:"),
1178                  nest 2 (vcat (map ppr_decl sorted_decls))])
1179   where
1180     sorted_decls = sortLocated syn_decls
1181     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
1182
1183 recClsErr cls_decls
1184   = setSrcSpan (getLoc (head sorted_decls)) $
1185     addErr (sep [ptext SLIT("Cycle in class declarations (via superclasses):"),
1186                  nest 2 (vcat (map ppr_decl sorted_decls))])
1187   where
1188     sorted_decls = sortLocated cls_decls
1189     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
1190
1191 sortLocated :: [Located a] -> [Located a]
1192 sortLocated things = sortLe le things
1193   where
1194     le (L l1 _) (L l2 _) = l1 <= l2
1195
1196 badDataConTyCon data_con
1197   = hang (ptext SLIT("Data constructor") <+> quotes (ppr data_con) <+>
1198                 ptext SLIT("returns type") <+> quotes (ppr (dataConTyCon data_con)))
1199        2 (ptext SLIT("instead of its parent type"))
1200
1201 badGadtDecl tc_name
1202   = vcat [ ptext SLIT("Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
1203          , nest 2 (parens $ ptext SLIT("Use -XGADTs to allow GADTs")) ]
1204
1205 badStupidTheta tc_name
1206   = ptext SLIT("A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
1207
1208 newtypeConError tycon n
1209   = sep [ptext SLIT("A newtype must have exactly one constructor,"),
1210          nest 2 $ ptext SLIT("but") <+> quotes (ppr tycon) <+> ptext SLIT("has") <+> speakN n ]
1211
1212 newtypeExError con
1213   = sep [ptext SLIT("A newtype constructor cannot have an existential context,"),
1214          nest 2 $ ptext SLIT("but") <+> quotes (ppr con) <+> ptext SLIT("does")]
1215
1216 newtypeStrictError con
1217   = sep [ptext SLIT("A newtype constructor cannot have a strictness annotation,"),
1218          nest 2 $ ptext SLIT("but") <+> quotes (ppr con) <+> ptext SLIT("does")]
1219
1220 newtypePredError con
1221   = sep [ptext SLIT("A newtype constructor must have a return type of form T a1 ... an"),
1222          nest 2 $ ptext SLIT("but") <+> quotes (ppr con) <+> ptext SLIT("does not")]
1223
1224 newtypeFieldErr con_name n_flds
1225   = sep [ptext SLIT("The constructor of a newtype must have exactly one field"), 
1226          nest 2 $ ptext SLIT("but") <+> quotes (ppr con_name) <+> ptext SLIT("has") <+> speakN n_flds]
1227
1228 badSigTyDecl tc_name
1229   = vcat [ ptext SLIT("Illegal kind signature") <+>
1230            quotes (ppr tc_name)
1231          , nest 2 (parens $ ptext SLIT("Use -XKindSignatures to allow kind signatures")) ]
1232
1233 badFamInstDecl tc_name
1234   = vcat [ ptext SLIT("Illegal family instance for") <+>
1235            quotes (ppr tc_name)
1236          , nest 2 (parens $ ptext SLIT("Use -XTypeFamilies to allow indexed type families")) ]
1237
1238 badGadtIdxTyDecl tc_name
1239   = vcat [ ptext SLIT("Illegal generalised algebraic data declaration for") <+>
1240            quotes (ppr tc_name)
1241          , nest 2 (parens $ ptext SLIT("Family instances can not yet use GADT declarations")) ]
1242
1243 tooManyParmsErr tc_name
1244   = ptext SLIT("Family instance has too many parameters:") <+> 
1245     quotes (ppr tc_name)
1246
1247 tooFewParmsErr arity
1248   = ptext SLIT("Family instance has too few parameters; expected") <+> 
1249     ppr arity
1250
1251 wrongNumberOfParmsErr exp_arity
1252   = ptext SLIT("Number of parameters must match family declaration; expected")
1253     <+> ppr exp_arity
1254
1255 badBootFamInstDeclErr = 
1256   ptext SLIT("Illegal family instance in hs-boot file")
1257
1258 wrongKindOfFamily family =
1259   ptext SLIT("Wrong category of family instance; declaration was for a") <+>
1260   kindOfFamily
1261   where
1262     kindOfFamily | isSynTyCon family = ptext SLIT("type synonym")
1263                  | isAlgTyCon family = ptext SLIT("data type")
1264                  | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1265
1266 emptyConDeclsErr tycon
1267   = sep [quotes (ppr tycon) <+> ptext SLIT("has no constructors"),
1268          nest 2 $ ptext SLIT("(-XEmptyDataDecls permits this)")]
1269 \end{code}