on b1dd157 help sign in
81 lines 2.3 kB history raw
1{-# LANGUAGE DeriveDataTypeable #-}
2module SourceSyntax.Type where
4import Data.Binary
5import Data.Data
6import qualified Data.Map as Map
7import qualified SourceSyntax.Helpers as Help
8import Control.Applicative ((<$>), (<*>))
9import SourceSyntax.PrettyPrint
10import Text.PrettyPrint as P
12data Type = Lambda Type Type
13 | Var String
14 | Data String [Type]
15 | EmptyRecord
16 | Record (Map.Map String [Type]) Type
17 deriving (Eq, Show, Data, Typeable)
19fieldMap :: [(String,Type)] -> Map.Map String [Type]
20fieldMap fields =
21 foldl (\r (x,t) -> Map.insertWith (++) x [t] r) Map.empty fields
23recordOf :: [(String,Type)] -> Type
24recordOf fields = Record (fieldMap fields) EmptyRecord
26listOf :: Type -> Type
27listOf t = Data "_List" [t]
29tupleOf :: [Type] -> Type
30tupleOf ts = Data ("_Tuple" ++ show (length ts)) ts
33instance Pretty Type where
34 pretty tipe =
35 case tipe of
36 Lambda t1 t2 -> P.sep [ t, P.sep (map (P.text "->" <+>) ts) ]
37 where t:ts = collectLambdas tipe
38 Var x -> P.text x
39 Data "_List" [t] -> P.brackets (pretty t)
40 Data name tipes
41 | Help.isTuple name -> P.parens . P.sep . P.punctuate P.comma $ map prettyParens tipes
42 | otherwise -> P.hang (P.text name) 2 (P.sep $ map prettyParens tipes)
43 EmptyRecord -> P.braces P.empty
44 Record fields ext -> error "not done yet"
46collectLambdas tipe =
47 case tipe of
48 Lambda arg@(Lambda _ _) body -> P.parens (pretty arg) : collectLambdas body
49 Lambda arg body -> pretty arg : collectLambdas body
50 _ -> [pretty tipe]
52prettyParens tipe = parensIf needed (pretty tipe)
53 where
54 needed =
55 case tipe of
56 Lambda _ _ -> True
57 Data _ _ -> True
58 _ -> False
60instance Binary Type where
61 put tipe =
62 case tipe of
63 Lambda t1 t2 ->
64 putWord8 0 >> put t1 >> put t2
65 Var x ->
66 putWord8 1 >> put x
67 Data ctor tipes ->
68 putWord8 2 >> put ctor >> put tipes
69 EmptyRecord ->
70 putWord8 3
71 Record fs ext ->
72 putWord8 4 >> put fs >> put ext
74 get = do
75 n <- getWord8
76 case n of
77 0 -> Lambda <$> get <*> get
78 1 -> Var <$> get
79 2 -> Data <$> get <*> get
80 3 -> return EmptyRecord
81 4 -> Record <$> get <*> get