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