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