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