a300469ce820b01ad92443a075aa3ddd160a4186
[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, 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 (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
328                                    ; return (TypeSig 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   ; checkTc (new_or_data == DataType || isSingleton cons) 
404             (newtypeConError tc_name (length cons))
405
406   ; tycon <- fixM (\ tycon -> do 
407         { data_cons <- mappM (addLocM (tcConDecl unbox_strict new_or_data 
408                                                  tycon final_tvs)) 
409                              cons
410         ; let tc_rhs 
411                 | null cons && is_boot  -- In a hs-boot file, empty cons means
412                 = AbstractTyCon         -- "don't know"; hence Abstract
413                 | otherwise
414                 = case new_or_data of
415                         DataType -> mkDataTyConRhs data_cons
416                         NewType  -> ASSERT( isSingleton data_cons )
417                                     mkNewTyConRhs tycon (head data_cons)
418         ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs arg_vrcs is_rec
419                         (want_generic && canDoGenerics data_cons)
420         })
421   ; return (ATyCon tycon)
422   }
423   where
424     arg_vrcs = calc_vrcs tc_name
425     is_rec   = calc_isrec tc_name
426     h98_syntax = case cons of   -- All constructors have same shape
427                         L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
428                         other -> True
429
430 tcTyClDecl1 calc_vrcs calc_isrec 
431   (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs, 
432               tcdCtxt = ctxt, tcdMeths = meths,
433               tcdFDs = fundeps, tcdSigs = sigs} )
434   = tcTyVarBndrs tvs            $ \ tvs' -> do 
435   { ctxt' <- tcHsKindedContext ctxt
436   ; fds' <- mappM (addLocM tc_fundep) fundeps
437   ; sig_stuff <- tcClassSigs class_name sigs meths
438   ; clas <- fixM (\ clas ->
439                 let     -- This little knot is just so we can get
440                         -- hold of the name of the class TyCon, which we
441                         -- need to look up its recursiveness and variance
442                     tycon_name = tyConName (classTyCon clas)
443                     tc_isrec = calc_isrec tycon_name
444                     tc_vrcs  = calc_vrcs  tycon_name
445                 in
446                 buildClass class_name tvs' ctxt' fds' 
447                            sig_stuff tc_isrec tc_vrcs)
448   ; return (AClass clas) }
449   where
450     tc_fundep (tvs1, tvs2) = do { tvs1' <- mappM tcLookupTyVar tvs1 ;
451                                 ; tvs2' <- mappM tcLookupTyVar tvs2 ;
452                                 ; return (tvs1', tvs2') }
453
454
455 tcTyClDecl1 calc_vrcs calc_isrec 
456   (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
457   = returnM (ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0 []))
458
459 -----------------------------------
460 tcConDecl :: Bool               -- True <=> -funbox-strict_fields
461           -> NewOrData -> TyCon -> [TyVar]
462           -> ConDecl Name -> TcM DataCon
463
464 tcConDecl unbox_strict NewType tycon tc_tvs     -- Newtypes
465           (ConDecl name _ ex_tvs ex_ctxt details ResTyH98)
466   = ASSERT( null ex_tvs && null (unLoc ex_ctxt) )       
467     do  { let tc_datacon field_lbls arg_ty
468                 = do { arg_ty' <- tcHsKindedType arg_ty -- No bang on newtype
469                      ; buildDataCon (unLoc name) False {- Prefix -} 
470                                     True {- Vanilla -} [NotMarkedStrict]
471                                     (map unLoc field_lbls)
472                                     tc_tvs [] [arg_ty']
473                                     tycon (mkTyVarTys tc_tvs) }
474         ; case details of
475             PrefixCon [arg_ty] -> tc_datacon [] arg_ty
476             RecCon [(field_lbl, arg_ty)] -> tc_datacon [field_lbl] arg_ty
477             other -> failWithTc (newTypeFieldErr name (length (hsConArgs details)))
478                         -- Check that the constructor has exactly one field
479         }
480
481 tcConDecl unbox_strict DataType tycon tc_tvs    -- Data types
482           (ConDecl name _ tvs ctxt details res_ty)
483   = tcTyVarBndrs tvs            $ \ tvs' -> do 
484     { ctxt' <- tcHsKindedContext ctxt
485     ; (data_tc, res_ty_args) <- tcResultType tycon tc_tvs res_ty
486     ; let 
487         con_tvs = case res_ty of
488                     ResTyH98    -> tc_tvs ++ tvs'
489                     ResTyGADT _ -> tryVanilla tvs' res_ty_args
490
491         -- Vanilla iff result type matches the quantified vars exactly,
492         -- and there is no existential context
493         -- Must check the context too because of implicit params; e.g.
494         --      data T = (?x::Int) => MkT Int
495         is_vanilla = res_ty_args `tcEqTypes` mkTyVarTys con_tvs
496                      && null (unLoc ctxt)
497
498         tc_datacon is_infix field_lbls btys
499           = do { let bangs = map getBangStrictness btys
500                ; arg_tys <- mappM tcHsBangType btys
501                ; buildDataCon (unLoc name) is_infix is_vanilla
502                     (argStrictness unbox_strict tycon bangs arg_tys)
503                     (map unLoc field_lbls)
504                     con_tvs ctxt' arg_tys
505                     data_tc res_ty_args }
506                 -- NB:  we put data_tc, the type constructor gotten from the constructor 
507                 --      type signature into the data constructor; that way 
508                 --      checkValidDataCon can complain if it's wrong.
509
510     ; case details of
511         PrefixCon btys     -> tc_datacon False [] btys
512         InfixCon bty1 bty2 -> tc_datacon True  [] [bty1,bty2]
513         RecCon fields      -> tc_datacon False field_names btys
514                            where
515                               (field_names, btys) = unzip fields
516                               
517     }
518
519 tcResultType :: TyCon -> [TyVar] -> ResType Name -> TcM (TyCon, [TcType])
520 tcResultType tycon tvs ResTyH98           = return (tycon, mkTyVarTys tvs)
521 tcResultType _     _   (ResTyGADT res_ty) = tcLHsConResTy res_ty
522
523 tryVanilla :: [TyVar] -> [TcType] -> [TyVar]
524 -- (tryVanilla tvs tys) returns a permutation of tvs.
525 -- It tries to re-order the tvs so that it exactly 
526 -- matches the [Type], if that is possible
527 tryVanilla tvs (ty:tys) | Just tv <- tcGetTyVar_maybe ty        -- The type is a tyvar
528                         , tv `elem` tvs                         -- That tyvar is in the list
529                         = tv : tryVanilla (delete tv tvs) tys
530 tryVanilla tvs tys = tvs        -- Fall through case
531
532
533 -------------------
534 argStrictness :: Bool           -- True <=> -funbox-strict_fields
535               -> TyCon -> [HsBang]
536               -> [TcType] -> [StrictnessMark]
537 argStrictness unbox_strict tycon bangs arg_tys
538  = ASSERT( length bangs == length arg_tys )
539    zipWith (chooseBoxingStrategy unbox_strict tycon) arg_tys bangs
540
541 -- We attempt to unbox/unpack a strict field when either:
542 --   (i)  The field is marked '!!', or
543 --   (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
544
545 chooseBoxingStrategy :: Bool -> TyCon -> TcType -> HsBang -> StrictnessMark
546 chooseBoxingStrategy unbox_strict_fields tycon arg_ty bang
547   = case bang of
548         HsNoBang                                    -> NotMarkedStrict
549         HsStrict | unbox_strict_fields && can_unbox -> MarkedUnboxed
550         HsUnbox  | can_unbox                        -> MarkedUnboxed
551         other                                       -> MarkedStrict
552   where
553     can_unbox = case splitTyConApp_maybe arg_ty of
554                    Nothing             -> False
555                    Just (arg_tycon, _) -> not (isRecursiveTyCon tycon) &&
556                                           isProductTyCon arg_tycon
557 \end{code}
558
559 %************************************************************************
560 %*                                                                      *
561 \subsection{Dependency analysis}
562 %*                                                                      *
563 %************************************************************************
564
565 Validity checking is done once the mutually-recursive knot has been
566 tied, so we can look at things freely.
567
568 \begin{code}
569 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
570 checkCycleErrs tyclss
571   | null cls_cycles
572   = return ()
573   | otherwise
574   = do  { mappM_ recClsErr cls_cycles
575         ; failM }       -- Give up now, because later checkValidTyCl
576                         -- will loop if the synonym is recursive
577   where
578     cls_cycles = calcClassCycles tyclss
579
580 checkValidTyCl :: TyClDecl Name -> TcM ()
581 -- We do the validity check over declarations, rather than TyThings
582 -- only so that we can add a nice context with tcAddDeclCtxt
583 checkValidTyCl decl
584   = tcAddDeclCtxt decl $
585     do  { thing <- tcLookupLocatedGlobal (tcdLName decl)
586         ; traceTc (text "Validity of" <+> ppr thing)    
587         ; case thing of
588             ATyCon tc -> checkValidTyCon tc
589             AClass cl -> checkValidClass cl 
590         ; traceTc (text "Done validity of" <+> ppr thing)       
591         }
592
593 -------------------------
594 -- For data types declared with record syntax, we require
595 -- that each constructor that has a field 'f' 
596 --      (a) has the same result type
597 --      (b) has the same type for 'f'
598 -- module alpha conversion of the quantified type variables
599 -- of the constructor.
600
601 checkValidTyCon :: TyCon -> TcM ()
602 checkValidTyCon tc
603   | isSynTyCon tc 
604   = checkValidType syn_ctxt syn_rhs
605   | otherwise
606   =     -- Check the context on the data decl
607     checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)     `thenM_` 
608         
609         -- Check arg types of data constructors
610     mappM_ (checkValidDataCon tc) data_cons                     `thenM_`
611
612         -- Check that fields with the same name share a type
613     mappM_ check_fields groups
614
615   where
616     syn_ctxt     = TySynCtxt name
617     name         = tyConName tc
618     (_, syn_rhs) = getSynTyConDefn tc
619     data_cons    = tyConDataCons tc
620
621     groups = equivClasses cmp_fld (concatMap get_fields data_cons)
622     cmp_fld (f1,_) (f2,_) = f1 `compare` f2
623     get_fields con = dataConFieldLabels con `zip` repeat con
624         -- dataConFieldLabels may return the empty list, which is fine
625
626     -- XXX - autrijus - Make this far more complex to acommodate 
627     --       for different return types.  Add res_ty to the mix,
628     --       comparing them in two steps, all for good error messages.
629     --       Plan: Use Unify.tcMatchTys to compare the first candidate's
630     --             result type against other candidates' types (check bothways).
631     --             If they magically agrees, take the substitution and
632     --             apply them to the latter ones, and see if they match perfectly.
633     -- check_fields fields@((first_field_label, field_ty) : other_fields)
634     check_fields fields@((label, con1) : other_fields)
635         -- These fields all have the same name, but are from
636         -- different constructors in the data type
637         = recoverM (return ()) $ mapM_ checkOne other_fields
638                 -- Check that all the fields in the group have the same type
639                 -- NB: this check assumes that all the constructors of a given
640                 -- data type use the same type variables
641         where
642         tvs1 = mkVarSet (dataConTyVars con1)
643         res1 = dataConResTys con1
644         fty1 = dataConFieldType con1 label
645
646         checkOne (_, con2)    -- Do it bothways to ensure they are structurally identical
647             = do { checkFieldCompat label con1 con2 tvs1 res1 res2 fty1 fty2
648                  ; checkFieldCompat label con2 con1 tvs2 res2 res1 fty2 fty1 }
649             where        
650                 tvs2 = mkVarSet (dataConTyVars con2)
651                 res2 = dataConResTys con2 
652                 fty2 = dataConFieldType con2 label
653
654 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
655   = do  { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
656         ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
657   where
658     mb_subst1 = tcMatchTys tvs1 res1 res2
659     mb_subst2 = tcMatchTyX tvs1 (fromJust mb_subst1) fty1 fty2
660
661 -------------------------------
662 checkValidDataCon :: TyCon -> DataCon -> TcM ()
663 checkValidDataCon tc con
664   = addErrCtxt (dataConCtxt con) $ 
665     do  { checkTc (dataConTyCon con == tc) (badDataConTyCon con)
666         ; checkValidType ctxt (idType (dataConWrapId con)) }
667
668                 -- This checks the argument types and
669                 -- ambiguity of the existential context (if any)
670                 -- 
671                 -- Note [Sept 04] Now that tvs is all the tvs, this
672                 -- test doesn't actually check anything
673 --      ; checkFreeness tvs ex_theta }
674   where
675     ctxt = ConArgCtxt (dataConName con) 
676 --    (tvs, ex_theta, _, _, _) = dataConSig con
677
678
679 -------------------------------
680 checkValidClass :: Class -> TcM ()
681 checkValidClass cls
682   = do  {       -- CHECK ARITY 1 FOR HASKELL 1.4
683           gla_exts <- doptM Opt_GlasgowExts
684
685         -- Check that the class is unary, unless GlaExs
686         ; checkTc (notNull tyvars) (nullaryClassErr cls)
687         ; checkTc (gla_exts || unary) (classArityErr cls)
688
689         -- Check the super-classes
690         ; checkValidTheta (ClassSCCtxt (className cls)) theta
691
692         -- Check the class operations
693         ; mappM_ (check_op gla_exts) op_stuff
694
695         -- Check that if the class has generic methods, then the
696         -- class has only one parameter.  We can't do generic
697         -- multi-parameter type classes!
698         ; checkTc (unary || no_generics) (genericMultiParamErr cls)
699         }
700   where
701     (tyvars, theta, _, op_stuff) = classBigSig cls
702     unary       = isSingleton tyvars
703     no_generics = null [() | (_, GenDefMeth) <- op_stuff]
704
705     check_op gla_exts (sel_id, dm) 
706       = addErrCtxt (classOpCtxt sel_id tau) $ do
707         { checkValidTheta SigmaCtxt (tail theta)
708                 -- The 'tail' removes the initial (C a) from the
709                 -- class itself, leaving just the method type
710
711         ; checkValidType (FunSigCtxt op_name) tau
712
713                 -- Check that the type mentions at least one of
714                 -- the class type variables
715         ; checkTc (any (`elemVarSet` tyVarsOfType tau) tyvars)
716                   (noClassTyVarErr cls sel_id)
717
718                 -- Check that for a generic method, the type of 
719                 -- the method is sufficiently simple
720         ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
721                   (badGenericMethodType op_name op_ty)
722         }
723         where
724           op_name = idName sel_id
725           op_ty   = idType sel_id
726           (_,theta1,tau1) = tcSplitSigmaTy op_ty
727           (_,theta2,tau2)  = tcSplitSigmaTy tau1
728           (theta,tau) | gla_exts  = (theta1 ++ theta2, tau2)
729                       | otherwise = (theta1,           mkPhiTy (tail theta1) tau1)
730                 -- Ugh!  The function might have a type like
731                 --      op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
732                 -- With -fglasgow-exts, we want to allow this, even though the inner 
733                 -- forall has an (Eq a) constraint.  Whereas in general, each constraint 
734                 -- in the context of a for-all must mention at least one quantified
735                 -- type variable.  What a mess!
736
737
738 ---------------------------------------------------------------------
739 resultTypeMisMatch field_name con1 con2
740   = vcat [sep [ptext SLIT("Constructors") <+> ppr con1 <+> ptext SLIT("and") <+> ppr con2, 
741                 ptext SLIT("have a common field") <+> quotes (ppr field_name) <> comma],
742           nest 2 $ ptext SLIT("but have different result types")]
743 fieldTypeMisMatch field_name con1 con2
744   = sep [ptext SLIT("Constructors") <+> ppr con1 <+> ptext SLIT("and") <+> ppr con2, 
745          ptext SLIT("give different types for field"), quotes (ppr field_name)]
746
747 dataConCtxt con = sep [ptext SLIT("When checking the data constructor:"),
748                        nest 2 (ex_part <+> pprThetaArrow ex_theta <+> ppr con <+> arg_part)]
749   where
750     (ex_tvs, ex_theta, arg_tys, _, _) = dataConSig con
751     ex_part | null ex_tvs = empty
752             | otherwise   = ptext SLIT("forall") <+> hsep (map ppr ex_tvs) <> dot
753         -- The 'ex_theta' part could be non-empty, if the user (bogusly) wrote
754         --      data T a = Eq a => T a a
755         -- So we make sure to print it
756
757     fields = dataConFieldLabels con
758     arg_part | null fields = sep (map pprParendType arg_tys)
759              | otherwise   = braces (sep (punctuate comma 
760                              [ ppr n <+> dcolon <+> ppr ty 
761                              | (n,ty) <- fields `zip` arg_tys]))
762
763 classOpCtxt sel_id tau = sep [ptext SLIT("When checking the class method:"),
764                               nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
765
766 nullaryClassErr cls
767   = ptext SLIT("No parameters for class")  <+> quotes (ppr cls)
768
769 classArityErr cls
770   = vcat [ptext SLIT("Too many parameters for class") <+> quotes (ppr cls),
771           parens (ptext SLIT("Use -fglasgow-exts to allow multi-parameter classes"))]
772
773 noClassTyVarErr clas op
774   = sep [ptext SLIT("The class method") <+> quotes (ppr op),
775          ptext SLIT("mentions none of the type variables of the class") <+> 
776                 ppr clas <+> hsep (map ppr (classTyVars clas))]
777
778 genericMultiParamErr clas
779   = ptext SLIT("The multi-parameter class") <+> quotes (ppr clas) <+> 
780     ptext SLIT("cannot have generic methods")
781
782 badGenericMethodType op op_ty
783   = hang (ptext SLIT("Generic method type is too complex"))
784        4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
785                 ptext SLIT("You can only use type variables, arrows, lists, and tuples")])
786
787 recSynErr syn_decls
788   = setSrcSpan (getLoc (head sorted_decls)) $
789     addErr (sep [ptext SLIT("Cycle in type synonym declarations:"),
790                  nest 2 (vcat (map ppr_decl sorted_decls))])
791   where
792     sorted_decls = sortLocated syn_decls
793     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
794
795 recClsErr cls_decls
796   = setSrcSpan (getLoc (head sorted_decls)) $
797     addErr (sep [ptext SLIT("Cycle in class declarations (via superclasses):"),
798                  nest 2 (vcat (map ppr_decl sorted_decls))])
799   where
800     sorted_decls = sortLocated cls_decls
801     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
802
803 sortLocated :: [Located a] -> [Located a]
804 sortLocated things = sortLe le things
805   where
806     le (L l1 _) (L l2 _) = l1 <= l2
807
808 badDataConTyCon data_con
809   = hang (ptext SLIT("Data constructor") <+> quotes (ppr data_con) <+>
810                 ptext SLIT("returns type") <+> quotes (ppr (dataConTyCon data_con)))
811        2 (ptext SLIT("instead of its parent type"))
812
813 badGadtDecl tc_name
814   = vcat [ ptext SLIT("Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
815          , nest 2 (parens $ ptext SLIT("Use -fglasgow-exts to allow GADTs")) ]
816
817 newtypeConError tycon n
818   = sep [ptext SLIT("A newtype must have exactly one constructor"),
819          nest 2 $ ptext SLIT("but") <+> quotes (ppr tycon) <+> ptext SLIT("has") <+> speakN n ]
820
821 newTypeFieldErr con_name n_flds
822   = sep [ptext SLIT("The constructor of a newtype must have exactly one field"), 
823          nest 2 $ ptext SLIT("but") <+> quotes (ppr con_name) <+> ptext SLIT("has") <+> speakN n_flds]
824
825 emptyConDeclsErr tycon
826   = sep [quotes (ppr tycon) <+> ptext SLIT("has no constructors"),
827          nest 2 $ ptext SLIT("(-fglasgow-exts permits this)")]
828
829 badBootClassDeclErr = ptext SLIT("Illegal class declaration in hs-boot file")
830 \end{code}