{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
module UnitypeSupport
( Json (..)
, parseJson
, renderJson
, ToJson (..)
, FromJson (..)
, MapKey (..)
, object
, field
, asObject
, required
, optional
, variant
, asVariant
, payload
, unknownTag
, asText
, unknownName
, firstOf
) where
import Data.Bits (shiftL, shiftR, (.&.), (.|.))
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Char (chr, digitToInt, intToDigit, isDigit, isHexDigit, ord)
import Data.Int (Int32, Int64)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Text (Text)
import qualified Data.Text as T
import Data.Void (Void, absurd)
import Data.Word (Word8)
import Text.Read (readMaybe)
data Json
= JNull
| JBool Bool
| JInt Integer
| JFloat Double
| JString Text
| JArray [Json]
| JObject (Map Text Json)
deriving (Eq, Show)
class ToJson a where
toJson :: a -> Json
class FromJson a where
fromJson :: Json -> Either String a
class Ord k => MapKey k where
keyText :: k -> Text
keyFrom :: Text -> Either String k
parseJson :: Text -> Either String Json
parseJson input = do
(v, rest) <- value (skipSpace input)
case T.uncons (skipSpace rest) of
Nothing -> Right v
Just (c, _) -> Left ("unexpected `" ++ [c] ++ "` after the value")
type Parse a = Text -> Either String (a, Text)
skipSpace :: Text -> Text
skipSpace = T.dropWhile (\c -> c == ' ' || c == '\n' || c == '\t' || c == '\r')
value :: Parse Json
value t = case T.uncons t of
Nothing -> Left "unexpected end of input"
Just ('n', _) -> word "null" JNull t
Just ('t', _) -> word "true" (JBool True) t
Just ('f', _) -> word "false" (JBool False) t
Just ('"', rest) -> do
(s, r) <- stringBody rest
Right (JString s, r)
Just ('[', rest) -> array (skipSpace rest)
Just ('{', rest) -> members (skipSpace rest)
Just (c, _)
| c == '-' || isDigit c -> number t
| otherwise -> Left ("unexpected `" ++ [c] ++ "`")
word :: Text -> Json -> Parse Json
word spelled result t = case T.stripPrefix spelled t of
Just rest -> Right (result, rest)
Nothing -> Left ("expected `" ++ T.unpack spelled ++ "`")
array :: Parse Json
array t = case T.uncons t of
Just (']', rest) -> Right (JArray [], rest)
_ -> go [] t
where
go acc s = do
(v, r) <- value s
case T.uncons (skipSpace r) of
Just (',', r') -> go (v : acc) (skipSpace r')
Just (']', r') -> Right (JArray (reverse (v : acc)), r')
_ -> Left "expected `,` or `]` in an array"
members :: Parse Json
members t = case T.uncons t of
Just ('}', rest) -> Right (JObject Map.empty, rest)
_ -> go [] t
where
go acc s = case T.uncons s of
Just ('"', afterQuote) -> do
(key, r) <- stringBody afterQuote
case T.uncons (skipSpace r) of
Just (':', r') -> do
(v, r'') <- value (skipSpace r')
case T.uncons (skipSpace r'') of
Just (',', r3) -> go ((key, v) : acc) (skipSpace r3)
Just ('}', r3) -> Right (JObject (Map.fromList (reverse ((key, v) : acc))), r3)
_ -> Left "expected `,` or `}` in an object"
_ -> Left "expected `:` after a property name"
_ -> Left "expected a property name in an object"
stringBody :: Parse Text
stringBody = go []
where
go acc t =
let (plain, rest) = T.break (\c -> c == '"' || c == '\\') t
in case T.uncons rest of
Nothing -> Left "unterminated string"
Just ('"', r) -> Right (T.concat (reverse (plain : acc)), r)
Just (_, r) -> do
(c, r') <- escape r
go (c : plain : acc) r'
escape :: Parse Text
escape t = case T.uncons t of
Just ('"', r) -> Right ("\"", r)
Just ('\\', r) -> Right ("\\", r)
Just ('/', r) -> Right ("/", r)
Just ('b', r) -> Right ("\b", r)
Just ('f', r) -> Right ("\f", r)
Just ('n', r) -> Right ("\n", r)
Just ('r', r) -> Right ("\r", r)
Just ('t', r) -> Right ("\t", r)
Just ('u', r) -> do
(hi, r1) <- hex4 r
if hi >= 0xD800 && hi <= 0xDBFF
then case T.stripPrefix "\\u" r1 of
Just r2 -> do
(lo, r3) <- hex4 r2
if lo >= 0xDC00 && lo <= 0xDFFF
then Right (T.singleton (chr (0x10000 + ((hi - 0xD800) `shiftL` 10) + (lo - 0xDC00))), r3)
else Left "a high surrogate has to be followed by a low one"
Nothing -> Left "a high surrogate has to be followed by a low one"
else
if hi >= 0xDC00 && hi <= 0xDFFF
then Left "a low surrogate has nothing before it"
else Right (T.singleton (chr hi), r1)
_ -> Left "unknown escape in a string"
hex4 :: Text -> Either String (Int, Text)
hex4 t =
let (digits, rest) = T.splitAt 4 t
in if T.length digits == 4 && T.all isHexDigit digits
then Right (T.foldl' (\n c -> n * 16 + digitToInt c) 0 digits, rest)
else Left "`\\u` needs four hexadecimal digits"
number :: Parse Json
number t =
let (sign, r0) = case T.uncons t of
Just ('-', r) -> ("-", r)
_ -> ("", t)
(whole, r1) = T.span isDigit r0
(fraction, r2) = case T.uncons r1 of
Just ('.', r) -> let (d, r') = T.span isDigit r in (Just d, r')
_ -> (Nothing, r1)
(power, r3) = case T.uncons r2 of
Just (e, r)
| e == 'e' || e == 'E' ->
let (s, afterSign) = case T.uncons r of
Just ('-', q) -> ("-", q)
Just ('+', q) -> ("", q)
_ -> ("", r)
(d, r') = T.span isDigit afterSign
in (Just (s <> d, T.null d), r')
_ -> (Nothing, r2)
in if T.null whole
then Left "a number needs digits"
else
if fraction == Just "" || fmap snd power == Just True
then Left "a number needs digits after its `.` or its exponent"
else case (fraction, power) of
(Nothing, Nothing) -> case readMaybe (T.unpack (sign <> whole)) of
Just n -> Right (JInt n, r3)
Nothing -> Left "that is not a number"
_ ->
let spelled = sign <> whole <> maybe "" ("." <>) fraction <> maybe "" (("e" <>) . fst) power
in case readMaybe (T.unpack spelled) of
Just d
| isInfinite (d :: Double) -> Left "that number is too large for a float"
| otherwise -> Right (JFloat d, r3)
Nothing -> Left "that is not a number"
renderJson :: Json -> Either String Text
renderJson JNull = Right "null"
renderJson (JBool b) = Right (if b then "true" else "false")
renderJson (JInt n) = Right (T.pack (show n))
renderJson (JFloat d)
| isNaN d || isInfinite d = Left "NaN and the infinities cannot be written as JSON"
| otherwise = Right (T.pack (show d))
renderJson (JString s) = Right (quote s)
renderJson (JArray xs) = do
parts <- traverse renderJson xs
Right ("[" <> T.intercalate "," parts <> "]")
renderJson (JObject o) = do
parts <- traverse (\(k, v) -> (\r -> quote k <> ":" <> r) <$> renderJson v) (Map.toList o)
Right ("{" <> T.intercalate "," parts <> "}")
quote :: Text -> Text
quote s = "\"" <> T.concatMap escaped s <> "\""
where
escaped '"' = "\\\""
escaped '\\' = "\\\\"
escaped '\n' = "\\n"
escaped '\r' = "\\r"
escaped '\t' = "\\t"
escaped c
| ord c < 0x20 = T.pack ("\\u00" ++ [intToDigit (ord c `shiftR` 4), intToDigit (ord c .&. 15)])
| otherwise = T.singleton c
expected :: String -> Json -> String
expected what found = "expected " ++ what ++ ", found " ++ describe found
describe :: Json -> String
describe JNull = "null"
describe (JBool _) = "a boolean"
describe (JInt _) = "an integer"
describe (JFloat _) = "a float"
describe (JString _) = "a string"
describe (JArray _) = "an array"
describe (JObject _) = "an object"
instance ToJson Json where
toJson = id
instance FromJson Json where
fromJson = Right
instance ToJson Bool where
toJson = JBool
instance FromJson Bool where
fromJson (JBool b) = Right b
fromJson j = Left (expected "a boolean" j)
instance ToJson Int32 where
toJson = JInt . toInteger
instance FromJson Int32 where
fromJson = integral "an i32"
instance ToJson Int64 where
toJson = JInt . toInteger
instance FromJson Int64 where
fromJson = integral "an i64"
integral :: forall a. (Integral a, Bounded a) => String -> Json -> Either String a
integral what (JInt n)
| n < toInteger (minBound :: a) || n > toInteger (maxBound :: a) =
Left (show n ++ " does not fit " ++ what)
| otherwise = Right (fromInteger n)
integral what j = Left (expected what j)
instance ToJson Double where
toJson = JFloat
instance FromJson Double where
fromJson (JFloat d) = Right d
fromJson (JInt n)
| abs n <= 2 ^ (53 :: Int) = Right (fromInteger n)
| otherwise = Left (show n ++ " is more than a float holds exactly")
fromJson j = Left (expected "a number" j)
instance ToJson Text where
toJson = JString
instance FromJson Text where
fromJson (JString s) = Right s
fromJson j = Left (expected "a string" j)
instance ToJson () where
toJson () = JNull
instance FromJson () where
fromJson JNull = Right ()
fromJson j = Left (expected "null" j)
instance ToJson Void where
toJson = absurd
instance FromJson Void where
fromJson _ = Left "nothing is a value of this type"
instance ToJson ByteString where
toJson = JString . encodeBase64
instance FromJson ByteString where
fromJson (JString s) = decodeBase64 s
fromJson j = Left (expected "base64 text" j)
instance ToJson a => ToJson [a] where
toJson = JArray . map toJson
instance FromJson a => FromJson [a] where
fromJson (JArray xs) = traverse (\(i, x) -> within ("[" ++ show i ++ "]") (fromJson x)) (zip [0 :: Int ..] xs)
fromJson j = Left (expected "an array" j)
instance ToJson a => ToJson (Maybe a) where
toJson = maybe JNull toJson
instance FromJson a => FromJson (Maybe a) where
fromJson JNull = Right Nothing
fromJson j = Just <$> fromJson j
instance (MapKey k, ToJson v) => ToJson (Map k v) where
toJson m = JObject (Map.fromList [(keyText k, toJson v) | (k, v) <- Map.toList m])
instance (MapKey k, FromJson v) => FromJson (Map k v) where
fromJson (JObject o) = Map.fromList <$> traverse entry (Map.toList o)
where
entry (k, v) = do
key <- within (show k) (keyFrom k)
v' <- within (show k) (fromJson v)
Right (key, v')
fromJson j = Left (expected "an object" j)
instance MapKey Text where
keyText = id
keyFrom = Right
instance MapKey Int32 where
keyText = integerText
keyFrom = integerFrom "an i32"
instance MapKey Int64 where
keyText = integerText
keyFrom = integerFrom "an i64"
integerText :: Integral a => a -> Text
integerText = T.pack . show . toInteger
integerFrom :: forall a. (Integral a, Bounded a) => String -> Text -> Either String a
integerFrom what t = case T.unpack t of
s
| digits s, Just n <- readMaybe s ->
if n < toInteger (minBound :: a) || n > toInteger (maxBound :: a)
then Left (s ++ " does not fit " ++ what)
else Right (fromInteger n)
| otherwise -> Left (show t ++ " is not " ++ what)
where
digits "0" = True
digits ('-' : rest@(c : _)) = c /= '0' && all isDigit rest
digits s@(c : _) = c /= '0' && all isDigit s
digits [] = False
instance (ToJson a, ToJson b) => ToJson (a, b) where
toJson (a, b) = JArray [toJson a, toJson b]
instance (FromJson a, FromJson b) => FromJson (a, b) where
fromJson (JArray [a, b]) = (,) <$> at 0 a <*> at 1 b
fromJson j = Left (expected "an array of 2" j)
instance (ToJson a, ToJson b, ToJson c) => ToJson (a, b, c) where
toJson (a, b, c) = JArray [toJson a, toJson b, toJson c]
instance (FromJson a, FromJson b, FromJson c) => FromJson (a, b, c) where
fromJson (JArray [a, b, c]) = (,,) <$> at 0 a <*> at 1 b <*> at 2 c
fromJson j = Left (expected "an array of 3" j)
instance (ToJson a, ToJson b, ToJson c, ToJson d) => ToJson (a, b, c, d) where
toJson (a, b, c, d) = JArray [toJson a, toJson b, toJson c, toJson d]
instance (FromJson a, FromJson b, FromJson c, FromJson d) => FromJson (a, b, c, d) where
fromJson (JArray [a, b, c, d]) = (,,,) <$> at 0 a <*> at 1 b <*> at 2 c <*> at 3 d
fromJson j = Left (expected "an array of 4" j)
instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e) => ToJson (a, b, c, d, e) where
toJson (a, b, c, d, e) = JArray [toJson a, toJson b, toJson c, toJson d, toJson e]
instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e) => FromJson (a, b, c, d, e) where
fromJson (JArray [a, b, c, d, e]) = (,,,,) <$> at 0 a <*> at 1 b <*> at 2 c <*> at 3 d <*> at 4 e
fromJson j = Left (expected "an array of 5" j)
instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e, ToJson f) => ToJson (a, b, c, d, e, f) where
toJson (a, b, c, d, e, f) = JArray [toJson a, toJson b, toJson c, toJson d, toJson e, toJson f]
instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f) => FromJson (a, b, c, d, e, f) where
fromJson (JArray [a, b, c, d, e, f]) = (,,,,,) <$> at 0 a <*> at 1 b <*> at 2 c <*> at 3 d <*> at 4 e <*> at 5 f
fromJson j = Left (expected "an array of 6" j)
instance (ToJson a, ToJson b, ToJson c, ToJson d, ToJson e, ToJson f, ToJson g) => ToJson (a, b, c, d, e, f, g) where
toJson (a, b, c, d, e, f, g) = JArray [toJson a, toJson b, toJson c, toJson d, toJson e, toJson f, toJson g]
instance (FromJson a, FromJson b, FromJson c, FromJson d, FromJson e, FromJson f, FromJson g) => FromJson (a, b, c, d, e, f, g) where
fromJson (JArray [a, b, c, d, e, f, g]) = (,,,,,,) <$> at 0 a <*> at 1 b <*> at 2 c <*> at 3 d <*> at 4 e <*> at 5 f <*> at 6 g
fromJson j = Left (expected "an array of 7" j)
at :: FromJson a => Int -> Json -> Either String a
at n = within ("." ++ show n) . fromJson
within :: String -> Either String a -> Either String a
within place = either (\e -> Left (place ++ ": " ++ e)) Right
alphabet :: ByteString
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
encodeBase64 :: ByteString -> Text
encodeBase64 = T.pack . go . BS.unpack
where
sextet :: Int -> Char
sextet n = chr (fromIntegral (BS.index alphabet (n .&. 63)))
go (a : b : c : rest) =
let n = fromIntegral a `shiftL` 16 .|. fromIntegral b `shiftL` 8 .|. fromIntegral c :: Int
in sextet (n `shiftR` 18) : sextet (n `shiftR` 12) : sextet (n `shiftR` 6) : sextet n : go rest
go [a, b] =
let n = fromIntegral a `shiftL` 16 .|. fromIntegral b `shiftL` 8 :: Int
in [sextet (n `shiftR` 18), sextet (n `shiftR` 12), sextet (n `shiftR` 6), '=']
go [a] =
let n = fromIntegral a `shiftL` 16 :: Int
in [sextet (n `shiftR` 18), sextet (n `shiftR` 12), '=', '=']
go [] = []
decodeBase64 :: Text -> Either String ByteString
decodeBase64 t
| T.length t `mod` 4 /= 0 = Left "base64 text comes in groups of four"
| otherwise = BS.pack . concat <$> traverse group (zip [1 :: Int ..] (chunks (T.unpack t)))
where
groups = T.length t `div` 4
chunks [] = []
chunks s = let (g, r) = splitAt 4 s in g : chunks r
group (i, g) = do
let padding = if i == groups then length (takeWhile (== '=') (reverse g)) else 0
if padding > 2
then Left "too much padding"
else do
sextets <- traverse (value' padding) (zip [0 :: Int ..] g)
let n = foldl (\acc s -> acc `shiftL` 6 .|. s) 0 sextets :: Int
bytes = [fromIntegral (n `shiftR` 16), fromIntegral (n `shiftR` 8), fromIntegral n] :: [Word8]
Right (take (3 - padding) bytes)
value' padding (j, c)
| j >= 4 - padding = if c == '=' then Right 0 else Left ("`" ++ [c] ++ "` is not base64")
| otherwise = case BS.elemIndex (fromIntegral (ord c)) alphabet of
Just ix | ord c < 128 -> Right ix
_ -> Left ("`" ++ [c] ++ "` is not base64")
object :: [(Text, Maybe Json)] -> Json
object fields = JObject (Map.fromList [(k, v) | (k, Just v) <- fields])
field :: ToJson a => Text -> a -> (Text, Maybe Json)
field k v = case toJson v of
JNull -> (k, Nothing)
json -> (k, Just json)
asObject :: Text -> Json -> Either String (Map Text Json)
asObject _ (JObject o) = Right o
asObject what j = Left (expected ("a " ++ T.unpack what ++ " (an object)") j)
required :: FromJson a => Text -> Map Text Json -> Either String a
required k o = case Map.lookup k o of
Nothing -> Left ("missing field `" ++ T.unpack k ++ "`")
Just v -> within ("field `" ++ T.unpack k ++ "`") (fromJson v)
optional :: FromJson a => Text -> Map Text Json -> Either String a
optional k o = within ("field `" ++ T.unpack k ++ "`") (fromJson (Map.findWithDefault JNull k o))
variant :: Text -> Maybe Json -> Json
variant tag carried = object [("$tag", Just (JString tag)), ("value", carried >>= nonNull)]
where
nonNull JNull = Nothing
nonNull v = Just v
asVariant :: Text -> Json -> Either String (Text, Maybe Json)
asVariant what j = do
o <- asObject what j
case Map.lookup "$tag" o of
Just (JString tag) -> Right (tag, Map.lookup "value" o)
_ -> Left ("a " ++ T.unpack what ++ " needs a `$tag` that is text")
payload :: FromJson a => Text -> Maybe Json -> Either String a
payload tag carried = within ("variant `" ++ T.unpack tag ++ "`") (fromJson (maybe JNull id carried))
unknownTag :: Text -> Text -> String
unknownTag what tag = show tag ++ " is not a variant of " ++ T.unpack what
asText :: Text -> Json -> Either String Text
asText _ (JString s) = Right s
asText what j = Left (expected ("a " ++ T.unpack what ++ " (a string)") j)
unknownName :: Text -> Text -> String
unknownName what name = show name ++ " is not one of the " ++ T.unpack what
firstOf :: Text -> [Either String a] -> Either String a
firstOf what attempts = case [x | Right x <- attempts] of
x : _ -> Right x
[] -> Left ("matches none of the alternatives of " ++ T.unpack what)