on c19ccfe help sign in
48 lines 1.5 kB history raw
1{-# LANGUAGE DeriveDataTypeable #-}
2module SourceSyntax.Pattern where
4import Data.List (intercalate)
5import Data.Data
6import SourceSyntax.Helpers as Help
7import SourceSyntax.PrettyPrint
8import Text.PrettyPrint as PP
9import SourceSyntax.Literal as Literal
11data Pattern = PData String [Pattern]
12 | PRecord [String]
13 | PAlias String Pattern
14 | PVar String
15 | PAnything
16 | PLiteral Literal.Literal
17 deriving (Eq, Ord, Data, Typeable, Show)
19cons h t = PData "::" [h,t]
20nil = PData "[]" []
21list = foldr cons nil
22tuple es = PData ("_Tuple" ++ show (length es)) es
25instance Pretty Pattern where
26 pretty pattern =
27 case pattern of
28 PVar x -> variable x
29 PLiteral lit -> pretty lit
30 PRecord fs -> PP.braces (commaCat $ map PP.text fs)
31 PAlias x p -> prettyParens p <+> PP.text "as" <+> PP.text x
32 PAnything -> PP.text "_"
33 PData "::" [hd,tl] -> parensIf isCons (pretty hd) <+> PP.text "::" <+> pretty tl
34 where isCons = case hd of
35 PData "::" _ -> True
36 _ -> False
37 PData name ps ->
38 if isTuple name then
39 PP.parens . commaCat $ map pretty ps
40 else sep (PP.text name : map prettyParens ps)
42prettyParens pattern = parensIf needsThem (pretty pattern)
43 where
44 needsThem =
45 case pattern of
46 PData name (_:_) | not (isTuple name) -> True
47 PAlias _ _ -> True
48 _ -> False