hsmt-0.1.0.0: src/HSMT/SMTLib/Parser.hs
{-# LANGUAGE ViewPatterns #-}
-- | A parser for the subset of SMT-LIB 2.6 scripts that hsmt supports.
--
-- Scripts are read as S-expressions and then elaborated into 'Command's
-- whose terms are sort-checked core expressions. Macros introduced by
-- @define-fun@ and @define-const@, local bindings of @let@ and sort
-- abbreviations of @define-sort@ are expanded at their use sites.
-- Single-constructor datatypes are read as records. Declarations are
-- scoped: @pop@ removes the declarations made since the matching @push@.
--
-- Regular expressions are supported as ground terms: symbols of sort
-- @RegLan@ cannot be declared.
--
-- Not supported: quantifiers, real arithmetic, parametric sorts and
-- multi-constructor datatypes.
module HSMT.SMTLib.Parser
( -- * Scripts
parseScript
-- * Command by command
, ParseState
, initialParseState
, parseCommand
, parseTerm
, parseSort
, declareConstants
-- * S-expressions
, SExpr (..)
, parseSExprs
, parseSExprsPartial
, showS
) where
import Control.Monad (foldM, unless, when)
import Data.Char (chr, isDigit, isHexDigit, isSpace)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Text (Text)
import qualified Data.Text as T
import Numeric (readHex)
import HSMT.Core.Expr
import HSMT.Core.Float (RoundingMode (..))
import qualified HSMT.Core.Float as F
import HSMT.Core.Op
import HSMT.Core.Sort
import HSMT.Core.Typing
import HSMT.SMTLib.Syntax
-------------------------------------------------------------------------------
-- S-expressions
-- | A raw S-expression, before elaboration into commands.
data SExpr
= SSym Text
-- ^ Simple or quoted symbol (quotes removed).
| SKey Text
-- ^ Keyword, without the leading colon.
| SNum Integer
-- ^ Decimal numeral.
| SBin Text
-- ^ Binary literal digits (after @#b@).
| SHex Text
-- ^ Hexadecimal literal digits (after @#x@).
| SStr Text
-- ^ String literal, already unescaped.
| SList [SExpr]
-- ^ Parenthesized list.
deriving (Eq, Show)
-- | Read a sequence of S-expressions.
parseSExprs :: Text -> Either Text [SExpr]
parseSExprs t = case parseSExprsPartial t of
(es, Nothing) -> Right es
(_, Just err) -> Left err
-- | Read S-expressions up to the first syntax error, returning the
-- expressions before it and the error, if any.
parseSExprsPartial :: Text -> ([SExpr], Maybe Text)
parseSExprsPartial = go []
where
go acc t = case skip t of
t' | T.null t' -> (reverse acc, Nothing)
t' -> case sexpr t' of
Left err -> (reverse acc, Just err)
Right (e, rest) -> go (e : acc) rest
-- Whitespace and comments.
skip t =
let t' = T.dropWhile isSpace t
in case T.uncons t' of
Just (';', r) -> skip (T.dropWhile (/= '\n') r)
_ -> t'
sexpr t = case T.uncons t of
Just ('(', r) -> list [] (skip r)
Just (')', _) -> Left "unexpected ')'"
Just ('|', r) ->
let (s, r') = T.break (== '|') r
in if T.null r' then Left "unterminated quoted symbol" else Right (SSym s, T.drop 1 r')
Just ('"', r) -> stringLit [] r
Just (':', r) -> let (k, r') = token r in Right (SKey k, r')
Just ('#', r) -> case T.uncons r of
Just ('b', r') -> let (d, r'') = token r' in Right (SBin d, r'')
Just ('x', r') -> let (d, r'') = token r' in Right (SHex d, r'')
_ -> Left "invalid # literal"
Just _ ->
let (tok, r) = token t
in if T.all isDigit tok
then Right (SNum (read (T.unpack tok)), r)
else Right (SSym tok, r)
Nothing -> Left "unexpected end of input"
list acc t = case T.uncons t of
Just (')', r) -> Right (SList (reverse acc), r)
Nothing -> Left "unbalanced parentheses"
_ -> do
(e, r) <- sexpr t
list (e : acc) (skip r)
token = T.break (\c -> isSpace c || c `elem` ("()|\";" :: String))
stringLit acc t =
let (chunk, r) = T.break (== '"') t
in case T.uncons r of
Nothing -> Left "unterminated string literal"
Just (_, r') -> case T.uncons r' of
Just ('"', r'') -> stringLit (acc <> [chunk, "\""]) r''
_ -> do
s <- unescape (T.concat (acc <> [chunk]))
Right (SStr s, r')
-- | Resolve the @\\u{d...}@ and @\\udddd@ escapes of SMT-LIB 2.6.
unescape :: Text -> Either Text Text
unescape t = case T.breakOn "\\u" t of
(pre, rest)
| T.null rest -> Right pre
| otherwise -> do
let body = T.drop 2 rest
(c, rest') <- case T.uncons body of
Just ('{', r) ->
let (digits, r') = T.break (== '}') r
in if T.null r' || T.null digits || T.length digits > 5 || not (T.all isHexDigit digits)
then Right ('\\', T.drop 1 rest)
else Right (hexChar digits, T.drop 1 r')
_ ->
let digits = T.take 4 body
in if T.length digits == 4 && T.all isHexDigit digits
then Right (hexChar digits, T.drop 4 body)
else Right ('\\', T.drop 1 rest)
((pre <> T.singleton c) <>) <$> unescape rest'
where
hexChar ds = case readHex (T.unpack ds) of
[(n, "")] -> chr n
_ -> '\\'
-------------------------------------------------------------------------------
-- Elaboration
data Env = Env
{ envSorts :: Map Text Sort
, envFuns :: Map Text Symbol
, envMacros :: Map Text ([Symbol], Expr)
, envCtors :: Map Text [Text]
-- ^ Record constructors and their field names.
, envSelectors :: Map Text Text
-- ^ Record selectors and their field names.
, envLocals :: Map Text (Expr, Sort)
-- ^ Variables bound by @let@.
}
emptyEnv :: Env
emptyEnv = Env Map.empty Map.empty Map.empty Map.empty Map.empty Map.empty
-- | The declarations in scope, and those of the enclosing assertion levels
-- (innermost first), restored by @pop@.
data ParseState = ParseState Env [Env]
-- | The state at the start of a script: no declarations, no open
-- assertion levels.
initialParseState :: ParseState
initialParseState = ParseState emptyEnv []
type P a = Either Text a
-- | Parse and elaborate a script. The first error aborts the parse.
parseScript :: Text -> Either Text [Command]
parseScript txt = do
ses <- parseSExprs txt
(_, cmds) <- foldM step (initialParseState, []) ses
pure (reverse cmds)
where
step (st, acc) se = do
(st', cs) <- parseCommand st se
pure (st', reverse cs <> acc)
-- | Elaborate one command. An error leaves the state unchanged (the caller
-- keeps the old one), as SMT-LIB asks of solvers that continue after an
-- error.
parseCommand :: ParseState -> SExpr -> Either Text (ParseState, [Command])
parseCommand st@(ParseState env saved) se =
either (Left . (<> (" in " <> showS se))) Right $ case se of
SList [SSym "push"] -> push 1
SList [SSym "push", SNum k] -> push k
SList [SSym "pop"] -> pop 1
SList [SSym "pop", SNum k] -> pop k
SList [SSym "reset"] -> Right (initialParseState, [Reset])
SList [SSym "reset-assertions"] -> Right (initialParseState, [ResetAssertions])
_ -> do
(env', cs) <- command env se
Right (ParseState env' saved, cs)
where
push k = Right (ParseState env (replicate (fromInteger k) env <> saved), [Push (fromInteger k)])
pop k
| k == 0 = Right (st, [Pop 0])
| fromInteger k <= length saved =
Right (ParseState (saved !! (fromInteger k - 1)) (drop (fromInteger k) saved), [Pop (fromInteger k)])
| otherwise = Left "pop: not enough assertion levels"
-- | Elaborate a term in the declarations of the state, returning it with
-- its sort.
parseTerm :: ParseState -> SExpr -> Either Text (Expr, Sort)
parseTerm (ParseState env _) = term env
-- | Elaborate a sort in the declarations of the state.
parseSort :: ParseState -> SExpr -> Either Text Sort
parseSort (ParseState env _) = sortOfS env
-- | Make nullary symbols known to later elaborations, shadowing earlier
-- symbols of the same names.
declareConstants :: [Symbol] -> ParseState -> ParseState
declareConstants syms (ParseState env saved) =
ParseState
env
{ envFuns = Map.union (Map.fromList [(symName s, s) | s <- syms]) (envFuns env)
, envMacros = foldr (Map.delete . symName) (envMacros env) syms
}
saved
command :: Env -> SExpr -> P (Env, [Command])
command env = \case
SList [SSym "set-logic", SSym l] -> ok [SetLogic l]
SList [SSym "set-option", SKey o, v] -> ok [SetOption o (showS v)]
SList [SSym "set-info", SKey o, v] -> ok [SetInfo o (showS v)]
SList [SSym "set-info", SKey o] -> ok [SetInfo o ""]
SList [SSym "declare-sort", SSym n] -> declareSort n
SList [SSym "declare-sort", SSym n, SNum 0] -> declareSort n
SList [SSym "declare-const", SSym n, s] -> declareFun n [] s
SList [SSym "declare-fun", SSym n, SList as, s] -> declareFun n as s
SList [SSym "define-fun", SSym n, SList ps, s, body] -> do
fresh n
result <- sortOfS env s
params <- traverse param ps
let scope = Map.fromList [(symName p, p) | p <- params]
(e, s') <- term env {envFuns = Map.union scope (envFuns env)} body
unless (s' == result) $ Left "body sort does not match the declared sort"
let sym = Symbol n (map symResult params) result
pure (env {envMacros = Map.insert n (params, e) (envMacros env)}, [DefineFun sym params e])
SList [SSym "declare-datatypes", SList [SList [SSym n, SNum 0]], SList [SList [SList (SSym c : fields)]]] ->
declareRecord n c fields
SList [SSym "declare-datatype", SSym n, SList [SList (SSym c : fields)]] ->
declareRecord n c fields
SList [SSym "assert", SList [SSym "!", t, SKey "named", SSym n]] -> do
fresh n
(e, s) <- term env t
unless (s == BoolSort) $ Left "assertion is not Boolean"
-- The name also stands for the term, like a nullary macro.
pure (env {envMacros = Map.insert n ([], e) (envMacros env)}, [AssertNamed n e])
SList [SSym "assert", t] -> do
(e, s) <- term env t
unless (s == BoolSort) $ Left "assertion is not Boolean"
ok [Assert e]
SList [SSym "define-const", SSym n, s, body] -> do
fresh n
result <- sortOfS env s
(e, s') <- term env body
unless (s' == result) $ Left "body sort does not match the declared sort"
pure (env {envMacros = Map.insert n ([], e) (envMacros env)}, [DefineFun (Symbol n [] result) [] e])
SList [SSym "define-sort", SSym n, SList [], s] -> do
when (Map.member n (envSorts env)) $ Left ("sort already declared: " <> n)
s' <- sortOfS env s
pure (env {envSorts = Map.insert n s' (envSorts env)}, [])
SList [SSym "define-sort", SSym _, SList _, _] -> Left "parametric sorts are not supported"
SList [SSym "check-sat"] -> ok [CheckSat]
SList [SSym "check-sat-assuming", SList ts] -> do
es <- traverse (term env) ts
unless (all ((== BoolSort) . snd) es) $ Left "assumption is not Boolean"
ok [CheckSatAssuming (map fst es)]
SList [SSym "get-model"] -> ok [GetModel]
SList [SSym "get-value", SList ts@(_ : _)] -> do
es <- traverse (term env) ts
ok [GetValue (map fst es)]
SList [SSym "get-assertions"] -> ok [GetAssertions]
SList [SSym "get-info", SKey k] -> ok [GetInfo k]
SList [SSym "get-option", SKey k] -> ok [GetOption k]
SList [SSym "get-unsat-core"] -> ok [GetUnsatCore]
SList [SSym "echo", SStr s] -> ok [Echo s]
SList [SSym "exit"] -> ok [Exit]
SList (SSym c : _) -> Left ("unsupported command: " <> c)
_ -> Left "malformed command"
where
ok cs = Right (env, cs)
fresh n =
when (Map.member n (envFuns env) || Map.member n (envMacros env)) $
Left ("symbol already declared: " <> n)
declareSort n = do
when (Map.member n (envSorts env)) $ Left ("sort already declared: " <> n)
pure (env {envSorts = Map.insert n (UninterpretedSort n) (envSorts env)}, [DeclareSort n])
declareFun n as s = do
fresh n
args <- traverse (sortOfS env) as
result <- sortOfS env s
when (RegLanSort `elem` (result : args)) $ Left "symbols of sort RegLan are not supported"
let sym = Symbol n args result
pure (env {envFuns = Map.insert n sym (envFuns env)}, [DeclareFun sym])
param = \case
SList [SSym p, s] -> Symbol p [] <$> sortOfS env s
_ -> Left "malformed parameter"
-- Selectors named "<datatype>.<field>" (as produced by the printer) give
-- the field name; other selectors are used as field names verbatim.
declareRecord n c fields = do
when (Map.member n (envSorts env)) $ Left ("sort already declared: " <> n)
sels <- traverse field fields
let fieldName sel = maybe sel id (T.stripPrefix (n <> ".") sel)
fs = [(fieldName sel, s) | (sel, s) <- sels]
sort = RecordSort fs
pure
( env
{ envSorts = Map.insert n sort (envSorts env)
, envCtors = Map.insert c (map fst fs) (envCtors env)
, envSelectors =
Map.union (Map.fromList [(sel, fieldName sel) | (sel, _) <- sels]) (envSelectors env)
}
, [DeclareRecord fs]
)
field = \case
SList [SSym sel, s] -> (,) sel <$> sortOfS env s
_ -> Left "malformed datatype field"
sortOfS :: Env -> SExpr -> P Sort
sortOfS env = \case
SSym "Bool" -> pure BoolSort
SSym "Int" -> pure IntSort
SSym "String" -> pure StringSort
SSym n | Just s <- Map.lookup n (envSorts env) -> pure s
SList [SSym "_", SSym "BitVec", SNum w] | w > 0 -> pure (BVSort (fromInteger w))
SList [SSym "Array", i, e] -> ArraySort <$> sortOfS env i <*> sortOfS env e
SList [SSym "_", SSym "FloatingPoint", SNum eb, SNum sb]
| eb >= 2 && sb >= 2 -> pure (FPSort (fromInteger eb) (fromInteger sb))
SSym "Float16" -> pure (FPSort 5 11)
SSym "Float32" -> pure (FPSort 8 24)
SSym "Float64" -> pure (FPSort 11 53)
SSym "Float128" -> pure (FPSort 15 113)
SSym "RoundingMode" -> pure RoundingModeSort
SSym "RegLan" -> pure RegLanSort
s -> Left ("unknown sort: " <> showS s)
sortOfE :: Expr -> P Sort
sortOfE e = either (Left . seMessage) Right (sortOf e)
-- | Elaborate a term, returning it with its sort.
term :: Env -> SExpr -> P (Expr, Sort)
term env = \case
SNum n -> typed (IntConst n) []
SBin ds
| not (T.null ds) && T.all (`elem` ['0', '1']) ds ->
typed (BVConst (T.length ds) (T.foldl' (\a c -> 2 * a + (if c == '1' then 1 else 0)) 0 ds)) []
SHex ds
| [(v, "")] <- readHex (T.unpack ds), not (T.null ds) ->
typed (BVConst (4 * T.length ds) v) []
SStr s -> typed (StrConst s) []
SSym "true" -> typed (BoolConst True) []
SSym "false" -> typed (BoolConst False) []
SSym n | Just rm <- lookup n roundingModes -> typed (RMConst rm) []
SSym n -> applyName n []
SList [SSym "_", SSym bv, SNum w]
| Just digits <- T.stripPrefix "bv" bv
, not (T.null digits) && T.all isDigit digits ->
typed (BVConst (fromInteger w) (read (T.unpack digits))) []
-- Floating-point special values.
SList [SSym "_", SSym special, SNum eb, SNum sb]
| Just v <- lookup special fpSpecials
, eb >= 2 && sb >= 2 ->
let (e, s) = (fromInteger eb, fromInteger sb)
in typed (FPConst e s (F.encode e s v)) []
-- A floating-point literal from binary fields.
SList [SSym "fp", bitsOf -> Just sg, bitsOf -> Just ex, bitsOf -> Just sig]
| T.length sg == 1 && T.length ex >= 2 && T.length sig >= 1 ->
let (e, s) = (T.length ex, T.length sig + 1)
in typed (FPConst e s (F.fpFromFields e s (binValue sg) (binValue ex) (binValue sig))) []
SList (SList [SSym "_", SSym ix, SNum a, SNum b] : args@(_ : _))
| ix == "to_fp" -> traverse (term env) args >>= typed (ToFP (fromInteger a) (fromInteger b))
| ix == "to_fp_unsigned" -> traverse (term env) args >>= typed (ToFPUnsigned (fromInteger a) (fromInteger b))
SList (SList [SSym "_", SSym "re.loop", SNum i, SNum j] : args@(_ : _)) ->
traverse (term env) args >>= typed (ReLoop (fromInteger i) (fromInteger j))
SList (SList [SSym "_", SSym ix, SNum w] : args@(_ : _))
| ix == "re.^" -> traverse (term env) args >>= typed (RePower (fromInteger w))
| ix == "fp.to_ubv" -> traverse (term env) args >>= typed (FPToUBV (fromInteger w))
| ix == "fp.to_sbv" -> traverse (term env) args >>= typed (FPToSBV (fromInteger w))
-- A negative numeral.
SList [SSym "-", SNum n] -> typed (IntConst (negate n)) []
SList [SList [SSym "as", SSym "const", s], v] ->
sortOfS env s >>= \case
ArraySort i e -> do
x <- term env v
unless (snd x == e) $ Left "const array element of the wrong sort"
typed (ConstArray i) [x]
_ -> Left "const expects an array sort"
SList [SList [SSym "_", SSym ix, SNum a, SNum b], t]
| ix == "extract" -> indexed (BVExtract (fromInteger a) (fromInteger b)) t
SList [SList [SSym "_", SSym ix, SNum a], t]
| ix == "zero_extend" -> indexed (BVZeroExtend (fromInteger a)) t
| ix == "sign_extend" -> indexed (BVSignExtend (fromInteger a)) t
SList [SSym "let", SList binds@(_ : _), body] -> do
bound <- traverse binding binds
term env {envLocals = Map.union (Map.fromList bound) (envLocals env)} body
SList (SSym q : _) | q `elem` ["forall", "exists"] -> Left "quantifiers are not supported"
SList [SList [SSym "_", SSym ix, SNum k], t]
| ix `elem` ["rotate_left", "rotate_right", "repeat"] -> do
x@(e, s) <- term env t
case s of
BVSort w
| ix == "repeat" ->
if k < 1 then Left "repeat: the count must be positive" else foldM (\acc _ -> typed BVConcat [acc, x]) x [2 .. k]
| otherwise ->
-- Rotating left by i is rotating right by w - i.
let i = fromInteger (if ix == "rotate_left" then k `mod` toInteger w else (toInteger w - k `mod` toInteger w) `mod` toInteger w)
in if i == 0
then pure x
else do
hi <- typed (BVExtract (w - 1 - i) 0) [(e, s)]
lo <- typed (BVExtract (w - 1) (w - i)) [(e, s)]
typed BVConcat [hi, lo]
_ -> Left (ix <> " expects a bit-vector")
-- Annotations other than the names of assertions are ignored.
SList (SSym "!" : t : _) -> term env t
SList (SSym f : args) | not (null args) -> traverse (term env) args >>= applyName f
s -> Left ("malformed term: " <> showS s)
where
indexed op t = term env t >>= \x -> typed op [x]
binding = \case
SList [SSym x, t] -> (,) x <$> term env t
_ -> Left "malformed let binding"
applyName n args
| null args, Just x <- Map.lookup n (envLocals env) = pure x
| Just sym <- Map.lookup n (envFuns env) = typed (Uninterpreted sym) args
| Just (params, body) <- Map.lookup n (envMacros env) = do
unless (map snd args == map symResult params) $
Left ("wrong number or sorts of arguments to " <> n)
let e = substitute (Map.fromList (zip params (map fst args))) body
(,) e <$> sortOfE e
| Just names <- Map.lookup n (envCtors env) = typed (RecordMk names) args
| Just f <- Map.lookup n (envSelectors env) = typed (RecordGet f) args
| n == "-" && length args == 1 = typed Neg args
| Just op <- lookup n negated = typed op args >>= \x -> typed BVNot [x]
| n == "bvcomp" = do
c <- typed Eq args
one <- typed (BVConst 1 1) []
zero <- typed (BVConst 1 0) []
typed Ite [c, one, zero]
| Just op <- Map.lookup n builtins = typed op args
| otherwise = Left ("unknown symbol: " <> n)
typed :: Op -> [(Expr, Sort)] -> P (Expr, Sort)
typed op args = case inferSort op (map snd args) of
Right s -> Right (App op (map fst args), s)
Left err -> Left (opName op <> ": " <> seMessage err)
-- | Replace parameters (nullary uninterpreted symbols) by expressions.
substitute :: Map Symbol Expr -> Expr -> Expr
substitute sub = go
where
go (App op@(Uninterpreted sym) [])
| Just e <- Map.lookup sym sub = e
| otherwise = App op []
go (App op args) = App op (map go args)
builtins :: Map Text Op
builtins =
Map.fromList
[ (opName op, op)
| op <-
[ Not, And, Or, Xor, Implies, Ite, Eq, Distinct
, Add, Sub, Mul, IntDiv, IntMod, Abs, Le, Lt, Ge, Gt
, BVNot, BVAnd, BVOr, BVXor, BVNeg, BVAdd, BVSub, BVMul
, BVUDiv, BVURem, BVSDiv, BVSRem, BVSMod, BVShl, BVLShr, BVAShr, BVConcat
, BVULt, BVULe, BVUGt, BVUGe, BVSLt, BVSLe, BVSGt, BVSGe
, Select, Store
, StrConcat, StrLen, StrAt, StrSubstr, StrContains, StrPrefixOf, StrSuffixOf
, StrIndexOf, StrReplace, StrToInt, StrFromInt, StrLt, StrLe
, StrToRe, StrInRe, ReNone, ReAll, ReAllChar, ReConcat, ReUnion, ReInter
, ReStar, RePlus, ReOpt, ReRange, ReComp, ReDiff
, FPFromFields, FPAbs, FPNeg, FPAdd, FPSub, FPMul, FPDiv, FPFma, FPSqrt, FPRem
, FPRoundToIntegral, FPMin, FPMax, FPLeq, FPLt, FPGeq, FPGt, FPEq
, FPIsNormal, FPIsSubnormal, FPIsZero, FPIsInfinite, FPIsNaN, FPIsNegative, FPIsPositive
]
]
<> Map.fromList
[ ("str.to.int", StrToInt)
, ("int.to.str", StrFromInt)
, ("str.to.re", StrToRe)
, ("str.in.re", StrInRe)
]
-- | Bit-vector operators defined as the complement of another.
negated :: [(Text, Op)]
negated = [("bvnand", BVAnd), ("bvnor", BVOr), ("bvxnor", BVXor)]
roundingModes :: [(Text, RoundingMode)]
roundingModes =
[ ("RNE", RNE)
, ("RNA", RNA)
, ("RTP", RTP)
, ("RTN", RTN)
, ("RTZ", RTZ)
, ("roundNearestTiesToEven", RNE)
, ("roundNearestTiesToAway", RNA)
, ("roundTowardPositive", RTP)
, ("roundTowardNegative", RTN)
, ("roundTowardZero", RTZ)
]
fpSpecials :: [(Text, F.FP)]
fpSpecials =
[ ("+zero", F.Zero False)
, ("-zero", F.Zero True)
, ("+oo", F.Inf False)
, ("-oo", F.Inf True)
, ("NaN", F.NaN)
]
-- | The binary digits of a bit-vector literal (hexadecimal digits stand for
-- four bits each, as Z3 prints floating-point fields).
bitsOf :: SExpr -> Maybe Text
bitsOf = \case
SBin d -> Just d
SHex d
| not (T.null d) && T.all isHexDigit d -> Just (T.concatMap hexBits d)
_ -> Nothing
where
hexBits c = case readHex [c] of
[(n, "")] -> T.pack [if odd (n `div` (2 ^ k) :: Int) then '1' else '0' | k <- [3, 2, 1, 0 :: Int]]
_ -> "0000"
binValue :: Text -> Integer
binValue = T.foldl' (\a c -> 2 * a + (if c == '1' then 1 else 0)) 0
-- | Render an S-expression back to text, for error messages and options.
showS :: SExpr -> Text
showS = \case
SSym s -> s
SKey k -> ":" <> k
SNum n -> T.pack (show n)
SBin d -> "#b" <> d
SHex d -> "#x" <> d
SStr s -> T.pack (show s)
SList xs -> "(" <> T.unwords (map showS xs) <> ")"