-- (c) The University of Glasgow 2006
-- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
--
-- The @Class@ datatype

{-# LANGUAGE CPP #-}

module Class (
        Class,
        ClassOpItem,
        ClassATItem(..),
        ClassMinimalDef,
        DefMethInfo, pprDefMethInfo,

        FunDep, pprFundeps, pprFunDep,

        mkClass, mkAbstractClass, classTyVars, classArity,
        classKey, className, classATs, classATItems, classTyCon, classMethods,
        classOpItems, classBigSig, classExtraBigSig, classTvsFds, classSCTheta,
        classAllSelIds, classSCSelId, classSCSelIds, classMinimalDef, classHasFds,
        isAbstractClass,
    ) where

#include "HsVersions.h"

import GhcPrelude

import {-# SOURCE #-} TyCon     ( TyCon )
import {-# SOURCE #-} TyCoRep   ( Type, PredType, pprType )
import Var
import Name
import BasicTypes
import Unique
import Util
import SrcLoc
import Outputable
import BooleanFormula (BooleanFormula, mkTrue)

import qualified Data.Data as Data

{-
************************************************************************
*                                                                      *
\subsection[Class-basic]{@Class@: basic definition}
*                                                                      *
************************************************************************

A @Class@ corresponds to a Greek kappa in the static semantics:
-}

data Class
  = Class {
        Class -> TyCon
classTyCon :: TyCon,    -- The data type constructor for
                                -- dictionaries of this class
                                -- See Note [ATyCon for classes] in TyCoRep

        Class -> Name
className :: Name,              -- Just the cached name of the TyCon
        Class -> Unique
classKey  :: Unique,            -- Cached unique of TyCon

        Class -> [TyVar]
classTyVars  :: [TyVar],        -- The class kind and type variables;
                                        -- identical to those of the TyCon
           -- If you want visibility info, look at the classTyCon
           -- This field is redundant because it's duplicated in the
           -- classTyCon, but classTyVars is used quite often, so maybe
           -- it's a bit faster to cache it here

        Class -> [FunDep TyVar]
classFunDeps :: [FunDep TyVar],  -- The functional dependencies

        Class -> ClassBody
classBody :: ClassBody -- Superclasses, ATs, methods

     }

--  | e.g.
--
-- >  class C a b c | a b -> c, a c -> b where...
--
--  Here fun-deps are [([a,b],[c]), ([a,c],[b])]
--
--  - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow'',

-- For details on above see note [Api annotations] in ApiAnnotation
type FunDep a = ([a],[a])

type ClassOpItem = (Id, DefMethInfo)
        -- Selector function; contains unfolding
        -- Default-method info

type DefMethInfo = Maybe (Name, DefMethSpec Type)
   -- Nothing                    No default method
   -- Just ($dm, VanillaDM)      A polymorphic default method, name $dm
   -- Just ($gm, GenericDM ty)   A generic default method, name $gm, type ty
   --                              The generic dm type is *not* quantified
   --                              over the class variables; ie has the
   --                              class variables free

data ClassATItem
  = ATI TyCon         -- See Note [Associated type tyvar names]
        (Maybe (Type, SrcSpan))
                      -- Default associated type (if any) from this template
                      -- Note [Associated type defaults]

type ClassMinimalDef = BooleanFormula Name -- Required methods

data ClassBody
  = AbstractClass
  | ConcreteClass {
        -- Superclasses: eg: (F a ~ b, F b ~ G a, Eq a, Show b)
        -- We need value-level selectors for both the dictionary
        -- superclasses and the equality superclasses
        ClassBody -> [PredType]
cls_sc_theta :: [PredType],     -- Immediate superclasses,
        ClassBody -> [TyVar]
cls_sc_sel_ids :: [Id],          -- Selector functions to extract the
                                        --   superclasses from a
                                        --   dictionary of this class
        -- Associated types
        ClassBody -> [ClassATItem]
cls_ats :: [ClassATItem],  -- Associated type families

        -- Class operations (methods, not superclasses)
        ClassBody -> [ClassOpItem]
cls_ops :: [ClassOpItem],  -- Ordered by tag

        -- Minimal complete definition
        ClassBody -> ClassMinimalDef
cls_min_def :: ClassMinimalDef
    }
    -- TODO: maybe super classes should be allowed in abstract class definitions

classMinimalDef :: Class -> ClassMinimalDef
classMinimalDef :: Class -> ClassMinimalDef
classMinimalDef Class{ classBody :: Class -> ClassBody
classBody = ConcreteClass{ cls_min_def :: ClassBody -> ClassMinimalDef
cls_min_def = ClassMinimalDef
d } } = ClassMinimalDef
d
classMinimalDef _ = ClassMinimalDef
forall a. BooleanFormula a
mkTrue -- TODO: make sure this is the right direction

{-
Note [Associated type defaults]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following is an example of associated type defaults:
   class C a where
     data D a r

     type F x a b :: *
     type F p q r = (p,q)->r    -- Default

Note that

 * The TyCons for the associated types *share type variables* with the
   class, so that we can tell which argument positions should be
   instantiated in an instance decl.  (The first for 'D', the second
   for 'F'.)

 * We can have default definitions only for *type* families,
   not data families

 * In the default decl, the "patterns" should all be type variables,
   but (in the source language) they don't need to be the same as in
   the 'type' decl signature or the class.  It's more like a
   free-standing 'type instance' declaration.

 * HOWEVER, in the internal ClassATItem we rename the RHS to match the
   tyConTyVars of the family TyCon.  So in the example above we'd get
   a ClassATItem of
        ATI F ((x,a) -> b)
   So the tyConTyVars of the family TyCon bind the free vars of
   the default Type rhs

The @mkClass@ function fills in the indirect superclasses.

The SrcSpan is for the entire original declaration.
-}

mkClass :: Name -> [TyVar]
        -> [FunDep TyVar]
        -> [PredType] -> [Id]
        -> [ClassATItem]
        -> [ClassOpItem]
        -> ClassMinimalDef
        -> TyCon
        -> Class

mkClass :: Name
-> [TyVar]
-> [FunDep TyVar]
-> [PredType]
-> [TyVar]
-> [ClassATItem]
-> [ClassOpItem]
-> ClassMinimalDef
-> TyCon
-> Class
mkClass cls_name :: Name
cls_name tyvars :: [TyVar]
tyvars fds :: [FunDep TyVar]
fds super_classes :: [PredType]
super_classes superdict_sels :: [TyVar]
superdict_sels at_stuff :: [ClassATItem]
at_stuff
        op_stuff :: [ClassOpItem]
op_stuff mindef :: ClassMinimalDef
mindef tycon :: TyCon
tycon
  = Class :: TyCon
-> Name
-> Unique
-> [TyVar]
-> [FunDep TyVar]
-> ClassBody
-> Class
Class { classKey :: Unique
classKey     = Name -> Unique
nameUnique Name
cls_name,
            className :: Name
className    = Name
cls_name,
                -- NB:  tyConName tycon = cls_name,
                -- But it takes a module loop to assert it here
            classTyVars :: [TyVar]
classTyVars  = [TyVar]
tyvars,
            classFunDeps :: [FunDep TyVar]
classFunDeps = [FunDep TyVar]
fds,
            classBody :: ClassBody
classBody = ConcreteClass :: [PredType]
-> [TyVar]
-> [ClassATItem]
-> [ClassOpItem]
-> ClassMinimalDef
-> ClassBody
ConcreteClass {
                    cls_sc_theta :: [PredType]
cls_sc_theta = [PredType]
super_classes,
                    cls_sc_sel_ids :: [TyVar]
cls_sc_sel_ids = [TyVar]
superdict_sels,
                    cls_ats :: [ClassATItem]
cls_ats  = [ClassATItem]
at_stuff,
                    cls_ops :: [ClassOpItem]
cls_ops  = [ClassOpItem]
op_stuff,
                    cls_min_def :: ClassMinimalDef
cls_min_def = ClassMinimalDef
mindef
                },
            classTyCon :: TyCon
classTyCon   = TyCon
tycon }

mkAbstractClass :: Name -> [TyVar]
        -> [FunDep TyVar]
        -> TyCon
        -> Class

mkAbstractClass :: Name -> [TyVar] -> [FunDep TyVar] -> TyCon -> Class
mkAbstractClass cls_name :: Name
cls_name tyvars :: [TyVar]
tyvars fds :: [FunDep TyVar]
fds tycon :: TyCon
tycon
  = Class :: TyCon
-> Name
-> Unique
-> [TyVar]
-> [FunDep TyVar]
-> ClassBody
-> Class
Class { classKey :: Unique
classKey     = Name -> Unique
nameUnique Name
cls_name,
            className :: Name
className    = Name
cls_name,
                -- NB:  tyConName tycon = cls_name,
                -- But it takes a module loop to assert it here
            classTyVars :: [TyVar]
classTyVars  = [TyVar]
tyvars,
            classFunDeps :: [FunDep TyVar]
classFunDeps = [FunDep TyVar]
fds,
            classBody :: ClassBody
classBody = ClassBody
AbstractClass,
            classTyCon :: TyCon
classTyCon   = TyCon
tycon }

{-
Note [Associated type tyvar names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The TyCon of an associated type should use the same variable names as its
parent class. Thus
    class C a b where
      type F b x a :: *
We make F use the same Name for 'a' as C does, and similary 'b'.

The reason for this is when checking instances it's easier to match
them up, to ensure they match.  Eg
    instance C Int [d] where
      type F [d] x Int = ....
we should make sure that the first and third args match the instance
header.

Having the same variables for class and tycon is also used in checkValidRoles
(in TcTyClsDecls) when checking a class's roles.


************************************************************************
*                                                                      *
\subsection[Class-selectors]{@Class@: simple selectors}
*                                                                      *
************************************************************************

The rest of these functions are just simple selectors.
-}

classArity :: Class -> Arity
classArity :: Class -> Arity
classArity clas :: Class
clas = [TyVar] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length (Class -> [TyVar]
classTyVars Class
clas)
        -- Could memoise this

classAllSelIds :: Class -> [Id]
-- Both superclass-dictionary and method selectors
classAllSelIds :: Class -> [TyVar]
classAllSelIds c :: Class
c@(Class { classBody :: Class -> ClassBody
classBody = ConcreteClass { cls_sc_sel_ids :: ClassBody -> [TyVar]
cls_sc_sel_ids = [TyVar]
sc_sels }})
  = [TyVar]
sc_sels [TyVar] -> [TyVar] -> [TyVar]
forall a. [a] -> [a] -> [a]
++ Class -> [TyVar]
classMethods Class
c
classAllSelIds c :: Class
c = ASSERT( null (classMethods c) ) []

classSCSelIds :: Class -> [Id]
-- Both superclass-dictionary and method selectors
classSCSelIds :: Class -> [TyVar]
classSCSelIds (Class { classBody :: Class -> ClassBody
classBody = ConcreteClass { cls_sc_sel_ids :: ClassBody -> [TyVar]
cls_sc_sel_ids = [TyVar]
sc_sels }})
  = [TyVar]
sc_sels
classSCSelIds c :: Class
c = ASSERT( null (classMethods c) ) []

classSCSelId :: Class -> Int -> Id
-- Get the n'th superclass selector Id
-- where n is 0-indexed, and counts
--    *all* superclasses including equalities
classSCSelId :: Class -> Arity -> TyVar
classSCSelId (Class { classBody :: Class -> ClassBody
classBody = ConcreteClass { cls_sc_sel_ids :: ClassBody -> [TyVar]
cls_sc_sel_ids = [TyVar]
sc_sels } }) n :: Arity
n
  = ASSERT( n >= 0 && lengthExceeds sc_sels n )
    [TyVar]
sc_sels [TyVar] -> Arity -> TyVar
forall a. [a] -> Arity -> a
!! Arity
n
classSCSelId c :: Class
c n :: Arity
n = String -> SDoc -> TyVar
forall a. HasCallStack => String -> SDoc -> a
pprPanic "classSCSelId" (Class -> SDoc
forall a. Outputable a => a -> SDoc
ppr Class
c SDoc -> SDoc -> SDoc
<+> Arity -> SDoc
forall a. Outputable a => a -> SDoc
ppr Arity
n)

classMethods :: Class -> [Id]
classMethods :: Class -> [TyVar]
classMethods (Class { classBody :: Class -> ClassBody
classBody = ConcreteClass { cls_ops :: ClassBody -> [ClassOpItem]
cls_ops = [ClassOpItem]
op_stuff } })
  = [TyVar
op_sel | (op_sel :: TyVar
op_sel, _) <- [ClassOpItem]
op_stuff]
classMethods _ = []

classOpItems :: Class -> [ClassOpItem]
classOpItems :: Class -> [ClassOpItem]
classOpItems (Class { classBody :: Class -> ClassBody
classBody = ConcreteClass { cls_ops :: ClassBody -> [ClassOpItem]
cls_ops = [ClassOpItem]
op_stuff }})
  = [ClassOpItem]
op_stuff
classOpItems _ = []

classATs :: Class -> [TyCon]
classATs :: Class -> [TyCon]
classATs (Class { classBody :: Class -> ClassBody
classBody = ConcreteClass { cls_ats :: ClassBody -> [ClassATItem]
cls_ats = [ClassATItem]
at_stuff } })
  = [TyCon
tc | ATI tc :: TyCon
tc _ <- [ClassATItem]
at_stuff]
classATs _ = []

classATItems :: Class -> [ClassATItem]
classATItems :: Class -> [ClassATItem]
classATItems (Class { classBody :: Class -> ClassBody
classBody = ConcreteClass { cls_ats :: ClassBody -> [ClassATItem]
cls_ats = [ClassATItem]
at_stuff }})
  = [ClassATItem]
at_stuff
classATItems _ = []

classSCTheta :: Class -> [PredType]
classSCTheta :: Class -> [PredType]
classSCTheta (Class { classBody :: Class -> ClassBody
classBody = ConcreteClass { cls_sc_theta :: ClassBody -> [PredType]
cls_sc_theta = [PredType]
theta_stuff }})
  = [PredType]
theta_stuff
classSCTheta _ = []

classTvsFds :: Class -> ([TyVar], [FunDep TyVar])
classTvsFds :: Class -> ([TyVar], [FunDep TyVar])
classTvsFds c :: Class
c = (Class -> [TyVar]
classTyVars Class
c, Class -> [FunDep TyVar]
classFunDeps Class
c)

classHasFds :: Class -> Bool
classHasFds :: Class -> Bool
classHasFds (Class { classFunDeps :: Class -> [FunDep TyVar]
classFunDeps = [FunDep TyVar]
fds }) = Bool -> Bool
not ([FunDep TyVar] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [FunDep TyVar]
fds)

classBigSig :: Class -> ([TyVar], [PredType], [Id], [ClassOpItem])
classBigSig :: Class -> ([TyVar], [PredType], [TyVar], [ClassOpItem])
classBigSig (Class {classTyVars :: Class -> [TyVar]
classTyVars = [TyVar]
tyvars,
                    classBody :: Class -> ClassBody
classBody = ClassBody
AbstractClass})
  = ([TyVar]
tyvars, [], [], [])
classBigSig (Class {classTyVars :: Class -> [TyVar]
classTyVars = [TyVar]
tyvars,
                    classBody :: Class -> ClassBody
classBody = ConcreteClass {
                        cls_sc_theta :: ClassBody -> [PredType]
cls_sc_theta = [PredType]
sc_theta,
                        cls_sc_sel_ids :: ClassBody -> [TyVar]
cls_sc_sel_ids = [TyVar]
sc_sels,
                        cls_ops :: ClassBody -> [ClassOpItem]
cls_ops  = [ClassOpItem]
op_stuff
                    }})
  = ([TyVar]
tyvars, [PredType]
sc_theta, [TyVar]
sc_sels, [ClassOpItem]
op_stuff)

classExtraBigSig :: Class -> ([TyVar], [FunDep TyVar], [PredType], [Id], [ClassATItem], [ClassOpItem])
classExtraBigSig :: Class
-> ([TyVar], [FunDep TyVar], [PredType], [TyVar], [ClassATItem],
    [ClassOpItem])
classExtraBigSig (Class {classTyVars :: Class -> [TyVar]
classTyVars = [TyVar]
tyvars, classFunDeps :: Class -> [FunDep TyVar]
classFunDeps = [FunDep TyVar]
fundeps,
                         classBody :: Class -> ClassBody
classBody = ClassBody
AbstractClass})
  = ([TyVar]
tyvars, [FunDep TyVar]
fundeps, [], [], [], [])
classExtraBigSig (Class {classTyVars :: Class -> [TyVar]
classTyVars = [TyVar]
tyvars, classFunDeps :: Class -> [FunDep TyVar]
classFunDeps = [FunDep TyVar]
fundeps,
                         classBody :: Class -> ClassBody
classBody = ConcreteClass {
                             cls_sc_theta :: ClassBody -> [PredType]
cls_sc_theta = [PredType]
sc_theta, cls_sc_sel_ids :: ClassBody -> [TyVar]
cls_sc_sel_ids = [TyVar]
sc_sels,
                             cls_ats :: ClassBody -> [ClassATItem]
cls_ats = [ClassATItem]
ats, cls_ops :: ClassBody -> [ClassOpItem]
cls_ops = [ClassOpItem]
op_stuff
                         }})
  = ([TyVar]
tyvars, [FunDep TyVar]
fundeps, [PredType]
sc_theta, [TyVar]
sc_sels, [ClassATItem]
ats, [ClassOpItem]
op_stuff)

isAbstractClass :: Class -> Bool
isAbstractClass :: Class -> Bool
isAbstractClass Class{ classBody :: Class -> ClassBody
classBody = ClassBody
AbstractClass } = Bool
True
isAbstractClass _ = Bool
False

{-
************************************************************************
*                                                                      *
\subsection[Class-instances]{Instance declarations for @Class@}
*                                                                      *
************************************************************************

We compare @Classes@ by their keys (which include @Uniques@).
-}

instance Eq Class where
    c1 :: Class
c1 == :: Class -> Class -> Bool
== c2 :: Class
c2 = Class -> Unique
classKey Class
c1 Unique -> Unique -> Bool
forall a. Eq a => a -> a -> Bool
== Class -> Unique
classKey Class
c2
    c1 :: Class
c1 /= :: Class -> Class -> Bool
/= c2 :: Class
c2 = Class -> Unique
classKey Class
c1 Unique -> Unique -> Bool
forall a. Eq a => a -> a -> Bool
/= Class -> Unique
classKey Class
c2

instance Uniquable Class where
    getUnique :: Class -> Unique
getUnique c :: Class
c = Class -> Unique
classKey Class
c

instance NamedThing Class where
    getName :: Class -> Name
getName clas :: Class
clas = Class -> Name
className Class
clas

instance Outputable Class where
    ppr :: Class -> SDoc
ppr c :: Class
c = Name -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Class -> Name
forall a. NamedThing a => a -> Name
getName Class
c)

pprDefMethInfo :: DefMethInfo -> SDoc
pprDefMethInfo :: DefMethInfo -> SDoc
pprDefMethInfo Nothing                  = SDoc
empty   -- No default method
pprDefMethInfo (Just (n :: Name
n, VanillaDM))    = String -> SDoc
text "Default method" SDoc -> SDoc -> SDoc
<+> Name -> SDoc
forall a. Outputable a => a -> SDoc
ppr Name
n
pprDefMethInfo (Just (n :: Name
n, GenericDM ty :: PredType
ty)) = String -> SDoc
text "Generic default method"
                                          SDoc -> SDoc -> SDoc
<+> Name -> SDoc
forall a. Outputable a => a -> SDoc
ppr Name
n SDoc -> SDoc -> SDoc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
<+> PredType -> SDoc
pprType PredType
ty

pprFundeps :: Outputable a => [FunDep a] -> SDoc
pprFundeps :: [FunDep a] -> SDoc
pprFundeps []  = SDoc
empty
pprFundeps fds :: [FunDep a]
fds = [SDoc] -> SDoc
hsep (SDoc
vbar SDoc -> [SDoc] -> [SDoc]
forall a. a -> [a] -> [a]
: SDoc -> [SDoc] -> [SDoc]
punctuate SDoc
comma ((FunDep a -> SDoc) -> [FunDep a] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map FunDep a -> SDoc
forall a. Outputable a => FunDep a -> SDoc
pprFunDep [FunDep a]
fds))

pprFunDep :: Outputable a => FunDep a -> SDoc
pprFunDep :: FunDep a -> SDoc
pprFunDep (us :: [a]
us, vs :: [a]
vs) = [SDoc] -> SDoc
hsep [[a] -> SDoc
forall a. Outputable a => [a] -> SDoc
interppSP [a]
us, SDoc
arrow, [a] -> SDoc
forall a. Outputable a => [a] -> SDoc
interppSP [a]
vs]

instance Data.Data Class where
    -- don't traverse?
    toConstr :: Class -> Constr
toConstr _   = String -> Constr
abstractConstr "Class"
    gunfold :: (forall b r. Data b => c (b -> r) -> c r)
-> (forall r. r -> c r) -> Constr -> c Class
gunfold _ _  = String -> Constr -> c Class
forall a. HasCallStack => String -> a
error "gunfold"
    dataTypeOf :: Class -> DataType
dataTypeOf _ = String -> DataType
mkNoRepType "Class"