[project @ 2003-02-12 15:01:31 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcTyClsDecls.lhs
index 225b4de..d978e3c 100644 (file)
 %
-% (c) The AQUA Project, Glasgow University, 1996
+% (c) The AQUA Project, Glasgow University, 1996-1998
 %
 \section[TcTyClsDecls]{Typecheck type and class declarations}
 
 \begin{code}
-#include "HsVersions.h"
-
 module TcTyClsDecls (
-       tcTyAndClassDecls1
+       tcTyAndClassDecls
     ) where
 
-IMP_Ubiq(){-uitous-}
+#include "HsVersions.h"
 
-import HsSyn           ( HsDecl(..), TyDecl(..),  ConDecl(..), ConDetails(..), BangType(..),
-                         ClassDecl(..), HsType(..), HsTyVar, DefaultDecl, InstDecl,
-                         IfaceSig, Sig(..), MonoBinds, Fake, InPat, HsBinds(..), HsExpr, NewOrData,
-                         hsDeclName
+import HsSyn           ( TyClDecl(..),  
+                         ConDecl(..),   Sig(..), HsPred(..), 
+                         tyClDeclName, hsTyVarNames, tyClDeclTyVars,
+                         isTypeOrClassDecl, isClassDecl, isSynDecl, isClassOpSig
                        )
-import RnHsSyn         ( RenamedTyDecl(..), RenamedClassDecl(..), SYN_IE(RenamedHsDecl)
-                       )
-import TcHsSyn         ( SYN_IE(TcHsBinds), TcIdOcc(..) )
-
-import TcMonad
-import Inst            ( SYN_IE(InstanceMapper) )
+import RnHsSyn         ( RenamedTyClDecl, tyClDeclFVs )
+import BasicTypes      ( RecFlag(..), NewOrData(..) )
+import HscTypes                ( implicitTyThings )
+
+import TcRnMonad
+import TcEnv           ( TcTyThing(..), TyThing(..), TyThingDetails(..),
+                         tcExtendKindEnv, tcLookup, tcLookupGlobal, tcExtendGlobalEnv,
+                         isLocalThing )
+import TcTyDecls       ( tcTyDecl, kcConDetails )
 import TcClassDcl      ( tcClassDecl1 )
-import TcEnv           ( tcExtendTyConEnv, tcExtendClassEnv )
-import SpecEnv         ( SpecEnv )
-import TcKind          ( TcKind, newKindVars )
-import TcTyDecls       ( tcTyDecl, mkDataBinds )
-import TcMonoType      ( tcTyVarScope )
-
-import Bag     
-import Class           ( SYN_IE(Class) )
+import TcInstDcls      ( tcAddDeclCtxt )
+import TcMonoType      ( kcHsTyVars, kcHsType, kcHsLiftedSigType, kcHsContext, mkTyClTyVars )
+import TcMType         ( newKindVar, zonkKindEnv, checkValidTyCon, checkValidClass )
+import TcUnify         ( unifyKind )
+import TcType          ( Type, Kind, TcKind, mkArrowKind, liftedTypeKind, zipFunTys )
+import Type            ( splitTyConApp_maybe )
+import Variance         ( calcTyConArgVrcs )
+import Class           ( Class, mkClass, classTyCon )
+import TyCon           ( TyCon, ArgVrcs, AlgTyConFlavour(..), DataConDetails(..), visibleDataCons,
+                         tyConKind, tyConTyVars, tyConDataCons, isNewTyCon,
+                         mkSynTyCon, mkAlgTyCon, mkClassTyCon, mkForeignTyCon
+                       )
+import TysWiredIn      ( unitTy )
+import Subst           ( substTyWith )
+import DataCon         ( dataConOrigArgTys )
+import Var             ( varName )
+import FiniteMap
 import Digraph         ( stronglyConnComp, SCC(..) )
-import Name            ( Name, getSrcLoc, isTvOcc, nameOccName )
+import Name            ( Name )
+import NameEnv
+import NameSet
 import Outputable
-import Pretty
 import Maybes          ( mapMaybe )
-import UniqSet         ( SYN_IE(UniqSet), emptyUniqSet,
-                         unitUniqSet, unionUniqSets, 
-                         unionManyUniqSets, uniqSetToList ) 
-import SrcLoc          ( SrcLoc )
-import TyCon           ( TyCon, SYN_IE(Arity) )
-import Unique          ( Unique, Uniquable(..) )
-import Util            ( panic{-, pprTrace-} )
-
 \end{code}
 
+
+%************************************************************************
+%*                                                                     *
+\subsection{Type checking for type and class declarations}
+%*                                                                     *
+%************************************************************************
+
 The main function
 ~~~~~~~~~~~~~~~~~
 \begin{code}
-tcTyAndClassDecls1 :: TcEnv s -> InstanceMapper        -- Knot tying stuff
-                  -> [RenamedHsDecl]
-                  -> TcM s (TcEnv s)
+tcTyAndClassDecls :: [RenamedTyClDecl]
+                 -> TcM TcGblEnv       -- Returns extended environment
 
-tcTyAndClassDecls1 unf_env inst_mapper decls
-  = sortByDependency decls             `thenTc` \ groups ->
-    tcGroups unf_env inst_mapper groups
-
-tcGroups unf_env inst_mapper []
-  = tcGetEnv   `thenNF_Tc` \ env ->
-    returnTc env
-
-tcGroups unf_env inst_mapper (group:groups)
-  = tcGroup unf_env inst_mapper group  `thenTc` \ new_env ->
+tcTyAndClassDecls decls
+  = tcGroups (stronglyConnComp edges)
+  where
+    edges = map mkEdges (filter isTypeOrClassDecl decls)
 
-       -- Extend the environment using the new tycons and classes
-    tcSetEnv new_env $
+tcGroups [] = getGblEnv
 
-       -- Do the remaining groups
-    tcGroups unf_env inst_mapper groups
+tcGroups (group:groups)
+  = tcGroup group      `thenM` \ env ->
+    setGblEnv env      $
+    tcGroups groups
 \end{code}
 
 Dealing with a group
 ~~~~~~~~~~~~~~~~~~~~
-\begin{code}
-tcGroup :: TcEnv s -> InstanceMapper -> Bag RenamedHsDecl -> TcM s (TcEnv s)
-tcGroup unf_env inst_mapper decls
-  =    -- TIE THE KNOT
-    fixTc ( \ ~(tycons,classes,_) ->
-
-               -- EXTEND TYPE AND CLASS ENVIRONMENTS
-               -- NB: it's important that the tycons and classes come back in just
-               -- the same order from this fix as from get_binders, so that these
-               -- extend-env things work properly.  A bit UGH-ish.
-      tcExtendTyConEnv tycon_names_w_arities tycons              $
-      tcExtendClassEnv class_names classes                       $
-
-               -- DEAL WITH TYPE VARIABLES
-      tcTyVarScope tyvar_names                         ( \ tyvars ->
-
-               -- DEAL WITH THE DEFINITIONS THEMSELVES
-       foldBag combine (tcDecl unf_env inst_mapper)
-               (returnTc (emptyBag, emptyBag))
-               decls
-      )                                                `thenTc` \ (tycon_bag,class_bag) ->
-      let
-       tycons = bagToList tycon_bag
-       classes = bagToList class_bag
-      in 
-
-               -- SNAFFLE ENV TO RETURN
-      tcGetEnv                                 `thenNF_Tc` \ final_env ->
-
-      returnTc (tycons, classes, final_env)
-    ) `thenTc` \ (_, _, final_env) ->
-
-    returnTc final_env
+Consider a mutually-recursive group, binding 
+a type constructor T and a class C.
 
-  where
-    (tyvar_names, tycon_names_w_arities, class_names) = get_binders decls
+Step 1:        getInitialKind
+       Construct a KindEnv by binding T and C to a kind variable 
 
-    combine do_a do_b
-      = do_a `thenTc` \ (a1,a2) ->
-        do_b `thenTc` \ (b1,b2) ->
-       returnTc (a1 `unionBags` b1, a2 `unionBags` b2)
-\end{code}
+Step 2:        kcTyClDecl
+       In that environment, do a kind check
 
-Dealing with one decl
-~~~~~~~~~~~~~~~~~~~~~
-\begin{code}
-tcDecl  :: TcEnv s -> InstanceMapper
-       -> RenamedHsDecl
-       -> TcM s (Bag TyCon, Bag Class)
+Step 3: Zonk the kinds
 
-tcDecl unf_env inst_mapper (TyD decl)
-  = tcTyDecl decl      `thenTc` \ tycon ->
-    returnTc (unitBag tycon, emptyBag)
+Step 4:        buildTyConOrClass
+       Construct an environment binding T to a TyCon and C to a Class.
+       a) Their kinds comes from zonking the relevant kind variable
+       b) Their arity (for synonyms) comes direct from the decl
+       c) The funcional dependencies come from the decl
+       d) The rest comes a knot-tied binding of T and C, returned from Step 4
+       e) The variances of the tycons in the group is calculated from 
+               the knot-tied stuff
 
