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