General.hs 9.8 KB

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