on b79a8a8 help sign in
elk/compiler/SourceSyntax/Declaration.hs
93 lines 2.8 kB history raw
1{-# OPTIONS_GHC -Wall #-}
2module SourceSyntax.Declaration where
4import Data.Binary
5import qualified SourceSyntax.Expression as Expr
6import qualified SourceSyntax.Type as T
7import SourceSyntax.PrettyPrint
8import Text.PrettyPrint as P
10data Declaration' port def
11 = Definition def
12 | Datatype String [String] [(String,[T.Type])]
13 | TypeAlias String [String] T.Type
14 | Port port
15 | Fixity Assoc Int String
16 deriving (Show)
18data Assoc = L | N | R
19 deriving (Eq)
21data ParsePort
22 = PPAnnotation String T.Type
23 | PPDef String Expr.LParseExpr
24 deriving (Show)
26data Port
27 = Out String Expr.LExpr T.Type
28 | In String T.Type
29 deriving (Show)
31type ParseDeclaration = Declaration' ParsePort Expr.ParseDef
32type Declaration = Declaration' Port Expr.Def
34instance Show Assoc where
35 show assoc =
36 case assoc of
37 L -> "left"
38 N -> "non"
39 R -> "right"
41instance Binary Assoc where
42 get = do n <- getWord8
43 return $ case n of
44 0 -> L
45 1 -> N
46 2 -> R
47 _ -> error "Error reading valid associativity from serialized string"
49 put assoc = putWord8 $ case assoc of { L -> 0 ; N -> 1 ; R -> 2 }
51instance (Pretty port, Pretty def) => Pretty (Declaration' port def) where
52 pretty decl =
53 case decl of
54 Definition def -> pretty def
56 Datatype tipe tvars ctors ->
57 P.hang (P.text "data" <+> P.text tipe <+> P.hsep (map P.text tvars)) 4
58 (P.sep $ zipWith join ("=" : repeat "|") ctors)
59 where
60 join c ctor = P.text c <+> prettyCtor ctor
61 prettyCtor (name, tipes) =
62 P.hang (P.text name) 2 (P.sep (map T.prettyParens tipes))
64 TypeAlias name tvars tipe ->
65 P.hang (P.text "type" <+> name' <+> P.equals) 4 (pretty tipe)
66 where
67 name' = P.text name <+> P.hsep (map P.text tvars)
69 Port port -> pretty port
71 Fixity assoc prec op -> P.text "infix" <> assoc' <+> P.int prec <+> P.text op
72 where
73 assoc' = case assoc of
74 L -> P.text "l"
75 N -> P.empty
76 R -> P.text "r"
78instance Pretty ParsePort where
79 pretty port =
80 case port of
81 PPAnnotation name tipe -> prettyPort name ":" tipe
82 PPDef name expr -> prettyPort name "=" expr
84instance Pretty Port where
85 pretty port =
86 case port of
87 In name tipe -> prettyPort name ":" tipe
88 Out name expr tipe -> P.vcat [ prettyPort name ":" tipe
89 , prettyPort name "=" expr ]
92prettyPort :: (Pretty a) => String -> String -> a -> Doc
93prettyPort name op e = P.text "port" <+> P.text name <+> P.text op <+> pretty e