Types.hs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. module Gidl.Types
  2. ( module Gidl.Types.AST
  3. , module Gidl.Types.Base
  4. , TypeDescr
  5. , TypeRepr(..)
  6. , lookupTypeName
  7. , insertType
  8. , typeLeaves
  9. , typeDescrToRepr
  10. , sizeOf
  11. ) where
  12. import Data.List (nub)
  13. import Data.Maybe (fromJust)
  14. import Gidl.Types.AST
  15. import Gidl.Types.Base
  16. lookupTypeName :: TypeName -> TypeEnv -> Maybe TypeDescr
  17. lookupTypeName tn te =
  18. case aux te of
  19. Just a -> Just a
  20. Nothing -> case aux baseTypeEnv of
  21. Just a -> Just a
  22. Nothing -> Nothing
  23. where
  24. aux (TypeEnv e) = lookup tn e
  25. insertType :: TypeName -> TypeDescr -> TypeEnv -> TypeEnv
  26. insertType tn t e@(TypeEnv te) = case lookupTypeName tn e of
  27. Nothing -> TypeEnv ((tn,t):te)
  28. Just _ -> error ("insertType invariant broken: type " ++ tn ++ " already exists")
  29. typeLeaves :: (Eq t) => Type t -> [t]
  30. typeLeaves (StructType (Struct s)) = nub (map snd s)
  31. typeLeaves (NewtypeType (Newtype tn)) = [tn]
  32. typeLeaves (EnumType _) = []
  33. typeLeaves (AtomType _) = []
  34. type TypeDescr = Type TypeName
  35. data TypeRepr = TypeRepr TypeName (Type TypeRepr)
  36. deriving (Eq, Show)
  37. -- invariant: TypeName exists in a well-formed TypeEnv
  38. typeDescrToRepr :: TypeName -> TypeEnv -> TypeRepr
  39. typeDescrToRepr tn te = TypeRepr tn tr
  40. where
  41. tr = case fromJust $ lookupTypeName tn te of
  42. EnumType e -> EnumType e
  43. AtomType a -> AtomType a
  44. NewtypeType (Newtype ntn) ->
  45. NewtypeType (Newtype (typeDescrToRepr ntn te))
  46. StructType (Struct s) ->
  47. StructType (Struct [(i, typeDescrToRepr stn te) | (i, stn) <- s])
  48. sizeOf :: TypeRepr -> Integer
  49. sizeOf (TypeRepr _ (StructType (Struct s))) = sum [ sizeOf tr | (_, tr) <- s ]
  50. sizeOf (TypeRepr _ (NewtypeType (Newtype tr))) = sizeOf tr
  51. sizeOf (TypeRepr _ (EnumType (EnumT bs _))) = bitsSize bs
  52. sizeOf (TypeRepr _ (AtomType (AtomInt bs))) = bitsSize bs
  53. sizeOf (TypeRepr _ (AtomType (AtomWord bs))) = bitsSize bs
  54. sizeOf (TypeRepr _ (AtomType AtomFloat)) = 4
  55. sizeOf (TypeRepr _ (AtomType AtomDouble)) = 8
  56. bitsSize :: Bits -> Integer
  57. bitsSize Bits8 = 1
  58. bitsSize Bits16 = 2
  59. bitsSize Bits32 = 4
  60. bitsSize Bits64 = 8