on 06503fe help sign in
57 lines 1.8 kB history raw
1module SourceSyntax.Pattern where
3import Data.List (intercalate)
4import SourceSyntax.Helpers as Help
5import SourceSyntax.PrettyPrint
6import Text.PrettyPrint as PP
7import qualified Data.Set as Set
8import SourceSyntax.Literal as Literal
10data Pattern = PData String [Pattern]
11 | PRecord [String]
12 | PAlias String Pattern
13 | PVar String
14 | PAnything
15 | PLiteral Literal.Literal
16 deriving (Eq, Ord, Show)
18cons h t = PData "::" [h,t]
19nil = PData "[]" []
20list = foldr cons nil
21tuple es = PData ("_Tuple" ++ show (length es)) es
23boundVars :: Pattern -> Set.Set String
24boundVars pattern =
25 case pattern of
26 PVar x -> Set.singleton x
27 PAlias x p -> Set.insert x (boundVars p)
28 PData _ ps -> Set.unions (map boundVars ps)
29 PRecord fields -> Set.fromList fields
30 PAnything -> Set.empty
31 PLiteral _ -> Set.empty
34instance Pretty Pattern where
35 pretty pattern =
36 case pattern of
37 PVar x -> variable x
38 PLiteral lit -> pretty lit
39 PRecord fs -> PP.braces (commaCat $ map variable fs)
40 PAlias x p -> prettyParens p <+> PP.text "as" <+> variable x
41 PAnything -> PP.text "_"
42 PData "::" [hd,tl] -> parensIf isCons (pretty hd) <+> PP.text "::" <+> pretty tl
43 where isCons = case hd of
44 PData "::" _ -> True
45 _ -> False
46 PData name ps ->
47 if isTuple name then
48 PP.parens . commaCat $ map pretty ps
49 else hsep (PP.text name : map prettyParens ps)
51prettyParens pattern = parensIf needsThem (pretty pattern)
52 where
53 needsThem =
54 case pattern of
55 PData name (_:_) | not (isTuple name) -> True
56 PAlias _ _ -> True
57 _ -> False