General.hs 10 KB

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