-tcDecl unf_env inst_mapper (ClD decl)
-  = tcClassDecl1 unf_env inst_mapper decl   `thenTc` \ clas ->
-    returnTc (emptyBag, unitBag clas)
-\end{code}
+Step 5:        tcTyClDecl1
+       In this environment, walk over the decls, constructing the TyCons and Classes.
+       This uses in a strict way items (a)-(c) above, which is why they must
+       be constructed in Step 4. Feed the results back to Step 4.
+       For this step, pass the is-recursive flag as the wimp-out flag
+       to tcTyClDecl1.
+       
 
-Dependency analysis
-~~~~~~~~~~~~~~~~~~~
-\begin{code}
-sortByDependency :: [RenamedHsDecl] -> TcM s [Bag RenamedHsDecl]
-sortByDependency decls
-  = let                -- CHECK FOR SYNONYM CYCLES
-       syn_sccs   = stronglyConnComp (filter is_syn_decl edges)
-       syn_cycles = [ decls | CyclicSCC decls <- syn_sccs]
+Step 6:                Extend environment
+       We extend the type environment with bindings not only for the TyCons and Classes,
+       but also for their "implicit Ids" like data constructors and class selectors
 
-    in
-    checkTc (null syn_cycles) (typeCycleErr syn_cycles)                `thenTc_`
+Step 7:                checkValidTyCl
+       For a recursive group only, check all the decls again, just
+       to check all the side conditions on validity.  We could not
+       do this before because we were in a mutually recursive knot.
 
