2 | import public Data.Array
3 | import public Data.List
4 | import public Text.ILex.RExp
6 | import Data.Linear.Traverse1
7 | import Control.Monad.State
9 | import Data.SortedMap as SM
11 | import Text.ILex.Char.UTF8
12 | import Text.ILex.Internal.DFA
13 | import Text.ILex.Internal.Types
18 | data Trans : Type -> Type where
19 | Run : (res : a) -> Trans a
24 | data Transition : (n : Nat) -> Type -> Type where
25 | Keep : Transition n a
26 | Done : (val : a) -> Transition n a
27 | Ignore : Transition n a
28 | Move : Fin (S n) -> (val : a) -> Transition n a
29 | MoveI : Fin (S n) -> Transition n a
30 | MoveE : Fin (S n) -> Transition n a
31 | Bottom : Transition n a
33 | move : Trans a -> Fin (S n) -> Transition n a
34 | move (Run f) y = Move y f
35 | move Ign y = MoveI y
38 | done : Trans a -> Transition n a
39 | done (Run f) = Done f
45 | 0 ByteTrans : Nat -> Type -> Type
46 | ByteTrans n a = IArray 256 (Transition n a)
50 | 0 Machine : Nat -> Type -> Type
51 | Machine n a = IArray (S n) (ByteTrans n a)
67 | next : Machine states a
74 | 0 Results : Type -> Type
75 | Results a = TokenMap (Trans a)
77 | emptyRow : ByteTrans n a
78 | emptyRow = fill _ Bottom
81 | emptyDFA = L 0 (fill _ emptyRow)
86 | terminals : SortedMap Nat a -> Node -> Maybe (Nat, Either a a)
87 | terminals m (N n (t::_) []) = ((n,) . Left) <$> lookup t m
88 | terminals m (N n (t::_) _) = ((n,) . Right) <$> lookup t m
89 | terminals _ _ = Nothing
91 | nonFinal : SortedMap Nat (Either a a) -> Node -> Maybe Node
93 | case lookup n.pos m of
94 | Just (Left _) => Nothing
97 | index : {n : _} -> List (Nat,Node) -> SortedMap Nat (Fin (S n))
98 | index ns = SM.fromList $
mapMaybe (\(x,n) => (n.pos,) <$> tryNatToFin x) ns
101 | SortedMap Nat (Either (Trans a) (Trans a))
102 | -> (index : SortedMap Nat (Fin (S n)))
103 | -> (node : (Nat,Node))
104 | -> (Nat, ByteTrans n a)
105 | node terms index (ix, N me _ out) =
106 | (ix, fromPairs _ Bottom $
mapMaybe pair (out >>= transitions))
108 | pair : (Bits8,Nat) -> Maybe (Nat, Transition n a)
110 | case lookup tgt terms of
111 | Nothing => case tgt == me of
112 | True => Just (cast b, Keep)
113 | False => ((cast b,) . MoveE) <$> lookup tgt index
114 | Just (Left f) => Just (cast b, done f)
115 | Just (Right f) => case tgt == me of
116 | True => Just (cast b, Keep)
117 | False => ((cast b,) . (move f)) <$> lookup tgt index
121 | byteDFA : (m : TokenMap8 (Trans a)) -> DFA a
123 | let M tms graph := assert_total $
machine (toDFA m)
124 | terms := SM.fromList (mapMaybe (terminals tms . snd) graph)
125 | nodes := zipWithIndex $
mapMaybe (nonFinal terms . snd) graph
126 | S len := length nodes | 0 => emptyDFA
128 | trans := fromPairs (S len) emptyRow (map (node terms ix) nodes)
133 | dfa : Results a -> DFA a
134 | dfa = byteDFA . map toUTF8