]> Git — Sourcephile - haskell/symantic-parser.git/blob - src/Symantic/Parser/Grammar/Dump.hs
Polish
[haskell/symantic-parser.git] / src / Symantic / Parser / Grammar / Dump.hs
1 module Symantic.Parser.Grammar.Dump where
2
3 import Data.Function (($), (.), id)
4 import Data.Semigroup (Semigroup(..))
5 import Data.String (String, IsString(..))
6 import Text.Show (Show(..))
7 import qualified Control.Applicative as Fct
8 import qualified Data.Tree as Tree
9 import qualified Data.List as List
10
11 import Symantic.Univariant.Letable
12 import Symantic.Parser.Grammar.Combinators
13
14 -- * Type 'DumpGrammar'
15 newtype DumpGrammar a = DumpGrammar { unDumpGrammar :: Tree.Tree String }
16
17 dumpGrammar :: DumpGrammar a -> DumpGrammar a
18 dumpGrammar = id
19
20 instance Show (DumpGrammar a) where
21 show = drawTree . unDumpGrammar
22 where
23 drawTree :: Tree.Tree String -> String
24 drawTree = List.unlines . draw
25 draw :: Tree.Tree String -> [String]
26 draw (Tree.Node x ts0) = List.lines x <> drawSubTrees ts0
27 where
28 drawSubTrees [] = []
29 drawSubTrees [t] = shift "` " " " (draw t)
30 drawSubTrees (t:ts) = shift "+ " "| " (draw t) <> drawSubTrees ts
31 shift first other = List.zipWith (<>) (first : List.repeat other)
32 instance IsString (DumpGrammar a) where
33 fromString s = DumpGrammar $ Tree.Node (fromString s) []
34
35 instance Show letName => Letable letName DumpGrammar where
36 def name x = DumpGrammar $
37 Tree.Node ( "def "
38 <> show name
39 ) [unDumpGrammar x]
40 ref rec name = DumpGrammar $
41 Tree.Node
42 ( (if rec then "rec " else "ref ")
43 <> show name
44 )
45 []
46 instance Applicable DumpGrammar where
47 _f <$> x = DumpGrammar $ Tree.Node "<$>" [unDumpGrammar x]
48 pure a = DumpGrammar $ Tree.Node ("pure "<>show a) []
49 x <*> y = DumpGrammar $ Tree.Node "<*>" [unDumpGrammar x, unDumpGrammar y]
50 instance Alternable DumpGrammar where
51 empty = DumpGrammar $ Tree.Node "empty" []
52 x <|> y = DumpGrammar $ Tree.Node "<|>" [unDumpGrammar x, unDumpGrammar y]
53 try x = DumpGrammar $ Tree.Node "try" [unDumpGrammar x]
54 instance Charable DumpGrammar where
55 satisfy _p = DumpGrammar $ Tree.Node "satisfy" []
56 instance Selectable DumpGrammar where
57 branch lr l r = DumpGrammar $ Tree.Node "branch"
58 [ unDumpGrammar lr, unDumpGrammar l, unDumpGrammar r ]
59 instance Matchable DumpGrammar where
60 conditional _cs bs a b = DumpGrammar $ Tree.Node "conditional"
61 [ Tree.Node "bs" (unDumpGrammar Fct.<$> bs)
62 , unDumpGrammar a
63 , unDumpGrammar b
64 ]
65 instance Lookable DumpGrammar where
66 look x = DumpGrammar $ Tree.Node "look" [unDumpGrammar x]
67 negLook x = DumpGrammar $ Tree.Node "negLook" [unDumpGrammar x]
68 instance Foldable DumpGrammar where
69 chainPre f x = DumpGrammar $ Tree.Node "chainPre" [unDumpGrammar f, unDumpGrammar x]
70 chainPost x f = DumpGrammar $ Tree.Node "chainPost" [unDumpGrammar x, unDumpGrammar f]