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