General.hs 10 KB

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