Efficient parsing and serialisation of S-Expressions (as used by Lisp).
This module is intended to be imported qualified, e.g.:
import qualified Data.AttoLisp as L
- data Lisp
- nil :: Lisp
- isNull :: Lisp -> Bool
- class FromLisp a where
- data Result a
- type Failure f r = String -> f r
- type Success a f r = a -> f r
- data Parser a
- parse :: (a -> Parser b) -> a -> Result b
- parseMaybe :: (a -> Parser b) -> a -> Maybe b
- parseEither :: (a -> Parser b) -> a -> Either String b
- typeMismatch :: String -> Lisp -> Parser a
- class ToLisp a where
- mkStruct :: Text -> [Lisp] -> Lisp
- struct :: ParseList f a => Text -> f -> Lisp -> Parser a
- encode :: ToLisp a => a -> ByteString
- fromLisp :: Lisp -> Builder
- lisp :: Parser Lisp
- atom :: Parser Lisp
Core Lisp Types
A Lisp expression (S-expression).
Symbols are case-sensitive.
Type Conversion
A type that can be converted from an S-expression, with the possibility of failure.
When writing an instance, use mzero
or fail
to make a
conversion fail, e.g. the value is of the wrong type.
An example type and instance:
data Coord { x :: Double, y :: Double } instance FromLisp Coord where parseLisp (DotList
[x] y) = pure (Coord x y) -- A non-DotList value is of the wrong shape, so use mzero to fail. parseLisp _ =mzero
The above instance expects that Coord 4 5
is encoded as (4
. 5)
. This makes sense for a few special types, but most of the
time the standard encoding should be used: (coord 4 5)
. The
struct
combinator provides special support for this use case:
instance FromLisp Coord where
parseLisp = struct
"coord" Coord
It uses some special type class magic to figure out the arity of its second argument.
The result of running a Parser
.
A continuation-based parser type.
parseEither :: (a -> Parser b) -> a -> Either String bSource
:: String | The name of the type you are trying to parse. |
-> Lisp | The actual value encountered. |
-> Parser a |
Fail parsing due to a type mismatch, with a descriptive message.
A type that can be converted to an S-expression.
An example type and instance:
data Coord { x :: Double, y :: Double }
instance ToLisp Coord where
toLisp (Coord x y) = struct
"coord" [toLisp x, toLisp y]
Constructors and destructors
mkStruct :: Text -> [Lisp] -> LispSource
Create a Lisp struct in a standardised format.
Fields in a struct are accessed by position.
struct :: ParseList f a => Text -> f -> Lisp -> Parser aSource
Decode structure serialised with mkStruct
.
The second argument should be a function, usually a constructor. The resulting parser automatically figures out the arity of the function. For example:
data Foo = Foo Int deriving (Eq, Show) parseFoo :: Lisp ->Parser
Foo parseFoo = struct "foo" Foo test =parseMaybe
parseFoo val == Just (Foo 23) where val =List
[Symbol
"foo",Number
23]
Encoding and parsing
encode :: ToLisp a => a -> ByteStringSource