class: center, middle # Permutation Parser # CindyLinz 2015.6.4 --- layout: true # Parsing --- 一開始我們有一個要解析的目標, 一串文字 ```c ... int lamp_count = 0; while( is_sleepless ){ lamp_count += 10; play_mobile_phone(); } ... ``` --- 這串文字背後有一組語法定義, 以及語意的定義 ```yacc statement : block_statement { ... } | while_statement { ... } | if_statement { ... } | expression { ... } block_statement : "{" statements "}" { ... } statements : { ... } | statements statement { ... } (LR parser 通常寫上面這個, LL parser 通常寫下面這個, 不過不是今天重點 XD) | statement statements { ... } while_statement : "while" "(" expression ")" statement { $3...; $5...; $$ = ... } ... ``` 我們要用程式去解析它, 檢查有沒有寫對, 或是依語意定義去作出應用.. --- layout: true # Parser Combinator 簡略介紹 ---
Functor
Applicative
Alternative
Monad
MonadPlus
```haskell class Functor m where (<$>) :: (a -> b) -> m a -> m b class Functor m => Applicative m where pure :: a -> m a (<*>) :: m (a -> b) -> m a -> m b -- m (x -> y -> z) -> m x -> m (y -> z) ... -- a <$> b = pure a <*> b class Applicative m => Alternative m where empty :: m a (<|>) :: m a -> m a -> m a -- 以下這兩個不是今天重點 class Applicative m => Monad m where (>>=) :: m a -> (a -> m b) -> m b class (Monad m, Alternative m) => MonadPlus m where ... ``` --- ```haskell data Statement = BlockStatement | WhileStatement | IfStatement | Expression data WhileStatement = WhileStatement Expression Statement data IfStatement = IfStatement1 Expression Statement -- 沒有 else 的 if | IfStatement2 Expression Statement Statement -- 有 else 的 data Expression = ... ... statement = whileStatement <|> ifStatement <|> expression whileStatement = (\_ _ cond _ body -> WhileStatement cond body) <$> string "while" <*> string "(" <*> expression <*> string ")" <*> statement ifStatement = (\_ _ cond _ thenDo _ elseDo -> IfStatement2 cond thenDo elseDo) <$> string "if" <*> string "(" <*> expression <*> string ")" <*> statement <*> string "else" <*> statement <|> (\_ _ cond _ thenDo -> IfStatement1 cond thenDo) <$> string "if" <*> string "(" <*> expression <*> string ")" <*> statement ... ``` --- `Alternative` 不是專門作 Parser 的, 它只是一個數學結構而已..
(or 常見的 Parser 行徑剛好很符合 `Alternative` 這個數學結構) -- 還有一些在許多語言裡面也蠻常見的 pattern: * 用某某分隔符號(例如逗點)隔開的 list
-- 1, 20, 3, 5, 7 * 用某某分隔符號隔開, 並且有開頭結尾符號(例如用括號包起來)的 list
-- (1, 20, 3, 5, 7) * 某某項目可有可無, 如果沒寫的話就用預設的某某某 (例如 if 後面的 else 部分) * ... -- 或是一些很可能會想用的偏差(?)行為: * 把 parse 吃 source 的動作暫停一下, 先前後左右偷看一些東西, 或是互動式地問一下使用者現在該怎麼辦 * 為效能考量, 約定怎樣情況下會把已經看過的輸入原始碼丟掉, 需要提供額外的機制在必要的時候要求把部分看過的原始碼保留著用 * ... --- Parser Combinator 即是提供輔助寫這些 pattern 的函數, 讓我們偷懶不用全都從頭刻 ```haskell sepBy :: Alternative m => m a -> m sep -> m [a] sepEndBy :: Alternative m => m a -> m sep -> m [a] sepBy1 :: Alternative m => m a -> m sep -> m [a] ... between :: Applicative m => m bra -> m ket -> m a -> m a option :: Alternative m => a -> m a -> m a choice :: Alternative m => [m a] -> m a many :: Alternative m => m a -> m [a] some :: Alternative m => m a -> m [a] ... -- 以上都是 helper 偷懶函數, 都可以手動只用 Alternative 提供的功能組合出來 -- 以下是只用 Alternative 提供的功能辦不到, 所以要求底層多吐一些功能出來用 class Alternative m => Parsing m where try :: m a -> m a ... skipMany :: m a -> m () -- 這個只用 Alternative 其實就夠了 -- 叫底層額外做是看他能不能用效能更好的方法實作 -- 今天要介紹的東西只需要 Alternative, 不需要 Parsing 的功能 ``` --- layout: false # Permutation Parsing 要處理的對象 ```c int static const unsigned n = 5; ``` 這裡 `int`, `static`, `const`, `unsigned` 順序可隨意, 不可重複, 有些可以省略
(那就用預設行為) ```html <img width="200" height="100" title="一張圖" src="http://.../...jpg" /> ``` `img` 裡面的參數也有一樣性質, 並且出現時有部分的資料要粹取出來 -- `Alternative` 結構沒有表達接受任意排列組合的特性的方法, 一般常見的 parser 產生器也沒有提供這種功能. 今天介紹的 library (與 paper) 就是要提供描述這個特性的方法, 並且轉譯為 `Alternative` 能表達的方式, 並且效能是在合理範圍內. --- layout: false # Permutation Parser 預期用法 ```haskell data Img = Img { imgSrc , imgWidth , imgHeight , imgTitle :: String } parseImg = (\_ _ img _ -> img) <$> string "<" <*> istring "img" -- 不分大小寫 :p <*> permute ( Img -- Img 或寫成 (\a b c d -> Img a b c d) 意思一樣 -- 寫成 (\src width height title -> Img src width height title) -- 可能更好讀 <$$> attr "src" <|?> ("", attr "width") <|?> ("", attr "height") <|?> ("", attr "title") ) <*> string "/>" ``` --- layout: true # Permutation Parser 的程式碼 (by EdwardK) --- ```haskell data Permutation m a = Permutation (Maybe a) [Branch m a] data Branch m a = forall b. Branch (Permutation m (b -> a)) (m b) instance Functor m => Functor (Permutation m) where fmap f (Permutation x xs) = Permutation (fmap f x) (fmap f <$> xs) instance Functor m => Functor (Branch m) where fmap f (Branch perm p) = Branch (fmap (f.) perm) p ``` --- ```haskell permute :: Alternative m => Permutation m a -> m a permute (Permutation def xs) = asum (map branch xs ++ e) where e = maybe [] (pure . pure) def branch (Branch perm p) = flip id <$> p <*> permute perm newPermutation :: Functor m => (a -> b) -> Permutation m (a -> b) newPermutation f = Permutation (Just f) [] add :: Functor m => Permutation m (a -> b) -> m a -> Permutation m b add perm@(Permutation _mf fs) p = Permutation Nothing (first:map insert fs) where first = Branch perm p insert (Branch perm' p') = Branch (add (fmap flip perm') p) p' addOpt :: Functor m => Permutation m (a -> b) -> a -> m a -> Permutation m b addOpt perm@(Permutation mf fs) x p = Permutation (fmap ($ x) mf) (first:map insert fs) where first = Branch perm p insert (Branch perm' p') = Branch (addOpt (fmap flip perm') x p) p' ``` --- ```haskell (<||>) :: Functor m => Permutation m (a -> b) -> m a -> Permutation m b (<||>) = add infixl 1 <||> (<$$>) :: Functor m => (a -> b) -> m a -> Permutation m b (<$$>) f p = newPermutation f <||> p infixl 2 <$$> (<|?>) :: Functor m => Permutation m (a -> b) -> (a, m a) -> Permutation m b (<|?>) perm (x,p) = addOpt perm x p infixl 1 <|?> (<$?>) :: Functor m => (a -> b) -> (a, m a) -> Permutation m b (<$?>) f (x,p) = newPermutation f <|?> (x,p) infixl 2 <$?> ``` --- layout: true # 以玩具範例說明運作機制 --- + 假設這是我們要 parse 的排列組合 ``` a* <||> b <||> c? ``` (其中 `a*`, `b`, `c?` 是 regex 的寫法) -- + 把排列組合展開寫成 regex 是這樣 ``` a* b c? | a* c? b | b a* c? | b c? a* | c? a* b | c? b a* ``` --- + 畫成決策樹是這樣
a*
b
c?
c?
b
b
a*
c?
c?
a*
c?
a*
b
b
a*
.....對, 不意外地會展開出 N! 個終點
(1, 2, 6, 24, 120, 720, 5040, 40320, 362880..)
手工寫 SVG 畫圖有點累, 複製貼上很多, 很難修改 :(
--- * 而且有 ambiguity
a*
b
c?
c?
b
b
a*
c?
c?
a*
c?
a*
b
b
a*
(這邊是以 match `aaab` 為例) --- * 為去除 ambiguity, 我們把這些可能為「空」的 element 拆開成「空」與「非空」的部分.
且不失一般性, 限制它們只有出現在尾巴的時候可以走「空」的選擇
a*
b
c?
c?
b
b
a*
c?
c?
a*
c?
a*
b
b
a*
a+
b
c
c
b
b
a+
c
c
a+
c
a+
b
b
a+
--- * 而 N! 條路徑, 利用 Haskell non-strict evaluation 的特性, 把一整坨還沒走過的未來路徑排列當成糾纏態包在 thunk 裡面 每往前走一步, 糾纏態就崩塌(解開)一步, 而旁支不會走到的糾纏態就整團捨棄. --- layout: true # 決策樹與資料結構的對應
a+
b
c
c
b
b
a+
c
c
a+
c
a+
b
b
a+
--- ```haskell data Permutation m a = Permutation (Maybe a) [Branch m a] -- subtree root 與其下整個 subtree data Branch m a = forall b. Branch (Permutation m (b -> a)) (m b) -- subtree root 與其下整個 subtree -- 和 subtree root 的 parent edge ``` --- 這棵決策樹對應的(`N!`展開後的)資料結構 ```haskell Permutation Nothing [ Branch ( Permutation Nothing [ Branch ( Permutation (Just (,, "")) [Branch (Permutation (Just (,,)) []) (regex "c")] ) (regex "b") , Branch ( Permutation Nothing [Branch (Permutation (Just (,,)) []) (regex "b")] ) (regex "c") ] ) (regex "a+") , Branch ... (regex "b"), Branch ... (regex "c") ] -- 剩下通通縮起來擠在這XD ``` ```haskell data Permutation m a = Permutation (Maybe a) [Branch m a] data Branch m a = forall b. Branch (Permutation m (b -> a)) (m b) ``` --- 執行的方式.. ```haskell permute :: Alternative m => Permutation m a -> m a permute (Permutation def xs) = asum (map branch xs ++ e) -- asum [a..z] = a <|> .. <|> z where e = maybe [] (pure . pure) def -- pure (pure def) = [pure def] branch (Branch perm p) = flip id <$> p <*> permute perm -- flip id :: a -> (a -> b) -> b ``` ```haskell Permutation Nothing [ Branch ( Permutation Nothing [ Branch ( Permutation (Just (,, "")) [Branch (Permutation (Just (,,)) []) (regex "c")] ) (regex "b") , Branch ( Permutation Nothing [Branch (Permutation (Just (,,)) []) (regex "b")] ) ``` --- 產生這串資料結構的手寫程式碼寫法 ```haskell permute ( (,,) <$?> ("", regex "a+") <||> regex "b" <|?> ("", regex "c") ) ``` -- ```haskell permute ( addOpt ( add ( addOpt (newPermutation (,,)) "" (regex "a+") ) (regex "b") ) "" (regex "c") ) ``` --- ```haskell permute ( addOpt ( add ( addOpt (newPermutation (,,)) "" (regex "a+") ) (regex "b") ) "" (regex "c") ) ``` ```haskell permute :: Alternative m => Permutation m a -> m a newPermutation :: Functor m => (a -> b) -> Permutation m (a -> b) add :: Functor m => Permutation m (a -> b) -> m a -> Permutation m b addOpt :: Functor m => Permutation m (a -> b) -> a -> m a -> Permutation m b ``` --- layout: false # 決策樹與資料結構的對應 ```haskell data Permutation m a = Permutation (Maybe a) [Branch m a] data Branch m a = forall b. Branch (Permutation m (b -> a)) (m b) instance Functor m => Functor (Permutation m) where fmap f (Permutation x xs) = Permutation (fmap f x) (fmap f <$> xs) instance Functor m => Functor (Branch m) where fmap f (Branch perm p) = Branch (fmap (f.) perm) p newPermutation :: Functor > (a -> b) -> Permutation m (a -> b) newPermutation f = Permutation (Just f) [] ``` --- layout: false # 決策樹與資料結構的對應 ```haskell data Permutation m a = Permutation (Maybe a) [Branch m a] data Branch m a = forall b. Branch (Permutation m (b -> a)) (m b) instance Functor m => Functor (Permutation m) where fmap f (Permutation x xs) = Permutation (fmap f x) (fmap f <$> xs) instance Functor m => Functor (Branch m) where fmap f (Branch perm p) = Branch (fmap (f.) perm) p add :: Functor m => Permutation m (a -> b) -> m a -> Permutation m b add perm@(Permutation _mf fs) p = Permutation Nothing (first:map insert fs) where first = Branch perm p insert (Branch perm' p') = Branch (add (fmap flip perm') p) p' addOpt :: Functor m => Permutation m (a -> b) -> a -> m a -> Permutation m b addOpt perm@(Permutation mf fs) x p = Permutation (fmap ($ x) mf) (first:map insert fs) where first = Branch perm p insert (Branch perm' p') = Branch (addOpt (fmap flip perm') x p) p' ``` --- layout: false # 參考資料 * [Parsing Permutation Phrases](http://www.cs.ox.ac.uk/jeremy.gibbons/wg21/meeting56/loeh-slides.pdf) -- Arthur Baars, Andres L ̈oh, Doaitse Swierstra, 2001 * [Hackage package: Parsers](http://hackage.haskell.org/package/parsers)'s Text.Parser.Permutation -- Edward A. Kmett