on 73cff94 help sign in
92 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)
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
30instance Show Type where
31 show = render . pretty
33instance Pretty Type where
34 pretty tipe =
35 case tipe of
36 Lambda _ _ -> P.sep [ t, P.sep (map (P.text "->" <+>) ts) ]
37 where
38 t:ts = map prettyLambda (collectLambdas tipe)
39 prettyLambda t = case t of
40 Lambda _ _ -> P.parens (pretty t)
41 _ -> pretty t
43 Var x -> P.text x
44 Data "_List" [t] -> P.brackets (pretty t)
45 Data name tipes
46 | Help.isTuple name -> P.parens . P.sep . P.punctuate P.comma $ map pretty tipes
47 | otherwise -> P.hang (P.text name) 2 (P.sep $ map prettyParens tipes)
48 Record fields ext ->
49 P.braces $ case ext of
50 Nothing -> prettyFields
51 Just x -> P.hang (P.text x <+> P.text "|") 4 prettyFields
52 where
53 prettyField (f,t) = P.text f <+> P.text ":" <+> pretty t
54 prettyFields = commaSep . map prettyField $ fields
56collectLambdas :: Type -> [Type]
57collectLambdas tipe =
58 case tipe of
59 Lambda arg body -> arg : collectLambdas body
60 _ -> [tipe]
62prettyParens :: Type -> Doc
63prettyParens tipe = parensIf needed (pretty tipe)
64 where
65 needed =
66 case tipe of
67 Lambda _ _ -> True
68 Data "_List" [_] -> False
69 Data _ [] -> False
70 Data _ _ -> True
71 _ -> False
73instance Binary Type where
74 put tipe =
75 case tipe of
76 Lambda t1 t2 ->
77 putWord8 0 >> put t1 >> put t2
78 Var x ->
79 putWord8 1 >> put x
80 Data ctor tipes ->
81 putWord8 2 >> put ctor >> put tipes
82 Record fs ext ->
83 putWord8 3 >> put fs >> put ext
85 get = do
86 n <- getWord8
87 case n of
88 0 -> Lambda <$> get <*> get
89 1 -> Var <$> get
90 2 -> Data <$> get <*> get
91 3 -> Record <$> get <*> get
92 _ -> error "Error reading a valid type from serialized string"