tobogganSe connecter

packages

The Louise packages, each released on its own

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

285 lignes · 6526 octetsBrut · Historique
1/// Decoders: from a `json.Value` to your own types, with the path to
2/// whatever did not fit.
3///
4/// ```louise
5/// import json/decode.{type Decoder}
6///
7/// fn ship :: -> Decoder<Ship>
8/// {
9/// use symbol <- decode.field "symbol" (decode.string ())
10/// use fuel <- decode.optional_field "fuel" (decode.int ())
11/// decode.succeed Ship(symbol, option.unwrap_or fuel 0)
12/// }
13///
14/// decode.from_string "\{\"symbol\": \"ORION-1\"\}" (ship ())
15/// // Ok(Ship("ORION-1", 0))
16/// decode.from_string "\{\"symbol\": 7\}" (ship ())
17/// // Error(Mismatch(["symbol"], "a string", "an integer"))
18/// ```
19///
20/// A decoder only says what shape it reads; rules about the values (a
21/// symbol's length, a positive quantity) belong to whoever owns them.
22
23import json.
24{ type DecodeError
25, type Value
26, Array
27, Bool
28, Float
29, Int
30, Malformed
31, Mismatch
32, Missing
33, Null
34, Object
35, String
36}
37import std/float as std_float
38import std/list as lists
39import std/result
40
41/// Reads an `a` out of a `json.Value`.
42pub opaque type Decoder<a> { Decoder(fn(Value) -> Result<a, DecodeError>) }
43
44/// `decoder` applied to `value`.
45pub fn run :: value: Value decoder: Decoder<a> -> Result<a, DecodeError>
46{
47 let Decoder(read) = decoder
48 read value
49}
50
51/// [`json.parse`](json), then `decoder`.
52pub fn from_string :: text: String decoder: Decoder<a> -> Result<a, DecodeError>
53{
54 use value <- result.try (json.parse text)
55 run value decoder
56}
57
58/// [`json.parse_bytes`](json) (a request body), then `decoder`.
59pub fn from_bytes :: data: Bytes decoder: Decoder<a> -> Result<a, DecodeError>
60{
61 use value <- result.try (json.parse_bytes data)
62 run value decoder
63}
64
65// ---- building blocks -----------------------------------------------------------
66
67/// Always `x`, whatever the value.
68pub fn succeed :: x: a -> Decoder<a>
69{
70 Decoder(fn _ { Ok(x) })
71}
72
73/// Always a mismatch: the value is not `expected`.
74pub fn fail :: expected: String -> Decoder<a>
75{
76 Decoder(fn v { Error(Mismatch([], expected, json.kind v)) })
77}
78
79/// The value itself, whatever it is.
80pub fn value :: -> Decoder<Value>
81{
82 Decoder(fn v { Ok(v) })
83}
84
85pub fn string :: -> Decoder<String>
86{
87 Decoder(fn v { match v { String(s) -> Ok(s), _ -> mismatch "a string" v } })
88}
89
90/// An integer: a number with no fraction and no exponent.
91pub fn int :: -> Decoder<Int>
92{
93 Decoder(fn v { match v { Int(n) -> Ok(n), _ -> mismatch "an integer" v } })
94}
95
96/// Any number; an integer is widened.
97pub fn float :: -> Decoder<Float>
98{
99 Decoder( fn v
100 {
101 match v
102 { Float(x) -> Ok(x)
103 , Int(n) -> Ok(std_float.from_int n)
104 , _ -> mismatch "a number" v
105 }
106 }
107 )
108}
109
110pub fn bool :: -> Decoder<Bool>
111{
112 Decoder(fn v { match v { Bool(b) -> Ok(b), _ -> mismatch "a bool" v } })
113}
114
115/// An array, each item read by `item`; a failing item's index is in the
116/// error's path.
117pub fn list :: item: Decoder<a> -> Decoder<List<a>>
118{
119 Decoder( fn v
120 {
121 match v
122 { Array(items) -> items_from items 0 item [], _ -> mismatch "an array" v }
123 }
124 )
125}
126
127fn items_from ::
128 items: List<Value>
129 index: Int
130 item: Decoder<a>
131 kept: List<a>
132 -> Result<List<a>, DecodeError>
133{
134 match items
135 { [] -> Ok(lists.reverse kept)
136 , [first, ..rest] ->
137 {
138 use x <- result.try (within "{index}" (run first item))
139 items_from rest (index + 1) item [x, ..kept]
140 }
141 }
142}
143
144/// `null` as `None`, anything else read by `inner`.
145pub fn nullable :: inner: Decoder<a> -> Decoder<Option<a>>
146{
147 Decoder( fn v
148 {
149 match v
150 { Null -> Ok(None), _ -> run v inner |> result.map fn x { Some(x) } }
151 }
152 )
153}
154
155/// The field `name` of an object, read by `inner`, handed to `next`:
156/// written with `use`, one line per field (see the module's example).
157pub fn field ::
158 name: String
159 inner: Decoder<a>
160 next: fn(a) -> Decoder<b>
161 -> Decoder<b>
162{
163 Decoder( fn v
164 {
165 match v
166 { Object(entries) -> match lookup entries name
167 { Some(found) ->
168 {
169 use x <- result.try (within name (run found inner))
170 run v (next x)
171 }
172 , None -> Error(Missing([], name))
173 }
174 , _ -> mismatch "an object" v
175 }
176 }
177 )
178}
179
180/// Like [`field`], but a missing field or a `null` is `None`.
181pub fn optional_field ::
182 name: String
183 inner: Decoder<a>
184 next: fn(Option<a>) -> Decoder<b>
185 -> Decoder<b>
186{
187 Decoder( fn v
188 {
189 match v
190 { Object(entries) -> match lookup entries name
191 { Some(Null) | None -> run v (next None)
192 , Some(found) ->
193 {
194 use x <- result.try (within name (run found inner))
195 run v (next (Some(x)))
196 }
197 }
198 , _ -> mismatch "an object" v
199 }
200 }
201 )
202}
203
204/// `decoder`'s result passed through `f`.
205pub fn map :: decoder: Decoder<a> f: fn(a) -> b -> Decoder<b>
206{
207 Decoder(fn v { run v decoder |> result.map f })
208}
209
210/// `decoder`'s result chooses the decoder that reads the same value
211/// next: a tagged union reads its tag, then the fields that tag has.
212pub fn then :: decoder: Decoder<a> f: fn(a) -> Decoder<b> -> Decoder<b>
213{
214 Decoder( fn v
215 {
216 use x <- result.try (run v decoder)
217 run v (f x)
218 }
219 )
220}
221
222/// The first of `decoders` that reads the value; when none does, the
223/// first one's error.
224pub fn one_of :: first: Decoder<a> rest: List<Decoder<a>> -> Decoder<a>
225{
226 Decoder( fn v
227 {
228 match run v first { Ok(x) -> Ok(x), Error(e) -> first_of v rest e }
229 }
230 )
231}
232
233fn first_of ::
234 v: Value
235 decoders: List<Decoder<a>>
236 first_error: DecodeError
237 -> Result<a, DecodeError>
238{
239 match decoders
240 { [] -> Error(first_error)
241 , [d, ..rest] -> match run v d
242 { Ok(x) -> Ok(x), Error(_) -> first_of v rest first_error }
243 }
244}
245
246// ---- paths ---------------------------------------------------------------------
247
248/// `outcome`'s error, one level down: under `key`.
249fn within ::
250 key: String
251 outcome: Result<a, DecodeError>
252 -> Result<a, DecodeError>
253{
254 result.map_error
255 outcome
256 fn e
257 {
258 match e
259 { Mismatch(path, expected, found) ->
260 Mismatch([key, ..path], expected, found)
261 , Missing(path, name) -> Missing([key, ..path], name)
262 , Malformed(_, _) -> e
263 }
264 }
265}
266
267fn lookup :: entries: List<(String, Value)> name: String -> Option<Value>
268{
269 match entries
270 { [] -> None
271 , [(key, found), ..rest] -> if key == name
272 {
273 Some(found)
274 }
275 else
276 {
277 lookup rest name
278 }
279 }
280}
281
282fn mismatch :: expected: String v: Value -> Result<a, DecodeError>
283{
284 Error(Mismatch([], expected, json.kind v))
285}