on bc6ac14 help sign in
90 lines 2.7 kB history raw
1{-# OPTIONS_GHC -W #-}
2module SourceSyntax.Type where
4import Data.Binary
5import qualified Data.Map as Map
6import qualified SourceSyntax.Helpers as Help
7import Control.Applicative ((<$>), (<*>))
8import SourceSyntax.PrettyPrint
9import Text.PrettyPrint as P
11data Type = Lambda Type Type
12 | Var String
13 | Data String [Type]
14 | Record [(String,Type)] (Maybe String)
15 deriving (Eq, Show)
17fieldMap :: [(String,a)] -> Map.Map String [a]
18fieldMap fields =
19 foldl (\r (x,t) -> Map.insertWith (++) x [t] r) Map.empty fields
21recordOf :: [(String,Type)] -> Type
22recordOf fields = Record fields Nothing
24listOf :: Type -> Type
25listOf t = Data "_List" [t]
27tupleOf :: [Type] -> Type
28tupleOf ts = Data ("_Tuple" ++ show (length ts)) ts
31instance Pretty Type where
32 pretty tipe =
33 case tipe of
34 Lambda _ _ -> P.sep [ t, P.sep (map (P.text "->" <+>) ts) ]
35 where
36 t:ts = map prettyLambda (collectLambdas tipe)
37 prettyLambda t = case t of
38 Lambda _ _ -> P.parens (pretty t)
39 _ -> pretty t
41 Var x -> P.text x
42 Data "_List" [t] -> P.brackets (pretty t)
43 Data name tipes
44 | Help.isTuple name -> P.parens . P.sep . P.punctuate P.comma $ map pretty tipes
45 | otherwise -> P.hang (P.text name) 2 (P.sep $ map prettyParens tipes)
46 Record fields ext ->
47 P.braces $ case ext of
48 Nothing -> prettyFields
49 Just x -> P.hang (P.text x <+> P.text "|") 4 prettyFields
50 where
51 prettyField (f,t) = P.text f <+> P.text ":" <+> pretty t
52 prettyFields = commaSep . map prettyField $ fields
54collectLambdas :: Type -> [Type]
55collectLambdas tipe =
56 case tipe of
57 Lambda arg body -> arg : collectLambdas body
58 _ -> [tipe]
60prettyParens :: Type -> Doc
61prettyParens tipe = parensIf needed (pretty tipe)
62 where
63 needed =
64 case tipe of
65 Lambda _ _ -> True
66 Data "_List" [_] -> False
67 Data _ [] -> False
68 Data _ _ -> True
69 _ -> False
71instance Binary Type where
72 put tipe =
73 case tipe of
74 Lambda t1 t2 ->
75 putWord8 0 >> put t1 >> put t2
76 Var x ->
77 putWord8 1 >> put x
78 Data ctor tipes ->
79 putWord8 2 >> put ctor >> put tipes
80 Record fs ext ->
81 putWord8 3 >> put fs >> put ext
83 get = do
84 n <- getWord8
85 case n of
86 0 -> Lambda <$> get <*> get
87 1 -> Var <$> get
88 2 -> Data <$> get <*> get
89 3 -> Record <$> get <*> get
90 _ -> error "Error reading a valid type from serialized string"