-    let                -- CHECK FOR CLASS CYCLES
-       cls_sccs   = stronglyConnComp (filter is_cls_decl edges)
-       cls_cycles = [ decls | CyclicSCC decls <- cls_sccs]
 
-    in
-    checkTc (null cls_cycles) (classCycleErr cls_cycles)       `thenTc_`
+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.
 
-               -- DO THE MAIN DEPENDENCY ANALYSIS
-    let
-       decl_sccs  = stronglyConnComp (filter is_ty_cls_decl edges)
-       scc_bags   = map bag_acyclic decl_sccs
+\begin{code}
+tcGroup :: SCC RenamedTyClDecl 
+       -> TcM TcGblEnv         -- Input env extended by types and classes 
+                               -- and their implicit Ids,DataCons
+                                       
+tcGroup scc
+  =    -- Step 1
+    mappM getInitialKind decls                 `thenM` \ initial_kinds ->
+
+       -- Step 2
+    tcExtendKindEnv initial_kinds (mappM kcTyClDecl decls)     `thenM_`
+
+       -- Step 3
+    zonkKindEnv initial_kinds          `thenM` \ final_kinds ->
+
+       -- Check for loops; if any are found, bale out now
+       -- because the compiler itself will loop otherwise!
+    checkNoErrs (checkLoops scc)       `thenM` \ is_rec_tycon ->
+
+       -- Tie the knot
+    traceTc (text "starting" <+> ppr final_kinds)              `thenM_`
+    fixM ( \ ~(rec_details_list, _, rec_all_tyclss) ->
+               -- Step 4 
+       let
+           kind_env    = mkNameEnv final_kinds
+           rec_details = mkNameEnv rec_details_list
+
+               -- Calculate variances, and feed into buildTyConOrClass
+            rec_vrcs = calcTyConArgVrcs [tc | ATyCon tc <- rec_all_tyclss]
+
+           build_one = buildTyConOrClass is_rec_tycon kind_env
+                                         rec_vrcs rec_details
+           tyclss = map build_one decls
+
+       in
+               -- Step 5
+               -- Extend the environment with the final 
+               -- TyCons/Classes and check the decls
+       tcExtendGlobalEnv tyclss        $
+       mappM tcTyClDecl1 decls         `thenM` \ tycls_details ->
+
+               -- Return results
+       getGblEnv                               `thenM` \ env ->
+       returnM (tycls_details, env, tyclss)
+    )                                          `thenM` \ (_, env, tyclss) ->
+
+       -- Step 7: Check validity
+    setGblEnv env                              $
+
+    traceTc (text "ready for validity check")  `thenM_`
+    getModule                                  `thenM` \ mod ->
+    mappM_ (checkValidTyCl mod) decls          `thenM_`
+    traceTc (text "done")                      `thenM_`
+   
+    let                -- Add the tycons that come from the classes
+               -- We want them in the environment because 
+               -- they are mentioned in interface files
+       implicit_things = implicitTyThings tyclss
     in
