on d55e960 help sign in
85 lines 2.5 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 [(String,Type)] Type
17 deriving (Eq, Show, Data, Typeable)
19fieldMap :: [(String,a)] -> Map.Map String [a]
20fieldMap fields =
21 foldl (\r (x,t) -> Map.insertWith (++) x [t] r) Map.empty fields
23recordOf :: [(String,Type)] -> Type
24recordOf fields = Record 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 pretty tipes
42 | otherwise -> P.hang (P.text name) 2 (P.sep $ map prettyParens tipes)
43 EmptyRecord -> P.braces P.empty
44 Record fields ext -> P.braces $ P.hang (pretty ext <+> P.text "|") 4 prettyFields
45 where
46 prettyField (f,t) = P.text f <+> P.text ":" <+> pretty t
47 prettyFields = commaSep . map prettyField $ fields
49collectLambdas tipe =
50 case tipe of
51 Lambda arg@(Lambda _ _) body -> P.parens (pretty arg) : collectLambdas body
52 Lambda arg body -> pretty arg : collectLambdas body
53 _ -> [pretty tipe]
55prettyParens tipe = parensIf needed (pretty tipe)
56 where
57 needed =
58 case tipe of
59 Lambda _ _ -> True
60 Data _ [] -> False
61 Data _ _ -> True
62 _ -> False
64instance Binary Type where
65 put tipe =
66 case tipe of
67 Lambda t1 t2 ->
68 putWord8 0 >> put t1 >> put t2
69 Var x ->
70 putWord8 1 >> put x
71 Data ctor tipes ->
72 putWord8 2 >> put ctor >> put tipes
73 EmptyRecord ->
74 putWord8 3
75 Record fs ext ->
76 putWord8 4 >> put fs >> put ext
78 get = do
79 n <- getWord8
80 case n of
81 0 -> Lambda <$> get <*> get
82 1 -> Var <$> get
83 2 -> Data <$> get <*> get
84 3 -> return EmptyRecord
85 4 -> Record <$> get <*> get