on c2fc03c help sign in
elk/compiler/Types/Types.hs
91 lines 2.7 kB history raw
2module Types.Types where
4import Context
5import Data.Char (isDigit)
6import Data.List (intercalate,isPrefixOf)
7import qualified Data.Set as Set
8import qualified Data.Map as Map
10type X = Int
12data Type = LambdaT Type Type
13 | VarT X
14 | ADT String [Type]
15 | EmptyRecord
16 | RecordT (Map.Map String [Type]) Type
17 | Super (Set.Set Type)
18 deriving (Eq, Ord)
20data Scheme = Forall [X] [Context Constraint] Type deriving (Eq, Ord, Show)
22data Constraint = Type :=: Type
23 | Type :<: Type
24 | X :<<: Scheme
25 deriving (Eq, Ord, Show)
27recordT :: [(String,Type)] -> Map.Map String [Type]
28recordT fields =
29 foldl (\r (x,t) -> Map.insertWith (++) x [t] r) Map.empty fields
31recordOf :: [(String,Type)] -> Type
32recordOf fields = RecordT (recordT fields) EmptyRecord
34tipe t = ADT t []
36int = tipe "Int"
37float = tipe "Float"
38number = Super (Set.fromList [ int, float ])
40char = tipe "Char"
41bool = tipe "Bool"
42text = tipe "Text"
43string = tipe "String"
45element = tipe "Element"
47listOf t = ADT "List" [t]
48signalOf t = ADT "Signal" [t]
49tupleOf ts = ADT ("Tuple" ++ show (length ts)) ts
50maybeOf t = ADT "Maybe" [t]
51eitherOf a b = ADT "Either" [a,b]
52pairOf t = tupleOf [t,t]
53point = pairOf int
54appendable t = Super (Set.fromList [ string, text, listOf (VarT t) ])
55--comparable = Super (Set.fromList [ int, float, char, string, time, date ])
57infixr ==>
58t1 ==> t2 = LambdaT t1 t2
60infix 8 -:
61name -: tipe = (,) name $ Forall [] [] tipe
63parens = ("("++) . (++")")
65instance Show Type where
66 show t =
67 let show' t = case t of { LambdaT _ _ -> parens (show t) ; _ -> show t }
68 in case t of
69 LambdaT t1@(LambdaT _ _) t2 -> show' t1 ++ " -> " ++ show t2
70 LambdaT t1 t2 -> show t1 ++ " -> " ++ show t2
71 VarT x -> 't' : show x
72 --ADT "List" [ADT "Char" []] -> "String"
73 ADT "List" [tipe] -> "[" ++ show tipe ++ "]"
74 ADT name cs ->
75 if isTupleString name
76 then parens . intercalate "," $ map show cs
77 else case cs of
78 [] -> name
79 _ -> name ++ " " ++ unwords (map show cs)
80 Super ts -> "{" ++ (intercalate "," . map show $ Set.toList ts) ++ "}"
81 EmptyRecord -> "{}"
82 RecordT fs t ->
83 start ++ intercalate ", " (concatMap fields $ Map.toList fs) ++ " }"
84 where field n s = n ++ " : " ++ show s
85 fields (n,ss) = map (field n) ss
86 start = case t of
87 EmptyRecord -> "{ "
88 _ -> "{ " ++ show t ++ " | "
91isTupleString str = "Tuple" `isPrefixOf` str && all isDigit (drop 5 str)