General.hs 11 KB

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