-    returnTc (scc_bags)
+    traceTc ((text "Adding" <+> ppr tyclss) $$ (text "and" <+> ppr implicit_things))   `thenM_`
+    tcExtendGlobalEnv implicit_things getGblEnv
 
   where
-    edges = mapMaybe mk_edges decls
-    
-bag_acyclic (AcyclicSCC scc) = unitBag scc
-bag_acyclic (CyclicSCC sccs) = listToBag sccs
-
-is_syn_decl (TyD (TySynonym _ _ _ _), _, _) = True
-is_syn_decl _                              = False
-
-is_ty_cls_decl (TyD _, _, _) = True
-is_ty_cls_decl (ClD _, _, _) = True
-is_ty_cls_decl other         = False
-
-is_cls_decl (ClD _, _, _) = True
-is_cls_decl other         = False
+    decls = case scc of
+               AcyclicSCC decl -> [decl]
+               CyclicSCC decls -> decls
+
+tcTyClDecl1 decl
+  | isClassDecl decl = tcAddDeclCtxt decl (tcClassDecl1 decl)
+  | otherwise       = tcAddDeclCtxt decl (tcTyDecl     decl)
+
+-- We do the validity check over declarations, rather than TyThings
+-- only so that we can add a nice context with tcAddDeclCtxt
+checkValidTyCl this_mod decl
+  = tcLookupGlobal (tcdName decl)      `thenM` \ thing ->
+    if not (isLocalThing this_mod thing) then
+       -- Don't bother to check validity for non-local things
+       returnM ()
+    else
+    tcAddDeclCtxt decl $
+    case thing of
+       ATyCon tc -> checkValidTyCon tc
+       AClass cl -> checkValidClass cl
 \end{code}
 
-Edges in Type/Class decls
-~~~~~~~~~~~~~~~~~~~~~~~~~
-\begin{code}
-mk_edges decl@(TyD (TyData _ ctxt name _ condecls derivs _ _))
-  = Just (decl, uniqueOf name, uniqSetToList (get_ctxt ctxt `unionUniqSets` 
-                                        get_cons condecls `unionUniqSets` 
-                                        get_deriv derivs))
 
-mk_edges decl@(TyD (TySynonym name _ rhs _))
-  = Just (decl, uniqueOf name, uniqSetToList (get_ty rhs))
+%************************************************************************
+%*                                                                     *
+\subsection{Step 1: Initial environment}
+%*                                                                     *
+%************************************************************************
 
-mk_edges decl@(ClD (ClassDecl ctxt name _ sigs _ _ _))
-  = Just (decl, uniqueOf name, uniqSetToList (get_ctxt ctxt `unionUniqSets`
-                                        get_sigs sigs))
+\begin{code}
+getInitialKind :: RenamedTyClDecl -> TcM (Name, TcKind)
+getInitialKind decl
+ = kcHsTyVars (tyClDeclTyVars decl)    `thenM` \ arg_kinds ->
+   newKindVar                          `thenM` \ result_kind  ->
+   returnM (tcdName decl, mk_kind arg_kinds result_kind)
 
-mk_edges other_decl = Nothing
+mk_kind tvs_w_kinds res_kind = foldr (mkArrowKind . snd) res_kind tvs_w_kinds
+\end{code}
 
-get_ctxt ctxt = unionManyUniqSets (map (set_name.fst) ctxt)
 
-get_deriv Nothing     = emptyUniqSet
-get_deriv (Just clss) = unionManyUniqSets (map set_name clss)
+%************************************************************************
+%*                                                                     *
+\subsection{Step 2: Kind checking}
+%*                                                                     *
+%************************************************************************
 
-get_cons cons = unionManyUniqSets (map get_con cons)
+We need to kind check all types in the mutually recursive group
+before we know the kind of the type variables.  For example:
 
-get_con (ConDecl _ ctxt details _) 
-  = get_ctxt ctxt `unionUniqSets` get_con_details details
+class C a where
+   op :: D b => a -> b -> b
 
