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