/// Decoders: from a `json.Value` to your own types, with the path to /// whatever did not fit. /// /// ```louise /// import json/decode.{type Decoder} /// /// fn ship :: -> Decoder /// { /// use symbol <- decode.field "symbol" (decode.string ()) /// use fuel <- decode.optional_field "fuel" (decode.int ()) /// decode.succeed Ship(symbol, option.unwrap_or fuel 0) /// } /// /// decode.from_string "\{\"symbol\": \"ORION-1\"\}" (ship ()) /// // Ok(Ship("ORION-1", 0)) /// decode.from_string "\{\"symbol\": 7\}" (ship ()) /// // Error(Mismatch(["symbol"], "a string", "an integer")) /// ``` /// /// A decoder only says what shape it reads; rules about the values (a /// symbol's length, a positive quantity) belong to whoever owns them. import json. { type DecodeError , type Value , Array , Bool , Float , Int , Malformed , Mismatch , Missing , Null , Object , String } import std/float as std_float import std/list as lists import std/result /// Reads an `a` out of a `json.Value`. pub opaque type Decoder { Decoder(fn(Value) -> Result) } /// `decoder` applied to `value`. pub fn run :: value: Value decoder: Decoder -> Result { let Decoder(read) = decoder read value } /// [`json.parse`](json), then `decoder`. pub fn from_string :: text: String decoder: Decoder -> Result { use value <- result.try (json.parse text) run value decoder } /// [`json.parse_bytes`](json) (a request body), then `decoder`. pub fn from_bytes :: data: Bytes decoder: Decoder -> Result { use value <- result.try (json.parse_bytes data) run value decoder } // ---- building blocks ----------------------------------------------------------- /// Always `x`, whatever the value. pub fn succeed :: x: a -> Decoder { Decoder(fn _ { Ok(x) }) } /// Always a mismatch: the value is not `expected`. pub fn fail :: expected: String -> Decoder { Decoder(fn v { Error(Mismatch([], expected, json.kind v)) }) } /// The value itself, whatever it is. pub fn value :: -> Decoder { Decoder(fn v { Ok(v) }) } pub fn string :: -> Decoder { Decoder(fn v { match v { String(s) -> Ok(s), _ -> mismatch "a string" v } }) } /// An integer: a number with no fraction and no exponent. pub fn int :: -> Decoder { Decoder(fn v { match v { Int(n) -> Ok(n), _ -> mismatch "an integer" v } }) } /// Any number; an integer is widened. pub fn float :: -> Decoder { Decoder( fn v { match v { Float(x) -> Ok(x) , Int(n) -> Ok(std_float.from_int n) , _ -> mismatch "a number" v } } ) } pub fn bool :: -> Decoder { Decoder(fn v { match v { Bool(b) -> Ok(b), _ -> mismatch "a bool" v } }) } /// An array, each item read by `item`; a failing item's index is in the /// error's path. pub fn list :: item: Decoder -> Decoder> { Decoder( fn v { match v { Array(items) -> items_from items 0 item [], _ -> mismatch "an array" v } } ) } fn items_from :: items: List index: Int item: Decoder kept: List -> Result, DecodeError> { match items { [] -> Ok(lists.reverse kept) , [first, ..rest] -> { use x <- result.try (within "{index}" (run first item)) items_from rest (index + 1) item [x, ..kept] } } } /// `null` as `None`, anything else read by `inner`. pub fn nullable :: inner: Decoder -> Decoder> { Decoder( fn v { match v { Null -> Ok(None), _ -> run v inner |> result.map fn x { Some(x) } } } ) } /// The field `name` of an object, read by `inner`, handed to `next`: /// written with `use`, one line per field (see the module's example). pub fn field :: name: String inner: Decoder next: fn(a) -> Decoder -> Decoder { Decoder( fn v { match v { Object(entries) -> match lookup entries name { Some(found) -> { use x <- result.try (within name (run found inner)) run v (next x) } , None -> Error(Missing([], name)) } , _ -> mismatch "an object" v } } ) } /// Like [`field`], but a missing field or a `null` is `None`. pub fn optional_field :: name: String inner: Decoder next: fn(Option) -> Decoder -> Decoder { Decoder( fn v { match v { Object(entries) -> match lookup entries name { Some(Null) | None -> run v (next None) , Some(found) -> { use x <- result.try (within name (run found inner)) run v (next (Some(x))) } } , _ -> mismatch "an object" v } } ) } /// `decoder`'s result passed through `f`. pub fn map :: decoder: Decoder f: fn(a) -> b -> Decoder { Decoder(fn v { run v decoder |> result.map f }) } /// `decoder`'s result chooses the decoder that reads the same value /// next: a tagged union reads its tag, then the fields that tag has. pub fn then :: decoder: Decoder f: fn(a) -> Decoder -> Decoder { Decoder( fn v { use x <- result.try (run v decoder) run v (f x) } ) } /// The first of `decoders` that reads the value; when none does, the /// first one's error. pub fn one_of :: first: Decoder rest: List> -> Decoder { Decoder( fn v { match run v first { Ok(x) -> Ok(x), Error(e) -> first_of v rest e } } ) } fn first_of :: v: Value decoders: List> first_error: DecodeError -> Result { match decoders { [] -> Error(first_error) , [d, ..rest] -> match run v d { Ok(x) -> Ok(x), Error(_) -> first_of v rest first_error } } } // ---- paths --------------------------------------------------------------------- /// `outcome`'s error, one level down: under `key`. fn within :: key: String outcome: Result -> Result { result.map_error outcome fn e { match e { Mismatch(path, expected, found) -> Mismatch([key, ..path], expected, found) , Missing(path, name) -> Missing([key, ..path], name) , Malformed(_, _) -> e } } } fn lookup :: entries: List<(String, Value)> name: String -> Option { match entries { [] -> None , [(key, found), ..rest] -> if key == name { Some(found) } else { lookup rest name } } } fn mismatch :: expected: String v: Value -> Result { Error(Mismatch([], expected, json.kind v)) }