Skip to main content

flow_abi/
decode.rs

1//! Decoding a value of a declared type (`abi.md`, *Decoding*).
2//!
3//! Decoding is directed by the type and never coerces, guesses a
4//! constructor, fills a default or repairs a value. Every failure names where
5//! it happened and why.
6
7use std::borrow::Cow;
8use std::sync::Arc;
9
10use flow_types::{JsonValueCtor, OptionCtor, Payload};
11use flow_value::{Bytes, Decimal, Dict, Int, Set, Text, Value, Variant};
12use num_bigint::BigInt;
13
14use crate::build::{Begun, Frame, Make, Source, build, distinct_dict, distinct_set, normal};
15use crate::catalog::{Catalog, StdForm};
16use crate::error::{DecodeError, DecodeErrorKind, Place};
17use crate::form::part_types;
18use crate::json::{Json, parse, quote};
19use crate::limits::Limits;
20use crate::time;
21use flow_types::{Body, Crossing, Settings, Spelling, Type};
22
23/// What is being decoded, which decides what a field the type does not
24/// declare means and which types decoding may build ([`Mode::settings`]).
25#[derive(Clone, Copy, PartialEq, Eq, Debug)]
26pub enum Mode {
27    /// A Tool reply: an undeclared field is ignored.
28    Reply,
29    /// The text `json.decode` reads: an undeclared field is ignored, and a
30    /// host value is refused, as in a run's input.
31    Decode,
32    /// `json.decode` with `json.Names.Relaxed`: as [`Mode::Decode`], and
33    /// each record field and enum constructor the type declares is matched
34    /// by its relaxed key ([`Spelling::Relaxed`]).
35    Relaxed,
36    /// A run's input: an undeclared field is refused, and so is a host value,
37    /// since input is data.
38    Input,
39    /// A value the program made, read back from its canonical text, such as
40    /// a checkpoint's arguments on resume. This is not decoding (`abi.md`,
41    /// *Decoding*): every type is rebuilt, opaque types and host tokens
42    /// included, and a type with a part that has no encoding, such as a
43    /// list of functions, whose text holds no value there. An undeclared
44    /// field is refused, since the text is canonical.
45    Rebuild,
46}
47
48impl Mode {
49    /// What a type decoded in this mode is judged for.
50    pub const fn settings(self) -> Settings {
51        match self {
52            Mode::Reply => REPLY,
53            Mode::Decode | Mode::Input => INPUT,
54            Mode::Relaxed => RELAXED,
55            Mode::Rebuild => REBUILD,
56        }
57    }
58
59    /// How a name the JSON writes is matched with a name the type declares.
60    pub(crate) const fn spelling(self) -> Spelling {
61        self.settings().names
62    }
63}
64
65/// A Tool's reply: data that crosses the boundary, with no opaque part,
66/// which may carry the host's tokens.
67pub const REPLY: Settings = Settings {
68    data: true,
69    host_ok: true,
70    no_opaque: true,
71    crossing: Crossing::Crosses,
72    names: Spelling::Exact,
73};
74
75/// A run's input, and what `json.decode` builds: data with no opaque part,
76/// which carries no host token either, since only a Tool's answer may.
77pub const INPUT: Settings = Settings {
78    host_ok: false,
79    ..REPLY
80};
81
82/// What `json.decode` with `json.Names.Relaxed` builds: as [`INPUT`], with
83/// each name the type declares matched by its relaxed key.
84pub(crate) const RELAXED: Settings = Settings {
85    names: Spelling::Relaxed,
86    ..INPUT
87};
88
89/// A generic Tool's type argument, which the call's types bind: data with
90/// no opaque part, as a run's input is, but which crosses no boundary
91/// unless the Tool's parameters or result carry it (`tools.md`, *Generic
92/// Tools*).
93pub const BINDING: Settings = Settings {
94    crossing: Crossing::Stays,
95    ..INPUT
96};
97
98/// A value the program made, rebuilt from its canonical text: no type is
99/// refused, but one whose type parameter is unbound has no encoding.
100pub const REBUILD: Settings = Settings {
101    data: false,
102    host_ok: true,
103    no_opaque: false,
104    crossing: Crossing::Stays,
105    names: Spelling::Exact,
106};
107
108/// An existing value carried across a Tool boundary, which may be opaque
109/// or hold the host's tokens.
110pub const CROSSING: Settings = Settings {
111    no_opaque: false,
112    ..REPLY
113};
114
115/// Decodes `text` as a value of `ty`.
116///
117/// # Errors
118///
119/// A [`DecodeError`] when `text` is not JSON within `limits`, or the JSON
120/// is not a value of `ty` in `mode`.
121pub fn decode_text(
122    catalog: &Catalog,
123    ty: &Type,
124    text: &str,
125    mode: Mode,
126    limits: &Limits,
127) -> Result<Value, DecodeError> {
128    decodable(catalog, ty, mode.settings())?;
129    let json = parse(text, limits)?;
130    run(catalog, ty, &json, mode, limits)
131}
132
133/// Decodes `json` as a value of `ty`.
134///
135/// # Errors
136///
137/// A [`DecodeError`] when `ty` cannot be decoded in `mode`, or `json` is
138/// not a value of it within `limits`.
139pub fn decode(
140    catalog: &Catalog,
141    ty: &Type,
142    json: &Json,
143    mode: Mode,
144    limits: &Limits,
145) -> Result<Value, DecodeError> {
146    decodable(catalog, ty, mode.settings())?;
147    run(catalog, ty, json, mode, limits)
148}
149
150fn run(
151    catalog: &Catalog,
152    ty: &Type,
153    json: &Json,
154    mode: Mode,
155    limits: &Limits,
156) -> Result<Value, DecodeError> {
157    Decoder {
158        catalog,
159        mode,
160        limits,
161        path: Place::default(),
162    }
163    .value(ty, json, 0)
164}
165
166/// Whether a value of `ty` may be built or carried where `settings` judge
167/// it, such as a mode's ([`Mode::settings`]) or [`CROSSING`]
168/// (`tools.md`, *Decoding*). This is judged of the type, before any text is
169/// read, so an absent part refuses as surely as a present one, and a type
170/// parameter left unbound refuses every judgment.
171///
172/// # Errors
173///
174/// A [`DecodeError`] naming the first part of `ty` the judgment refuses.
175pub fn decodable(catalog: &Catalog, ty: &Type, settings: Settings) -> Result<(), DecodeError> {
176    match catalog.problem(ty, settings) {
177        Some(problem) => Err(DecodeError::of(
178            &Place::default(),
179            DecodeErrorKind::Mismatch,
180            problem,
181        )),
182        None => Ok(()),
183    }
184}
185
186struct Decoder<'c> {
187    catalog: &'c Catalog,
188    mode: Mode,
189    limits: &'c Limits,
190    path: Place,
191}
192
193impl<'c> Decoder<'c> {
194    fn refuse(&self, kind: DecodeErrorKind, problem: impl Into<String>) -> DecodeError {
195        DecodeError::of(&self.path, kind, problem.into())
196    }
197
198    fn expected(&self, what: &str, json: &Json) -> DecodeError {
199        self.refuse(
200            DecodeErrorKind::Mismatch,
201            format!("should be {what}, not {}", json.kind()),
202        )
203    }
204
205    /// Enters an aggregate `level` deep, which [`Limits::depth`] bounds.
206    fn enter(&self, level: usize) -> Result<usize, DecodeError> {
207        let level = level + 1;
208        if level > self.limits.depth {
209            return Err(self.refuse(
210                DecodeErrorKind::TooLarge,
211                format!("nests deeper than {} levels", self.limits.depth),
212            ));
213        }
214        Ok(level)
215    }
216
217    fn text(&self, text: &str) -> Result<Text, DecodeError> {
218        if text.len() > self.limits.text_bytes {
219            return Err(self.refuse(
220                DecodeErrorKind::TooLarge,
221                format!("is longer than {} bytes", self.limits.text_bytes),
222            ));
223        }
224        Ok(Text::new(text))
225    }
226
227    /// Decodes a value of `ty` from `json`, `level` deep. The aggregates
228    /// it is inside wait on a stack on the heap, so the native stack does
229    /// not grow with the value's depth.
230    fn value(&mut self, ty: &Type, json: &Json, level: usize) -> Result<Value, DecodeError> {
231        let root = self.begin(&Cow::Borrowed(ty), json, level)?;
232        build(self, root)
233    }
234
235    /// Begins decoding a value of `ty` from `json`: one that holds no other
236    /// value is done at once, and an aggregate is opened.
237    fn begin<'t, 'j>(
238        &mut self,
239        ty: &Cow<'t, Type>,
240        json: &'j Json,
241        level: usize,
242    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
243        let value = match (&**ty, json) {
244            (Type::Int, Json::Number(number)) => Value::Int(self.int(number)?),
245            (Type::Int, _) => return Err(self.expected("an integer", json)),
246            (Type::Decimal, Json::Number(number)) => self.decimal(number)?,
247            (Type::Decimal, _) => return Err(self.expected("a number", json)),
248            (Type::Bool, Json::Bool(flag)) => Value::Bool(*flag),
249            (Type::Bool, _) => return Err(self.expected("a boolean", json)),
250            (Type::Text, Json::String(text)) => Value::Text(self.text(text)?),
251            (Type::Text, _) => return Err(self.expected("a string", json)),
252            (Type::Bytes, Json::String(text)) => Value::Bytes(self.bytes(text)?),
253            (Type::Bytes, _) => return Err(self.expected("a base64 string", json)),
254            (Type::Duration, Json::String(text)) => {
255                Value::Duration(time::duration(text).ok_or_else(|| {
256                    self.refuse(DecodeErrorKind::Mismatch, "should be an ISO 8601 duration")
257                })?)
258            }
259            (Type::Duration, _) => return Err(self.expected("an ISO 8601 duration", json)),
260            (Type::Instant, Json::String(text)) => {
261                Value::Instant(time::instant(text).ok_or_else(|| {
262                    self.refuse(
263                        DecodeErrorKind::Mismatch,
264                        "should be an ISO 8601 date and time",
265                    )
266                })?)
267            }
268            (Type::Instant, _) => return Err(self.expected("an ISO 8601 date and time", json)),
269            (Type::Unit, Json::Array(items)) if items.is_empty() => Value::Unit,
270            (Type::Unit, _) => return Err(self.expected("`[]`", json)),
271            // Only rebuilding reaches a type with no encoding, and a value
272            // the program made holds nothing of one: had it held one, no
273            // checkpoint would have been taken.
274            (Type::NotData | Type::Function { .. }, _) => {
275                return Err(self.refuse(
276                    DecodeErrorKind::Mismatch,
277                    "has a type with no encoding, so it holds no value",
278                ));
279            }
280            // Only `Never`, and a task outside a checkpoint, reach here of
281            // these: the others were refused before any text was read.
282            (Type::Never | Type::Param(_) | Type::Task(_), _) => {
283                return Err(self.refuse(
284                    DecodeErrorKind::Mismatch,
285                    "has a type with no values to decode",
286                ));
287            }
288            (Type::Json, _) => return self.raw(json, level),
289            (Type::List(_), Json::Array(items)) => {
290                let level = self.enter(level)?;
291                return Ok(Frame::open(
292                    Make::List,
293                    Parts::Items(part_types(ty).swap_remove(0), items),
294                    0,
295                    level,
296                ));
297            }
298            (Type::Set(_), Json::Array(items)) => {
299                let level = self.enter(level)?;
300                return Ok(Frame::open(
301                    Make::Set,
302                    Parts::Items(part_types(ty).swap_remove(0), items),
303                    0,
304                    level,
305                ));
306            }
307            (Type::List(_) | Type::Set(_), _) => return Err(self.expected("an array", json)),
308            (Type::Dict(..), _) => return self.dict(ty, json, level),
309            (Type::Option(_), _) => {
310                return self.option(part_types(ty).swap_remove(0), json, level);
311            }
312            (Type::Tuple(parts), Json::Array(items)) if parts.len() == items.len() => {
313                let level = self.enter(level)?;
314                return Ok(Frame::open(
315                    Make::Tuple,
316                    Parts::Indexed(part_types(ty), items),
317                    0,
318                    level,
319                ));
320            }
321            (Type::Tuple(parts), _) => {
322                return Err(self.expected(&format!("an array of {} elements", parts.len()), json));
323            }
324            (Type::Named(decl, args), _) => return self.named(ty, *decl, args, json, level),
325        };
326        Ok(Begun::Done(value))
327    }
328    fn decimal(&self, number: &Decimal) -> Result<Value, DecodeError> {
329        if number.coefficient().bits() > self.limits.int_bits {
330            return Err(self.refuse(
331                DecodeErrorKind::TooLarge,
332                format!(
333                    "has a coefficient larger than {} bits",
334                    self.limits.int_bits
335                ),
336            ));
337        }
338        Ok(Value::Decimal(number.clone()))
339    }
340
341    fn int(&self, number: &Decimal) -> Result<Int, DecodeError> {
342        if number.exponent() < 0 {
343            return Err(self.refuse(DecodeErrorKind::Mismatch, "should be a whole number"));
344        }
345        // The number is coefficient × 10^exponent with a nonzero coefficient
346        // or a zero exponent, and 10^p has more than p bits, so an exponent
347        // past the limit is refused without building a power of ten as long
348        // as it; one within it is built and measured exactly.
349        let too_large = || {
350            self.refuse(
351                DecodeErrorKind::TooLarge,
352                format!("is an integer larger than {} bits", self.limits.int_bits),
353            )
354        };
355        let places = number.exponent().unsigned_abs();
356        if places > self.limits.int_bits {
357            return Err(too_large());
358        }
359        let places = u32::try_from(places).expect("an exponent the limit bounds");
360        crate::work::built(usize::try_from(places).map_or(usize::MAX, |places| places + 1));
361        let value = number.coefficient() * BigInt::from(10).pow(places);
362        if value.magnitude().bits() > self.limits.int_bits {
363            return Err(too_large());
364        }
365        Ok(Int::from(value))
366    }
367
368    fn bytes(&self, text: &str) -> Result<Bytes, DecodeError> {
369        let bytes = base64(text).ok_or_else(|| {
370            self.refuse(
371                DecodeErrorKind::Mismatch,
372                "should be standard base64 with padding",
373            )
374        })?;
375        if bytes.len() > self.limits.text_bytes {
376            return Err(self.refuse(
377                DecodeErrorKind::TooLarge,
378                format!("is longer than {} bytes", self.limits.text_bytes),
379            ));
380        }
381        Ok(Bytes::from(bytes))
382    }
383
384    /// Begins a named field's value from its member: an absent or `null`
385    /// member is `None` for an `Option` field and refused for any other.
386    fn field<'t, 'j>(
387        &mut self,
388        field: &Cow<'t, Type>,
389        member: Option<&'j Json>,
390        level: usize,
391    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
392        match (&*self.catalog.erase(field), member) {
393            (Type::Option(item), member) => {
394                self.option_field(Cow::Owned((**item).clone()), member, level)
395            }
396            (_, Some(Json::Null)) => Err(self.refuse(
397                DecodeErrorKind::Mismatch,
398                "is null, which only an Option field may be",
399            )),
400            (_, Some(json)) => self.begin(field, json, level),
401            (_, None) => Err(self.refuse(DecodeErrorKind::Missing, "is missing")),
402        }
403    }
404
405    fn dict<'t, 'j>(
406        &mut self,
407        ty: &Cow<'t, Type>,
408        json: &'j Json,
409        level: usize,
410    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
411        let [key, item]: [Cow<'t, Type>; 2] = part_types(ty)
412            .try_into()
413            .expect("a key type and a value type");
414        let parts = match (&*self.catalog.erase(&key), json) {
415            (Type::Text, Json::Object(members)) => Parts::Members(key, item, members),
416            (Type::Text, _) => return Err(self.expected("an object", json)),
417            (_, Json::Array(pairs)) => Parts::Pairs(key, item, pairs),
418            _ => return Err(self.expected("an array of `[key, value]` pairs", json)),
419        };
420        let level = self.enter(level)?;
421        Ok(Frame::open(Make::Dict, parts, 0, level))
422    }
423
424    fn option<'t, 'j>(
425        &mut self,
426        item: Cow<'t, Type>,
427        json: &'j Json,
428        level: usize,
429    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
430        let catalog = self.catalog;
431        let option = catalog.option();
432        let level = self.enter(level)?;
433        let spelling = self.mode.spelling();
434        let is = |written: &str, name: &str| spelling.key(written) == spelling.key(name);
435        match json {
436            Json::String(name) if is(name, OptionCtor::None.name()) => {
437                Ok(Begun::Done(catalog.none()))
438            }
439            Json::Object(members)
440                if members.len() == 1 && is(&members[0].0, OptionCtor::Some.name()) =>
441            {
442                self.path.constructor(OptionCtor::Some.name());
443                Ok(Frame::open(
444                    Make::Variant(
445                        Arc::clone(&option.shape),
446                        option.ctors.index(OptionCtor::Some),
447                    ),
448                    Parts::One(item, &members[0].1),
449                    0,
450                    level,
451                ))
452            }
453            Json::String(name) => Err(self.unknown_option(name)),
454            Json::Object(members) if members.len() == 1 => Err(self.unknown_option(&members[0].0)),
455            Json::Null => Err(self.refuse(
456                DecodeErrorKind::Mismatch,
457                "is null, which only an Option field may be",
458            )),
459            _ => Err(self.expected("`\"None\"` or `{\"Some\": ...}`", json)),
460        }
461    }
462
463    fn unknown_option(&self, name: &str) -> DecodeError {
464        self.refuse(
465            DecodeErrorKind::Unknown,
466            format!(
467                "names {}, which is not a constructor of Option",
468                quote(name)
469            ),
470        )
471    }
472
473    /// The value of an `Option` field: absent or `null` is `None`, and
474    /// anything else is the payload of `Some`.
475    fn option_field<'t, 'j>(
476        &mut self,
477        item: Cow<'t, Type>,
478        json: Option<&'j Json>,
479        level: usize,
480    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
481        let catalog = self.catalog;
482        let option = catalog.option();
483        let level = self.enter(level)?;
484        match json {
485            None | Some(Json::Null) => Ok(Begun::Done(catalog.none())),
486            Some(json) => Ok(Frame::open(
487                Make::Unwritten(
488                    Arc::clone(&option.shape),
489                    option.ctors.index(OptionCtor::Some),
490                ),
491                Parts::One(item, json),
492                0,
493                level,
494            )),
495        }
496    }
497
498    fn named<'t, 'j>(
499        &mut self,
500        ty: &Type,
501        decl: flow_types::DeclId,
502        args: &[Type],
503        json: &'j Json,
504        level: usize,
505    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
506        let catalog = self.catalog;
507        let declared = catalog.decl(decl);
508        match &declared.body {
509            Body::Record(shape, fields) => {
510                let Json::Object(members) = json else {
511                    return Err(self.expected("an object", json));
512                };
513                let level = self.enter(level)?;
514                let names = shape.fields().collect();
515                let fields = fields
516                    .iter()
517                    .map(|field| Cow::Owned(field.subst(args)))
518                    .collect();
519                let index = catalog.names(decl, self.mode);
520                let parts =
521                    self.fields(ty, names, fields, members, |written| index.member(written))?;
522                Ok(Frame::open(
523                    Make::Record(Arc::clone(shape)),
524                    parts,
525                    0,
526                    level,
527                ))
528            }
529            Body::Enum(shape, ctors) => {
530                let (name, payload) = match json {
531                    Json::String(name) => (name, None),
532                    Json::Object(members) if members.len() == 1 => {
533                        (&members[0].0, Some(&members[0].1))
534                    }
535                    _ => {
536                        return Err(self
537                            .expected("a constructor's name or an object with one member", json));
538                    }
539                };
540                let names = catalog.names(decl, self.mode);
541                let Some(index) = names.member(name) else {
542                    return Err(self.refuse(
543                        DecodeErrorKind::Unknown,
544                        format!(
545                            "names {}, which is not a constructor of {}",
546                            quote(name),
547                            self.catalog.name(ty)
548                        ),
549                    ));
550                };
551                let ctor = shape.constructor(index).expect("found above");
552                let parts = ctors[index]
553                    .iter()
554                    .map(|part| Cow::Owned(part.subst(args)))
555                    .collect();
556                let level = self.enter(level)?;
557                self.path.constructor(ctor.name());
558                let parts = self.payload(ty, ctor.payload(), parts, payload, |written| {
559                    names.payload_field(index, written)
560                })?;
561                Ok(Frame::open(
562                    Make::Variant(Arc::clone(shape), index),
563                    parts,
564                    0,
565                    level,
566                ))
567            }
568            Body::Newtype(base) => Ok(Frame::open(
569                Make::Newtype(StdForm::of(declared)),
570                Parts::One(Cow::Owned(base.subst(args)), json),
571                0,
572                level,
573            )),
574            Body::NonData => Err(self.refuse(
575                DecodeErrorKind::Mismatch,
576                "has a type with no encoding, so it holds no value",
577            )),
578            Body::Host => match json {
579                Json::String(token) => {
580                    Ok(Begun::Done(Value::Host(flow_value::HostToken::new(token))))
581                }
582                _ => Err(self.expected("a host token string", json)),
583            },
584        }
585    }
586
587    /// Where the payload of a constructor of `ty`, whose parts are of
588    /// `types`, comes from in `json`.
589    fn payload<'t, 'j>(
590        &mut self,
591        ty: &Type,
592        payload: &'c Payload,
593        types: Vec<Cow<'t, Type>>,
594        json: Option<&'j Json>,
595        field: impl Fn(&str) -> Option<usize>,
596    ) -> Result<Parts<'t, 'c, 'j>, DecodeError> {
597        match (payload, json) {
598            (Payload::None, None) => Ok(Parts::Indexed(Vec::new(), &[])),
599            (Payload::None, Some(_)) => {
600                Err(self.refuse(DecodeErrorKind::Mismatch, "carries no payload"))
601            }
602            (_, None) => Err(self.refuse(
603                DecodeErrorKind::Mismatch,
604                "carries a payload, so it is written as an object",
605            )),
606            (Payload::Positional(1), Some(json)) => Ok(Parts::One(
607                types.into_iter().next().expect("one part"),
608                json,
609            )),
610            (Payload::Positional(count), Some(Json::Array(items))) if items.len() == *count => {
611                Ok(Parts::Indexed(types, items))
612            }
613            (Payload::Positional(count), Some(json)) => {
614                Err(self.expected(&format!("an array of {count} elements"), json))
615            }
616            (Payload::Named(names), Some(Json::Object(members))) => {
617                let names = names.iter().map(|name| &**name).collect();
618                self.fields(ty, names, types, members, field)
619            }
620            (Payload::Named(_), Some(json)) => Err(self.expected("an object", json)),
621        }
622    }
623
624    /// Named fields `names` of `types`, each read from the member of
625    /// `members` whose name `field` finds it by. Each member is matched
626    /// once, in the order of the text: one that names no field is ignored in
627    /// a reply and refused otherwise, and one that names a field an earlier
628    /// member named is refused.
629    fn fields<'t, 'j>(
630        &mut self,
631        ty: &Type,
632        names: Vec<&'c str>,
633        types: Vec<Cow<'t, Type>>,
634        members: &'j [(String, Json)],
635        field: impl Fn(&str) -> Option<usize>,
636    ) -> Result<Parts<'t, 'c, 'j>, DecodeError> {
637        let mut found: Vec<Option<&'j (String, Json)>> = vec![None; names.len()];
638        for member in members {
639            match field(&member.0) {
640                Some(at) => {
641                    if let Some(first) = found[at] {
642                        self.path.field(names[at]);
643                        return Err(self.refuse(
644                            DecodeErrorKind::Duplicate,
645                            format!(
646                                "is written twice, as {} and {}",
647                                quote(&first.0),
648                                quote(&member.0)
649                            ),
650                        ));
651                    }
652                    found[at] = Some(member);
653                }
654                None if matches!(self.mode, Mode::Input | Mode::Rebuild) => {
655                    self.path.field(&member.0);
656                    return Err(self.refuse(
657                        DecodeErrorKind::Unknown,
658                        format!("is not a field of {}", self.catalog.name(ty)),
659                    ));
660                }
661                None => {}
662            }
663        }
664        let members = found
665            .into_iter()
666            .map(|member| member.map(|(_, json)| json))
667            .collect();
668        Ok(Parts::Fields(names, types, members))
669    }
670
671    /// A `json.Value` standing for `json`.
672    fn raw<'t, 'j>(
673        &mut self,
674        json: &'j Json,
675        level: usize,
676    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
677        let catalog = self.catalog;
678        let raw = catalog.json();
679        let level = self.enter(level)?;
680        let (ctor, payload) = match json {
681            Json::Null => (JsonValueCtor::Null, Vec::new()),
682            Json::Bool(value) => (JsonValueCtor::Bool, vec![Value::Bool(*value)]),
683            Json::Number(value) => (JsonValueCtor::Number, vec![self.decimal(value)?]),
684            Json::String(value) => (JsonValueCtor::Text, vec![Value::Text(self.text(value)?)]),
685            Json::Array(_) => {
686                return Ok(Frame::open(
687                    Make::Unwritten(Arc::clone(&raw.shape), raw.ctors.index(JsonValueCtor::List)),
688                    Parts::One(Cow::Owned(Type::list(Type::Json)), json),
689                    0,
690                    level,
691                ));
692            }
693            Json::Object(_) => {
694                return Ok(Frame::open(
695                    Make::Unwritten(
696                        Arc::clone(&raw.shape),
697                        raw.ctors.index(JsonValueCtor::Object),
698                    ),
699                    Parts::One(Cow::Owned(Type::dict(Type::Text, Type::Json)), json),
700                    0,
701                    level,
702                ));
703            }
704        };
705        Ok(Begun::Done(Value::Variant(
706            Variant::new(Arc::clone(&raw.shape), raw.ctors.index(ctor), payload)
707                .expect("std's json.Value"),
708        )))
709    }
710}
711
712/// Where an aggregate's parts come from, and their types, each borrowed for
713/// as long as the type of the whole value is when it is a part of it.
714enum Parts<'t, 'c, 'j> {
715    /// The elements of a list or a set, all of one type, each at its index.
716    Items(Cow<'t, Type>, &'j [Json]),
717    /// The elements of a tuple or a payload, each of its own type and at its
718    /// index.
719    Indexed(Vec<Cow<'t, Type>>, &'j [Json]),
720    /// One value, read where the aggregate is.
721    One(Cow<'t, Type>, &'j Json),
722    /// Named fields of these types, each read from the member found for it,
723    /// if any.
724    Fields(Vec<&'c str>, Vec<Cow<'t, Type>>, Vec<Option<&'j Json>>),
725    /// A dictionary's entries of these key and value types, written as an
726    /// object's members.
727    Members(Cow<'t, Type>, Cow<'t, Type>, &'j [(String, Json)]),
728    /// A dictionary's entries of these key and value types, written as
729    /// `[key, value]` pairs.
730    Pairs(Cow<'t, Type>, Cow<'t, Type>, &'j [Json]),
731}
732
733impl<'t, 'c, 'j> Source<Parts<'t, 'c, 'j>> for Decoder<'c> {
734    fn path(&mut self) -> &mut Place {
735        &mut self.path
736    }
737
738    fn next(
739        &mut self,
740        frame: &mut Frame<Parts<'t, 'c, 'j>>,
741    ) -> Result<Option<Begun<Parts<'t, 'c, 'j>>>, DecodeError> {
742        let at = frame.values.len();
743        let level = frame.level;
744        let begun = match &frame.parts {
745            Parts::Items(item, items) => {
746                let Some(json) = items.get(at) else {
747                    return Ok(None);
748                };
749                self.path.index(at);
750                self.begin(item, json, level)?
751            }
752            Parts::Indexed(types, items) => {
753                let Some((ty, json)) = types.get(at).zip(items.get(at)) else {
754                    return Ok(None);
755                };
756                self.path.index(at);
757                self.begin(ty, json, level)?
758            }
759            Parts::One(ty, json) => {
760                if at > 0 {
761                    return Ok(None);
762                }
763                self.begin(ty, json, level)?
764            }
765            Parts::Fields(names, types, members) => {
766                let Some((name, ty)) = names.get(at).zip(types.get(at)) else {
767                    return Ok(None);
768                };
769                self.path.field(name);
770                let member = members[at];
771                self.field(ty, member, level)?
772            }
773            Parts::Members(key, item, members) => {
774                let Some((name, member)) = members.get(at / 2) else {
775                    return Ok(None);
776                };
777                self.path.key(name);
778                // The key is read through its own type, so a newtype with a
779                // form holds it to that form.
780                let key = self.value(key, &Json::String(name.clone()), level)?;
781                frame.values.push(key);
782                self.begin(item, member, level)?
783            }
784            Parts::Pairs(key, item, pairs) => {
785                let Some(pair) = pairs.get(at / 2) else {
786                    return Ok(None);
787                };
788                let parts = match pair {
789                    Json::Array(parts) if parts.len() == 2 => parts,
790                    _ => {
791                        self.path.index(at / 2);
792                        return Err(self.expected("a `[key, value]` pair", pair));
793                    }
794                };
795                if at.is_multiple_of(2) {
796                    self.path.index(at / 2);
797                    self.path.index(0);
798                    self.begin(key, &parts[0], level)?
799                } else {
800                    self.path.index(1);
801                    self.begin(item, &parts[1], level)?
802                }
803            }
804        };
805        Ok(Some(begun))
806    }
807
808    fn steps(frame: &Frame<Parts<'t, 'c, 'j>>) -> usize {
809        match frame.parts {
810            Parts::One(..) => 0,
811            // A pair's key leaves its index in the pair, and its value
812            // leaves that and the pair's own.
813            Parts::Pairs(..) if frame.values.len() % 2 == 1 => 1,
814            Parts::Pairs(..) => 2,
815            Parts::Items(..) | Parts::Indexed(..) | Parts::Fields(..) | Parts::Members(..) => 1,
816        }
817    }
818
819    fn set(&self, items: Vec<Value>) -> Result<Set, DecodeError> {
820        distinct_set(items, &self.path)
821    }
822
823    fn dict(&self, entries: Vec<(Value, Value)>) -> Result<Dict, DecodeError> {
824        distinct_dict(entries, &self.path)
825    }
826
827    fn form(&self, form: StdForm, text: Text) -> Result<Value, DecodeError> {
828        normal(form, &text, self.limits, &self.path)
829    }
830}
831
832/// The bytes standard base64 with padding spells, or `None` for any other
833/// text: a character outside the alphabet, missing or misplaced padding, or
834/// bits set past the last byte.
835pub fn base64(text: &str) -> Option<Vec<u8>> {
836    let sextet = |byte: u8| -> Option<u32> {
837        Some(u32::from(match byte {
838            b'A'..=b'Z' => byte - b'A',
839            b'a'..=b'z' => byte - b'a' + 26,
840            b'0'..=b'9' => byte - b'0' + 52,
841            b'+' => 62,
842            b'/' => 63,
843            _ => return None,
844        }))
845    };
846    let bytes = text.as_bytes();
847    if !bytes.len().is_multiple_of(4) {
848        return None;
849    }
850    let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
851    let groups = bytes.len() / 4;
852    for (at, group) in bytes.chunks(4).enumerate() {
853        let padding = group.iter().rev().take_while(|byte| **byte == b'=').count();
854        if padding > 2 || (padding > 0 && at + 1 != groups) {
855            return None;
856        }
857        let mut bits = 0u32;
858        for byte in &group[..4 - padding] {
859            // The low six bits are clear, so adding places the sextet.
860            bits = (bits << 6) + sextet(*byte)?;
861        }
862        bits <<= 6 * padding;
863        let [_, first, second, third] = bits.to_be_bytes();
864        let kept = 3 - padding;
865        let unused = [first, second, third];
866        if unused[kept..].iter().any(|byte| *byte != 0) {
867            return None;
868        }
869        out.extend_from_slice(&unused[..kept]);
870    }
871    Some(out)
872}
873
874#[cfg(test)]
875#[cfg_attr(coverage, coverage(off))]
876mod tests;