unitype-codegen 0.2.0

TypeScript, Python, Rust, and Haskell code generation backends for unitype
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
-- Generated by unitype. Do not edit.
--
-- What generated Haskell shares between universes: the JSON every generated
-- type reads and writes. GHC ships no JSON library, so this is one, small and
-- strict, written to the wire form the protocol specifies. It needs nothing
-- beyond the packages that come with GHC: base, bytestring, containers, text.
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
module UnitypeSupport
  ( -- * JSON
    Json (..)
  , parseJson
  , renderJson
    -- * Types that travel
  , ToJson (..)
  , FromJson (..)
  , MapKey (..)
    -- * What generated instances are built from
  , 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)

-- | JSON, with integers and floats kept apart so that `1` and `1.0` stay what
-- they were written as.
data Json
  = JNull
  | JBool Bool
  | JInt Integer
  | JFloat Double
  | JString Text
  | JArray [Json]
  | JObject (Map Text Json)
  deriving (Eq, Show)

-- | A type that is written as JSON.
class ToJson a where
  toJson :: a -> Json

-- | A type that is read from JSON, or says why it cannot be.
class FromJson a where
  fromJson :: Json -> Either String a

-- | A type a map can be keyed by. A JSON object's property names are text, so a
-- key has to be turned into text and back.
class Ord k => MapKey k where
  keyText :: k -> Text
  keyFrom :: Text -> Either String k

-- ---------------------------------------------------------------------------
-- Reading text as JSON

-- | Reads one JSON value, and nothing after it.
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"

-- | Reads a string whose opening quote has gone.
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"

-- ---------------------------------------------------------------------------
-- Writing JSON as text

-- | Writes a value as JSON. NaN and the infinities are refused rather than
-- approximated, since JSON cannot carry them.
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

-- ---------------------------------------------------------------------------
-- What a type does when it travels

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

-- | An integer is a float when nothing is lost by it, which is up to 2^53.
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"

-- | Bytes travel as base64 text, standard and padded.
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)

-- | Absent and null are one state.
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

-- | An integer key is its digits, with no sign but `-`, no leading zeros and
-- no exponent.
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)

-- | One item of a tuple, with its position in what is said when it is wrong.
at :: FromJson a => Int -> Json -> Either String a
at n = within ("." ++ show n) . fromJson

-- | Says where in a value something went wrong.
within :: String -> Either String a -> Either String a
within place = either (\e -> Left (place ++ ": " ++ e)) Right

-- ---------------------------------------------------------------------------
-- Base64

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")

-- ---------------------------------------------------------------------------
-- What generated instances are built from

-- | An object, leaving out what is absent.
object :: [(Text, Maybe Json)] -> Json
object fields = JObject (Map.fromList [(k, v) | (k, Just v) <- fields])

-- | A field. One that holds nothing -- an optional that is absent, a null, an
-- `any` with nothing in it -- is left out rather than written as null, since
-- absence has one representation.
field :: ToJson a => Text -> a -> (Text, Maybe Json)
field k v = case toJson v of
  JNull -> (k, Nothing)
  json -> (k, Just json)

-- | The members of an object, or what was found instead.
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)

-- | A field that has to be there.
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)

-- | A field that may be left out, which reads as null.
optional :: FromJson a => Text -> Map Text Json -> Either String a
optional k o = within ("field `" ++ T.unpack k ++ "`") (fromJson (Map.findWithDefault JNull k o))

-- | One alternative of a tagged sum: the tag beside what it carries.
variant :: Text -> Maybe Json -> Json
variant tag carried = object [("$tag", Just (JString tag)), ("value", carried >>= nonNull)]
  where
    nonNull JNull = Nothing
    nonNull v = Just v

-- | The tag of a tagged sum, and what it carries if anything.
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")

-- | What a variant carries. A payload that may be absent can be left out.
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

-- | The text a name is written as.
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

-- | The first alternative of an untagged union that reads.
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)