-get_con_details (VanillaCon btys)    = unionManyUniqSets (map get_bty btys)
-get_con_details (InfixCon bty1 bty2) = unionUniqSets (get_bty bty1) (get_bty bty2)
-get_con_details (NewCon ty)          =  get_ty ty
-get_con_details (RecCon nbtys)       = unionManyUniqSets (map (get_bty.snd) nbtys)
+class D c where
+   bop :: (Monad c) => ...
 
-get_bty (Banged ty)   = get_ty ty
-get_bty (Unbanged ty) = get_ty ty
+Here, the kind of the locally-polymorphic type variable "b"
+depends on *all the uses of class D*.  For example, the use of
+Monad c in bop's type signature means that D must have kind Type->Type.
 
-get_ty (MonoTyVar name)
-  = if isTvOcc (nameOccName name) then emptyUniqSet else set_name name
-get_ty (MonoTyApp ty1 ty2)
-  = unionUniqSets (get_ty ty1) (get_ty ty2)
-get_ty (MonoFunTy ty1 ty2)     
-  = unionUniqSets (get_ty ty1) (get_ty ty2)
-get_ty (MonoListTy tc ty)
-  = set_name tc `unionUniqSets` get_ty ty
-get_ty (MonoTupleTy tc tys)
-  = set_name tc `unionUniqSets` get_tys tys
-get_ty (HsForAllTy _ ctxt mty)
-  = get_ctxt ctxt `unionUniqSets` get_ty mty
-get_ty other = panic "TcTyClsDecls:get_ty"
+\begin{code}
+kcTyClDecl :: RenamedTyClDecl -> TcM ()
 
-get_tys tys
-  = unionManyUniqSets (map get_ty tys)
+kcTyClDecl decl@(TySynonym {tcdSynRhs = rhs})
+  = kcTyClDeclBody decl                $ \ result_kind ->
+    kcHsType rhs               `thenM` \ rhs_kind ->
+    unifyKind result_kind rhs_kind
 
-get_sigs sigs
-  = unionManyUniqSets (map get_sig sigs)
-  where 
-    get_sig (ClassOpSig _ _ ty _) = get_ty ty
-    get_sig other = panic "TcTyClsDecls:get_sig"
+kcTyClDecl (ForeignType {}) = returnM ()
 
