General.hs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. {-# LANGUAGE ViewPatterns #-}
  2. {-# LANGUAGE OverloadedStrings #-}
  3. module Data.SCargot.General
  4. ( -- * SExprSpec
  5. SExprSpec
  6. , mkSpec
  7. , convertSpec
  8. , addReader
  9. , setComment
  10. -- * Specific SExprSpec Conversions
  11. , asRich
  12. , asWellFormed
  13. , withSemicolonComments
  14. , withQuote
  15. -- * Using a SExprSpec
  16. , decode
  17. , decodeOne
  18. , encode
  19. -- * Useful Type Aliases
  20. , Reader
  21. , Comment
  22. , Serializer
  23. ) where
  24. import Control.Applicative ((<*), (*>), (<|>), (<*>), (<$>), pure)
  25. import Control.Monad ((>=>))
  26. import Data.Attoparsec.Text
  27. import Data.Char (isAlpha, isDigit, isAlphaNum)
  28. import Data.Map.Strict (Map)
  29. import qualified Data.Map.Strict as M
  30. import Data.Monoid ((<>))
  31. import Data.Text (Text, pack, unpack)
  32. import qualified Data.Text as T
  33. import Prelude hiding (takeWhile)
  34. import Data.SCargot.Repr
  35. type ReaderMacroMap atom = Map Char (Reader atom)
  36. -- | A 'Reader' represents a reader macro: it takes a parser for
  37. -- the S-Expression type and performs as much or as little
  38. -- parsing as it would like, and then returns an S-expression.
  39. type Reader atom = (Parser (SExpr atom) -> Parser (SExpr atom))
  40. -- | A 'Comment' represents any kind of skippable comment. This
  41. -- parser __must__ be able to fail if a comment is not being
  42. -- recognized, and it __must__ not consume any input.
  43. type Comment = Parser ()
  44. -- | A 'Serializer' is any function which can serialize an Atom
  45. -- to 'Text'.
  46. type Serializer atom = atom -> Text
  47. -- | A 'SExprSpec' describes a parser and emitter for a particular
  48. -- variant of S-Expressions. The @atom@ type corresponds to a
  49. -- Haskell type used to represent the atoms, and the @carrier@
  50. -- type corresponds to the parsed S-Expression structure. The
  51. -- 'SExprSpec' type is deliberately opaque so that it must be
  52. -- constructed and modified with other helper functions.
  53. data SExprSpec atom carrier = SExprSpec
  54. { sesPAtom :: Parser atom
  55. , sesSAtom :: Serializer atom
  56. , readerMap :: ReaderMacroMap atom
  57. , comment :: Maybe Comment
  58. , postparse :: SExpr atom -> Either String carrier
  59. , preserial :: carrier -> SExpr atom
  60. }
  61. -- | Create a basic 'SExprSpec' when given a parser and serializer
  62. -- for an atom type. A small minimal 'SExprSpec' that recognizes
  63. -- any alphanumeric sequence as a valid atom looks like:
  64. --
  65. -- > simpleSpec :: SExprSpec Text (SExpr Text)
  66. -- > simpleSpec = mkSpec (takeWhile1 isAlphaNum) id
  67. mkSpec :: Parser atom -> Serializer atom -> SExprSpec atom (SExpr atom)
  68. mkSpec p s = SExprSpec
  69. { sesPAtom = p
  70. , sesSAtom = s
  71. , readerMap = M.empty
  72. , comment = Nothing
  73. , postparse = return
  74. , preserial = id
  75. }
  76. -- | Modify the carrier type for a 'SExprSpec'. This is
  77. -- used internally to convert between various 'SExpr' representations,
  78. -- but could also be used externally to add an extra conversion layer
  79. -- onto a 'SExprSpec'.
  80. --
  81. -- The following defines an S-expression spec that recognizes the
  82. -- language of binary addition trees. It does so by first transforming
  83. -- the internal S-expression representation using 'asWellFormed', and
  84. -- then providing a conversion between the 'WellFormedSExpr' type and
  85. -- an @Expr@ AST. Notice that the below parser uses 'String' as its
  86. -- underlying atom type.
  87. --
  88. -- > data Expr = Add Expr Expr | Num Int deriving (Eq, Show)
  89. -- >
  90. -- > toExpr :: WellFormedSExpr String -> Either String Expr
  91. -- > toExpr (WFSList [WFSAtom "+", l, r]) = Add <$> toExpr l <*> toExpr r
  92. -- > toExpr (WFSAtom c) | all isDigit c = pure (Num (read c))
  93. -- > toExpr c = Left ("Invalid expr: " ++ show c)
  94. -- >
  95. -- > fromExpr :: Expr -> WellFormedSExpr String
  96. -- > fromExpr (Add l r) = WFSList [WFSAtom "+", fromExpr l, fromExpr r]
  97. -- > fromExpr (Num n) = WFSAtom (show n)
  98. -- >
  99. -- > mySpec :: SExprSpec String Expr
  100. -- > mySpec = convertSpec toExpr fromExpr $ asWellFormed $ mkSpec parser pack
  101. -- > where parser = unpack <$> takeWhile1 isValidChar
  102. -- > isValidChar c = isDigit c || c == '+'
  103. convertSpec :: (b -> Either String c) -> (c -> b)
  104. -> SExprSpec a b -> SExprSpec a c
  105. convertSpec f g spec = spec
  106. { postparse = postparse spec >=> f
  107. , preserial = preserial spec . g
  108. }
  109. -- | Convert the final output representation from the 'SExpr' type
  110. -- to the 'RichSExpr' type.
  111. asRich :: SExprSpec a (SExpr b) -> SExprSpec a (RichSExpr b)
  112. asRich = convertSpec (return . toRich) fromRich
  113. -- | Convert the final output representation from the 'SExpr' type
  114. -- to the 'WellFormedSExpr' type.
  115. asWellFormed :: SExprSpec a (SExpr b) -> SExprSpec a (WellFormedSExpr b)
  116. asWellFormed = convertSpec toWellFormed fromWellFormed
  117. -- | Add the ability to execute some particular reader macro, as
  118. -- defined by its initial character and the 'Parser' which returns
  119. -- the parsed S-Expression. The 'Reader' is passed a 'Parser' which
  120. -- can be recursively called to parse more S-Expressions, and begins
  121. -- parsing after the reader character has been removed from the
  122. -- stream.
  123. --
  124. -- The following defines an S-expression variant that treats
  125. -- @'expr@ as being sugar for @(quote expr)@:
  126. --
  127. -- > mySpec :: SExprSpec Text (SExpr Text)
  128. -- > mySpec = addReader '\'' reader $ mkSpec (takeWhile1 isAlphaNum) id
  129. -- > where reader p = quote <$> p
  130. -- > quote e = SCons (SAtom "quote") (SCons e SNil)
  131. addReader :: Char -> Reader a -> SExprSpec a c -> SExprSpec a c
  132. addReader c reader spec = spec
  133. { readerMap = M.insert c reader (readerMap spec) }
  134. -- | Add the ability to ignore some kind of comment. This gets
  135. -- factored into whitespace parsing, and it's very important that
  136. -- the parser supplied __be able to fail__ (as otherwise it will
  137. -- cause an infinite loop), and also that it __not consume any input__
  138. -- (which may require it to be wrapped in 'try'.)
  139. --
  140. -- The following code defines an S-expression variant that skips
  141. -- C++-style comments, i.e. those which begin with @//@ and last
  142. -- until the end of a line:
  143. --
  144. -- > t :: SExprSpec Text (SExpr Text)
  145. -- > t = setComment comm $ mkSpec (takeWhile1 isAlphaNum) id
  146. -- > where comm = try (string "//" *> takeWhile (/= '\n') *> pure ())
  147. setComment :: Comment -> SExprSpec a c -> SExprSpec a c
  148. setComment c spec = spec { comment = Just c }
  149. -- | Add the ability to skip line comments beginning with a semicolon.
  150. withSemicolonComments :: SExprSpec a c -> SExprSpec a c
  151. withSemicolonComments = setComment (char ';' >> takeWhile (/='\n') >> return ())
  152. -- | Add the ability to understand a quoted S-Expression. In general,
  153. -- many Lisps use @'sexpr@ as sugar for @(quote sexpr)@. This is
  154. -- a convenience function which allows you to easily add quoted
  155. -- expressions to a 'SExprSpec', provided that you supply which
  156. -- atom you want substituted in for the symbol @quote@.
  157. withQuote :: a -> SExprSpec a (SExpr a) -> SExprSpec a (SExpr a)
  158. withQuote q = addReader '\'' (fmap go)
  159. where go s = SCons (SAtom q) (SCons s SNil)
  160. parseGenericSExpr ::
  161. Parser atom -> ReaderMacroMap atom -> Parser () -> Parser (SExpr atom)
  162. parseGenericSExpr atom reader skip = do
  163. let sExpr = parseGenericSExpr atom reader skip
  164. skip
  165. c <- peekChar
  166. r <- case c of
  167. Nothing -> fail "Unexpected end of input"
  168. Just '(' -> char '(' >> skip >> parseList sExpr skip
  169. Just (flip M.lookup reader -> Just r) -> anyChar >> r sExpr
  170. _ -> SAtom `fmap` atom
  171. skip
  172. return r
  173. parseList :: Parser (SExpr atom) -> Parser () -> Parser (SExpr atom)
  174. parseList sExpr skip = do
  175. i <- peekChar
  176. case i of
  177. Nothing -> fail "Unexpected end of input"
  178. Just ')' -> char ')' >> return SNil
  179. _ -> do
  180. car <- sExpr
  181. skip
  182. c <- peekChar
  183. case c of
  184. Just '.' -> do
  185. char '.'
  186. cdr <- sExpr
  187. skip
  188. char ')'
  189. skip
  190. return (SCons car cdr)
  191. Just ')' -> do
  192. char ')'
  193. skip
  194. return (SCons car SNil)
  195. _ -> do
  196. cdr <- parseList sExpr skip
  197. return (SCons car cdr)
  198. -- | Given a CommentMap, create the corresponding parser to
  199. -- skip those comments (if they exist).
  200. buildSkip :: Maybe (Parser ()) -> Parser ()
  201. buildSkip Nothing = skipSpace
  202. buildSkip (Just c) = alternate
  203. where alternate = skipSpace >> ((c >> alternate) <|> return ())
  204. -- | Decode a single S-expression. If any trailing input is left after
  205. -- the S-expression (ignoring comments or whitespace) then this
  206. -- will fail: for those cases, use 'decode', which returns a list of
  207. -- all the S-expressions found at the top level.
  208. decodeOne :: SExprSpec atom carrier -> Text -> Either String carrier
  209. decodeOne spec = parseOnly (parser <* endOfInput) >=> (postparse spec)
  210. where parser = parseGenericSExpr
  211. (sesPAtom spec)
  212. (readerMap spec)
  213. (buildSkip (comment spec))
  214. -- | Decode several S-expressions according to a given 'SExprSpec'. This
  215. -- will return a list of every S-expression that appears at the top-level
  216. -- of the document.
  217. decode :: SExprSpec atom carrier -> Text -> Either String [carrier]
  218. decode spec =
  219. parseOnly (many1 parser <* endOfInput) >=> mapM (postparse spec)
  220. where parser = parseGenericSExpr
  221. (sesPAtom spec)
  222. (readerMap spec)
  223. (buildSkip (comment spec))
  224. -- | Encode (without newlines) a single S-expression.
  225. encodeSExpr :: SExpr atom -> (atom -> Text) -> Text
  226. encodeSExpr SNil _ = "()"
  227. encodeSExpr (SAtom s) t = t s
  228. encodeSExpr (SCons x xs) t = go xs (encodeSExpr x t)
  229. where go (SAtom s) rs = "(" <> rs <> " . " <> t s <> ")"
  230. go SNil rs = "(" <> rs <> ")"
  231. go (SCons x xs) rs = go xs (rs <> " " <> encodeSExpr x t)
  232. -- | Emit an S-Expression in a machine-readable way. This does no
  233. -- pretty-printing or indentation, and produces no comments.
  234. encodeOne :: SExprSpec atom carrier -> carrier -> Text
  235. encodeOne spec c = encodeSExpr (preserial spec c) (sesSAtom spec)
  236. encode :: SExprSpec atom carrier -> [carrier] -> Text
  237. encode spec cs = T.concat (map (encodeOne spec) cs)