on ebb570d help sign in
elk/compiler/Types/Types.hs
92 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"
43string = tipe "String"
44text = tipe "Text"
46element = tipe "Element"
48listOf t = ADT "List" [t]
49signalOf t = ADT "Signal" [t]
50tupleOf ts = ADT ("Tuple" ++ show (length ts)) ts
51maybeOf t = ADT "Maybe" [t]
52eitherOf a b = ADT "Either" [a,b]
53pairOf t = tupleOf [t,t]
54point = pairOf int
55appendable t = Super (Set.fromList [ string, text, listOf t ])
56--comparable = Super (Set.fromList [ int, float, char, string, time, date ])
58infixr ==>
59t1 ==> t2 = LambdaT t1 t2
61infix 8 -:
62name -: tipe = (,) name $ Forall [] [] tipe
64parens = ("("++) . (++")")
66instance Show Type where
67 show t =
68 let show' t = case t of { LambdaT _ _ -> parens (show t) ; _ -> show t }
69 in case t of
70 LambdaT t1@(LambdaT _ _) t2 -> show' t1 ++ " -> " ++ show t2
71 LambdaT t1 t2 -> show t1 ++ " -> " ++ show t2
72 VarT x -> 't' : show x
73 --ADT "List" [ADT "Char" []] -> "String"
74 ADT "List" [tipe] -> "[" ++ show tipe ++ "]"
75 ADT name cs ->
76 if isTupleString name
77 then parens . intercalate "," $ map show cs
78 else case cs of
79 [] -> name
80 _ -> name ++ " " ++ unwords (map show cs)
81 Super ts -> "{" ++ (intercalate "," . map show $ Set.toList ts) ++ "}"
82 EmptyRecord -> "{}"
83 RecordT fs t ->
84 start ++ intercalate ", " (concatMap fields $ Map.toList fs) ++ " }"
85 where field n s = n ++ " : " ++ show s
86 fields (n,ss) = map (field n) ss
87 start = case t of
88 EmptyRecord -> "{ "
89 _ -> "{ " ++ show t ++ " | "
92isTupleString str = "Tuple" `isPrefixOf` str && all isDigit (drop 5 str)