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