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