-set_name name = unitUniqSet (uniqueOf name)
+kcTyClDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = context, tcdCons = con_decls})
+  = kcTyClDeclBody decl                        $ \ result_kind ->
+    kcHsContext context                        `thenM_` 
+    mappM_ kc_con_decl (visibleDataCons con_decls)
+  where
+    kc_con_decl (ConDecl _ ex_tvs ex_ctxt details loc)
+      = kcHsTyVars ex_tvs              `thenM` \ kind_env ->
+       tcExtendKindEnv kind_env        $
+       kcConDetails new_or_data ex_ctxt details
+
+kcTyClDecl decl@(ClassDecl {tcdCtxt = context,  tcdSigs = class_sigs})
+  = kcTyClDeclBody decl                $ \ result_kind ->
+    kcHsContext context                `thenM_`
+    mappM_ kc_sig (filter isClassOpSig class_sigs)
+  where
+    kc_sig (ClassOpSig _ _ op_ty loc) = kcHsLiftedSigType op_ty
+
+kcTyClDeclBody :: RenamedTyClDecl -> (Kind -> 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
+kcTyClDeclBody decl thing_inside
+  = tcAddDeclCtxt decl         $
+    tcLookup (tcdName decl)    `thenM` \ thing ->
+    let
+       kind = case thing of
+                 AGlobal (ATyCon tc) -> tyConKind tc
+                 AGlobal (AClass cl) -> tyConKind (classTyCon cl)
+                 AThing kind         -> kind
+               -- For some odd reason, a class doesn't include its kind
 
-set_to_bag set = listToBag (uniqSetToList set)
+       (tyvars_w_kinds, result_kind) = zipFunTys (hsTyVarNames (tyClDeclTyVars decl)) kind
+    in
+    tcExtendKindEnv tyvars_w_kinds (thing_inside result_kind)
 \end{code}
 
 
-get_binders
-~~~~~~~~~~~
-Extract *binding* names from type and class decls.  Type variables are
-bound in type, data, newtype and class declarations and the polytypes
-in the class op sigs.
 
-Why do we need to grab all these type variables at once, including
-those locally-quantified type variables in class op signatures?
-Because we can only commit to the final kind of a type variable when
-we've completed the mutually recursive group. For example:
+%************************************************************************
+%*                                                                     *
+\subsection{Step 4: Building the tycon/class}
+%*                                                                     *
+%************************************************************************
 
-class C a where
-   op :: D b => a -> b -> b
-
-class D c where
-   bop :: (Monad c) => ...
+\begin{code}
+buildTyConOrClass 
+       :: (Name -> AlgTyConFlavour -> RecFlag) -- Whether it's recursive
+       -> NameEnv Kind
+       -> FiniteMap TyCon ArgVrcs -> NameEnv TyThingDetails
+       -> RenamedTyClDecl -> TyThing
+
+buildTyConOrClass rec_tycon kenv rec_vrcs rec_details
+    (TySynonym {tcdName = tycon_name, tcdTyVars = tyvar_names})
+  = ATyCon tycon
+  where
+       tycon = mkSynTyCon tycon_name tycon_kind arity tyvars rhs_ty argvrcs
+       tycon_kind          = lookupNameEnv_NF kenv tycon_name
+       arity               = length tyvar_names
+       tyvars              = mkTyClTyVars tycon_kind tyvar_names
+       SynTyDetails rhs_ty = lookupNameEnv_NF rec_details tycon_name
+        argvrcs                    = lookupWithDefaultFM rec_vrcs bogusVrcs tycon
+
+buildTyConOrClass rec_tycon kenv rec_vrcs rec_details
+    (TyData {tcdND = data_or_new, tcdName = tycon_name, 
+            tcdTyVars = tyvar_names})
+  = ATyCon tycon
+  where
+       tycon = mkAlgTyCon tycon_name tycon_kind tyvars ctxt argvrcs
+                          data_cons sel_ids flavour 
+                          (rec_tycon tycon_name flavour) gen_info
+
+       DataTyDetails ctxt data_cons sel_ids gen_info = lookupNameEnv_NF rec_details tycon_name
+
+       tycon_kind = lookupNameEnv_NF kenv tycon_name
+       tyvars     = mkTyClTyVars tycon_kind tyvar_names
+        argvrcs           = lookupWithDefaultFM rec_vrcs bogusVrcs tycon
+
+       -- Watch out!  mkTyConApp asks whether the tycon is a NewType,
+       -- so flavour has to be able to answer this question without consulting rec_details
+       flavour = case data_or_new of
+                   NewType  -> NewTyCon (mkNewTyConRep tycon)
+                   DataType | all_nullary data_cons -> EnumTyCon
+                            | otherwise             -> DataTyCon
+
+       all_nullary (DataCons cons) = all (null . dataConOrigArgTys) cons
+       all_nullary other           = False     -- Safe choice for unknown data types
+                       -- NB (null . dataConOrigArgTys).  It used to say isNullaryDataCon
+                       -- but that looks at the *representation* arity, and that in turn
+                       -- depends on deciding whether to unpack the args, and that 
+                       -- depends on whether it's a data type or a newtype --- so
+                       -- in the recursive case we can get a loop.  This version is simple!
+
+buildTyConOrClass rec_tycon kenv rec_vrcs rec_details
+  (ForeignType {tcdName = tycon_name, tcdExtName = tycon_ext_name})
+  = ATyCon (mkForeignTyCon tycon_name tycon_ext_name liftedTypeKind 0 [])
+
+buildTyConOrClass rec_tycon kenv rec_vrcs rec_details
+  (ClassDecl {tcdName = class_name, tcdTyVars = tyvar_names, tcdFDs = fundeps} )
+  = AClass clas
+  where
+       clas = mkClass class_name tyvars fds
+                      sc_theta sc_sel_ids op_items
+                      tycon
+
+       tycon = mkClassTyCon tycon_name class_kind tyvars
+                             argvrcs dict_con
+                            clas               -- Yes!  It's a dictionary 
+                            flavour
+                            (rec_tycon class_name flavour)
+               -- A class can be recursive, and in the case of newtypes 
+               -- this matters.  For example
+               --      class C a where { op :: C b => a -> b -> Int }
+               -- Because C has only one operation, it is represented by
+               -- a newtype, and it should be a *recursive* newtype.
+               -- [If we don't make it a recursive newtype, we'll expand the
+               -- newtype like a synonym, but that will lead toan inifinite type
+
+       ClassDetails sc_theta sc_sel_ids op_items dict_con tycon_name 
+               = lookupNameEnv_NF rec_details class_name
+
+       class_kind = lookupNameEnv_NF kenv class_name
+       tyvars     = mkTyClTyVars class_kind tyvar_names
+        argvrcs           = lookupWithDefaultFM rec_vrcs bogusVrcs tycon
+
+       flavour = case dataConOrigArgTys dict_con of
+                       -- The tyvars in the datacon are the same as in the class
+                   [rep_ty] -> NewTyCon rep_ty
+                   other    -> DataTyCon 
+
+       -- We can find the functional dependencies right away, 
+       -- and it is vital to do so. Why?  Because in the next pass
+       -- we check for ambiguity in all the type signatures, and we
+       -- need the functional dependcies to be done by then
+       fds        = [(map lookup xs, map lookup ys) | (xs,ys) <- fundeps]
+       tyvar_env  = mkNameEnv [(varName tv, tv) | tv <- tyvars]
+       lookup     = lookupNameEnv_NF tyvar_env
+
+bogusVrcs = panic "Bogus tycon arg variances"
+\end{code}
 
-Here, the kind of the locally-polymorphic type variable "b"
-depends on *all the uses of class D*.  For example, the use of
-Monad c in bop's type signature means that D must have kind Type->Type.
+\begin{code}
+mkNewTyConRep :: TyCon         -- The original type constructor
+             -> Type           -- Chosen representation type
+                               -- (guaranteed not to be another newtype)
+
+-- Find the representation type for this newtype TyCon
+-- Remember that the representation type is the ultimate representation
+-- type, looking through other newtypes.
+-- 
+-- The non-recursive newtypes are easy, because they look transparent
+-- to splitTyConApp_maybe, but recursive ones really are represented as
+-- TyConApps (see TypeRep).
+-- 
+-- The trick is to to deal correctly with recursive newtypes
+-- such as     newtype T = MkT T
+
+mkNewTyConRep tc
+  = go [] tc
+  where
+       -- Invariant: tc is a NewTyCon
+       --            tcs have been seen before
+    go tcs tc 
+       | tc `elem` tcs = unitTy
+       | otherwise
+       = let
+             rep_ty = head (dataConOrigArgTys (head (tyConDataCons tc)))
+         in
+         case splitTyConApp_maybe rep_ty of
+                       Nothing -> rep_ty 
+                       Just (tc', tys) | not (isNewTyCon tc') -> rep_ty
+                                       | otherwise            -> go1 (tc:tcs) tc' tys
+
+    go1 tcs tc tys = substTyWith (tyConTyVars tc) tys (go tcs tc)
+\end{code}
 
+%************************************************************************
+%*                                                                     *
+\subsection{Dependency analysis}
+%*                                                                     *
+%************************************************************************
 
+Dependency analysis
+~~~~~~~~~~~~~~~~~~~
 \begin{code}
-get_binders :: Bag RenamedHsDecl
-           -> ([HsTyVar Name],         -- TyVars;  no dups
-               [(Name, Maybe Arity)],  -- Tycons;  no dups; arities for synonyms
-               [Name])                 -- Classes; no dups
+checkLoops :: SCC RenamedTyClDecl
+          -> TcM (Name -> AlgTyConFlavour -> RecFlag)
+-- Check for illegal loops, 
+--     a) type synonyms
+--     b) superclass hierarchy
+--
+-- Also return a function that says which tycons are recursive.
+-- Remember: 
+--     a newtype is recursive if it is part of a recursive
+--             group consisting only of newtype and synonyms
+
+checkLoops (AcyclicSCC _)
+  = returnM (\ _ _ -> NonRecursive)
+
+checkLoops (CyclicSCC decls)
+  = let                -- CHECK FOR CLASS CYCLES
+       cls_edges  = mapMaybe mkClassEdges decls
+       cls_cycles = findCycles cls_edges
+    in
+    mapM_ (cycleErr "class") cls_cycles                `thenM_`
 
