[project @ 2005-09-18 16:23:57 by wolfgang]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcTyClsDecls.lhs
index 120e6f8..6ff39bc 100644 (file)
@@ -12,36 +12,36 @@ module TcTyClsDecls (
 
 import HsSyn           ( TyClDecl(..),  HsConDetails(..), HsTyVarBndr(..),
                          ConDecl(..),   Sig(..), , NewOrData(..), 
-                         tyClDeclTyVars, isSynDecl, LConDecl,
-                         LTyClDecl, tcdName, LHsTyVarBndr, LHsContext
+                         tyClDeclTyVars, isSynDecl, 
+                         LTyClDecl, tcdName, hsTyVarName, LHsTyVarBndr
                        )
 import HsTypes          ( HsBang(..), getBangStrictness )
 import BasicTypes      ( RecFlag(..), StrictnessMark(..) )
-import HscTypes                ( implicitTyThings )
+import HscTypes                ( implicitTyThings, ModDetails )
 import BuildTyCl       ( buildClass, buildAlgTyCon, buildSynTyCon, buildDataCon,
                          mkDataTyConRhs, mkNewTyConRhs )
 import TcRnMonad
-import TcEnv           ( TcTyThing(..), TyThing(..), 
+import TcEnv           ( TyThing(..), 
                          tcLookupLocated, tcLookupLocatedGlobal, 
-                         tcExtendGlobalEnv, tcExtendKindEnv,
+                         tcExtendGlobalEnv, tcExtendKindEnv, tcExtendKindEnvTvs,
                          tcExtendRecEnv, tcLookupTyVar )
 import TcTyDecls       ( calcTyConArgVrcs, calcRecFlags, calcClassCycles, calcSynCycles )
 import TcClassDcl      ( tcClassSigs, tcAddDeclCtxt )
 import TcHsType                ( kcHsTyVars, kcHsLiftedSigType, kcHsType, 
                          kcHsContext, tcTyVarBndrs, tcHsKindedType, tcHsKindedContext,
-                         kcHsSigType, tcHsBangType, tcLHsConSig )
+                         kcHsSigType, tcHsBangType, tcLHsConSig, tcDataKindSig )
 import TcMType         ( newKindVar, checkValidTheta, checkValidType, checkFreeness, 
                          UserTypeCtxt(..), SourceTyCtxt(..) ) 
-import TcUnify         ( unifyKind )
-import TcType          ( TcKind, ThetaType, TcType, tyVarsOfType, 
+import TcType          ( TcKind, TcType, tyVarsOfType, mkPhiTy,
                          mkArrowKind, liftedTypeKind, mkTyVarTys, tcEqTypes,
                          tcSplitSigmaTy, tcEqType )
 import Type            ( splitTyConApp_maybe, pprThetaArrow, pprParendType )
+import Kind            ( mkArrowKinds, splitKindFunTys )
 import Generics                ( validGenericMethodType, canDoGenerics )
 import Class           ( Class, className, classTyCon, DefMeth(..), classBigSig, classTyVars )
-import TyCon           ( TyCon, ArgVrcs, 
+import TyCon           ( TyCon, ArgVrcs, AlgTyConRhs( AbstractTyCon ),
                          tyConDataCons, mkForeignTyCon, isProductTyCon, isRecursiveTyCon,
-                         tyConStupidTheta, getSynTyConDefn, tyConDataCons, isSynTyCon, tyConName )
+                         tyConStupidTheta, getSynTyConDefn, isSynTyCon, tyConName )
 import DataCon         ( DataCon, dataConWrapId, dataConName, dataConSig, 
                          dataConFieldLabels, dataConOrigArgTys, dataConTyCon )
 import Type            ( zipTopTvSubst, substTys )
@@ -49,12 +49,13 @@ import Var          ( TyVar, idType, idName )
 import VarSet          ( elemVarSet )
 import Name            ( Name )
 import Outputable
-import Util            ( zipLazy, isSingleton, notNull )
+import Util            ( zipLazy, isSingleton, notNull, sortLe )
 import List            ( partition )
 import SrcLoc          ( Located(..), unLoc, getLoc )
 import ListSetOps      ( equivClasses )
 import Digraph         ( SCC(..) )
-import CmdLineOpts     ( DynFlag( Opt_GlasgowExts, Opt_Generics, Opt_UnboxStrictFields ) )
+import DynFlags                ( DynFlag( Opt_GlasgowExts, Opt_Generics, 
+                                       Opt_UnboxStrictFields ) )
 \end{code}
 
 
@@ -108,14 +109,15 @@ The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
 @TyThing@s.  @rec_vrcs@ is a finite map from @Name@s to @ArgVrcs@s.
 
 \begin{code}
-tcTyAndClassDecls :: [Name] -> [LTyClDecl Name]
+tcTyAndClassDecls :: ModDetails -> [LTyClDecl Name]
                   -> TcM TcGblEnv      -- Input env extended by types and classes 
                                        -- and their implicit Ids,DataCons
-tcTyAndClassDecls boot_names decls
+tcTyAndClassDecls boot_details decls
   = do {       -- First check for cyclic type synonysm or classes
                -- See notes with checkCycleErrs
          checkCycleErrs decls
-
+       ; mod <- getModule
+       ; traceTc (text "tcTyAndCl" <+> ppr mod)
        ; (syn_tycons, alg_tyclss) <- fixM (\ ~(rec_syn_tycons, rec_alg_tyclss) ->
          do    { let { -- Calculate variances and rec-flag
                      ; (syn_decls, alg_decls) = partition (isSynDecl . unLoc) decls }
@@ -133,7 +135,7 @@ tcTyAndClassDecls boot_names decls
                { (kc_syn_decls, kc_alg_decls) <- kcTyClDecls syn_decls alg_decls
 
                ; let { calc_vrcs = calcTyConArgVrcs (rec_syn_tycons ++ rec_alg_tyclss)
-                     ; calc_rec  = calcRecFlags boot_names rec_alg_tyclss
+                     ; calc_rec  = calcRecFlags boot_details rec_alg_tyclss
                      ; tc_decl   = addLocM (tcTyClDecl calc_vrcs calc_rec) }
                        -- Type-check the type synonyms, and extend the envt
                ; syn_tycons <- tcSynDecls calc_vrcs kc_syn_decls
@@ -227,10 +229,22 @@ kcTyClDecls syn_decls alg_decls
 
 ------------------------------------------------------------------------
 getInitialKind :: LTyClDecl Name -> TcM (Name, TcKind)
+-- Only for data type and class declarations
+-- Get as much info as possible from the data or class decl,
+-- so as to maximise usefulness of error messages
+getInitialKind (L _ decl)
+  = do         { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
+       ; res_kind  <- mk_res_kind decl
+       ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
+  where
+    mk_arg_kind (UserTyVar _)        = newKindVar
+    mk_arg_kind (KindedTyVar _ kind) = return kind
+
+    mk_res_kind (TyData { tcdKindSig = Just kind }) = return kind
+       -- On GADT-style declarations we allow a kind signature
+       --      data T :: *->* where { ... }
+    mk_res_kind other = return liftedTypeKind
 
-getInitialKind decl
- = newKindVar                  `thenM` \ kind  ->
-   returnM (unLoc (tcdLName (unLoc decl)), kind)
 
 ----------------
 kcSynDecls :: [SCC (LTyClDecl Name)] 
@@ -262,6 +276,8 @@ kcSynDecl (CyclicSCC decls)
   = do { recSynErr decls; failM }      -- Fail here to avoid error cascade
                                        -- of out-of-scope tycons
 
+kindedTyVarKind (L _ (KindedTyVar _ k)) = k
+
 ------------------------------------------------------------------------
 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
        -- Not used for type synonyms (see kcSynDecl)
@@ -279,6 +295,7 @@ kcTyClDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
           ; return (ConDecl name ex_tvs' ex_ctxt' details')}
     kc_con_decl (GadtDecl name ty)
         = do { ty' <- kcHsSigType ty
+            ; traceTc (text "kc_con_decl" <+> ppr name <+> ppr ty')
             ; return (GadtDecl name ty') }
 
     kc_con_details (PrefixCon btys) 
@@ -299,7 +316,9 @@ kcTyClDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
 
 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt,  tcdSigs = sigs})
   = kcTyClDeclBody decl        $ \ tvs' ->
-    do { ctxt' <- kcHsContext ctxt     
+    do { is_boot <- tcIsHsBoot
+       ; checkTc (not is_boot) badBootClassDeclErr
+       ; ctxt' <- kcHsContext ctxt     
        ; sigs' <- mappM (wrapLocM kc_sig) sigs
        ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs'}) }
   where
@@ -313,19 +332,21 @@ kcTyClDecl decl@(ForeignType {})
 kcTyClDeclBody :: TyClDecl Name
               -> ([LHsTyVarBndr Name] -> TcM a)
               -> TcM a
-  -- Extend the env with bindings for the tyvars, taken from
-  -- the kind of the tycon/class.  Give it to the thing inside, and 
-  -- check the result kind matches
+-- getInitialKind has made a suitably-shaped kind for the type or class
+-- Unpack it, and attribute those kinds to the type variables
+-- Extend the env with bindings for the tyvars, taken from
+-- the kind of the tycon/class.  Give it to the thing inside, and 
+ -- check the result kind matches
 kcTyClDeclBody decl thing_inside
   = tcAddDeclCtxt decl         $
-    kcHsTyVars (tyClDeclTyVars decl)   $ \ kinded_tvs ->
     do         { tc_ty_thing <- tcLookupLocated (tcdLName decl)
-       ; let tc_kind = case tc_ty_thing of { AThing k -> k }
-       ; unifyKind tc_kind (foldr (mkArrowKind . kindedTyVarKind) 
-                                  liftedTypeKind kinded_tvs)
-       ; thing_inside kinded_tvs }
-
-kindedTyVarKind (L _ (KindedTyVar _ k)) = k
+       ; let tc_kind    = case tc_ty_thing of { AThing k -> k }
+             (kinds, _) = splitKindFunTys tc_kind
+             hs_tvs     = tcdTyVars decl
+             kinded_tvs = ASSERT( length kinds >= length hs_tvs )
+                          [ L loc (KindedTyVar (hsTyVarName tv) k)
+                          | (L loc tv, k) <- zip hs_tvs kinds]
+       ; tcExtendKindEnvTvs kinded_tvs (thing_inside kinded_tvs) }
 \end{code}
 
 
@@ -359,18 +380,37 @@ tcTyClDecl calc_vrcs calc_isrec decl
 
 tcTyClDecl1 calc_vrcs calc_isrec 
   (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
-          tcdLName = L _ tc_name, tcdCons = cons})
-  = tcTyVarBndrs tvs           $ \ tvs' -> do 
-  { stupid_theta <- tcStupidTheta ctxt cons
+          tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
+  = tcTyVarBndrs tvs   $ \ tvs' -> do 
+  { extra_tvs <- tcDataKindSig mb_ksig
+  ; let final_tvs = tvs' ++ extra_tvs
+  ; stupid_theta <- tcHsKindedContext ctxt
   ; want_generic <- doptM Opt_Generics
+  ; unbox_strict <- doptM Opt_UnboxStrictFields
+  ; gla_exts     <- doptM Opt_GlasgowExts
+  ; is_boot     <- tcIsHsBoot  -- Are we compiling an hs-boot file?
+
+       -- Check that we don't use GADT syntax in H98 world
+  ; checkTc (gla_exts || h98_syntax) (badGadtDecl tc_name)
+
+       -- Check that there's at least one condecl,
+       -- or else we're reading an interface file, or -fglasgow-exts
+  ; checkTc (not (null cons) || gla_exts || is_boot)
+           (emptyConDeclsErr tc_name)
+    
   ; tycon <- fixM (\ tycon -> do 
-       { unbox_strict <- doptM Opt_UnboxStrictFields
-       ; data_cons <- mappM (addLocM (tcConDecl unbox_strict new_or_data tycon tvs')) cons
-       ; let tc_rhs = case new_or_data of
-                       DataType -> mkDataTyConRhs stupid_theta data_cons
+       { data_cons <- mappM (addLocM (tcConDecl unbox_strict new_or_data 
+                                                tycon final_tvs)) 
+                            cons
+       ; let tc_rhs 
+               | null cons && is_boot  -- In a hs-boot file, empty cons means
+               = AbstractTyCon         -- "don't know"; hence Abstract
+               | otherwise
+               = case new_or_data of
+                       DataType -> mkDataTyConRhs data_cons
                        NewType  -> ASSERT( isSingleton data_cons )
                                    mkNewTyConRhs tycon (head data_cons)
-       ; buildAlgTyCon tc_name tvs' tc_rhs arg_vrcs is_rec
+       ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs arg_vrcs is_rec
                        (want_generic && canDoGenerics data_cons)
        })
   ; return (ATyCon tycon)
@@ -378,6 +418,9 @@ tcTyClDecl1 calc_vrcs calc_isrec
   where
     arg_vrcs = calc_vrcs tc_name
     is_rec   = calc_isrec tc_name
+    h98_syntax = case cons of  -- All constructors have same shape
+                       L _ (GadtDecl {}) : _ -> False
+                       other -> True
 
 tcTyClDecl1 calc_vrcs calc_isrec 
   (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs, 
@@ -413,13 +456,30 @@ tcConDecl :: Bool                 -- True <=> -funbox-strict_fields
          -> NewOrData -> TyCon -> [TyVar]
          -> ConDecl Name -> TcM DataCon
 
-tcConDecl unbox_strict new_or_data tycon tc_tvs
+tcConDecl unbox_strict NewType tycon tc_tvs    -- Newtypes
+         (ConDecl name ex_tvs ex_ctxt details)
+  = ASSERT( null ex_tvs && null (unLoc ex_ctxt) )      
+    do { let tc_datacon field_lbls arg_ty
+               = do { arg_ty' <- tcHsKindedType arg_ty -- No bang on newtype
+                    ; buildDataCon (unLoc name) False {- Prefix -} 
+                                   True {- Vanilla -} [NotMarkedStrict]
+                                   (map unLoc field_lbls)
+                                   tc_tvs [] [arg_ty']
+                                   tycon (mkTyVarTys tc_tvs) }
+       ; case details of
+           PrefixCon [arg_ty] -> tc_datacon [] arg_ty
+           RecCon [(field_lbl, arg_ty)] -> tc_datacon [field_lbl] arg_ty }
+
+tcConDecl unbox_strict DataType tycon tc_tvs   -- Ordinary data types
          (ConDecl name ex_tvs ex_ctxt details)
   = tcTyVarBndrs ex_tvs                $ \ ex_tvs' -> do 
     { ex_ctxt' <- tcHsKindedContext ex_ctxt
     ; let 
        is_vanilla = null ex_tvs && null (unLoc ex_ctxt) 
                -- Vanilla iff no ex_tvs and no context
+               -- Must check the context too because of
+               -- implicit params; e.g.
+               --  data T = (?x::Int) => MkT Int
 
        tc_datacon is_infix field_lbls btys
          = do { let { bangs = map getBangStrictness btys }
@@ -434,14 +494,17 @@ tcConDecl unbox_strict new_or_data tycon tc_tvs
     ; case details of
        PrefixCon btys     -> tc_datacon False [] btys
        InfixCon bty1 bty2 -> tc_datacon True [] [bty1,bty2]
-       RecCon fields      -> do { checkTc is_vanilla (exRecConErr name)
+       RecCon fields      -> do { checkTc (null ex_tvs) (exRecConErr name)
+               -- It's ok to have an implicit-parameter context
+               -- for the data constructor, provided it binds
+               -- no type variables
                                 ; let { (field_names, btys) = unzip fields }
                                 ; tc_datacon False field_names btys } }
 
-tcConDecl unbox_strict new_or_data tycon tc_tvs
+tcConDecl unbox_strict DataType tycon tc_tvs   -- GADTs
          decl@(GadtDecl name con_ty)
   = do { traceTc (text "tcConDecl"  <+> ppr name)
-       ; (tvs, theta, bangs, arg_tys, tc, res_tys) <- tcLHsConSig con_ty
+       ; (tvs, theta, bangs, arg_tys, data_tc, res_tys) <- tcLHsConSig con_ty
                
        ; traceTc (text "tcConDecl1"  <+> ppr name)
        ; let   -- Now dis-assemble the type, and check its form
@@ -458,15 +521,10 @@ tcConDecl unbox_strict new_or_data tycon tc_tvs
        ; buildDataCon (unLoc name) False {- Not infix -} is_vanilla
                       (argStrictness unbox_strict tycon bangs arg_tys)
                       [{- No field labels -}]
-                      tvs' theta arg_tys' tycon res_tys' }
-
-tcStupidTheta :: LHsContext Name -> [LConDecl Name] -> TcM (Maybe ThetaType)
--- For GADTs we don't allow a context on the data declaration
--- whereas for standard Haskell style data declarations, we do
-tcStupidTheta ctxt (L _ (ConDecl _ _ _ _) : _)
-  = do { theta <- tcHsKindedContext ctxt; return (Just theta) }
-tcStupidTheta ctxt other       -- Includes an empty constructor list
-  = ASSERT( null (unLoc ctxt) ) return Nothing
+                      tvs' theta arg_tys' data_tc res_tys' }
+               -- NB:  we put data_tc, the type constructor gotten from the constructor 
+               --      type signature into the data constructor; that way checkValidDataCon 
+               --      can complain if it's wrong.
 
 -------------------
 argStrictness :: Bool          -- True <=> -funbox-strict_fields
@@ -578,7 +636,7 @@ checkValidDataCon tc con
 --     ; checkFreeness tvs ex_theta }
   where
     ctxt = ConArgCtxt (dataConName con) 
-    (tvs, ex_theta, _, _, _) = dataConSig con
+--    (tvs, ex_theta, _, _, _) = dataConSig con
 
 
 -------------------------------
@@ -595,7 +653,7 @@ checkValidClass cls
        ; checkValidTheta (ClassSCCtxt (className cls)) theta
 
        -- Check the class operations
-       ; mappM_ check_op op_stuff
+       ; mappM_ (check_op gla_exts) op_stuff
 
        -- Check that if the class has generic methods, then the
        -- class has only one parameter.  We can't do generic
@@ -607,7 +665,7 @@ checkValidClass cls
     unary      = isSingleton tyvars
     no_generics = null [() | (_, GenDefMeth) <- op_stuff]
 
-    check_op (sel_id, dm) 
+    check_op gla_exts (sel_id, dm) 
       = addErrCtxt (classOpCtxt sel_id tau) $ do
        { checkValidTheta SigmaCtxt (tail theta)
                -- The 'tail' removes the initial (C a) from the
@@ -622,14 +680,22 @@ checkValidClass cls
 
                -- Check that for a generic method, the type of 
                -- the method is sufficiently simple
-       ; checkTc (dm /= GenDefMeth || validGenericMethodType op_ty)
+       ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
                  (badGenericMethodType op_name op_ty)
        }
        where
          op_name = idName sel_id
          op_ty   = idType sel_id
-         (_,theta,tau) = tcSplitSigmaTy op_ty
-
+         (_,theta1,tau1) = tcSplitSigmaTy op_ty
+         (_,theta2,tau2)  = tcSplitSigmaTy tau1
+         (theta,tau) | gla_exts  = (theta1 ++ theta2, tau2)
+                     | otherwise = (theta1,           mkPhiTy (tail theta1) tau1)
+               -- Ugh!  The function might have a type like
+               --      op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
+               -- With -fglasgow-exts, we want to allow this, even though the inner 
+               -- forall has an (Eq a) constraint.  Whereas in general, each constraint 
+               -- in the context of a for-all must mention at least one quantified
+               -- type variable.  What a mess!
 
 
 ---------------------------------------------------------------------
@@ -674,28 +740,46 @@ genericMultiParamErr clas
 badGenericMethodType op op_ty
   = hang (ptext SLIT("Generic method type is too complex"))
        4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
-               ptext SLIT("You can only use type variables, arrows, and tuples")])
+               ptext SLIT("You can only use type variables, arrows, lists, and tuples")])
 
 recSynErr syn_decls
-  = setSrcSpan (getLoc (head syn_decls)) $
+  = setSrcSpan (getLoc (head sorted_decls)) $
     addErr (sep [ptext SLIT("Cycle in type synonym declarations:"),
-                nest 2 (vcat (map ppr_decl syn_decls))])
+                nest 2 (vcat (map ppr_decl sorted_decls))])
   where
+    sorted_decls = sortLocated syn_decls
     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
 
 recClsErr cls_decls
-  = setSrcSpan (getLoc (head cls_decls)) $
+  = setSrcSpan (getLoc (head sorted_decls)) $
     addErr (sep [ptext SLIT("Cycle in class declarations (via superclasses):"),
-                nest 2 (vcat (map ppr_decl cls_decls))])
+                nest 2 (vcat (map ppr_decl sorted_decls))])
   where
+    sorted_decls = sortLocated cls_decls
     ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
 
+sortLocated :: [Located a] -> [Located a]
+sortLocated things = sortLe le things
+  where
+    le (L l1 _) (L l2 _) = l1 <= l2
+
 exRecConErr name
   = ptext SLIT("Can't combine named fields with locally-quantified type variables or context")
     $$
     (ptext SLIT("In the declaration of data constructor") <+> ppr name)
 
 badDataConTyCon data_con
-  = hang (ptext SLIT("Data constructor does not return its parent type:"))
-       2 (ppr data_con)
+  = hang (ptext SLIT("Data constructor") <+> quotes (ppr data_con) <+>
+               ptext SLIT("returns type") <+> quotes (ppr (dataConTyCon data_con)))
+       2 (ptext SLIT("instead of its parent type"))
+
+badGadtDecl tc_name
+  = vcat [ ptext SLIT("Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
+        , nest 2 (parens $ ptext SLIT("Use -fglasgow-exts to allow GADTs")) ]
+
+emptyConDeclsErr tycon
+  = sep [quotes (ppr tycon) <+> ptext SLIT("has no constructors"),
+        nest 4 (ptext SLIT("(-fglasgow-exts permits this)"))]
+
+badBootClassDeclErr = ptext SLIT("Illegal class declaration in hs-boot file")
 \end{code}