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