[project @ 2004-12-03 13:49:00 by simonpj]
[ghc-hetmet.git] / ghc / 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
9     ) where
10
11 #include "HsVersions.h"
12
13 import HsSyn            ( TyClDecl(..),  HsConDetails(..), HsTyVarBndr(..),
14                           ConDecl(..),   Sig(..), , NewOrData(..), 
15                           tyClDeclTyVars, isSynDecl, LConDecl,
16                           LTyClDecl, tcdName, LHsTyVarBndr, LHsContext
17                         )
18 import HsTypes          ( HsBang(..), getBangStrictness )
19 import BasicTypes       ( RecFlag(..), StrictnessMark(..) )
20 import HscTypes         ( implicitTyThings )
21 import BuildTyCl        ( buildClass, buildAlgTyCon, buildSynTyCon, buildDataCon,
22                           mkDataTyConRhs, mkNewTyConRhs )
23 import TcRnMonad
24 import TcEnv            ( TyThing(..), 
25                           tcLookupLocated, tcLookupLocatedGlobal, 
26                           tcExtendGlobalEnv, tcExtendKindEnv,
27                           tcExtendRecEnv, tcLookupTyVar )
28 import TcTyDecls        ( calcTyConArgVrcs, calcRecFlags, calcClassCycles, calcSynCycles )
29 import TcClassDcl       ( tcClassSigs, tcAddDeclCtxt )
30 import TcHsType         ( kcHsTyVars, kcHsLiftedSigType, kcHsType, 
31                           kcHsContext, tcTyVarBndrs, tcHsKindedType, tcHsKindedContext,
32                           kcHsSigType, tcHsBangType, tcLHsConSig, tcDataKindSig )
33 import TcMType          ( newKindVar, checkValidTheta, checkValidType, checkFreeness, 
34                           UserTypeCtxt(..), SourceTyCtxt(..) ) 
35 import TcUnify          ( unifyKind )
36 import TcType           ( TcKind, ThetaType, TcType, tyVarsOfType, 
37                           mkArrowKind, liftedTypeKind, mkTyVarTys, tcEqTypes,
38                           tcSplitSigmaTy, tcEqType )
39 import Type             ( splitTyConApp_maybe, pprThetaArrow, pprParendType )
40 import Generics         ( validGenericMethodType, canDoGenerics )
41 import Class            ( Class, className, classTyCon, DefMeth(..), classBigSig, classTyVars )
42 import TyCon            ( TyCon, ArgVrcs, 
43                           tyConDataCons, mkForeignTyCon, isProductTyCon, isRecursiveTyCon,
44                           tyConStupidTheta, getSynTyConDefn, isSynTyCon, tyConName )
45 import DataCon          ( DataCon, dataConWrapId, dataConName, dataConSig, 
46                           dataConFieldLabels, dataConOrigArgTys, dataConTyCon )
47 import Type             ( zipTopTvSubst, substTys )
48 import Var              ( TyVar, idType, idName )
49 import VarSet           ( elemVarSet )
50 import Name             ( Name )
51 import Outputable
52 import Util             ( zipLazy, isSingleton, notNull, sortLe )
53 import List             ( partition )
54 import SrcLoc           ( Located(..), unLoc, getLoc )
55 import ListSetOps       ( equivClasses )
56 import Digraph          ( SCC(..) )
57 import CmdLineOpts      ( DynFlag( Opt_GlasgowExts, Opt_Generics, Opt_UnboxStrictFields ) )
58 \end{code}
59
60
61 %************************************************************************
62 %*                                                                      *
63 \subsection{Type checking for type and class declarations}
64 %*                                                                      *
65 %************************************************************************
66
67 Dealing with a group
68 ~~~~~~~~~~~~~~~~~~~~
69 Consider a mutually-recursive group, binding 
70 a type constructor T and a class C.
71
72 Step 1:         getInitialKind
73         Construct a KindEnv by binding T and C to a kind variable 
74
75 Step 2:         kcTyClDecl
76         In that environment, do a kind check
77
78 Step 3: Zonk the kinds
79
80 Step 4:         buildTyConOrClass
81         Construct an environment binding T to a TyCon and C to a Class.
82         a) Their kinds comes from zonking the relevant kind variable
83         b) Their arity (for synonyms) comes direct from the decl
84         c) The funcional dependencies come from the decl
85         d) The rest comes a knot-tied binding of T and C, returned from Step 4
86         e) The variances of the tycons in the group is calculated from 
87                 the knot-tied stuff
88
89 Step 5:         tcTyClDecl1
90         In this environment, walk over the decls, constructing the TyCons and Classes.
91         This uses in a strict way items (a)-(c) above, which is why they must
92         be constructed in Step 4. Feed the results back to Step 4.
93         For this step, pass the is-recursive flag as the wimp-out flag
94         to tcTyClDecl1.
95         
96
97 Step 6:         Extend environment
98         We extend the type environment with bindings not only for the TyCons and Classes,
99         but also for their "implicit Ids" like data constructors and class selectors
100
101 Step 7:         checkValidTyCl
102         For a recursive group only, check all the decls again, just
103         to check all the side conditions on validity.  We could not
104         do this before because we were in a mutually recursive knot.
105
106
107 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
108 @TyThing@s.  @rec_vrcs@ is a finite map from @Name@s to @ArgVrcs@s.
109
110 \begin{code}
111 tcTyAndClassDecls :: [Name] -> [LTyClDecl Name]
112                    -> TcM TcGblEnv      -- Input env extended by types and classes 
113                                         -- and their implicit Ids,DataCons
114 tcTyAndClassDecls boot_names decls
115   = do  {       -- First check for cyclic type synonysm or classes
116                 -- See notes with checkCycleErrs
117           checkCycleErrs decls
118         ; mod <- getModule
119         ; traceTc (text "tcTyAndCl" <+> ppr mod <+> ppr boot_names)
120         ; (syn_tycons, alg_tyclss) <- fixM (\ ~(rec_syn_tycons, rec_alg_tyclss) ->
121           do    { let { -- Calculate variances and rec-flag
122                       ; (syn_decls, alg_decls) = partition (isSynDecl . unLoc) decls }
123
124                         -- Extend the global env with the knot-tied results
125                         -- for data types and classes
126                         -- 
127                         -- We must populate the environment with the loop-tied T's right
128                         -- away, because the kind checker may "fault in" some type 
129                         -- constructors that recursively mention T
130                 ; let { gbl_things = mkGlobalThings alg_decls rec_alg_tyclss }
131                 ; tcExtendRecEnv gbl_things $ do
132
133                         -- Kind-check the declarations
134                 { (kc_syn_decls, kc_alg_decls) <- kcTyClDecls syn_decls alg_decls
135
136                 ; let { calc_vrcs = calcTyConArgVrcs (rec_syn_tycons ++ rec_alg_tyclss)
137                       ; calc_rec  = calcRecFlags boot_names rec_alg_tyclss
138                       ; tc_decl   = addLocM (tcTyClDecl calc_vrcs calc_rec) }
139                         -- Type-check the type synonyms, and extend the envt
140                 ; syn_tycons <- tcSynDecls calc_vrcs kc_syn_decls
141                 ; tcExtendGlobalEnv syn_tycons $ do
142
143                         -- Type-check the data types and classes
144                 { alg_tyclss <- mappM tc_decl kc_alg_decls
145                 ; return (syn_tycons, alg_tyclss)
146             }}})
147         -- Finished with knot-tying now
148         -- Extend the environment with the finished things
149         ; tcExtendGlobalEnv (syn_tycons ++ alg_tyclss) $ do
150
151         -- Perform the validity check
152         { traceTc (text "ready for validity check")
153         ; mappM_ (addLocM checkValidTyCl) decls
154         ; traceTc (text "done")
155    
156         -- Add the implicit things;
157         -- we want them in the environment because 
158         -- they may be mentioned in interface files
159         ; let { implicit_things = concatMap implicitTyThings alg_tyclss }
160         ; traceTc ((text "Adding" <+> ppr alg_tyclss) $$ (text "and" <+> ppr implicit_things))
161         ; tcExtendGlobalEnv implicit_things getGblEnv
162     }}
163
164 mkGlobalThings :: [LTyClDecl Name]      -- The decls
165                -> [TyThing]             -- Knot-tied, in 1-1 correspondence with the decls
166                -> [(Name,TyThing)]
167 -- Driven by the Decls, and treating the TyThings lazily
168 -- make a TypeEnv for the new things
169 mkGlobalThings decls things
170   = map mk_thing (decls `zipLazy` things)
171   where
172     mk_thing (L _ (ClassDecl {tcdLName = L _ name}), ~(AClass cl))
173          = (name, AClass cl)
174     mk_thing (L _ decl, ~(ATyCon tc))
175          = (tcdName decl, ATyCon tc)
176 \end{code}
177
178
179 %************************************************************************
180 %*                                                                      *
181                 Kind checking
182 %*                                                                      *
183 %************************************************************************
184
185 We need to kind check all types in the mutually recursive group
186 before we know the kind of the type variables.  For example:
187
188 class C a where
189    op :: D b => a -> b -> b
190
191 class D c where
192    bop :: (Monad c) => ...
193
194 Here, the kind of the locally-polymorphic type variable "b"
195 depends on *all the uses of class D*.  For example, the use of
196 Monad c in bop's type signature means that D must have kind Type->Type.
197
198 However type synonyms work differently.  They can have kinds which don't
199 just involve (->) and *:
200         type R = Int#           -- Kind #
201         type S a = Array# a     -- Kind * -> #
202         type T a b = (# a,b #)  -- Kind * -> * -> (# a,b #)
203 So we must infer their kinds from their right-hand sides *first* and then
204 use them, whereas for the mutually recursive data types D we bring into
205 scope kind bindings D -> k, where k is a kind variable, and do inference.
206
207 \begin{code}
208 kcTyClDecls syn_decls alg_decls
209   = do  {       -- First extend the kind env with each data 
210                 -- type and class, mapping them to a type variable
211           alg_kinds <- mappM getInitialKind alg_decls
212         ; tcExtendKindEnv alg_kinds $ do
213
214                 -- Now kind-check the type synonyms, in dependency order
215                 -- We do these differently to data type and classes,
216                 -- because a type synonym can be an unboxed type
217                 --      type Foo = Int#
218                 -- and a kind variable can't unify with UnboxedTypeKind
219                 -- So we infer their kinds in dependency order
220         { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
221         ; tcExtendKindEnv syn_kinds $  do
222
223                 -- Now kind-check the data type and class declarations, 
224                 -- returning kind-annotated decls
225         { kc_alg_decls <- mappM (wrapLocM kcTyClDecl) alg_decls
226
227         ; return (kc_syn_decls, kc_alg_decls) }}}
228
229 ------------------------------------------------------------------------
230 getInitialKind :: LTyClDecl Name -> TcM (Name, TcKind)
231
232 getInitialKind decl
233  = newKindVar                   `thenM` \ kind  ->
234    returnM (unLoc (tcdLName (unLoc decl)), kind)
235
236 ----------------
237 kcSynDecls :: [SCC (LTyClDecl Name)] 
238            -> TcM ([LTyClDecl Name],    -- Kind-annotated decls
239                    [(Name,TcKind)])     -- Kind bindings
240 kcSynDecls []
241   = return ([], [])
242 kcSynDecls (group : groups)
243   = do  { (decl,  nk)  <- kcSynDecl group
244         ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
245         ; return (decl:decls, nk:nks) }
246                         
247 ----------------
248 kcSynDecl :: SCC (LTyClDecl Name) 
249            -> TcM (LTyClDecl Name,      -- Kind-annotated decls
250                    (Name,TcKind))       -- Kind bindings
251 kcSynDecl (AcyclicSCC ldecl@(L loc decl))
252   = tcAddDeclCtxt decl  $
253     kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
254     do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl)) 
255                         <+> brackets (ppr k_tvs))
256        ; (k_rhs, rhs_kind) <- kcHsType (tcdSynRhs decl)
257        ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
258        ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
259        ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
260                  (unLoc (tcdLName decl), tc_kind)) })
261
262 kcSynDecl (CyclicSCC decls)
263   = do { recSynErr decls; failM }       -- Fail here to avoid error cascade
264                                         -- of out-of-scope tycons
265
266 ------------------------------------------------------------------------
267 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
268         -- Not used for type synonyms (see kcSynDecl)
269
270 kcTyClDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
271   = kcTyClDeclBody decl $ \ tvs' ->
272     do  { ctxt' <- kcHsContext ctxt     
273         ; cons' <- mappM (wrapLocM kc_con_decl) cons
274         ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdCons = cons'}) }
275   where
276     kc_con_decl (ConDecl name ex_tvs ex_ctxt details)
277       = kcHsTyVars ex_tvs               $ \ ex_tvs' ->
278         do { ex_ctxt' <- kcHsContext ex_ctxt
279            ; details' <- kc_con_details details 
280            ; return (ConDecl name ex_tvs' ex_ctxt' details')}
281     kc_con_decl (GadtDecl name ty)
282         = do { ty' <- kcHsSigType ty
283              ; return (GadtDecl name ty') }
284
285     kc_con_details (PrefixCon btys) 
286         = do { btys' <- mappM kc_larg_ty btys ; return (PrefixCon btys') }
287     kc_con_details (InfixCon bty1 bty2) 
288         = do { bty1' <- kc_larg_ty bty1; bty2' <- kc_larg_ty bty2; return (InfixCon bty1' bty2') }
289     kc_con_details (RecCon fields) 
290         = do { fields' <- mappM kc_field fields; return (RecCon fields') }
291
292     kc_field (fld, bty) = do { bty' <- kc_larg_ty bty ; return (fld, bty') }
293
294     kc_larg_ty bty = case new_or_data of
295                         DataType -> kcHsSigType bty
296                         NewType  -> kcHsLiftedSigType bty
297         -- Can't allow an unlifted type for newtypes, because we're effectively
298         -- going to remove the constructor while coercing it to a lifted type.
299         -- And newtypes can't be bang'd
300
301 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt,  tcdSigs = sigs})
302   = kcTyClDeclBody decl $ \ tvs' ->
303     do  { ctxt' <- kcHsContext ctxt     
304         ; sigs' <- mappM (wrapLocM kc_sig) sigs
305         ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs'}) }
306   where
307     kc_sig (Sig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
308                                 ; return (Sig nm op_ty') }
309     kc_sig other_sig          = return other_sig
310
311 kcTyClDecl decl@(ForeignType {})
312   = return decl
313
314 kcTyClDeclBody :: TyClDecl Name
315                -> ([LHsTyVarBndr Name] -> TcM a)
316                -> TcM a
317   -- Extend the env with bindings for the tyvars, taken from
318   -- the kind of the tycon/class.  Give it to the thing inside, and 
319   -- check the result kind matches
320 kcTyClDeclBody decl thing_inside
321   = tcAddDeclCtxt decl          $
322     kcHsTyVars (tyClDeclTyVars decl)    $ \ kinded_tvs ->
323     do  { tc_ty_thing <- tcLookupLocated (tcdLName decl)
324         ; let tc_kind = case tc_ty_thing of { AThing k -> k }
325         ; unifyKind tc_kind (foldr (mkArrowKind . kindedTyVarKind) 
326                                    (result_kind decl)
327                                    kinded_tvs)
328         ; thing_inside kinded_tvs }
329   where
330     result_kind (TyData { tcdKindSig = Just kind }) = kind
331     result_kind other                               = liftedTypeKind
332         -- On GADT-style declarations we allow a kind signature
333         --      data T :: *->* where { ... }
334
335 kindedTyVarKind (L _ (KindedTyVar _ k)) = k
336 \end{code}
337
338
339 %************************************************************************
340 %*                                                                      *
341 \subsection{Type checking}
342 %*                                                                      *
343 %************************************************************************
344
345 \begin{code}
346 tcSynDecls :: (Name -> ArgVrcs) -> [LTyClDecl Name] -> TcM [TyThing]
347 tcSynDecls calc_vrcs [] = return []
348 tcSynDecls calc_vrcs (decl : decls) 
349   = do { syn_tc <- addLocM (tcSynDecl calc_vrcs) decl
350        ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls calc_vrcs decls)
351        ; return (syn_tc : syn_tcs) }
352
353 tcSynDecl calc_vrcs 
354   (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
355   = tcTyVarBndrs tvs            $ \ tvs' -> do 
356     { traceTc (text "tcd1" <+> ppr tc_name) 
357     ; rhs_ty' <- tcHsKindedType rhs_ty
358     ; return (ATyCon (buildSynTyCon tc_name tvs' rhs_ty' (calc_vrcs tc_name))) }
359
360 --------------------
361 tcTyClDecl :: (Name -> ArgVrcs) -> (Name -> RecFlag) 
362            -> TyClDecl Name -> TcM TyThing
363
364 tcTyClDecl calc_vrcs calc_isrec decl
365   = tcAddDeclCtxt decl (tcTyClDecl1 calc_vrcs calc_isrec decl)
366
367 tcTyClDecl1 calc_vrcs calc_isrec 
368   (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
369            tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
370   = tcTyVarBndrs tvs    $ \ tvs' -> do 
371   { extra_tvs <- tcDataKindSig mb_ksig
372   ; let final_tvs = tvs' ++ extra_tvs
373   ; stupid_theta <- tcStupidTheta ctxt cons
374   ; want_generic <- doptM Opt_Generics
375   ; tycon <- fixM (\ tycon -> do 
376         { unbox_strict <- doptM Opt_UnboxStrictFields
377         ; gla_exts <- doptM Opt_GlasgowExts
378         ; checkTc (gla_exts || h98_syntax) (badGadtDecl tc_name)
379
380         ; data_cons <- mappM (addLocM (tcConDecl unbox_strict new_or_data tycon final_tvs)) cons
381         ; let tc_rhs = case new_or_data of
382                         DataType -> mkDataTyConRhs stupid_theta data_cons
383                         NewType  -> ASSERT( isSingleton data_cons )
384                                     mkNewTyConRhs tycon (head data_cons)
385         ; buildAlgTyCon tc_name final_tvs tc_rhs arg_vrcs is_rec
386                         (want_generic && canDoGenerics data_cons)
387         })
388   ; return (ATyCon tycon)
389   }
390   where
391     arg_vrcs = calc_vrcs tc_name
392     is_rec   = calc_isrec tc_name
393     h98_syntax = case cons of   -- All constructors have same shape
394                         L _ (GadtDecl {}) : _ -> False
395                         other -> True
396
397 tcTyClDecl1 calc_vrcs calc_isrec 
398   (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs, 
399               tcdCtxt = ctxt, tcdMeths = meths,
400               tcdFDs = fundeps, tcdSigs = sigs} )
401   = tcTyVarBndrs tvs            $ \ tvs' -> do 
402   { ctxt' <- tcHsKindedContext ctxt
403   ; fds' <- mappM (addLocM tc_fundep) fundeps
404   ; sig_stuff <- tcClassSigs class_name sigs meths
405   ; clas <- fixM (\ clas ->
406                 let     -- This little knot is just so we can get
407                         -- hold of the name of the class TyCon, which we
408                         -- need to look up its recursiveness and variance
409                     tycon_name = tyConName (classTyCon clas)
410                     tc_isrec = calc_isrec tycon_name
411                     tc_vrcs  = calc_vrcs  tycon_name
412                 in
413                 buildClass class_name tvs' ctxt' fds' 
414                            sig_stuff tc_isrec tc_vrcs)
415   ; return (AClass clas) }
416   where
417     tc_fundep (tvs1, tvs2) = do { tvs1' <- mappM tcLookupTyVar tvs1 ;
418                                 ; tvs2' <- mappM tcLookupTyVar tvs2 ;
419                                 ; return (tvs1', tvs2') }
420
421
422 tcTyClDecl1 calc_vrcs calc_isrec 
423   (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
424   = returnM (ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0 []))
425
426 -----------------------------------
427 tcConDecl :: Bool               -- True <=> -funbox-strict_fields
428           -> NewOrData -> TyCon -> [TyVar]
429           -> ConDecl Name -> TcM DataCon
430
431 tcConDecl unbox_strict NewType tycon tc_tvs     -- Newtypes
432           (ConDecl name ex_tvs ex_ctxt details)
433   = ASSERT( null ex_tvs && null (unLoc ex_ctxt) )       
434     do  { let tc_datacon field_lbls arg_ty
435                 = do { arg_ty' <- tcHsKindedType arg_ty -- No bang on newtype
436                      ; buildDataCon (unLoc name) False {- Prefix -} 
437                                     True {- Vanilla -} [NotMarkedStrict]
438                                     (map unLoc field_lbls)
439                                     tc_tvs [] [arg_ty']
440                                     tycon (mkTyVarTys tc_tvs) }
441         ; case details of
442             PrefixCon [arg_ty] -> tc_datacon [] arg_ty
443             RecCon [(field_lbl, arg_ty)] -> tc_datacon [field_lbl] arg_ty }
444
445 tcConDecl unbox_strict DataType tycon tc_tvs    -- Ordinary data types
446           (ConDecl name ex_tvs ex_ctxt details)
447   = tcTyVarBndrs ex_tvs         $ \ ex_tvs' -> do 
448     { ex_ctxt' <- tcHsKindedContext ex_ctxt
449     ; let 
450         is_vanilla = null ex_tvs && null (unLoc ex_ctxt) 
451                 -- Vanilla iff no ex_tvs and no context
452                 -- Must check the context too because of
453                 -- implicit params; e.g.
454                 --  data T = (?x::Int) => MkT Int
455
456         tc_datacon is_infix field_lbls btys
457           = do { let { bangs = map getBangStrictness btys }
458                ; arg_tys <- mappM tcHsBangType btys
459                ; buildDataCon (unLoc name) is_infix is_vanilla
460                     (argStrictness unbox_strict tycon bangs arg_tys)
461                     (map unLoc field_lbls)
462                     (tc_tvs ++ ex_tvs')
463                     ex_ctxt'
464                     arg_tys
465                     tycon (mkTyVarTys tc_tvs) }
466     ; case details of
467         PrefixCon btys     -> tc_datacon False [] btys
468         InfixCon bty1 bty2 -> tc_datacon True [] [bty1,bty2]
469         RecCon fields      -> do { checkTc (null ex_tvs) (exRecConErr name)
470                 -- It's ok to have an implicit-parameter context
471                 -- for the data constructor, provided it binds
472                 -- no type variables
473                                  ; let { (field_names, btys) = unzip fields }
474                                  ; tc_datacon False field_names btys } }
475
476 tcConDecl unbox_strict DataType tycon tc_tvs    -- GADTs
477           decl@(GadtDecl name con_ty)
478   = do  { traceTc (text "tcConDecl"  <+> ppr name)
479         ; (tvs, theta, bangs, arg_tys, tc, res_tys) <- tcLHsConSig con_ty
480                 
481         ; traceTc (text "tcConDecl1"  <+> ppr name)
482         ; let   -- Now dis-assemble the type, and check its form
483               is_vanilla = null theta && mkTyVarTys tvs `tcEqTypes` res_tys
484
485                 -- Vanilla datacons guarantee to use the same
486                 -- type variables as the parent tycon
487               (tvs', arg_tys', res_tys') 
488                   | is_vanilla = (tc_tvs, substTys subst arg_tys, substTys subst res_tys)
489                   | otherwise  = (tvs, arg_tys, res_tys)
490               subst = zipTopTvSubst tvs (mkTyVarTys tc_tvs)
491
492         ; traceTc (text "tcConDecl3"  <+> ppr name)
493         ; buildDataCon (unLoc name) False {- Not infix -} is_vanilla
494                        (argStrictness unbox_strict tycon bangs arg_tys)
495                        [{- No field labels -}]
496                        tvs' theta arg_tys' tycon res_tys' }
497
498 -------------------
499 tcStupidTheta :: LHsContext Name -> [LConDecl Name] -> TcM (Maybe ThetaType)
500 -- For GADTs we don't allow a context on the data declaration
501 -- whereas for standard Haskell style data declarations, we do
502 tcStupidTheta ctxt (L _ (ConDecl _ _ _ _) : _)
503   = do { theta <- tcHsKindedContext ctxt; return (Just theta) }
504 tcStupidTheta ctxt other        -- Includes an empty constructor list
505   = ASSERT( null (unLoc ctxt) ) return Nothing
506
507 -------------------
508 argStrictness :: Bool           -- True <=> -funbox-strict_fields
509               -> TyCon -> [HsBang]
510               -> [TcType] -> [StrictnessMark]
511 argStrictness unbox_strict tycon bangs arg_tys
512  = ASSERT( length bangs == length arg_tys )
513    zipWith (chooseBoxingStrategy unbox_strict tycon) arg_tys bangs
514
515 -- We attempt to unbox/unpack a strict field when either:
516 --   (i)  The field is marked '!!', or
517 --   (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
518
519 chooseBoxingStrategy :: Bool -> TyCon -> TcType -> HsBang -> StrictnessMark
520 chooseBoxingStrategy unbox_strict_fields tycon arg_ty bang
521   = case bang of
522         HsNoBang                                    -> NotMarkedStrict
523         HsStrict | unbox_strict_fields && can_unbox -> MarkedUnboxed
524         HsUnbox  | can_unbox                        -> MarkedUnboxed
525         other                                       -> MarkedStrict
526   where
527     can_unbox = case splitTyConApp_maybe arg_ty of
528                    Nothing             -> False
529                    Just (arg_tycon, _) -> not (isRecursiveTyCon tycon) &&
530                                           isProductTyCon arg_tycon
531 \end{code}
532
533 %************************************************************************
534 %*                                                                      *
535 \subsection{Dependency analysis}
536 %*                                                                      *
537 %************************************************************************
538
539 Validity checking is done once the mutually-recursive knot has been
540 tied, so we can look at things freely.
541
542 \begin{code}
543 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
544 checkCycleErrs tyclss
545   | null cls_cycles
546   = return ()
547   | otherwise
548   = do  { mappM_ recClsErr cls_cycles
549         ; failM }       -- Give up now, because later checkValidTyCl
550                         -- will loop if the synonym is recursive
551   where
552     cls_cycles = calcClassCycles tyclss
553
554 checkValidTyCl :: TyClDecl Name -> TcM ()
555 -- We do the validity check over declarations, rather than TyThings
556 -- only so that we can add a nice context with tcAddDeclCtxt
557 checkValidTyCl decl
558   = tcAddDeclCtxt decl $
559     do  { thing <- tcLookupLocatedGlobal (tcdLName decl)
560         ; traceTc (text "Validity of" <+> ppr thing)    
561         ; case thing of
562             ATyCon tc -> checkValidTyCon tc
563             AClass cl -> checkValidClass cl 
564         ; traceTc (text "Done validity of" <+> ppr thing)       
565         }
566
567 -------------------------
568 checkValidTyCon :: TyCon -> TcM ()
569 checkValidTyCon tc
570   | isSynTyCon tc 
571   = checkValidType syn_ctxt syn_rhs
572   | otherwise
573   =     -- Check the context on the data decl
574     checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)     `thenM_` 
575         
576         -- Check arg types of data constructors
577     mappM_ (checkValidDataCon tc) data_cons                     `thenM_`
578
579         -- Check that fields with the same name share a type
580     mappM_ check_fields groups
581
582   where
583     syn_ctxt     = TySynCtxt name
584     name         = tyConName tc
585     (_, syn_rhs) = getSynTyConDefn tc
586     data_cons    = tyConDataCons tc
587
588     groups = equivClasses cmp_fld (concatMap get_fields data_cons)
589     cmp_fld (f1,_) (f2,_) = f1 `compare` f2
590     get_fields con = dataConFieldLabels con `zip` dataConOrigArgTys con
591         -- dataConFieldLabels may return the empty list, which is fine
592
593     check_fields fields@((first_field_label, field_ty) : other_fields)
594         -- These fields all have the same name, but are from
595         -- different constructors in the data type
596         =       -- Check that all the fields in the group have the same type
597                 -- NB: this check assumes that all the constructors of a given
598                 -- data type use the same type variables
599           checkTc (all (tcEqType field_ty . snd) other_fields) 
600                   (fieldTypeMisMatch first_field_label)
601
602 -------------------------------
603 checkValidDataCon :: TyCon -> DataCon -> TcM ()
604 checkValidDataCon tc con
605   = addErrCtxt (dataConCtxt con) $ 
606     do  { checkTc (dataConTyCon con == tc) (badDataConTyCon con)
607         ; checkValidType ctxt (idType (dataConWrapId con)) }
608
609                 -- This checks the argument types and
610                 -- ambiguity of the existential context (if any)
611                 -- 
612                 -- Note [Sept 04] Now that tvs is all the tvs, this
613                 -- test doesn't actually check anything
614 --      ; checkFreeness tvs ex_theta }
615   where
616     ctxt = ConArgCtxt (dataConName con) 
617 --    (tvs, ex_theta, _, _, _) = dataConSig con
618
619
620 -------------------------------
621 checkValidClass :: Class -> TcM ()
622 checkValidClass cls
623   = do  {       -- CHECK ARITY 1 FOR HASKELL 1.4
624           gla_exts <- doptM Opt_GlasgowExts
625
626         -- Check that the class is unary, unless GlaExs
627         ; checkTc (notNull tyvars) (nullaryClassErr cls)
628         ; checkTc (gla_exts || unary) (classArityErr cls)
629
630         -- Check the super-classes
631         ; checkValidTheta (ClassSCCtxt (className cls)) theta
632
633         -- Check the class operations
634         ; mappM_ check_op op_stuff
635
636         -- Check that if the class has generic methods, then the
637         -- class has only one parameter.  We can't do generic
638         -- multi-parameter type classes!
639         ; checkTc (unary || no_generics) (genericMultiParamErr cls)
640         }
641   where
642     (tyvars, theta, _, op_stuff) = classBigSig cls
643     unary       = isSingleton tyvars
644     no_generics = null [() | (_, GenDefMeth) <- op_stuff]
645
646     check_op (sel_id, dm) 
647       = addErrCtxt (classOpCtxt sel_id tau) $ do
648         { checkValidTheta SigmaCtxt (tail theta)
649                 -- The 'tail' removes the initial (C a) from the
650                 -- class itself, leaving just the method type
651
652         ; checkValidType (FunSigCtxt op_name) tau
653
654                 -- Check that the type mentions at least one of
655                 -- the class type variables
656         ; checkTc (any (`elemVarSet` tyVarsOfType tau) tyvars)
657                   (noClassTyVarErr cls sel_id)
658
659                 -- Check that for a generic method, the type of 
660                 -- the method is sufficiently simple
661         ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
662                   (badGenericMethodType op_name op_ty)
663         }
664         where
665           op_name = idName sel_id
666           op_ty   = idType sel_id
667           (_,theta,tau) = tcSplitSigmaTy op_ty
668
669
670
671 ---------------------------------------------------------------------
672 fieldTypeMisMatch field_name
673   = sep [ptext SLIT("Different constructors give different types for field"), quotes (ppr field_name)]
674
675 dataConCtxt con = sep [ptext SLIT("When checking the data constructor:"),
676                        nest 2 (ex_part <+> pprThetaArrow ex_theta <+> ppr con <+> arg_part)]
677   where
678     (ex_tvs, ex_theta, arg_tys, _, _) = dataConSig con
679     ex_part | null ex_tvs = empty
680             | otherwise   = ptext SLIT("forall") <+> hsep (map ppr ex_tvs) <> dot
681         -- The 'ex_theta' part could be non-empty, if the user (bogusly) wrote
682         --      data T a = Eq a => T a a
683         -- So we make sure to print it
684
685     fields = dataConFieldLabels con
686     arg_part | null fields = sep (map pprParendType arg_tys)
687              | otherwise   = braces (sep (punctuate comma 
688                              [ ppr n <+> dcolon <+> ppr ty 
689                              | (n,ty) <- fields `zip` arg_tys]))
690
691 classOpCtxt sel_id tau = sep [ptext SLIT("When checking the class method:"),
692                               nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
693
694 nullaryClassErr cls
695   = ptext SLIT("No parameters for class")  <+> quotes (ppr cls)
696
697 classArityErr cls
698   = vcat [ptext SLIT("Too many parameters for class") <+> quotes (ppr cls),
699           parens (ptext SLIT("Use -fglasgow-exts to allow multi-parameter classes"))]
700
701 noClassTyVarErr clas op
702   = sep [ptext SLIT("The class method") <+> quotes (ppr op),
703          ptext SLIT("mentions none of the type variables of the class") <+> 
704                 ppr clas <+> hsep (map ppr (classTyVars clas))]
705
706 genericMultiParamErr clas
707   = ptext SLIT("The multi-parameter class") <+> quotes (ppr clas) <+> 
708     ptext SLIT("cannot have generic methods")
709
710 badGenericMethodType op op_ty
711   = hang (ptext SLIT("Generic method type is too complex"))
712        4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
713                 ptext SLIT("You can only use type variables, arrows, lists, and tuples")])
714
715 recSynErr syn_decls
716   = setSrcSpan (getLoc (head sorted_decls)) $
717     addErr (sep [ptext SLIT("Cycle in type synonym declarations:"),
718                  nest 2 (vcat (map ppr_decl sorted_decls))])
719   where
720     sorted_decls = sortLocated syn_decls
721     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
722
723 recClsErr cls_decls
724   = setSrcSpan (getLoc (head sorted_decls)) $
725     addErr (sep [ptext SLIT("Cycle in class declarations (via superclasses):"),
726                  nest 2 (vcat (map ppr_decl sorted_decls))])
727   where
728     sorted_decls = sortLocated cls_decls
729     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
730
731 sortLocated :: [Located a] -> [Located a]
732 sortLocated things = sortLe le things
733   where
734     le (L l1 _) (L l2 _) = l1 <= l2
735
736 exRecConErr name
737   = ptext SLIT("Can't combine named fields with locally-quantified type variables or context")
738     $$
739     (ptext SLIT("In the declaration of data constructor") <+> ppr name)
740
741 badDataConTyCon data_con
742   = hang (ptext SLIT("Data constructor does not return its parent type:"))
743        2 (ppr data_con)
744
745 badGadtDecl tc_name
746   = vcat [ ptext SLIT("Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
747          , nest 2 (parens $ ptext SLIT("Use -fglasgow-exts to allow GADTs")) ]
748 \end{code}