-get_binders decls = (bagToList tyvars, bagToList tycons, bagToList classes)
-  where
-    (tyvars, tycons, classes) = foldBag union3 get_binders1
-                                       (emptyBag,emptyBag,emptyBag)
-                                       decls
-
-    union3 (a1,a2,a3) (b1,b2,b3)
-      = (a1 `unionBags` b1, a2 `unionBags` b2, a3 `unionBags` b3)
-
-get_binders1 (TyD (TyData _ _ name tyvars _ _ _ _))
- = (listToBag tyvars, unitBag (name,Nothing), emptyBag)
-get_binders1 (TyD (TySynonym name tyvars _ _))
- = (listToBag tyvars, unitBag (name, Just (length tyvars)), emptyBag)
-get_binders1 (ClD (ClassDecl _ name tyvar sigs _ _ _))
- = (unitBag tyvar `unionBags` sigs_tvs sigs,
-    emptyBag, unitBag name)
-
-sigs_tvs sigs = unionManyBags (map sig_tvs sigs)
-  where 
-    sig_tvs (ClassOpSig _ _ ty _) = pty_tvs ty
-    pty_tvs (HsForAllTy tvs _ _)  = listToBag tvs      -- tvs doesn't include the class tyvar
-    pty_tvs other                = emptyBag
+    let                -- CHECK FOR SYNONYM CYCLES
+       syn_edges  = map mkEdges (filter isSynDecl decls)
+       syn_cycles = findCycles syn_edges
+    in
+    mapM_ (cycleErr "type synonym") syn_cycles `thenM_`
+
+    let        -- CHECK FOR NEWTYPE CYCLES
+       newtype_edges  = map mkEdges (filter is_nt_cycle_decl decls)
+       newtype_cycles = findCycles newtype_edges
+       rec_newtypes   = mkNameSet [tcdName d | ds <- newtype_cycles, d <- ds]
+
+       rec_tycon name (NewTyCon _)
+         | name `elemNameSet` rec_newtypes = Recursive
+         | otherwise                       = NonRecursive
+       rec_tycon name other_flavour = Recursive
+    in
+    returnM rec_tycon
+
+----------------------------------------------------
+-- A class with one op and no superclasses, or vice versa,
+--             is treated just like a newtype.
+-- It's a bit unclean that this test is repeated in buildTyConOrClass
+is_nt_cycle_decl (TySynonym {})                                     = True
+is_nt_cycle_decl (TyData {tcdND = NewType})                 = True
+is_nt_cycle_decl (ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs}) = length ctxt + length sigs == 1
+is_nt_cycle_decl other                                      = False
+
+----------------------------------------------------
+findCycles edges = [ ds | CyclicSCC ds <- stronglyConnComp edges]
+
+----------------------------------------------------
+mkEdges :: RenamedTyClDecl -> (RenamedTyClDecl, Name, [Name])
+mkEdges decl = (decl, tyClDeclName decl, nameSetToList (tyClDeclFVs decl))
+
+----------------------------------------------------
+-- mk_cls_edges looks only at the context of class decls
+-- Its used when we are figuring out if there's a cycle in the
+-- superclass hierarchy
+
+mkClassEdges :: RenamedTyClDecl -> Maybe (RenamedTyClDecl, Name, [Name])
+mkClassEdges decl@(ClassDecl {tcdCtxt = ctxt, tcdName = name}) = Just (decl, name, [c | HsClassP c _ <- ctxt])
+mkClassEdges other_decl                                               = Nothing
 \end{code}
 
 
+%************************************************************************
+%*                                                                     *
+\subsection{Error management
+%*                                                                     *
+%************************************************************************
+
 \begin{code}
-typeCycleErr syn_cycles sty
-  = vcat (map (pp_cycle sty "Cycle in type declarations ...") syn_cycles)
+cycleErr :: String -> [RenamedTyClDecl] -> TcM ()
 
-classCycleErr cls_cycles sty
-  = vcat (map (pp_cycle sty "Cycle in class declarations ...") cls_cycles)
+cycleErr kind_of_decl decls
+  = addErrAt loc (ppr_cycle kind_of_decl decls)
+  where
+    loc = tcdLoc (head decls)
 
-pp_cycle sty str decls
-  = hang (text str)
+ppr_cycle kind_of_decl decls
+  = hang (ptext SLIT("Cycle in") <+> text kind_of_decl <+> ptext SLIT("declarations:"))
         4 (vcat (map pp_decl decls))
   where
-    pp_decl decl
-      = hsep [ppr sty name, ppr sty (getSrcLoc name)]
-     where
-        name = hsDeclName decl
+    pp_decl decl = hsep [quotes (ppr (tcdName decl)), 
+                        ptext SLIT("at"), ppr (tcdLoc decl)]
 \end{code}