Scanner.hs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. module System.IO.Uniform.Streamline.Scanner where
  2. import Control.Applicative
  3. import Data.Default.Class
  4. import Data.Word8 (Word8)
  5. -- | State of an IO scanner.
  6. -- Differently from a parser scanner, an IO scanner
  7. -- must deal with blocking behavior.
  8. data IOScannerState a =
  9. -- | A scanner returns Finished when the current input is not
  10. -- part of the result, and the scanning must stop before this
  11. -- input.
  12. Finished |
  13. -- | A scanner returns LastPass when the current input is the
  14. -- last one of the result, and the scanning must stop before
  15. -- after this input, without consuming more data.
  16. LastPass a |
  17. -- | A scanner returns Running when the current input is part
  18. -- of the result, and the scanning must continue.
  19. Running a
  20. instance Functor IOScannerState where
  21. fmap _ Finished = Finished
  22. fmap f (LastPass x) = LastPass $ f x
  23. fmap f (Running x) = Running $ f x
  24. instance Applicative IOScannerState where
  25. pure a = Running a
  26. Finished <*> _ = Finished
  27. _ <*> Finished = Finished
  28. (LastPass f) <*> (LastPass x) = LastPass $ f x
  29. (LastPass f) <*> (Running x) = LastPass $ f x
  30. (Running f) <*> (LastPass x) = LastPass $ f x
  31. (Running f) <*> (Running x) = Running $ f x
  32. instance Monad IOScannerState where
  33. return = pure
  34. Finished >>= _ = Finished
  35. (LastPass x) >>= f = case f x of
  36. Finished -> Finished
  37. LastPass y -> LastPass y
  38. Running y -> LastPass y
  39. (Running x) >>= f = f x
  40. type IOScanner a = a -> Word8 -> IOScannerState a
  41. anyScanner :: Default a => [IOScanner a] -> IOScanner [a]
  42. anyScanner scanners = scan
  43. where
  44. --scan :: IOScanner [a]
  45. scan st c = sequence $ apScanner scanners st c
  46. --apScanner :: [IOScanner a] -> [a] -> Word8 -> [IOScannerState a]
  47. apScanner [] _ _ = []
  48. apScanner (s:ss) [] h = s def h : apScanner ss [] h
  49. apScanner (s:ss) (t:tt) h = s t h : apScanner ss tt h
  50. textScanner :: [Word8] -> (IOScanner [[Word8]])
  51. textScanner [] = \_ _ -> Finished
  52. textScanner t@(c:_) = scanner
  53. where
  54. scanner st c'
  55. | c == c' = popStacks (t:st) c'
  56. | otherwise = popStacks st c'
  57. popStacks :: IOScanner [[Word8]]
  58. popStacks [] _ = Running []
  59. popStacks ([]:_) _ = Finished
  60. popStacks ((h':hh):ss) h
  61. | h == h' && null hh = case popStacks ss h of
  62. Finished -> Finished
  63. LastPass ss' -> LastPass $ ss'
  64. Running ss' -> LastPass $ ss'
  65. | h == h' = case popStacks ss h of
  66. Finished -> Finished
  67. LastPass ss' -> LastPass $ hh:ss'
  68. Running ss' -> Running $ hh:ss'
  69. | otherwise = popStacks ss h