Skip to main content

ostrya_gvariant/
text.rs

1//! The reader of the GVariant text form.
2//!
3//! `MAX_NESTING` bounds the depth of the node tree. This limit also bounds the
4//! recursion of type inference, of value construction, and of the drop of the
5//! tree.
6
7use std::fmt;
8
9use crate::{Type, Value};
10
11/// The nesting level at which the parser refuses a value.
12///
13/// A container, a `just`, a variant, a type declaration, and a type keyword
14/// each add one level. The parser refuses the value at this level with
15/// `variant nested too deeply`.
16const MAX_NESTING: usize = 128;
17
18/// A half-open byte range of the input text that a [`TextError`] names.
19///
20/// [`fmt::Display`] writes `start` for a zero-width span, and `start-end`
21/// for every other span.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct Span {
24    /// The byte offset at which the range starts.
25    pub start: usize,
26    /// The byte offset one past the end of the range.
27    ///
28    /// It equals [`start`](Span::start) for the zero-width position that an
29    /// `expected ...` refusal reports.
30    pub end: usize,
31}
32
33impl Span {
34    fn new(start: usize, end: usize) -> Span {
35        Span { start, end }
36    }
37
38    /// The zero-width position ahead of a token.
39    ///
40    /// An `expected ...` refusal reports this position.
41    fn point(at: usize) -> Span {
42        Span { start: at, end: at }
43    }
44}
45
46impl fmt::Display for Span {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        if self.start == self.end {
49            write!(f, "{}", self.start)
50        } else {
51            write!(f, "{}-{}", self.start, self.end)
52        }
53    }
54}
55
56/// The error for a GVariant text form that [`from_text`] refuses.
57///
58/// It holds the spans of the input that the refusal names, and the reason.
59/// [`fmt::Display`] writes the pair as `<spans>:<reason>`, the form that the
60/// `ostree` command reports. A comma separates two spans.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct TextError {
63    /// The ranges of the input that the refusal names.
64    ///
65    /// The ranges are in the order of the message. Most refusals hold one
66    /// span. If the reason names a pair that disagrees, the field holds two
67    /// spans, for example the two elements that a container cannot unify.
68    pub spans: Vec<Span>,
69    /// The refusal text, without the spans and without the separating colon.
70    pub reason: String,
71}
72
73impl TextError {
74    fn new(span: Span, reason: impl Into<String>) -> TextError {
75        TextError {
76            spans: vec![span],
77            reason: reason.into(),
78        }
79    }
80}
81
82impl fmt::Display for TextError {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        for (index, span) in self.spans.iter().enumerate() {
85            if index > 0 {
86                f.write_str(",")?;
87            }
88            write!(f, "{span}")?;
89        }
90        write!(f, ":{}", self.reason)
91    }
92}
93
94impl std::error::Error for TextError {}
95
96type TextResult<T> = std::result::Result<T, TextError>;
97
98/// The reason for the refusal of a literal that states no type.
99///
100/// [`value_type`] widens the span of this error to the whole value. The
101/// `ostree` command reports the refusal at that span.
102const CANNOT_INFER: &str = "unable to infer type";
103
104/// Reads one GVariant text form and returns the type it states and the value.
105///
106/// [`to_text`](crate::to_text) writes this form. The reader parses, types, and builds the
107/// first value. Then it checks the text for trailing input.
108///
109/// The rules and every refusal message come from the `ostree` command, run as
110/// a black box. `ostree commit --add-metadata=KEY=VALUE` stored each value,
111/// and `ostree show -B --print-metadata-key` read it back.
112///
113/// # Type inference
114///
115/// - A value takes its type from its literal. An integer literal with no
116///   other context is `i`, and a literal with a fraction is `d`.
117/// - If the literal cannot state the type, a declaration (`@ms 'x'`) or a
118///   keyword (`uint32 42`) states it.
119/// - A container with no declaration unifies the types of its elements.
120///   `[2, 1.5]` is `ad`, and `['a', @ms 'b']` is `ams`.
121/// - A declaration drives the check down into the members. The error for
122///   `@as [1]` names the element `1` and the type `s`.
123/// - The reader refuses a literal that states no type and has no context,
124///   for example `[]`, `{}`, or `nothing`. The reason is
125///   `unable to infer type`.
126///
127/// # Depth limit
128///
129/// A container, a `just`, a variant, a type declaration, and a type keyword
130/// each add one level. A value can nest inside at most 127 levels. If the
131/// text reaches level 128, the reader refuses it with
132/// `variant nested too deeply`.
133///
134/// A declared type counts its own levels, with the leaf as one level, from
135/// the level of the declaration. The empty tuple `()` holds no leaf, so it
136/// counts as zero levels. If the sum is more than 128, the reader
137/// refuses the declaration with `type declaration recurses too deeply`.
138///
139/// # Errors
140///
141/// If the reader refuses the text, it returns a [`TextError`]. The error for
142/// a fault in the first value has priority over the error for trailing input.
143/// For example, `nothing 5` reports the type that the reader cannot infer.
144/// `@i 'x' 5` reports the member that does not fit.
145///
146/// # Examples
147///
148/// ```
149/// use ostrya_gvariant::{from_text, to_text};
150///
151/// let (ty, value) = from_text("{'version': <'1'>}")?;
152/// assert_eq!(ty.signature(), "a{sv}");
153/// assert_eq!(to_text(&ty, &value)?, "{'version': <'1'>}");
154/// # Ok::<(), Box<dyn std::error::Error>>(())
155/// ```
156pub fn from_text(text: &str) -> TextResult<(Type, Value)> {
157    let mut parser = Parser::new(text);
158    let node = parser.value()?;
159    let ty = value_type(&node)?;
160    let value = build(&node, &ty)?;
161    parser.expect_end()?;
162    Ok((ty, value))
163}
164
165// --- tokens ------------------------------------------------------------------
166
167#[derive(Debug, Clone, PartialEq, Eq)]
168enum Tok {
169    Open(char),
170    Close(char),
171    Comma,
172    Colon,
173    /// `@` and the characters that follow it.
174    ///
175    /// The parser checks these characters as a type after the lexer scans the
176    /// token.
177    TypeDecl(String),
178    Word(String),
179    Number(String),
180    Str(String),
181    ByteString(Vec<u8>),
182    End,
183}
184
185#[derive(Debug, Clone)]
186struct Token {
187    tok: Tok,
188    span: Span,
189}
190
191struct Lexer<'a> {
192    text: &'a [u8],
193    pos: usize,
194}
195
196impl<'a> Lexer<'a> {
197    fn new(text: &'a str) -> Lexer<'a> {
198        Lexer {
199            text: text.as_bytes(),
200            pos: 0,
201        }
202    }
203
204    fn skip_space(&mut self) {
205        while matches!(self.text.get(self.pos), Some(b' ' | b'\t' | b'\n' | b'\r')) {
206            self.pos += 1;
207        }
208    }
209
210    fn next(&mut self) -> TextResult<Token> {
211        self.skip_space();
212        let start = self.pos;
213        let Some(&c) = self.text.get(start) else {
214            return Ok(Token {
215                tok: Tok::End,
216                span: Span::point(start),
217            });
218        };
219        let tok =
220            match c {
221                b'(' | b'[' | b'{' | b'<' => {
222                    self.pos += 1;
223                    Tok::Open(c as char)
224                }
225                b')' | b']' | b'}' | b'>' => {
226                    self.pos += 1;
227                    Tok::Close(c as char)
228                }
229                b',' => {
230                    self.pos += 1;
231                    Tok::Comma
232                }
233                b':' => {
234                    self.pos += 1;
235                    Tok::Colon
236                }
237                b'@' => {
238                    self.pos += 1;
239                    self.declaration();
240                    Tok::TypeDecl(self.slice(start + 1, self.pos))
241                }
242                b'\'' | b'"' => return self.string(start, c, false),
243                b'b' if matches!(self.text.get(start + 1), Some(b'\'' | b'"')) => {
244                    let quote = self.text[start + 1];
245                    self.pos += 1;
246                    return self.string(start, quote, true);
247                }
248                b'0'..=b'9' | b'-' | b'+' | b'.' => {
249                    self.pos += 1;
250                    while self.text.get(self.pos).is_some_and(|b| {
251                        b.is_ascii_alphanumeric() || matches!(b, b'.' | b'+' | b'-')
252                    }) {
253                        self.pos += 1;
254                    }
255                    Tok::Number(self.slice(start, self.pos))
256                }
257                b'a'..=b'z' => {
258                    while self
259                        .text
260                        .get(self.pos)
261                        .is_some_and(u8::is_ascii_alphanumeric)
262                    {
263                        self.pos += 1;
264                    }
265                    Tok::Word(self.slice(start, self.pos))
266                }
267                // Every other character is a one-character token. No keyword has
268                // one character, so the parser reports the token as a place where
269                // it expected a value.
270                _ => {
271                    self.pos += 1;
272                    Tok::Word(self.slice(start, self.pos))
273                }
274            };
275        Ok(Token {
276            tok,
277            span: Span::new(start, self.pos),
278        })
279    }
280
281    /// Scans the body of a `@` declaration.
282    ///
283    /// The scan stops at the first character that can close something around
284    /// the declaration. These characters are white space, `,`, `:`, `>`, `]`,
285    /// and an unmatched `)` or `}`. The scan reads all of `@i5` and `@**`,
286    /// and the parser reports each as one bad declaration. The scan of `@i)`
287    /// stops at the bracket.
288    fn declaration(&mut self) {
289        let mut depth = 0usize;
290        while let Some(&c) = self.text.get(self.pos) {
291            match c {
292                b' ' | b'\t' | b'\n' | b'\r' | b',' | b':' | b'>' | b']' => break,
293                b')' | b'}' if depth == 0 => break,
294                b')' | b'}' => depth -= 1,
295                b'(' | b'{' => depth += 1,
296                _ => {}
297            }
298            self.pos += 1;
299        }
300    }
301
302    /// Scans a quoted literal from `start`, with `quote` as its opening quote.
303    ///
304    /// A bytestring keeps its bytes. The scan decodes a string as UTF-8.
305    fn string(&mut self, start: usize, quote: u8, bytestring: bool) -> TextResult<Token> {
306        self.pos += 1; // the opening quote
307        let mut raw = Vec::new();
308        loop {
309            let Some(&c) = self.text.get(self.pos) else {
310                self.pos = self.text.len();
311                return Err(TextError::new(
312                    Span::new(start, self.pos),
313                    "unterminated string constant",
314                ));
315            };
316            self.pos += 1;
317            if c == quote {
318                break;
319            }
320            if c != b'\\' {
321                // A string value carries no NUL, so the scan refuses a raw NUL
322                // in a string at its position. A bytestring keeps the NUL, and
323                // its value ends there. An octal escape that names NUL has the
324                // same result.
325                if c == 0 && !bytestring {
326                    return Err(TextError::new(
327                        Span::new(self.pos - 1, self.pos),
328                        "NUL byte in string constant",
329                    ));
330                }
331                raw.push(c);
332                continue;
333            }
334            let Some(&escaped) = self.text.get(self.pos) else {
335                self.pos = self.text.len();
336                return Err(TextError::new(
337                    Span::new(start, self.pos),
338                    "unterminated string constant",
339                ));
340            };
341            self.pos += 1;
342            match escaped {
343                b'a' => raw.push(0x07),
344                b'b' => raw.push(0x08),
345                b'f' => raw.push(0x0c),
346                b'n' => raw.push(b'\n'),
347                b'r' => raw.push(b'\r'),
348                b't' => raw.push(b'\t'),
349                b'v' => raw.push(0x0b),
350                b'0'..=b'7' if bytestring => {
351                    // A bytestring reads a maximum of three octal digits. The
352                    // printer writes this escape for a bytestring.
353                    let mut value = u32::from(escaped - b'0');
354                    for _ in 0..2 {
355                        match self.text.get(self.pos) {
356                            Some(&d @ b'0'..=b'7') => {
357                                value = value * 8 + u32::from(d - b'0');
358                                self.pos += 1;
359                            }
360                            _ => break,
361                        }
362                    }
363                    raw.push(value as u8);
364                }
365                b'u' if !bytestring => self.unicode_escape(4, &mut raw)?,
366                b'U' if !bytestring => self.unicode_escape(8, &mut raw)?,
367                // A backslash before a line feed is a line continuation. Both
368                // characters leave the value. A string and a bytestring use the
369                // same rule.
370                b'\n' => {}
371                // Every other escape drops the backslash and keeps the byte.
372                other => raw.push(other),
373            }
374        }
375        let span = Span::new(start, self.pos);
376        if bytestring {
377            // A bytestring literal names a NUL-terminated byte array, so the
378            // value ends at the first NUL that its escapes produce. Then the
379            // value gets one terminator of its own.
380            if let Some(nul) = raw.iter().position(|&b| b == 0) {
381                raw.truncate(nul);
382            }
383            raw.push(0);
384            return Ok(Token {
385                tok: Tok::ByteString(raw),
386                span,
387            });
388        }
389        match String::from_utf8(raw) {
390            Ok(text) => Ok(Token {
391                tok: Tok::Str(text),
392                span,
393            }),
394            Err(_) => Err(TextError::new(span, "invalid character in string constant")),
395        }
396    }
397
398    /// Reads a `\u` or `\U` escape of `digits` hexadecimal digits.
399    ///
400    /// It appends the named character to `raw` in UTF-8. A refusal names the
401    /// digits that are present. If no digits are present, the refusal names a
402    /// zero-width position.
403    fn unicode_escape(&mut self, digits: usize, raw: &mut Vec<u8>) -> TextResult<()> {
404        let start = self.pos;
405        let mut count = 0;
406        while count < digits
407            && self
408                .text
409                .get(start + count)
410                .is_some_and(u8::is_ascii_hexdigit)
411        {
412            count += 1;
413        }
414        let bad = || {
415            TextError::new(
416                Span::new(start, start + count),
417                format!("invalid {digits}-character unicode escape"),
418            )
419        };
420        if count < digits {
421            return Err(bad());
422        }
423        let text = std::str::from_utf8(&self.text[start..start + digits]).map_err(|_| bad())?;
424        let code = u32::from_str_radix(text, 16).map_err(|_| bad())?;
425        // A string value carries no NUL, so this check refuses U+0000. It uses
426        // the words and the offset of the `ostree` command. This check also
427        // refuses a surrogate and a code point past U+10FFFF. For these, the
428        // `ostree` command builds a string that is not UTF-8 and aborts.
429        let ch = char::from_u32(code)
430            .filter(|&c| c != '\0')
431            .ok_or_else(bad)?;
432        self.pos = start + digits;
433        let mut buf = [0u8; 4];
434        raw.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
435        Ok(())
436    }
437
438    fn slice(&self, start: usize, end: usize) -> String {
439        String::from_utf8_lossy(&self.text[start..end]).into_owned()
440    }
441}
442
443// --- the syntax tree ---------------------------------------------------------
444
445#[derive(Debug, Clone)]
446struct Node {
447    ast: Ast,
448    span: Span,
449}
450
451#[derive(Debug, Clone)]
452enum Ast {
453    Bool(bool),
454    /// A numeric literal, kept as its text.
455    ///
456    /// Its value depends on the type that it gets. For example, `@d 017` is
457    /// 17.0, and `017` alone is 15.
458    Number(String),
459    Str(String),
460    ByteString(Vec<u8>),
461    /// A value under a `@type` declaration or a type keyword.
462    Typed(Type, Box<Node>),
463    /// `just <value>`, or `nothing`.
464    Maybe(Option<Box<Node>>),
465    Array(Vec<Node>),
466    /// `{key: value, ...}`, an array of dict entries.
467    Dict(Vec<(Node, Node)>),
468    /// `{key, value}`, one dict entry.
469    Entry(Box<Node>, Box<Node>),
470    Tuple(Vec<Node>),
471    Variant(Box<Node>),
472}
473
474/// Returns `true` if a token has the shape of a keyword.
475///
476/// A keyword has two or more characters, and its first two characters are
477/// letters. If a token has this shape and is not a known keyword, the parser
478/// reports `unknown keyword`. The parser reports a shorter token, or a token
479/// with a digit as its second character, with `expected value`.
480fn is_keyword_shaped(word: &str) -> bool {
481    let bytes = word.as_bytes();
482    bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1].is_ascii_alphabetic()
483}
484
485/// The type keywords that a value can carry in place of a `@` declaration.
486fn keyword_type(word: &str) -> Option<Type> {
487    Some(match word {
488        "boolean" => Type::Bool,
489        "byte" => Type::Byte,
490        "int16" => Type::I16,
491        "uint16" => Type::U16,
492        "int32" => Type::I32,
493        "handle" => Type::Handle,
494        "uint32" => Type::U32,
495        "int64" => Type::I64,
496        "uint64" => Type::U64,
497        "double" => Type::Double,
498        "string" => Type::Str,
499        "objectpath" => Type::ObjectPath,
500        "signature" => Type::Signature,
501        _ => return None,
502    })
503}
504
505struct Parser<'a> {
506    lexer: Lexer<'a>,
507    /// The next token, or the error from the lexer for that token.
508    ///
509    /// When the parser consumes the token, the error surfaces.
510    ahead: TextResult<Token>,
511    /// The end offset of the token that the parser consumed last.
512    ///
513    /// It closes the span of a container.
514    last_end: usize,
515    /// The number of levels of container, `just`, variant, or declaration
516    /// around the value that the parser reads.
517    depth: usize,
518}
519
520impl<'a> Parser<'a> {
521    fn new(text: &'a str) -> Parser<'a> {
522        let mut lexer = Lexer::new(text);
523        let ahead = lexer.next();
524        Parser {
525            lexer,
526            ahead,
527            last_end: 0,
528            depth: 0,
529        }
530    }
531
532    fn peek(&self) -> Option<&Tok> {
533        self.ahead.as_ref().ok().map(|token| &token.tok)
534    }
535
536    /// The offset at which the next token starts.
537    ///
538    /// An `expected ...` refusal reports this offset.
539    fn ahead_start(&self) -> usize {
540        self.ahead
541            .as_ref()
542            .map_or(self.last_end, |token| token.span.start)
543    }
544
545    fn bump(&mut self) -> TextResult<Token> {
546        let next = self.lexer.next();
547        let token = std::mem::replace(&mut self.ahead, next)?;
548        self.last_end = token.span.end;
549        Ok(token)
550    }
551
552    fn expect_end(&mut self) -> TextResult<()> {
553        match &self.ahead {
554            Ok(token) if token.tok == Tok::End => Ok(()),
555            Ok(token) => Err(TextError::new(
556                Span::point(token.span.start),
557                "expected end of input",
558            )),
559            Err(error) => Err(error.clone()),
560        }
561    }
562
563    /// Reads one value nested inside the current value, one level deeper.
564    fn nested(&mut self) -> TextResult<Node> {
565        self.depth += 1;
566        let node = self.value();
567        self.depth -= 1;
568        node
569    }
570
571    fn value(&mut self) -> TextResult<Node> {
572        if self.depth >= MAX_NESTING {
573            return Err(TextError::new(
574                Span::point(self.ahead_start()),
575                "variant nested too deeply",
576            ));
577        }
578        let token = self.bump()?;
579        let start = token.span.start;
580        match token.tok {
581            Tok::Str(text) => Ok(Node {
582                ast: Ast::Str(text),
583                span: token.span,
584            }),
585            Tok::ByteString(bytes) => Ok(Node {
586                ast: Ast::ByteString(bytes),
587                span: token.span,
588            }),
589            Tok::Number(text) => Ok(Node {
590                ast: Ast::Number(text),
591                span: token.span,
592            }),
593            Tok::TypeDecl(signature) => {
594                // The parser reads a declaration in three steps. First, the
595                // signature must spell one complete type. Next, that type must
596                // fit in the nesting that is left at this level. Last, the type
597                // must be definite.
598                let parsed = Type::parse(&signature).ok();
599                let levels = match &parsed {
600                    Some(ty) => type_depth(ty),
601                    None => match classify_declaration(&signature) {
602                        Declaration::Indefinite(levels) => levels,
603                        Declaration::Invalid => {
604                            return Err(TextError::new(token.span, "invalid type declaration"));
605                        }
606                    },
607                };
608                // The levels of the declared type count from the level of the
609                // declaration. The deeper the declaration is, the fewer
610                // levels its type can have.
611                if self.depth + levels > MAX_NESTING {
612                    return Err(TextError::new(
613                        token.span,
614                        "type declaration recurses too deeply",
615                    ));
616                }
617                let Some(ty) = parsed else {
618                    return Err(TextError::new(
619                        token.span,
620                        "type declarations must be definite",
621                    ));
622                };
623                let child = self.nested()?;
624                let end = child.span.end;
625                Ok(Node {
626                    ast: Ast::Typed(ty, Box::new(child)),
627                    span: Span::new(start, end),
628                })
629            }
630            // A keyword has two or more characters and starts with two
631            // letters. The parser reports any other word as a place where it
632            // expected a value.
633            Tok::Word(word) if is_keyword_shaped(&word) => self.word(&word, token.span),
634            Tok::Open('[') => self.array(start),
635            Tok::Open('{') => self.dict(start),
636            Tok::Open('(') => self.tuple(start),
637            Tok::Open('<') => {
638                let child = self.nested()?;
639                self.close('>', "expected '>' to follow variant value")?;
640                Ok(Node {
641                    ast: Ast::Variant(Box::new(child)),
642                    span: Span::new(start, self.last_end),
643                })
644            }
645            _ => Err(TextError::new(Span::point(start), "expected value")),
646        }
647    }
648
649    fn word(&mut self, word: &str, span: Span) -> TextResult<Node> {
650        match word {
651            "true" => Ok(Node {
652                ast: Ast::Bool(true),
653                span,
654            }),
655            "false" => Ok(Node {
656                ast: Ast::Bool(false),
657                span,
658            }),
659            // The two numeric literals that are words. `infinity` is a value
660            // only after a sign, for example `-infinity`.
661            "nan" | "inf" => Ok(Node {
662                ast: Ast::Number(word.to_owned()),
663                span,
664            }),
665            "nothing" => Ok(Node {
666                ast: Ast::Maybe(None),
667                span,
668            }),
669            "just" => {
670                let child = self.nested()?;
671                let end = child.span.end;
672                Ok(Node {
673                    ast: Ast::Maybe(Some(Box::new(child))),
674                    span: Span::new(span.start, end),
675                })
676            }
677            _ => match keyword_type(word) {
678                Some(ty) => {
679                    let child = self.nested()?;
680                    let end = child.span.end;
681                    Ok(Node {
682                        ast: Ast::Typed(ty, Box::new(child)),
683                        span: Span::new(span.start, end),
684                    })
685                }
686                None => Err(TextError::new(span, "unknown keyword")),
687            },
688        }
689    }
690
691    fn array(&mut self, start: usize) -> TextResult<Node> {
692        let mut items = Vec::new();
693        if matches!(self.peek(), Some(Tok::Close(']'))) {
694            self.bump()?;
695            return Ok(Node {
696                ast: Ast::Array(items),
697                span: Span::new(start, self.last_end),
698            });
699        }
700        loop {
701            items.push(self.nested()?);
702            match self.peek() {
703                Some(Tok::Comma) => {
704                    self.bump()?;
705                }
706                Some(Tok::Close(']')) => {
707                    self.bump()?;
708                    break;
709                }
710                _ => {
711                    return Err(TextError::new(
712                        Span::point(self.ahead_start()),
713                        "expected ',' or ']' to follow array element",
714                    ));
715                }
716            }
717        }
718        Ok(Node {
719            ast: Ast::Array(items),
720            span: Span::new(start, self.last_end),
721        })
722    }
723
724    fn dict(&mut self, start: usize) -> TextResult<Node> {
725        if matches!(self.peek(), Some(Tok::Close('}'))) {
726            self.bump()?;
727            return Ok(Node {
728                ast: Ast::Dict(Vec::new()),
729                span: Span::new(start, self.last_end),
730            });
731        }
732        let first_key = self.nested()?;
733        // `{key, value}` is one dict entry. `{key: value, ...}` is an array of
734        // dict entries.
735        if matches!(self.peek(), Some(Tok::Comma)) {
736            self.bump()?;
737            let value = self.nested()?;
738            self.close('}', "expected '}' at end of dictionary entry")?;
739            return Ok(Node {
740                ast: Ast::Entry(Box::new(first_key), Box::new(value)),
741                span: Span::new(start, self.last_end),
742            });
743        }
744        if !matches!(self.peek(), Some(Tok::Colon)) {
745            return Err(TextError::new(
746                Span::point(self.ahead_start()),
747                "expected ':' or ',' to follow dictionary entry key",
748            ));
749        }
750        self.bump()?;
751        let mut entries = vec![(first_key, self.nested()?)];
752        loop {
753            match self.peek() {
754                Some(Tok::Comma) => {
755                    self.bump()?;
756                }
757                Some(Tok::Close('}')) => {
758                    self.bump()?;
759                    break;
760                }
761                _ => {
762                    return Err(TextError::new(
763                        Span::point(self.ahead_start()),
764                        "expected ',' or '}' to follow dictionary entry",
765                    ));
766                }
767            }
768            let key = self.nested()?;
769            if !matches!(self.peek(), Some(Tok::Colon)) {
770                return Err(TextError::new(
771                    Span::point(self.ahead_start()),
772                    "expected ':' to follow dictionary entry key",
773                ));
774            }
775            self.bump()?;
776            entries.push((key, self.nested()?));
777        }
778        Ok(Node {
779            ast: Ast::Dict(entries),
780            span: Span::new(start, self.last_end),
781        })
782    }
783
784    fn tuple(&mut self, start: usize) -> TextResult<Node> {
785        let mut items = Vec::new();
786        if matches!(self.peek(), Some(Tok::Close(')'))) {
787            self.bump()?;
788            return Ok(Node {
789                ast: Ast::Tuple(items),
790                span: Span::new(start, self.last_end),
791            });
792        }
793        // The text form of a one-member tuple is `(x,)`. The comma after the
794        // first element is necessary, and the parser refuses `(x)`.
795        items.push(self.nested()?);
796        if !matches!(self.peek(), Some(Tok::Comma)) {
797            return Err(TextError::new(
798                Span::point(self.ahead_start()),
799                "expected ',' after first tuple element",
800            ));
801        }
802        self.bump()?;
803        if matches!(self.peek(), Some(Tok::Close(')'))) {
804            self.bump()?;
805            return Ok(Node {
806                ast: Ast::Tuple(items),
807                span: Span::new(start, self.last_end),
808            });
809        }
810        loop {
811            items.push(self.nested()?);
812            match self.peek() {
813                Some(Tok::Comma) => {
814                    self.bump()?;
815                }
816                Some(Tok::Close(')')) => {
817                    self.bump()?;
818                    break;
819                }
820                _ => {
821                    return Err(TextError::new(
822                        Span::point(self.ahead_start()),
823                        "expected ',' or ')' to follow tuple element",
824                    ));
825                }
826            }
827        }
828        Ok(Node {
829            ast: Ast::Tuple(items),
830            span: Span::new(start, self.last_end),
831        })
832    }
833
834    fn close(&mut self, bracket: char, reason: &str) -> TextResult<()> {
835        if matches!(self.peek(), Some(Tok::Close(c)) if *c == bracket) {
836            self.bump()?;
837            return Ok(());
838        }
839        Err(TextError::new(Span::point(self.ahead_start()), reason))
840    }
841}
842
843// --- type declarations -------------------------------------------------------
844
845/// The class of a `@` declaration that the [`Type`] parser refused.
846enum Declaration {
847    /// One complete type that names `r`, `*`, or `?`.
848    ///
849    /// The field holds the levels of the type, as [`type_depth`] counts them.
850    Indefinite(usize),
851    /// Not one complete type.
852    Invalid,
853}
854
855/// The maximum nesting of a declaration scan.
856///
857/// If a declaration is deeper, the scan reports it as invalid. This value is
858/// the depth that the [`Type`] parser accepts. If the scanner reads a
859/// declaration to the end, the parser refused that declaration for a
860/// different reason.
861const MAX_DECLARATION_DEPTH: usize = crate::de::MAX_VALUE_DEPTH;
862
863/// The number of levels that a declared type carries.
864///
865/// A value under the type takes up the same number of levels of nesting. A
866/// leaf is one level. Each container adds one level over its deepest member.
867/// For example, `y` is one level, `aay` is three, and `(y(y))` is three.
868///
869/// The empty tuple has no member, so it is zero levels. `a{s()}` is two
870/// levels, and `a{sy}` is three. A dict entry measures its value, because its
871/// key is always a leaf of one level.
872///
873/// [`Type::parse`] limits the type to [`MAX_DECLARATION_DEPTH`] levels of
874/// container. That limit also bounds the recursion of this function.
875fn type_depth(ty: &Type) -> usize {
876    match ty {
877        Type::Maybe(elem) | Type::Array(elem) => 1 + type_depth(elem),
878        Type::Tuple(members) => members
879            .iter()
880            .map(|member| 1 + type_depth(member))
881            .max()
882            .unwrap_or(0),
883        Type::DictEntry(_, value) => 1 + type_depth(value),
884        _ => 1,
885    }
886}
887
888/// Sorts a refused declaration into an indefinite type or an invalid text.
889///
890/// Only a declaration that [`Type::parse`] refused gets to this function.
891fn classify_declaration(signature: &str) -> Declaration {
892    let bytes = signature.as_bytes();
893    let mut pos = 0;
894    let mut indefinite = false;
895    match scan_declared_type(bytes, &mut pos, 0, &mut indefinite) {
896        Some(levels) if pos == bytes.len() && indefinite => Declaration::Indefinite(levels),
897        _ => Declaration::Invalid,
898    }
899}
900
901/// Scans one type and gives the levels that it carries.
902///
903/// The scan accepts the indefinite characters. If no complete type is
904/// present, it returns `None`. It counts the levels as [`type_depth`] counts
905/// them. The parser then reports a declaration that is too deep in the same
906/// way, definite or indefinite.
907fn scan_declared_type(
908    sig: &[u8],
909    pos: &mut usize,
910    depth: usize,
911    indefinite: &mut bool,
912) -> Option<usize> {
913    if depth > MAX_DECLARATION_DEPTH {
914        return None;
915    }
916    let &c = sig.get(*pos)?;
917    *pos += 1;
918    match c {
919        b'b' | b'y' | b'n' | b'q' | b'i' | b'u' | b'x' | b't' | b'h' | b'd' | b's' | b'o'
920        | b'g' | b'v' => Some(1),
921        b'r' | b'*' | b'?' => {
922            *indefinite = true;
923            Some(1)
924        }
925        b'm' | b'a' => Some(1 + scan_declared_type(sig, pos, depth + 1, indefinite)?),
926        b'(' => {
927            let mut levels = 0;
928            while sig.get(*pos) != Some(&b')') {
929                let member = scan_declared_type(sig, pos, depth + 1, indefinite)?;
930                levels = levels.max(1 + member);
931            }
932            *pos += 1;
933            Some(levels)
934        }
935        b'{' => {
936            scan_declared_type(sig, pos, depth + 1, indefinite)?;
937            let value = scan_declared_type(sig, pos, depth + 1, indefinite)?;
938            if sig.get(*pos) != Some(&b'}') {
939                return None;
940            }
941            *pos += 1;
942            Some(1 + value)
943        }
944        _ => None,
945    }
946}
947
948// --- numeric literals --------------------------------------------------------
949
950/// The type that a numeric literal names without context.
951#[derive(Debug, Clone, Copy, PartialEq, Eq)]
952enum NumberKind {
953    Integer,
954    Double,
955}
956
957/// Splits the leading `-` of a numeric literal from its body.
958///
959/// The `ostree` command reads the sign itself and gives the rest to the
960/// integer reader. A second sign inside the body belongs to the body.
961fn split_sign(text: &str) -> (bool, &str) {
962    match text.strip_prefix('-') {
963        Some(rest) => (true, rest),
964        None => (false, text),
965    }
966}
967
968/// Returns `true` if the body of a numeric literal spells an infinity or a NaN.
969///
970/// The spelling is lower case. The reader reads `-INF` as an integer and
971/// refuses it.
972fn is_special_double(body: &str) -> bool {
973    matches!(body, "inf" | "infinity" | "nan")
974        || matches!(body.strip_prefix('+'), Some("inf" | "infinity" | "nan"))
975}
976
977/// Returns the reader that takes a literal with no stated type.
978///
979/// A body with a fraction, a decimal exponent, or a special spelling is a
980/// double. Every other body is an integer. A hexadecimal body must have a `.`
981/// to be a double. `0x1e5` is 485, `0x1.8p1` is 3.0, and the reader refuses
982/// `0x1p3`.
983fn number_kind(text: &str) -> NumberKind {
984    let (_, body) = split_sign(text);
985    if is_special_double(body) {
986        return NumberKind::Double;
987    }
988    let digits = body.strip_prefix('+').unwrap_or(body);
989    let hex = digits.starts_with("0x") || digits.starts_with("0X");
990    let fractional = if hex {
991        digits.contains('.')
992    } else {
993        digits.contains(['.', 'e'])
994    };
995    if fractional {
996        NumberKind::Double
997    } else {
998        NumberKind::Integer
999    }
1000}
1001
1002/// The result of the integer reader for a literal body.
1003///
1004/// It holds the value, the end of the read, and a flag that is `true` if the
1005/// magnitude passed 64 bits.
1006struct IntegerScan {
1007    value: u64,
1008    end: usize,
1009    overflow: bool,
1010}
1011
1012/// Reads an unsigned integer in the same way as the `ostree` command.
1013///
1014/// The body is an optional sign, then a run of digits. The run is `0x`
1015/// hexadecimal, `0b` binary, leading-`0` octal, or decimal. If the body has
1016/// no digits, the result is zero and reports that the reader read nothing.
1017fn scan_integer(body: &str) -> IntegerScan {
1018    let bytes = body.as_bytes();
1019    let mut pos = 0;
1020    let mut negate = false;
1021    match bytes.first() {
1022        Some(b'+') => pos = 1,
1023        Some(b'-') => {
1024            negate = true;
1025            pos = 1;
1026        }
1027        _ => {}
1028    }
1029    let (radix, start) = if bytes.get(pos) == Some(&b'0')
1030        && matches!(bytes.get(pos + 1), Some(b'x' | b'X'))
1031        && bytes.get(pos + 2).is_some_and(u8::is_ascii_hexdigit)
1032    {
1033        (16u32, pos + 2)
1034    } else if bytes.get(pos) == Some(&b'0')
1035        && matches!(bytes.get(pos + 1), Some(b'b' | b'B'))
1036        && matches!(bytes.get(pos + 2), Some(b'0' | b'1'))
1037    {
1038        (2, pos + 2)
1039    } else if bytes.get(pos) == Some(&b'0') {
1040        (8, pos)
1041    } else {
1042        (10, pos)
1043    };
1044    let mut end = start;
1045    let mut value: u64 = 0;
1046    let mut overflow = false;
1047    while let Some(digit) = bytes.get(end).and_then(|c| char::from(*c).to_digit(radix)) {
1048        match value
1049            .checked_mul(u64::from(radix))
1050            .and_then(|v| v.checked_add(u64::from(digit)))
1051        {
1052            Some(next) => value = next,
1053            None => overflow = true,
1054        }
1055        end += 1;
1056    }
1057    if end == start {
1058        return IntegerScan {
1059            value: 0,
1060            end: 0,
1061            overflow: false,
1062        };
1063    }
1064    if negate {
1065        value = value.wrapping_neg();
1066    }
1067    IntegerScan {
1068        value,
1069        end,
1070        overflow,
1071    }
1072}
1073
1074/// Reads a numeric literal as an integer and gives its sign and magnitude.
1075fn integer_literal(text: &str, span: Span) -> TextResult<(bool, u64)> {
1076    let (negative, body) = split_sign(text);
1077    let offset = text.len() - body.len();
1078    let scan = scan_integer(body);
1079    if scan.end != body.len() {
1080        let at = span.start + offset + scan.end;
1081        return Err(TextError::new(
1082            Span::new(at, at + 1),
1083            "invalid character in number",
1084        ));
1085    }
1086    if scan.overflow {
1087        return Err(TextError::new(span, "integer too big for any type"));
1088    }
1089    Ok((negative, scan.value))
1090}
1091
1092/// A double read from a literal.
1093struct DoubleScan {
1094    /// The value of the literal, rounded to the nearest double.
1095    value: f64,
1096    /// The end of the read.
1097    ///
1098    /// If the reader cannot start on a body, it reads nothing.
1099    end: usize,
1100    /// `true` if the double holds the literal exactly.
1101    ///
1102    /// A decimal body reports `false`, because the decimal reader gives only
1103    /// the value.
1104    exact: bool,
1105}
1106
1107/// Reads a numeric literal as a double.
1108fn scan_double(text: &str) -> DoubleScan {
1109    let bytes = text.as_bytes();
1110    let mut pos = 0;
1111    let mut negative = false;
1112    match bytes.first() {
1113        Some(b'-') => {
1114            negative = true;
1115            pos = 1;
1116        }
1117        Some(b'+') => pos = 1,
1118        _ => {}
1119    }
1120    let signed = |value: f64| if negative { -value } else { value };
1121    let rest = &text[pos..];
1122    for (word, value) in [
1123        ("infinity", f64::INFINITY),
1124        ("inf", f64::INFINITY),
1125        ("nan", f64::NAN),
1126    ] {
1127        if rest.len() >= word.len() && rest[..word.len()].eq_ignore_ascii_case(word) {
1128            return DoubleScan {
1129                value: signed(value),
1130                end: pos + word.len(),
1131                exact: true,
1132            };
1133        }
1134    }
1135    if bytes.get(pos) == Some(&b'0') && matches!(bytes.get(pos + 1), Some(b'x' | b'X')) {
1136        return match scan_hex_double(bytes, pos + 2) {
1137            Some(scan) => DoubleScan {
1138                value: signed(scan.value),
1139                ..scan
1140            },
1141            None => nothing_read(),
1142        };
1143    }
1144    let mut end = pos;
1145    let mut integer = String::new();
1146    while let Some(&c) = bytes.get(end).filter(|c| c.is_ascii_digit()) {
1147        integer.push(char::from(c));
1148        end += 1;
1149    }
1150    let mut fraction = String::new();
1151    if bytes.get(end) == Some(&b'.') {
1152        let mut after = end + 1;
1153        while let Some(&c) = bytes.get(after).filter(|c| c.is_ascii_digit()) {
1154            fraction.push(char::from(c));
1155            after += 1;
1156        }
1157        end = after;
1158    }
1159    if integer.is_empty() && fraction.is_empty() {
1160        return nothing_read();
1161    }
1162    let mut exponent = String::new();
1163    if matches!(bytes.get(end), Some(b'e' | b'E')) {
1164        let mut after = end + 1;
1165        if matches!(bytes.get(after), Some(b'+' | b'-')) {
1166            exponent.push(char::from(bytes[after]));
1167            after += 1;
1168        }
1169        let digits = after;
1170        while let Some(&c) = bytes.get(after).filter(|c| c.is_ascii_digit()) {
1171            exponent.push(char::from(c));
1172            after += 1;
1173        }
1174        if after > digits {
1175            end = after;
1176        } else {
1177            exponent.clear();
1178        }
1179    }
1180    if integer.is_empty() {
1181        integer.push('0');
1182    }
1183    if fraction.is_empty() {
1184        fraction.push('0');
1185    }
1186    if exponent.is_empty() {
1187        exponent.push('0');
1188    }
1189    let value: f64 = format!("{integer}.{fraction}e{exponent}")
1190        .parse()
1191        .unwrap_or(f64::INFINITY);
1192    DoubleScan {
1193        value: signed(value),
1194        end,
1195        exact: false,
1196    }
1197}
1198
1199/// The scan result for a body that the double reader cannot start on.
1200fn nothing_read() -> DoubleScan {
1201    DoubleScan {
1202        value: 0.0,
1203        end: 0,
1204        exact: false,
1205    }
1206}
1207
1208/// The largest mantissa into which the accumulator takes one more hex digit.
1209///
1210/// A digit past this cap goes into the sticky bit. With 124 bits of mantissa
1211/// in the accumulator, the sticky bit keeps the rounding correct.
1212const HEX_MANTISSA_CAP: u128 = (u128::MAX - 15) / 16;
1213
1214/// Reads the body of a `0x` double.
1215///
1216/// The body is hexadecimal digits, an optional fraction, and an optional
1217/// binary exponent. The mantissa in the accumulator and the sticky bit
1218/// together state the value. `round_binary` rounds that value.
1219fn scan_hex_double(bytes: &[u8], start: usize) -> Option<DoubleScan> {
1220    let mut end = start;
1221    let mut mantissa: u128 = 0;
1222    let mut sticky = false;
1223    let mut digits = 0usize;
1224    let mut shift: i32 = 0;
1225    while let Some(&c) = bytes.get(end).filter(|c| c.is_ascii_hexdigit()) {
1226        let value = u128::from(char::from(c).to_digit(16).expect("a hexadecimal digit"));
1227        if mantissa <= HEX_MANTISSA_CAP {
1228            mantissa = mantissa * 16 + value;
1229        } else {
1230            shift = shift.saturating_add(4);
1231            sticky |= value != 0;
1232        }
1233        digits += 1;
1234        end += 1;
1235    }
1236    if bytes.get(end) == Some(&b'.') {
1237        let mut after = end + 1;
1238        while let Some(&c) = bytes.get(after).filter(|c| c.is_ascii_hexdigit()) {
1239            let value = u128::from(char::from(c).to_digit(16).expect("a hexadecimal digit"));
1240            if mantissa <= HEX_MANTISSA_CAP {
1241                mantissa = mantissa * 16 + value;
1242                shift = shift.saturating_sub(4);
1243            } else {
1244                sticky |= value != 0;
1245            }
1246            digits += 1;
1247            after += 1;
1248        }
1249        end = after;
1250    }
1251    if digits == 0 {
1252        return None;
1253    }
1254    if matches!(bytes.get(end), Some(b'p' | b'P')) {
1255        let mut after = end + 1;
1256        let mut negative = false;
1257        match bytes.get(after) {
1258            Some(b'-') => {
1259                negative = true;
1260                after += 1;
1261            }
1262            Some(b'+') => after += 1,
1263            _ => {}
1264        }
1265        let first = after;
1266        let mut exponent: i32 = 0;
1267        while let Some(&c) = bytes.get(after).filter(|c| c.is_ascii_digit()) {
1268            exponent = exponent
1269                .saturating_mul(10)
1270                .saturating_add(i32::from(c - b'0'));
1271            after += 1;
1272        }
1273        if after > first {
1274            shift = if negative {
1275                shift.saturating_sub(exponent)
1276            } else {
1277                shift.saturating_add(exponent)
1278            };
1279            end = after;
1280        }
1281    }
1282    let (value, exact) = round_binary(mantissa, sticky, shift);
1283    Some(DoubleScan { value, end, exact })
1284}
1285
1286/// Rounds `mantissa * 2^shift` to the nearest double, ties to even.
1287///
1288/// `sticky` states that a digit past the end of the mantissa held a bit. That
1289/// bit moves the value past a tie. The second member of the result is `true`
1290/// if the double holds the value exactly. A magnitude over the double range gives an
1291/// infinity.
1292fn round_binary(mantissa: u128, sticky: bool, shift: i32) -> (f64, bool) {
1293    if mantissa == 0 {
1294        return (0.0, true);
1295    }
1296    let width = i64::from(128 - mantissa.leading_zeros());
1297    // `top` is the weight of the top bit of the mantissa. `lowest` is the
1298    // weight of the lowest bit that a double holds at that magnitude. A
1299    // subnormal stops at 2^-1074.
1300    let top = i64::from(shift) + width - 1;
1301    let lowest = (top - 52).max(-1074);
1302    let drop = lowest - i64::from(shift);
1303    let (mut significand, inexact) = if drop <= 0 {
1304        // The mantissa fits with bits to spare, so the double holds every bit.
1305        (mantissa << (-drop) as u32, sticky)
1306    } else if drop > 128 {
1307        // Every bit is less than half of the lowest bit that a double holds.
1308        (0u128, true)
1309    } else {
1310        let dropped = drop as u32;
1311        let (kept, rest) = if dropped == 128 {
1312            (0, mantissa)
1313        } else {
1314            (mantissa >> dropped, mantissa & ((1u128 << dropped) - 1))
1315        };
1316        let half = 1u128 << (dropped - 1);
1317        let up = rest > half || (rest == half && (sticky || kept & 1 == 1));
1318        (kept + u128::from(up), rest != 0 || sticky)
1319    };
1320    if significand == 0 {
1321        return (0.0, !inexact);
1322    }
1323    let mut lowest = lowest;
1324    if significand == 1u128 << 53 {
1325        // The rounding carries into a new bit.
1326        significand >>= 1;
1327        lowest += 1;
1328    }
1329    let bits = if significand < 1u128 << 52 {
1330        // A subnormal. Its encoding is the count of 2^-1074 units in it.
1331        significand as u64
1332    } else {
1333        let biased = lowest + 1075;
1334        if biased >= 2047 {
1335            return (f64::INFINITY, false);
1336        }
1337        ((biased as u64) << 52) | ((significand - (1u128 << 52)) as u64)
1338    };
1339    (f64::from_bits(bits), !inexact)
1340}
1341
1342/// Reads a numeric literal as a double.
1343///
1344/// The reader refuses a magnitude that the double range cannot hold. It keeps
1345/// a hexadecimal literal that states a subnormal exactly. It refuses every
1346/// other value that rounds to a subnormal. It keeps a value that underflows
1347/// all the way to zero. If the binary exponent of a body leaves the range of
1348/// the shift, the reader clamps the shift to its range.
1349fn double_literal(text: &str, span: Span) -> TextResult<f64> {
1350    let scan = scan_double(text);
1351    if scan.end != text.len() {
1352        let at = span.start + scan.end;
1353        return Err(TextError::new(
1354            Span::new(at, at + 1),
1355            "invalid character in number",
1356        ));
1357    }
1358    let value = scan.value;
1359    let subnormal = value != 0.0 && value.abs() < f64::MIN_POSITIVE;
1360    let (_, body) = split_sign(text);
1361    if !is_special_double(body) && (!value.is_finite() || (subnormal && !scan.exact)) {
1362        return Err(TextError::new(span, "number too big for any type"));
1363    }
1364    Ok(value)
1365}
1366
1367// --- type inference ----------------------------------------------------------
1368
1369/// A type under construction.
1370///
1371/// A literal that states no type yet is `Any`. An integer literal is `Int`
1372/// until a sibling or a declaration makes it concrete. A literal with a
1373/// fraction is `Decimal`.
1374#[derive(Debug, Clone)]
1375enum Guess {
1376    Any(Span),
1377    Int,
1378    Decimal,
1379    /// A quoted literal.
1380    ///
1381    /// It is a string until an object path or a signature beside it gives a
1382    /// different type.
1383    StringLit,
1384    Basic(Type),
1385    Variant,
1386    Maybe(Box<Guess>),
1387    Array(Box<Guess>),
1388    Tuple(Vec<Guess>),
1389    Entry(Box<Guess>, Box<Guess>),
1390}
1391
1392impl Guess {
1393    /// The guess that a stated type sets exactly.
1394    fn of(ty: &Type) -> Guess {
1395        match ty {
1396            Type::Variant => Guess::Variant,
1397            Type::Maybe(elem) => Guess::Maybe(Box::new(Guess::of(elem))),
1398            Type::Array(elem) => Guess::Array(Box::new(Guess::of(elem))),
1399            Type::Tuple(members) => Guess::Tuple(members.iter().map(Guess::of).collect()),
1400            Type::DictEntry(key, value) => {
1401                Guess::Entry(Box::new(Guess::of(key)), Box::new(Guess::of(value)))
1402            }
1403            basic => Guess::Basic(basic.clone()),
1404        }
1405    }
1406}
1407
1408/// Returns `true` if a type holds a number.
1409///
1410/// An integer literal can become only a type of this group.
1411fn is_numeric(ty: &Type) -> bool {
1412    matches!(
1413        ty,
1414        Type::Byte
1415            | Type::I16
1416            | Type::U16
1417            | Type::I32
1418            | Type::U32
1419            | Type::I64
1420            | Type::U64
1421            | Type::Handle
1422            | Type::Double
1423    )
1424}
1425
1426/// Returns the one type on which two guesses agree.
1427///
1428/// If the guesses agree on no type, it returns `None`. A maybe absorbs the
1429/// value beside it, so `'a'` and `@ms 'b'` agree on `ms`.
1430fn unify(left: &Guess, right: &Guess) -> Option<Guess> {
1431    match (left, right) {
1432        (Guess::Any(_), other) | (other, Guess::Any(_)) => Some(other.clone()),
1433        (Guess::Int, Guess::Int) => Some(Guess::Int),
1434        (Guess::Int, Guess::Decimal) | (Guess::Decimal, Guess::Int) => Some(Guess::Decimal),
1435        (Guess::Decimal, Guess::Decimal) => Some(Guess::Decimal),
1436        (Guess::StringLit, Guess::StringLit) => Some(Guess::StringLit),
1437        (Guess::StringLit, Guess::Basic(ty)) | (Guess::Basic(ty), Guess::StringLit)
1438            if matches!(ty, Type::Str | Type::ObjectPath | Type::Signature) =>
1439        {
1440            Some(Guess::Basic(ty.clone()))
1441        }
1442        (Guess::Int, Guess::Basic(ty)) | (Guess::Basic(ty), Guess::Int) if is_numeric(ty) => {
1443            Some(Guess::Basic(ty.clone()))
1444        }
1445        (Guess::Decimal, Guess::Basic(Type::Double))
1446        | (Guess::Basic(Type::Double), Guess::Decimal) => Some(Guess::Basic(Type::Double)),
1447        (Guess::Basic(a), Guess::Basic(b)) if a == b => Some(Guess::Basic(a.clone())),
1448        (Guess::Variant, Guess::Variant) => Some(Guess::Variant),
1449        (Guess::Maybe(a), Guess::Maybe(b)) => Some(Guess::Maybe(Box::new(unify(a, b)?))),
1450        (Guess::Maybe(a), other) | (other, Guess::Maybe(a)) => {
1451            Some(Guess::Maybe(Box::new(unify(a, other)?)))
1452        }
1453        (Guess::Array(a), Guess::Array(b)) => Some(Guess::Array(Box::new(unify(a, b)?))),
1454        (Guess::Tuple(a), Guess::Tuple(b)) if a.len() == b.len() => {
1455            let mut members = Vec::with_capacity(a.len());
1456            for (x, y) in a.iter().zip(b) {
1457                members.push(unify(x, y)?);
1458            }
1459            Some(Guess::Tuple(members))
1460        }
1461        (Guess::Entry(ka, va), Guess::Entry(kb, vb)) => Some(Guess::Entry(
1462            Box::new(unify(ka, kb)?),
1463            Box::new(unify(va, vb)?),
1464        )),
1465        _ => None,
1466    }
1467}
1468
1469/// Returns the type that a guess names.
1470///
1471/// An integer literal with no other context is `i`, and a fractional literal
1472/// is `d`. The function refuses a literal that states no type.
1473fn resolve(guess: &Guess) -> TextResult<Type> {
1474    Ok(match guess {
1475        Guess::Any(span) => return Err(TextError::new(*span, CANNOT_INFER)),
1476        Guess::Int => Type::I32,
1477        Guess::Decimal => Type::Double,
1478        Guess::StringLit => Type::Str,
1479        Guess::Basic(ty) => ty.clone(),
1480        Guess::Variant => Type::Variant,
1481        Guess::Maybe(elem) => Type::maybe(resolve(elem)?),
1482        Guess::Array(elem) => Type::array(resolve(elem)?),
1483        Guess::Tuple(members) => {
1484            Type::tuple(members.iter().map(resolve).collect::<TextResult<_>>()?)
1485        }
1486        Guess::Entry(key, value) => Type::dict_entry(resolve(key)?, resolve(value)?),
1487    })
1488}
1489
1490/// Returns the type that one whole value states.
1491///
1492/// If a literal inside the value states no type, the error names the whole
1493/// value. The `ostree` command names the same span. The child of a variant is a whole
1494/// value of its own, so the error for `[<[]>]` names the `[]`.
1495fn value_type(node: &Node) -> TextResult<Type> {
1496    let guess = infer(node)?;
1497    resolve(&guess).map_err(|error| {
1498        if error.reason == CANNOT_INFER {
1499            TextError::new(node.span, CANNOT_INFER)
1500        } else {
1501            error
1502        }
1503    })
1504}
1505
1506fn cannot_parse(span: Span, ty: &Type) -> TextError {
1507    TextError::new(
1508        span,
1509        format!("can not parse as value of type '{}'", ty.signature()),
1510    )
1511}
1512
1513/// The refusal of a container whose members state types that do not unify.
1514///
1515/// It names two members: the member that settled the type, and the member
1516/// that broke it.
1517fn no_common_type(first: Span, other: Span) -> TextError {
1518    TextError {
1519        spans: vec![first, other],
1520        reason: "unable to find a common type".to_owned(),
1521    }
1522}
1523
1524fn infer(node: &Node) -> TextResult<Guess> {
1525    Ok(match &node.ast {
1526        Ast::Bool(_) => Guess::Basic(Type::Bool),
1527        Ast::Number(text) => match number_kind(text) {
1528            NumberKind::Integer => Guess::Int,
1529            NumberKind::Double => Guess::Decimal,
1530        },
1531        Ast::Str(_) => Guess::StringLit,
1532        Ast::ByteString(_) => Guess::Array(Box::new(Guess::Basic(Type::Byte))),
1533        // A declaration states the type directly. Construction checks the
1534        // value against it, member by member. If a member does not fit,
1535        // construction names the same member as the `ostree` command.
1536        Ast::Typed(ty, _) => Guess::of(ty),
1537        Ast::Maybe(None) => Guess::Maybe(Box::new(Guess::Any(node.span))),
1538        Ast::Maybe(Some(child)) => Guess::Maybe(Box::new(infer(child)?)),
1539        Ast::Array(items) => {
1540            let Some((first, rest)) = items.split_first() else {
1541                return Ok(Guess::Array(Box::new(Guess::Any(node.span))));
1542            };
1543            let mut common = infer(first)?;
1544            for item in rest {
1545                let found = infer(item)?;
1546                common =
1547                    unify(&common, &found).ok_or_else(|| no_common_type(first.span, item.span))?;
1548            }
1549            Guess::Array(Box::new(common))
1550        }
1551        Ast::Dict(entries) => {
1552            let Some(((first_key, first_value), rest)) = entries.split_first() else {
1553                return Ok(Guess::Array(Box::new(Guess::Entry(
1554                    Box::new(Guess::Any(node.span)),
1555                    Box::new(Guess::Any(node.span)),
1556                ))));
1557            };
1558            let mut key = infer(first_key)?;
1559            // Only the first entry settles the value type. Construction reads
1560            // every later value against that type, so a later value states
1561            // nothing here. If a key does not unify with the settled key type,
1562            // the error has the same form as for an array.
1563            let value = infer(first_value)?;
1564            for (k, _) in rest {
1565                let found = infer(k)?;
1566                key = unify(&key, &found).ok_or_else(|| no_common_type(first_key.span, k.span))?;
1567            }
1568            check_basic_key(&key, node.span)?;
1569            Guess::Array(Box::new(Guess::Entry(Box::new(key), Box::new(value))))
1570        }
1571        Ast::Entry(key, value) => {
1572            let key = infer(key)?;
1573            check_basic_key(&key, node.span)?;
1574            Guess::Entry(Box::new(key), Box::new(infer(value)?))
1575        }
1576        Ast::Tuple(items) => Guess::Tuple(items.iter().map(infer).collect::<TextResult<_>>()?),
1577        Ast::Variant(child) => {
1578            // A variant states no child type, so the child must state its own.
1579            value_type(child)?;
1580            Guess::Variant
1581        }
1582    })
1583}
1584
1585/// Returns `true` if a guess names a basic type.
1586///
1587/// The key of a dict entry must have a basic type. A key that states no type
1588/// is not basic, so the error for `{nothing: 1}` names the shape of the key,
1589/// with `dictionary keys must have basic types`.
1590fn guess_is_basic(guess: &Guess) -> bool {
1591    match guess {
1592        Guess::Int | Guess::Decimal | Guess::StringLit => true,
1593        Guess::Basic(ty) => ty.is_basic(),
1594        _ => false,
1595    }
1596}
1597
1598/// Refuses a dictionary whose key is a container.
1599///
1600/// A dict entry cannot hold a container key. The error names the whole
1601/// dictionary, which is the span that the `ostree` command reports.
1602fn check_basic_key(key: &Guess, span: Span) -> TextResult<()> {
1603    if guess_is_basic(key) {
1604        return Ok(());
1605    }
1606    Err(TextError::new(
1607        span,
1608        "dictionary keys must have basic types",
1609    ))
1610}
1611
1612// --- value construction ------------------------------------------------------
1613
1614/// Returns `true` if a string is a valid object path.
1615///
1616/// A valid path is `/`, or `/` and one or more elements with single slashes
1617/// between them. An element holds letters, digits, and underscores.
1618fn is_object_path(text: &str) -> bool {
1619    if text == "/" {
1620        return true;
1621    }
1622    let Some(rest) = text.strip_prefix('/') else {
1623        return false;
1624    };
1625    !rest.is_empty()
1626        && rest.split('/').all(|element| {
1627            !element.is_empty()
1628                && element
1629                    .bytes()
1630                    .all(|c| c.is_ascii_alphanumeric() || c == b'_')
1631        })
1632}
1633
1634/// Returns `true` if a string is a valid signature.
1635///
1636/// A valid signature is zero or more complete types. It excludes the maybe and
1637/// the indefinite characters.
1638fn is_signature(text: &str) -> bool {
1639    let bytes = text.as_bytes();
1640    let mut pos = 0;
1641    while pos < bytes.len() {
1642        if !scan_signature_type(bytes, &mut pos, 0) {
1643            return false;
1644        }
1645    }
1646    true
1647}
1648
1649fn scan_signature_type(sig: &[u8], pos: &mut usize, depth: usize) -> bool {
1650    if depth > MAX_DECLARATION_DEPTH {
1651        return false;
1652    }
1653    let Some(&c) = sig.get(*pos) else {
1654        return false;
1655    };
1656    *pos += 1;
1657    match c {
1658        b'b' | b'y' | b'n' | b'q' | b'i' | b'u' | b'x' | b't' | b'h' | b'd' | b's' | b'o'
1659        | b'g' | b'v' => true,
1660        b'a' => scan_signature_type(sig, pos, depth + 1),
1661        b'(' => {
1662            while sig.get(*pos) != Some(&b')') {
1663                if !scan_signature_type(sig, pos, depth + 1) {
1664                    return false;
1665                }
1666            }
1667            *pos += 1;
1668            true
1669        }
1670        b'{' => {
1671            let key = sig.get(*pos).copied();
1672            if !key.is_some_and(|k| {
1673                matches!(
1674                    k,
1675                    b'b' | b'y'
1676                        | b'n'
1677                        | b'q'
1678                        | b'i'
1679                        | b'u'
1680                        | b'x'
1681                        | b't'
1682                        | b'h'
1683                        | b'd'
1684                        | b's'
1685                        | b'o'
1686                        | b'g'
1687                )
1688            }) {
1689                return false;
1690            }
1691            *pos += 1;
1692            if !scan_signature_type(sig, pos, depth + 1) {
1693                return false;
1694            }
1695            if sig.get(*pos) != Some(&b'}') {
1696                return false;
1697            }
1698            *pos += 1;
1699            true
1700        }
1701        _ => false,
1702    }
1703}
1704
1705fn build(node: &Node, ty: &Type) -> TextResult<Value> {
1706    // A value beside a maybe takes the shape of the maybe, so
1707    // `['a', @ms 'b']` holds two `ms` values.
1708    if let Type::Maybe(elem) = ty
1709        && !matches!(node.ast, Ast::Maybe(_) | Ast::Typed(..))
1710    {
1711        return Ok(Value::Maybe(Some(Box::new(build(node, elem)?))));
1712    }
1713    match (&node.ast, ty) {
1714        (Ast::Typed(_, child), _) => build(child, ty),
1715        (Ast::Bool(b), Type::Bool) => Ok(Value::Bool(*b)),
1716        (Ast::Number(text), _) => number_value(text, ty, node.span),
1717        (Ast::Str(text), Type::Str) => Ok(Value::Str(text.clone())),
1718        (Ast::Str(text), Type::ObjectPath) => {
1719            if !is_object_path(text) {
1720                return Err(TextError::new(node.span, "not a valid object path"));
1721            }
1722            Ok(Value::Str(text.clone()))
1723        }
1724        (Ast::Str(text), Type::Signature) => {
1725            if !is_signature(text) {
1726                return Err(TextError::new(node.span, "not a valid signature"));
1727            }
1728            Ok(Value::Str(text.clone()))
1729        }
1730        (Ast::ByteString(bytes), Type::Array(elem)) if **elem == Type::Byte => {
1731            Ok(Value::Bytes(bytes.clone()))
1732        }
1733        (Ast::Maybe(None), Type::Maybe(_)) => Ok(Value::Maybe(None)),
1734        (Ast::Maybe(Some(child)), Type::Maybe(elem)) => {
1735            Ok(Value::Maybe(Some(Box::new(build(child, elem)?))))
1736        }
1737        (Ast::Array(items), Type::Array(elem)) if **elem == Type::Byte => {
1738            let mut bytes = Vec::with_capacity(items.len());
1739            for item in items {
1740                match build(item, elem)? {
1741                    Value::Byte(b) => bytes.push(b),
1742                    _ => return Err(cannot_parse(item.span, elem)),
1743                }
1744            }
1745            Ok(Value::Bytes(bytes))
1746        }
1747        (Ast::Array(items), Type::Array(elem)) => Ok(Value::Array(
1748            items
1749                .iter()
1750                .map(|item| build(item, elem))
1751                .collect::<TextResult<_>>()?,
1752        )),
1753        (Ast::Dict(entries), Type::Array(elem)) => {
1754            let Type::DictEntry(key_ty, value_ty) = &**elem else {
1755                return Err(cannot_parse(node.span, ty));
1756            };
1757            let mut items = Vec::with_capacity(entries.len());
1758            for (key, value) in entries {
1759                items.push(Value::Tuple(vec![
1760                    build(key, key_ty)?,
1761                    build(value, value_ty)?,
1762                ]));
1763            }
1764            Ok(Value::Array(items))
1765        }
1766        (Ast::Entry(key, value), Type::DictEntry(key_ty, value_ty)) => Ok(Value::Tuple(vec![
1767            build(key, key_ty)?,
1768            build(value, value_ty)?,
1769        ])),
1770        (Ast::Tuple(items), Type::Tuple(members)) if items.len() == members.len() => {
1771            Ok(Value::Tuple(
1772                items
1773                    .iter()
1774                    .zip(members)
1775                    .map(|(item, member)| build(item, member))
1776                    .collect::<TextResult<_>>()?,
1777            ))
1778        }
1779        (Ast::Variant(child), Type::Variant) => {
1780            let child_ty = value_type(child)?;
1781            let value = build(child, &child_ty)?;
1782            Ok(Value::variant(child_ty, value))
1783        }
1784        _ => Err(cannot_parse(node.span, ty)),
1785    }
1786}
1787
1788/// Makes a value of `ty` from a numeric literal.
1789///
1790/// A double target reads the text as a double. An integer target reads the
1791/// text as an integer. The same text `017` is 17.0 under `d` and 15 under
1792/// `i`.
1793fn number_value(text: &str, ty: &Type, span: Span) -> TextResult<Value> {
1794    if matches!(ty, Type::Double) {
1795        return Ok(Value::double(double_literal(text, span)?));
1796    }
1797    if !is_numeric(ty) {
1798        return Err(cannot_parse(span, ty));
1799    }
1800    let (negative, magnitude) = integer_literal(text, span)?;
1801    let value = if negative {
1802        -i128::from(magnitude)
1803    } else {
1804        i128::from(magnitude)
1805    };
1806    let range = || {
1807        TextError::new(
1808            span,
1809            format!("number out of range for type '{}'", ty.signature()),
1810        )
1811    };
1812    Ok(match ty {
1813        Type::Byte => Value::Byte(u8::try_from(value).map_err(|_| range())?),
1814        Type::I16 => Value::I16(i16::try_from(value).map_err(|_| range())?),
1815        Type::U16 => Value::U16(u16::try_from(value).map_err(|_| range())?),
1816        Type::I32 | Type::Handle => Value::I32(i32::try_from(value).map_err(|_| range())?),
1817        Type::U32 => Value::U32(u32::try_from(value).map_err(|_| range())?),
1818        Type::I64 => Value::I64(i64::try_from(value).map_err(|_| range())?),
1819        Type::U64 => Value::U64(u64::try_from(value).map_err(|_| range())?),
1820        _ => return Err(cannot_parse(span, ty)),
1821    })
1822}
1823
1824#[cfg(test)]
1825mod tests {
1826    use super::*;
1827    use crate::{to_bytes, to_text};
1828
1829    /// Parses `text` and writes it back as text.
1830    ///
1831    /// The `ostree` command has the same pair of steps. The value goes in
1832    /// through `commit --add-metadata` and comes out through
1833    /// `show -B --print-metadata-key`.
1834    fn round(text: &str) -> String {
1835        let (ty, value) = from_text(text).unwrap_or_else(|e| panic!("{text}: {e}"));
1836        // Every accepted value must also serialize.
1837        to_bytes(&ty, &value).unwrap_or_else(|e| panic!("{text}: {e:?}"));
1838        to_text(&ty, &value).unwrap()
1839    }
1840
1841    fn refuse(text: &str) -> String {
1842        from_text(text)
1843            .map(|(ty, _)| ty.signature())
1844            .expect_err(&format!("{text} was accepted"))
1845            .to_string()
1846    }
1847
1848    /// Parses `text` as a double and gives its value.
1849    fn double(text: &str) -> f64 {
1850        let (ty, value) = from_text(text).unwrap_or_else(|e| panic!("{text}: {e}"));
1851        assert_eq!(ty.signature(), "d", "type of {text}");
1852        match value {
1853            Value::Double(bits) => f64::from_bits(bits),
1854            other => panic!("{text}: {other:?}"),
1855        }
1856    }
1857
1858    /// Each pair is one `--add-metadata` value and the text that
1859    /// `show -B --print-metadata-key` printed for it. The `ostree` command
1860    /// is version 2026.1.
1861    #[test]
1862    fn reads_the_forms_the_tool_accepts() {
1863        let cases: &[(&str, &str)] = &[
1864            ("'a string'", "'a string'"),
1865            ("\"double quoted\"", "'double quoted'"),
1866            ("uint32 42", "uint32 42"),
1867            ("42", "42"),
1868            ("-42", "-42"),
1869            ("+42", "42"),
1870            ("int64 -5", "int64 -5"),
1871            ("@x 5", "int64 5"),
1872            ("uint64 99", "uint64 99"),
1873            ("byte 0x41", "byte 0x41"),
1874            ("true", "true"),
1875            ("false", "false"),
1876            ("1.5", "1.5"),
1877            ("0.1", "0.10000000000000001"),
1878            ("1.0", "1.0"),
1879            ("1e3", "1000.0"),
1880            ("-0.0", "-0.0"),
1881            ("1.7976931348623157e308", "1.7976931348623157e+308"),
1882            ("int16 -5", "int16 -5"),
1883            ("uint16 5", "uint16 5"),
1884            ("handle 5", "handle 5"),
1885            ("objectpath '/a/b'", "objectpath '/a/b'"),
1886            ("objectpath '/'", "objectpath '/'"),
1887            ("objectpath '/a_b'", "objectpath '/a_b'"),
1888            ("objectpath '/A/9'", "objectpath '/A/9'"),
1889            ("signature 'ay'", "signature 'ay'"),
1890            ("signature ''", "signature ''"),
1891            ("signature 'ii'", "signature 'ii'"),
1892            ("signature '{sv}'", "signature '{sv}'"),
1893            ("@o '/a/b'", "objectpath '/a/b'"),
1894            ("@g 'ay'", "signature 'ay'"),
1895            ("['a','b']", "['a', 'b']"),
1896            ("@as ['a','b']", "['a', 'b']"),
1897            ("@ay [1,2,3]", "[byte 0x01, 0x02, 0x03]"),
1898            ("b'bytes'", "b'bytes'"),
1899            ("b\"double\"", "b'double'"),
1900            ("{'x': 'y'}", "{'x': 'y'}"),
1901            ("@a{ss} {'x': 'y'}", "{'x': 'y'}"),
1902            ("('a', 5)", "('a', 5)"),
1903            ("<'nested variant'>", "<'nested variant'>"),
1904            ("<<'x'>>", "<<'x'>>"),
1905            ("@v <'x'>", "<'x'>"),
1906            ("@ms 'just'", "@ms 'just'"),
1907            ("@ms nothing", "@ms nothing"),
1908            ("just 'x'", "@ms 'x'"),
1909            ("@mi 5", "@mi 5"),
1910            ("@mu 7", "@mu 7"),
1911            ("'a=b'", "'a=b'"),
1912            ("[2, 1.5]", "[2.0, 1.5]"),
1913            ("[1.5, 2]", "[1.5, 2.0]"),
1914            ("[[1],[2]]", "[[1], [2]]"),
1915            ("{'a': 1, 'b': 2}", "{'a': 1, 'b': 2}"),
1916            ("{1: 'a'}", "{1: 'a'}"),
1917            ("[@ms 'a', 'b']", "[@ms 'a', 'b']"),
1918            ("['a', @ms 'b']", "[@ms 'a', 'b']"),
1919            ("[nothing, 'a']", "[@ms nothing, 'a']"),
1920            ("[just 'a', nothing]", "[@ms 'a', nothing]"),
1921            ("@(si) ('a', 5)", "('a', 5)"),
1922            ("@ai []", "@ai []"),
1923            ("@as []", "@as []"),
1924            ("@a{sv} {}", "@a{sv} {}"),
1925            ("@aai [[], []]", "[@ai [], []]"),
1926            ("[b'x', b'y']", "[b'x', b'y']"),
1927            ("[@o '/a', '/b']", "[objectpath '/a', '/b']"),
1928            ("@ao ['/a','/b']", "[objectpath '/a', '/b']"),
1929            ("'\\x41'", "'x41'"),
1930            ("'a\\'b'", "\"a'b\""),
1931            ("\"a'b\"", "\"a'b\""),
1932            ("'\\''", "\"'\""),
1933            ("  42  ", "42"),
1934            ("@i 42", "42"),
1935            ("@au [1,2]", "[uint32 1, 2]"),
1936            ("[<'a'>, <5>]", "[<'a'>, <5>]"),
1937            ("0x41", "65"),
1938            ("017", "15"),
1939            ("(1,)", "(1,)"),
1940            ("()", "()"),
1941            ("[1,2,3]", "[1, 2, 3]"),
1942            ("{'a', 5}", "{'a', 5}"),
1943            ("'a\\0b'", "'a0b'"),
1944            ("'a\\tb'", "'a\\tb'"),
1945            ("'\\u00e9'", "'é'"),
1946            // A bytestring has no `\\u` escape, so the reader drops the
1947            // backslash and keeps the digits.
1948            ("b'\\u0000'", "b'u0000'"),
1949            ("b'a\\u0000b'", "b'au0000b'"),
1950            // A bytestring ends at a raw NUL, the same as at a NUL that an
1951            // octal escape names.
1952            ("b'a\0b'", "b'a'"),
1953        ];
1954        for (input, expected) in cases {
1955            assert_eq!(round(input), *expected, "reading {input}");
1956        }
1957    }
1958
1959    /// Literals whose text alone does not tell which reader takes them.
1960    ///
1961    /// Each literal has its value beside it. `ostree` 2026.1 stores exactly
1962    /// these values.
1963    #[test]
1964    fn reads_the_numeric_literals_the_tool_accepts() {
1965        let cases: &[(&str, &str)] = &[
1966            // A binary literal, with both spellings of its prefix.
1967            ("0b101", "5"),
1968            ("0B101", "5"),
1969            ("0b0", "0"),
1970            ("byte 0b11111111", "byte 0xff"),
1971            ("@t 0b1", "uint64 1"),
1972            // A hexadecimal body is an integer until a `.` or a `p` is in it.
1973            ("0xe", "14"),
1974            ("0xE", "14"),
1975            ("0x1e5", "485"),
1976            ("-0x1", "-1"),
1977            ("+0x10", "16"),
1978            ("0x1.8p1", "3.0"),
1979            ("@d 0x1.8p1", "3.0"),
1980            ("@d 0x10", "16.0"),
1981            ("@t 0xFFFFFFFFFFFFFFFF", "uint64 18446744073709551615"),
1982            // A double target reads the same text as a decimal double.
1983            ("@d 017", "17.0"),
1984            ("double 0777", "777.0"),
1985            ("@d 08", "8.0"),
1986            ("@d 1E3", "1000.0"),
1987            ("double 1E3", "1000.0"),
1988            // The sign that the `ostree` command reads itself, and the body
1989            // that it gives to the integer reader.
1990            ("-", "0"),
1991            ("@i -", "0"),
1992            ("@y -", "byte 0x00"),
1993            ("@t -", "uint64 0"),
1994            ("-+5", "-5"),
1995            // Not-a-number and the infinities.
1996            ("nan", "nan"),
1997            ("-nan", "-nan"),
1998            ("inf", "inf"),
1999            ("-inf", "-inf"),
2000            ("+inf", "inf"),
2001            ("+nan", "nan"),
2002            ("-infinity", "-inf"),
2003            ("double nan", "nan"),
2004            ("double inf", "inf"),
2005            ("@d nan", "nan"),
2006            ("just nan", "@md nan"),
2007            ("[1, nan]", "[1.0, nan]"),
2008            ("[nan, 1]", "[nan, 1.0]"),
2009            // The reader keeps an underflow all the way to zero. It refuses a
2010            // subnormal.
2011            ("1e-400", "0.0"),
2012            ("-1e-400", "-0.0"),
2013            ("0.0e-400", "0.0"),
2014            ("2.2250738585072014e-308", "2.2250738585072014e-308"),
2015            // A decimal literal can omit the integer part or the fraction part
2016            // of the mantissa.
2017            ("1.", "1.0"),
2018            (".5", "0.5"),
2019            ("5.", "5.0"),
2020            ("-.5", "-0.5"),
2021            ("1.e3", "1000.0"),
2022        ];
2023        for (input, expected) in cases {
2024            assert_eq!(round(input), *expected, "reading {input}");
2025        }
2026    }
2027
2028    /// The reader clamps a binary exponent that leaves the range of the shift.
2029    ///
2030    /// `ostree` 2026.1 stores 0.0 for each of these bodies.
2031    #[test]
2032    fn a_binary_exponent_out_of_range_is_clamped() {
2033        assert_eq!(round("0x0.0p-2147483645"), "0.0");
2034        assert_eq!(round("0x0.0p-9999999999"), "0.0");
2035        assert_eq!(round("0x1.0p-2147483645"), "0.0");
2036        assert_eq!(round("0x0.0p2147483647"), "0.0");
2037    }
2038
2039    /// The reader rounds a hexadecimal body to the nearest double, ties to even.
2040    ///
2041    /// A hexadecimal body states a value in binary. `ostree` 2026.1 stores the
2042    /// value beside each literal.
2043    #[test]
2044    fn reads_the_hexadecimal_doubles_the_tool_stores() {
2045        let cases: &[(&str, f64)] = &[
2046            ("@d 0x1.8p1", 3.0),
2047            ("@d 0x1p1023", 8.98846567431158e307),
2048            ("@d 0x1.fffffffffffff7ffffffffp1023", f64::MAX),
2049            ("@d 0x1.00000000000008p0", 1.0),
2050            // If a mantissa has more digits than the accumulator holds, the
2051            // accumulator keeps its digits. The digits after them round the
2052            // result.
2053            (
2054                "@d 0xffffffffffffffffffffffffffffffffffffffffp0",
2055                1.461501637330903e48,
2056            ),
2057            ("@d 0x1.0000000000000000000000000000000000001p0", 1.0),
2058            ("@d 0x1000000000000000000000000000000000000p-140", 16.0),
2059            ("@d 0x1000000000000000000000000000000000001p-140", 16.0),
2060            (
2061                "@d 0x123456789abcdef123456789abcdef123456789abcdefp-100",
2062                8.596805828370696e22,
2063            ),
2064            // A subnormal that the literal states exactly.
2065            ("@d 0x1p-1023", f64::from_bits(0x0008_0000_0000_0000)),
2066            ("@d 0x1p-1074", f64::from_bits(1)),
2067            ("@d 0x2p-1074", f64::from_bits(2)),
2068            ("@d 0x3p-1074", f64::from_bits(3)),
2069            ("@d 0x1.8p-1073", f64::from_bits(3)),
2070            ("@d -0x1p-1074", -f64::from_bits(1)),
2071            ("@d 0x1.000001p-1030", f64::from_bits(0x0000_1000_0010_0000)),
2072            // A value under the smallest normal that rounds up to it.
2073            ("@d 0x1.fffffffffffffffp-1023", f64::MIN_POSITIVE),
2074            ("@d 0x1.fffffffffffff8p-1023", f64::MIN_POSITIVE),
2075            // The reader keeps an underflow all the way to zero, and a tie to
2076            // even that gives zero. A zero mantissa is zero under any exponent.
2077            ("@d 0x1p-1075", 0.0),
2078            ("@d 0x0.8p-1074", 0.0),
2079            ("@d 0x8000000000000000000000000000000000000000p-1234", 0.0),
2080            ("@d 0x1p-2000", 0.0),
2081            ("@d 0x1p-9999999999", 0.0),
2082            ("@d -0x1p-1075", -0.0),
2083            ("@d 0x0p2147483647", 0.0),
2084            ("@d 0x0p99999999999999999999", 0.0),
2085        ];
2086        for (input, expected) in cases {
2087            assert_eq!(
2088                double(input).to_bits(),
2089                expected.to_bits(),
2090                "reading {input}"
2091            );
2092        }
2093    }
2094
2095    /// The reader refuses a hex body that rounds to an inexact subnormal.
2096    ///
2097    /// An inexact subnormal is a subnormal that the body does not state
2098    /// exactly. The reader also refuses a body over the double range. Each
2099    /// text is the text that `ostree` 2026.1 reports. The offsets are relative
2100    /// to the value.
2101    #[test]
2102    fn refuses_the_hexadecimal_doubles_the_tool_refuses() {
2103        let cases: &[(&str, &str)] = &[
2104            // The rounding gives a subnormal that the literal does not state
2105            // exactly.
2106            ("@d 0x1.8p-1074", "3-14:number too big for any type"),
2107            ("@d 0x1.8p-1075", "3-14:number too big for any type"),
2108            (
2109                "@d 0x1.0000000000001p-1030",
2110                "3-26:number too big for any type",
2111            ),
2112            (
2113                "@d 0x1.0000000000000001p-1030",
2114                "3-29:number too big for any type",
2115            ),
2116            (
2117                "@d 0x1.0000000000000000001p-1075",
2118                "3-32:number too big for any type",
2119            ),
2120            (
2121                "@d 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1330",
2122                "3-80:number too big for any type",
2123            ),
2124            // A magnitude over the double range.
2125            ("@d 0x1p1024", "3-11:number too big for any type"),
2126            ("@d 0x2p1023", "3-11:number too big for any type"),
2127            ("@d -0x1p1024", "3-12:number too big for any type"),
2128            (
2129                "@d 0x1.fffffffffffff8p1023",
2130                "3-26:number too big for any type",
2131            ),
2132            ("@d 0x1p2147483647", "3-17:number too big for any type"),
2133            (
2134                "@d 0x1p99999999999999999999",
2135                "3-27:number too big for any type",
2136            ),
2137        ];
2138        for (input, expected) in cases {
2139            assert_eq!(refuse(input), *expected, "refusing {input}");
2140        }
2141    }
2142
2143    /// Each pair is one refused `--add-metadata` value and the report of the
2144    /// `ostree` command.
2145    ///
2146    /// The report is the text after `Parsing <KEY=VALUE>: `. The version of
2147    /// the `ostree` command is 2026.1. The offsets are relative to the value.
2148    #[test]
2149    fn refuses_what_the_tool_refuses_in_its_own_words() {
2150        let cases: &[(&str, &str)] = &[
2151            ("[]", "0-2:unable to infer type"),
2152            ("", "0:expected value"),
2153            ("garbage syntax (((", "0-7:unknown keyword"),
2154            (
2155                "uint32 99999999999999999999",
2156                "7-27:integer too big for any type",
2157            ),
2158            ("'unterminated", "0-13:unterminated string constant"),
2159            ("(1,2", "4:expected ',' or ')' to follow tuple element"),
2160            ("{'a':}", "5:expected value"),
2161            ("nothing", "0-7:unable to infer type"),
2162            ("@i 'str'", "3-8:can not parse as value of type 'i'"),
2163            ("3000000000", "0-10:number out of range for type 'i'"),
2164            (
2165                "9223372036854775807",
2166                "0-19:number out of range for type 'i'",
2167            ),
2168            (
2169                "18446744073709551615",
2170                "0-20:number out of range for type 'i'",
2171            ),
2172            ("99999999999999999999", "0-20:integer too big for any type"),
2173            ("uint32 -1", "7-9:number out of range for type 'u'"),
2174            ("uint32 4294967296", "7-17:number out of range for type 'u'"),
2175            ("byte 256", "5-8:number out of range for type 'y'"),
2176            ("0o17", "1-2:invalid character in number"),
2177            ("['a', 5]", "1-4,6-7:unable to find a common type"),
2178            (
2179                "{'a': 'b', 'c': 5}",
2180                "16-17:can not parse as value of type 's'",
2181            ),
2182            ("42 43", "3:expected end of input"),
2183            ("true false", "5:expected end of input"),
2184            ("@u", "2:expected value"),
2185            ("@", "0-1:invalid type declaration"),
2186            ("[,]", "1:expected value"),
2187            ("{}", "0-2:unable to infer type"),
2188            (
2189                "{'a'}",
2190                "4:expected ':' or ',' to follow dictionary entry key",
2191            ),
2192            ("(,)", "1:expected value"),
2193            ("@b 1", "3-4:can not parse as value of type 'b'"),
2194            ("B", "0:expected value"),
2195            ("_x", "0:expected value"),
2196            ("Foo", "0:expected value"),
2197            ("uint32x", "0-7:unknown keyword"),
2198            ("x1", "0:expected value"),
2199            ("a", "0:expected value"),
2200            ("%", "0:expected value"),
2201            ("=x", "0:expected value"),
2202            ("trueX", "0-5:unknown keyword"),
2203            ("TRUE", "0:expected value"),
2204            ("aB", "0-2:unknown keyword"),
2205            ("a_b", "0:expected value"),
2206            ("byte0x41", "0-8:unknown keyword"),
2207            ("just1", "0-5:unknown keyword"),
2208            ("ju st", "0-2:unknown keyword"),
2209            ("{[1]: 'a'}", "0-10:dictionary keys must have basic types"),
2210            // A one-member tuple needs its comma.
2211            ("(1)", "2:expected ',' after first tuple element"),
2212            ("('a')", "4:expected ',' after first tuple element"),
2213            ("((1))", "3:expected ',' after first tuple element"),
2214            ("((1,))", "5:expected ',' after first tuple element"),
2215            ("@(i) (1)", "7:expected ',' after first tuple element"),
2216            ("(((1),2),3)", "4:expected ',' after first tuple element"),
2217            ("(1 2)", "3:expected ',' after first tuple element"),
2218            ("(1,2,)", "5:expected value"),
2219            ("(1,2 3)", "5:expected ',' or ')' to follow tuple element"),
2220            // The exponent marker is lower case. With `E`, the body is an
2221            // integer.
2222            ("1E3", "1-2:invalid character in number"),
2223            ("1E+3", "1-2:invalid character in number"),
2224            ("1E", "1-2:invalid character in number"),
2225            ("1d", "1-2:invalid character in number"),
2226            ("0x1p3", "3-4:invalid character in number"),
2227            // A subnormal is out of the range that the `ostree` command
2228            // accepts.
2229            ("5e-324", "0-6:number too big for any type"),
2230            ("1e-310", "0-6:number too big for any type"),
2231            ("1e-308", "0-6:number too big for any type"),
2232            ("1e400", "0-5:number too big for any type"),
2233            ("-1e400", "0-6:number too big for any type"),
2234            ("1.7976931348623157e309", "0-22:number too big for any type"),
2235            ("@d 5e-324", "3-9:number too big for any type"),
2236            // The character at which the number reader stopped.
2237            ("1.5.5", "3-4:invalid character in number"),
2238            ("1..5", "2-3:invalid character in number"),
2239            ("1e", "1-2:invalid character in number"),
2240            ("1e+", "1-2:invalid character in number"),
2241            ("1.5e", "3-4:invalid character in number"),
2242            ("+", "0-1:invalid character in number"),
2243            ("++5", "0-1:invalid character in number"),
2244            ("+-5", "0-1:invalid character in number"),
2245            ("--5", "0-3:number out of range for type 'i'"),
2246            ("0xg", "1-2:invalid character in number"),
2247            ("0b12", "3-4:invalid character in number"),
2248            ("0b102", "4-5:invalid character in number"),
2249            ("0b1e1", "1-2:invalid character in number"),
2250            ("-INF", "1-2:invalid character in number"),
2251            ("+INFINITY", "0-1:invalid character in number"),
2252            ("infinity", "0-8:unknown keyword"),
2253            ("nan5", "0-4:unknown keyword"),
2254            ("nan(0x1)", "3:expected end of input"),
2255            // An integer target reads the literal as an integer.
2256            ("byte nan", "5-6:invalid character in number"),
2257            ("@i nan", "3-4:invalid character in number"),
2258            ("uint64 nan", "7-8:invalid character in number"),
2259            ("byte 1.5", "6-7:invalid character in number"),
2260            ("uint32 1.5", "8-9:invalid character in number"),
2261            ("@x 1.5", "4-5:invalid character in number"),
2262            ("int32 1e3", "7-8:invalid character in number"),
2263            ("@d 0b101", "4-5:invalid character in number"),
2264            ("@d -", "3-4:invalid character in number"),
2265            // A magnitude that no 64-bit type holds, compared with a magnitude
2266            // that no target holds.
2267            (
2268                "int64 -9223372036854775809",
2269                "6-26:number out of range for type 'x'",
2270            ),
2271            (
2272                "-18446744073709551615",
2273                "0-21:number out of range for type 'i'",
2274            ),
2275            ("18446744073709551616", "0-20:integer too big for any type"),
2276            // The reader checks an object path and a signature.
2277            ("objectpath 'notapath'", "11-21:not a valid object path"),
2278            ("objectpath ''", "11-13:not a valid object path"),
2279            ("objectpath '/a/'", "11-16:not a valid object path"),
2280            ("objectpath '//'", "11-15:not a valid object path"),
2281            ("objectpath '/a-b'", "11-17:not a valid object path"),
2282            ("@o 'bad'", "3-8:not a valid object path"),
2283            ("signature 'zz'", "10-14:not a valid signature"),
2284            ("signature 'a'", "10-13:not a valid signature"),
2285            ("signature 'ms'", "10-14:not a valid signature"),
2286            ("signature 'r'", "10-13:not a valid signature"),
2287            ("signature '{vs}'", "10-16:not a valid signature"),
2288            ("@g 'zz'", "3-7:not a valid signature"),
2289            // The scan of a declaration stops at the first character that can
2290            // close something around it. The error for an indefinite
2291            // declaration names it as indefinite.
2292            ("@z 5", "0-2:invalid type declaration"),
2293            ("@r 5", "0-2:type declarations must be definite"),
2294            ("@* 5", "0-2:type declarations must be definite"),
2295            ("@? 5", "0-2:type declarations must be definite"),
2296            ("@** 5", "0-3:invalid type declaration"),
2297            ("@i5", "0-3:invalid type declaration"),
2298            ("@ii", "0-3:invalid type declaration"),
2299            ("@m", "0-2:invalid type declaration"),
2300            ("@i(5)", "0-5:invalid type declaration"),
2301            ("@i[5]", "0-4:invalid type declaration"),
2302            ("@i)", "2:expected value"),
2303            ("@i,", "2:expected value"),
2304            // A declaration drives the check into the members.
2305            ("@as [1]", "5-6:can not parse as value of type 's'"),
2306            ("@ab [1]", "5-6:can not parse as value of type 'b'"),
2307            ("@ai [1,'a']", "7-10:can not parse as value of type 'i'"),
2308            ("@as ['a', 5]", "10-11:can not parse as value of type 's'"),
2309            (
2310                "@a{ss} {'a': 5}",
2311                "13-14:can not parse as value of type 's'",
2312            ),
2313            (
2314                "@a{sv} {'a': 1}",
2315                "13-14:can not parse as value of type 'v'",
2316            ),
2317            ("@av [1]", "5-6:can not parse as value of type 'v'"),
2318            ("@ai 5", "4-5:can not parse as value of type 'ai'"),
2319            ("@i []", "3-5:can not parse as value of type 'i'"),
2320            ("@as [nothing]", "5-12:can not parse as value of type 's'"),
2321            // If a value states no type, the error names the whole value. The
2322            // child of a variant is a whole value of its own.
2323            ("[[]]", "0-4:unable to infer type"),
2324            ("just []", "0-7:unable to infer type"),
2325            ("just nothing", "0-12:unable to infer type"),
2326            ("just just nothing", "0-17:unable to infer type"),
2327            ("('a', [])", "0-9:unable to infer type"),
2328            ("[nothing]", "0-9:unable to infer type"),
2329            ("[nothing, nothing]", "0-18:unable to infer type"),
2330            ("{'a': nothing}", "0-14:unable to infer type"),
2331            ("[[[]]]", "0-6:unable to infer type"),
2332            ("[[], []]", "0-8:unable to infer type"),
2333            ("nothing 5", "0-7:unable to infer type"),
2334            ("nothing nothing", "0-7:unable to infer type"),
2335            ("[<[]>]", "2-4:unable to infer type"),
2336            ("<just nothing>", "1-13:unable to infer type"),
2337            // The error for a key that is not basic names its shape.
2338            ("{nothing: 1}", "0-12:dictionary keys must have basic types"),
2339            ("{{}: 'a'}", "0-9:dictionary keys must have basic types"),
2340            ("{<1>: 'a'}", "0-10:dictionary keys must have basic types"),
2341            // The error for keys that do not unify has the same form as for an
2342            // array.
2343            ("{'a': 1, 2: 'b'}", "1-4,9-10:unable to find a common type"),
2344            ("{1: 'a', 'b': 2}", "1-2,9-12:unable to find a common type"),
2345            (
2346                "{'a': 'b', 5: 'c'}",
2347                "1-4,11-12:unable to find a common type",
2348            ),
2349            (
2350                "{'a': 1, 'b': 2, 'c': 'x'}",
2351                "22-25:can not parse as value of type 'i'",
2352            ),
2353            // Each closing bracket has its own wording.
2354            ("<1 2>", "3:expected '>' to follow variant value"),
2355            ("{'a', 5, 6}", "7:expected '}' at end of dictionary entry"),
2356            (
2357                "{'a': 1 'b': 2}",
2358                "8:expected ',' or '}' to follow dictionary entry",
2359            ),
2360            ("[1 2]", "3:expected ',' or ']' to follow array element"),
2361            // The error for a unicode escape names the digits that are present.
2362            ("'\\uZZZZ'", "3:invalid 4-character unicode escape"),
2363            ("'\\u'", "3:invalid 4-character unicode escape"),
2364            ("'\\u12'", "3-5:invalid 4-character unicode escape"),
2365            ("'\\u00'", "3-5:invalid 4-character unicode escape"),
2366            ("'\\U110000'", "3-9:invalid 8-character unicode escape"),
2367            ("'\\U0001'", "3-7:invalid 8-character unicode escape"),
2368            // The reader refuses an escape that names U+0000, at any position
2369            // in the literal. The error names the escape at the offset of its
2370            // digits.
2371            ("'\\u0000'", "3-7:invalid 4-character unicode escape"),
2372            ("'\\U00000000'", "3-11:invalid 8-character unicode escape"),
2373            ("'a\\u0000b'", "4-8:invalid 4-character unicode escape"),
2374            ("'ab\\u0000'", "5-9:invalid 4-character unicode escape"),
2375            ("'\\u0000x'", "3-7:invalid 4-character unicode escape"),
2376            ("@s '\\u0000'", "6-10:invalid 4-character unicode escape"),
2377            ("@o '/a\\u0000b'", "8-12:invalid 4-character unicode escape"),
2378            (
2379                "objectpath '\\u0000'",
2380                "14-18:invalid 4-character unicode escape",
2381            ),
2382            ("@g '\\u0000'", "6-10:invalid 4-character unicode escape"),
2383            (
2384                "signature 'a\\u0000y'",
2385                "14-18:invalid 4-character unicode escape",
2386            ),
2387            ("{'\\u0000': 1}", "4-8:invalid 4-character unicode escape"),
2388            (
2389                "{'a': '\\u0000'}",
2390                "9-13:invalid 4-character unicode escape",
2391            ),
2392            (
2393                "['a', '\\u0000']",
2394                "9-13:invalid 4-character unicode escape",
2395            ),
2396            ("<'\\u0000'>", "4-8:invalid 4-character unicode escape"),
2397            ("@ms '\\u0000'", "7-11:invalid 4-character unicode escape"),
2398            ("('\\u0000',)", "4-8:invalid 4-character unicode escape"),
2399            // A surrogate and a code point past U+10FFFF take the same refusal.
2400            ("'\\ud800'", "3-7:invalid 4-character unicode escape"),
2401            ("'\\U0000d800'", "3-11:invalid 8-character unicode escape"),
2402            ("'\\U00110000'", "3-11:invalid 8-character unicode escape"),
2403            // The reader refuses a raw NUL byte in a string literal at its
2404            // position. The `ostree` command takes its value through `argv`,
2405            // which carries no NUL, so only ostrya has this refusal.
2406            ("'a\0b'", "2-3:NUL byte in string constant"),
2407            ("'\0'", "1-2:NUL byte in string constant"),
2408            ("@o '/a\0b'", "6-7:NUL byte in string constant"),
2409            ("{'\0': 1}", "2-3:NUL byte in string constant"),
2410        ];
2411        for (input, expected) in cases {
2412            assert_eq!(refuse(input), *expected, "refusing {input:?}");
2413        }
2414    }
2415
2416    /// The first entry of an undeclared dictionary settles the value type.
2417    ///
2418    /// The reader reads every later value against that type. Each pair is one
2419    /// `--add-metadata` value and the text that `show -B --print-metadata-key`
2420    /// printed for it. The version of the `ostree` command is 2026.1.
2421    #[test]
2422    fn a_dictionary_reads_its_values_against_the_first_entry() {
2423        let cases: &[(&str, &str)] = &[
2424            // The order of the entries selects the type. The later value takes
2425            // that type.
2426            ("{'a': 1, 'b': uint32 2}", "{'a': 1, 'b': 2}"),
2427            ("{'a': uint32 2, 'b': 1}", "{'a': uint32 2, 'b': 1}"),
2428            ("{'a': 1.5, 'b': 1}", "{'a': 1.5, 'b': 1.0}"),
2429            ("{'a': 0x1.8p1, 'b': 1}", "{'a': 3.0, 'b': 1.0}"),
2430            ("{'a': 1.5, 'b': 1E3}", "{'a': 1.5, 'b': 1000.0}"),
2431            // A settled maybe absorbs the value beside it.
2432            ("{'a': just 'y', 'b': 'x'}", "{'a': @ms 'y', 'b': 'x'}"),
2433            ("{'a': just 2, 'b': 1}", "{'a': @mi 2, 'b': 1}"),
2434            (
2435                "{'a': @ms nothing, 'b': 'x'}",
2436                "{'a': @ms nothing, 'b': 'x'}",
2437            ),
2438            ("{'a': just 1, 'b': nothing}", "{'a': @mi 1, 'b': nothing}"),
2439            // A settled container type takes an empty container beside it.
2440            ("{'a': [1], 'b': []}", "{'a': [1], 'b': []}"),
2441            ("{'a': {'d': 2}, 'c': {}}", "{'a': {'d': 2}, 'c': {}}"),
2442            ("{'a': <1>, 'b': <'x'>}", "{'a': <1>, 'b': <'x'>}"),
2443            // The third entry follows the first as well.
2444            (
2445                "{'a': 1, 'b': 2, 'c': uint32 3}",
2446                "{'a': 1, 'b': 2, 'c': 3}",
2447            ),
2448            (
2449                "{'a': uint32 1, 'b': 2, 'c': 3}",
2450                "{'a': uint32 1, 'b': 2, 'c': 3}",
2451            ),
2452            // The keys unify to one common type, the same as the elements of
2453            // an array.
2454            ("{1: 'a', 2.5: 'b'}", "{1.0: 'a', 2.5: 'b'}"),
2455            ("{2.5: 'a', 1: 'b'}", "{2.5: 'a', 1.0: 'b'}"),
2456        ];
2457        for (input, expected) in cases {
2458            assert_eq!(round(input), *expected, "reading {input}");
2459        }
2460    }
2461
2462    /// A type that is already in force drops a declaration beside a value.
2463    ///
2464    /// The type takes the value, so `@o` under `s` stores a string, and the
2465    /// object-path check does not run. Each pair is one `--add-metadata` value
2466    /// and the text that `show -B --print-metadata-key` printed for it. The
2467    /// version of the `ostree` command is 2026.1.
2468    #[test]
2469    fn a_declaration_under_a_driven_type_gives_up_its_type() {
2470        let cases: &[(&str, &str)] = &[
2471            ("@as [@o '/a']", "['/a']"),
2472            ("@as [@ms 'a']", "['a']"),
2473            ("@ai [@u 5]", "[5]"),
2474            ("@ao ['/a', @s '/b']", "[objectpath '/a', '/b']"),
2475            ("@a{ss} {'a': @o '/b'}", "{'a': '/b'}"),
2476            ("{'a': 'x', 'b': @o '/y'}", "{'a': 'x', 'b': '/y'}"),
2477            (
2478                "{'a': 'x', 'b': @o 'notapath'}",
2479                "{'a': 'x', 'b': 'notapath'}",
2480            ),
2481            ("{'a': 'x', 'b': @g 'ii'}", "{'a': 'x', 'b': 'ii'}"),
2482            ("{'a': 'x', 'b': @ms 'y'}", "{'a': 'x', 'b': 'y'}"),
2483            ("{'a': 1, 'b': @mi 2}", "{'a': 1, 'b': 2}"),
2484            (
2485                "{'a': @g 'ii', 'b': 'x'}",
2486                "{'a': signature 'ii', 'b': 'x'}",
2487            ),
2488        ];
2489        for (input, expected) in cases {
2490            assert_eq!(round(input), *expected, "reading {input}");
2491        }
2492        // The value beside the declaration must still fit the driven type.
2493        let refusals: &[(&str, &str)] = &[
2494            ("@as [@i 5]", "8-9:can not parse as value of type 's'"),
2495            ("@ai [@d 1.5]", "9-10:invalid character in number"),
2496            (
2497                "{'a': 1, 'b': @s 'x'}",
2498                "17-20:can not parse as value of type 'i'",
2499            ),
2500            (
2501                "{'a': 1, 'b': @b true}",
2502                "17-21:can not parse as value of type 'i'",
2503            ),
2504            (
2505                "{'a': true, 'b': @i 1}",
2506                "20-21:can not parse as value of type 'b'",
2507            ),
2508            ("{'a': 1, 'b': @d 1.5}", "18-19:invalid character in number"),
2509            (
2510                "{'a': 'x', 'b': @ms nothing}",
2511                "20-27:can not parse as value of type 's'",
2512            ),
2513            (
2514                "{'a': 1, 'b': uint32 4294967296}",
2515                "21-31:number out of range for type 'i'",
2516            ),
2517        ];
2518        for (input, expected) in refusals {
2519            assert_eq!(refuse(input), *expected, "refusing {input:?}");
2520        }
2521    }
2522
2523    /// The error for a later dictionary value that does not fit names the
2524    /// settled type.
2525    ///
2526    /// If the first value states no type, the error names the whole value.
2527    /// Each pair is one refused `--add-metadata` value and the report of the
2528    /// `ostree` command. The report is the text after `Parsing <KEY=VALUE>: `.
2529    /// The version of the `ostree` command is 2026.1.
2530    #[test]
2531    fn refuses_a_dictionary_value_against_the_settled_type() {
2532        let cases: &[(&str, &str)] = &[
2533            // The integer reader takes the later literal and stops at the `.`.
2534            ("{'a': 1, 'b': 1.5}", "15-16:invalid character in number"),
2535            (
2536                "{'a': 1, 'b': 0x1.8p1}",
2537                "17-18:invalid character in number",
2538            ),
2539            ("{'a': 1, 'b': 1e3}", "15-16:invalid character in number"),
2540            (
2541                "{'a': 1, 'b': 2, 'c': 1.5}",
2542                "23-24:invalid character in number",
2543            ),
2544            // A maybe beside a settled plain type does not fit it.
2545            (
2546                "{'a': 'x', 'b': just 'y'}",
2547                "16-24:can not parse as value of type 's'",
2548            ),
2549            (
2550                "{'a': 'y', 'b': nothing}",
2551                "16-23:can not parse as value of type 's'",
2552            ),
2553            (
2554                "{'a': 1, 'b': just 2}",
2555                "14-20:can not parse as value of type 'i'",
2556            ),
2557            (
2558                "{'a': 1, 'b': 2, 'c': nothing}",
2559                "22-29:can not parse as value of type 'i'",
2560            ),
2561            (
2562                "{'a': 'x', 'b': 'y', 'c': just 'z'}",
2563                "26-34:can not parse as value of type 's'",
2564            ),
2565            // The check reaches into the later value one member at a time.
2566            (
2567                "{'a': (1,2), 'b': ('x','y')}",
2568                "19-22:can not parse as value of type 'i'",
2569            ),
2570            (
2571                "{'a': ('x','y'), 'b': (1,2)}",
2572                "23-24:can not parse as value of type 's'",
2573            ),
2574            (
2575                "{'a': [1], 'b': ['x']}",
2576                "17-20:can not parse as value of type 'i'",
2577            ),
2578            (
2579                "{'a': {'x': 1}, 'b': {'y': 'z'}}",
2580                "27-30:can not parse as value of type 'i'",
2581            ),
2582            ("{'a': @o '/y', 'b': 'x'}", "20-23:not a valid object path"),
2583            (
2584                "{'a': @o '/z', 'b': 'x', 'c': 'y'}",
2585                "20-23:not a valid object path",
2586            ),
2587            (
2588                "{'a': byte 1, 'b': 256}",
2589                "19-22:number out of range for type 'y'",
2590            ),
2591            (
2592                "{'a': 1, 'b': 99999999999999999999}",
2593                "14-34:integer too big for any type",
2594            ),
2595            // Type inference skips a later value, so the error names a later
2596            // shape against the settled type, also a shape that states its
2597            // own type.
2598            (
2599                "{'a': 1, 'b': ['x', 5]}",
2600                "14-22:can not parse as value of type 'i'",
2601            ),
2602            (
2603                "{'a': 1, 'b': {[1]: 'a'}}",
2604                "14-24:can not parse as value of type 'i'",
2605            ),
2606            (
2607                "{'a': 1, 'b': <[]>}",
2608                "14-18:can not parse as value of type 'i'",
2609            ),
2610            (
2611                "{'a': 1, 'b': {'y': 'z'}}",
2612                "14-24:can not parse as value of type 'i'",
2613            ),
2614            (
2615                "{'a': 5, 'b': []}",
2616                "14-16:can not parse as value of type 'i'",
2617            ),
2618            (
2619                "{'a': [1], 'b': 'x'}",
2620                "16-19:can not parse as value of type 'ai'",
2621            ),
2622            (
2623                "{'a': <1>, 'b': 'x'}",
2624                "16-19:can not parse as value of type 'v'",
2625            ),
2626            (
2627                "{'a': 'x', 'b': b'y'}",
2628                "16-20:can not parse as value of type 's'",
2629            ),
2630            (
2631                "{'a': b'x', 'b': 'y'}",
2632                "17-20:can not parse as value of type 'ay'",
2633            ),
2634            // A variant inside a later value is still a whole value of its own.
2635            ("{'a': <1>, 'b': <[]>}", "17-19:unable to infer type"),
2636            // If the first value states no type, the error names the whole
2637            // value. No later entry supplies the type.
2638            ("{'a': nothing, 'b': 'y'}", "0-24:unable to infer type"),
2639            (
2640                "{'a': nothing, 'b': 2, 'c': 3}",
2641                "0-30:unable to infer type",
2642            ),
2643            ("{'a': [], 'b': [1]}", "0-19:unable to infer type"),
2644            ("{'a': [], 'b': 5}", "0-17:unable to infer type"),
2645            ("{'a': [], 'b': 5, 'c': 6}", "0-25:unable to infer type"),
2646            ("{'a': [], 'b': ['x', 5]}", "0-24:unable to infer type"),
2647            ("{'a': {}, 'c': {'d': 2}}", "0-24:unable to infer type"),
2648            ("{'q': {'a': [], 'b': 5}}", "0-24:unable to infer type"),
2649            ("[{'a': [], 'b': 5}]", "0-19:unable to infer type"),
2650            ("({'a': [], 'b': 5},)", "0-20:unable to infer type"),
2651            ("just {'a': [], 'b': 5}", "0-22:unable to infer type"),
2652            ("<{'a': [], 'b': 5}>", "1-18:unable to infer type"),
2653            // The error for a key that does not unify with the settled key
2654            // type comes first. The value type is never resolved.
2655            (
2656                "{[1]: [], 'b': 5}",
2657                "1-4,10-13:unable to find a common type",
2658            ),
2659            (
2660                "{'a': [], [1]: 5}",
2661                "1-4,10-13:unable to find a common type",
2662            ),
2663            ("{'a': 1, @u 2: 3}", "1-4,9-13:unable to find a common type"),
2664            ("{@o '/a': 1, 'b': 2}", "13-16:not a valid object path"),
2665            ("{'a': 1, @o '/b': 2}", "1-4:not a valid object path"),
2666        ];
2667        for (input, expected) in cases {
2668            assert_eq!(refuse(input), *expected, "refusing {input:?}");
2669        }
2670    }
2671
2672    /// A bytestring literal ends at the first NUL that its escapes produce.
2673    ///
2674    /// `b'\0'` and `b'\400'` are the one-byte array that the `ostree` command
2675    /// stores.
2676    #[test]
2677    fn a_bytestring_ends_at_its_first_nul() {
2678        let cases: &[(&str, &[u8])] = &[
2679            (r"b'\0'", &[0]),
2680            (r"b''", &[0]),
2681            (r"b'\400'", &[0]),
2682            (r"b'\0001'", &[0]),
2683            (r"b'\0\0'", &[0]),
2684            (r"b'a\0b'", &[b'a', 0]),
2685            (r"b'a\0'", &[b'a', 0]),
2686            (r"b'\101'", &[b'A', 0]),
2687            ("b'bytes'", b"bytes\0"),
2688        ];
2689        for (input, expected) in cases {
2690            let (ty, value) = from_text(input).unwrap_or_else(|e| panic!("{input}: {e}"));
2691            assert_eq!(ty.signature(), "ay", "type of {input}");
2692            assert_eq!(
2693                value,
2694                Value::Bytes((*expected).to_vec()),
2695                "value of {input}"
2696            );
2697        }
2698    }
2699
2700    /// A backslash before a line feed is a line continuation.
2701    ///
2702    /// The rule applies to a string and to a bytestring. Both characters leave
2703    /// the value. `ostree` 2026.1 stores `'ab'` for `'a\<LF>b'`.
2704    #[test]
2705    fn a_backslash_before_a_line_feed_continues_the_line() {
2706        assert_eq!(round("'a\\\nb'"), "'ab'");
2707        assert_eq!(round("'\\\n'"), "''");
2708        assert_eq!(round("'a\\\n'"), "'a'");
2709        assert_eq!(round("'a\\\n\\\nb'"), "'ab'");
2710        // The line feed after a `\\` belongs to the literal, so it stays.
2711        assert_eq!(round("'a\\\\\nb'"), "'a\\\\\\nb'");
2712        // A raw line feed with no backslash before it stays as well.
2713        assert_eq!(round("'a\\\n\nb'"), "'a\\nb'");
2714        let (ty, value) = from_text("b'a\\\nb'").expect("the bytestring reads");
2715        assert_eq!(ty.signature(), "ay");
2716        assert_eq!(value, Value::Bytes(b"ab\0".to_vec()));
2717    }
2718
2719    /// The nesting that the `ostree` command accepts, the next level, and the
2720    /// refusal.
2721    ///
2722    /// The test also checks the wording of the refusal. A value sits inside a
2723    /// maximum of 127 levels.
2724    #[test]
2725    fn refuses_the_level_past_the_nesting_cap() {
2726        // A tuple of one member needs its comma, so the tuple form closes
2727        // each level with `,)`. The other two forms close with the bracket
2728        // alone.
2729        for (open, close) in [("[", "]"), ("(", ",)"), ("<", ">")] {
2730            for depth in [125usize, 126, 127] {
2731                let text = format!("{}1{}", open.repeat(depth), close.repeat(depth));
2732                assert!(
2733                    from_text(&text).is_ok(),
2734                    "depth {depth} of {open} was refused"
2735                );
2736            }
2737            for depth in [128usize, 129, 200] {
2738                let text = format!("{}1{}", open.repeat(depth), close.repeat(depth));
2739                assert_eq!(
2740                    refuse(&text),
2741                    "128:variant nested too deeply",
2742                    "depth {depth} of {open}"
2743                );
2744            }
2745        }
2746        // A `just`, a declaration, and a type keyword each add a level too.
2747        assert!(from_text(&format!("{}5", "just ".repeat(127))).is_ok());
2748        assert!(from_text(&format!("{}5", "@i ".repeat(127))).is_ok());
2749        assert!(from_text(&format!("{}5", "uint32 ".repeat(127))).is_ok());
2750        for text in [
2751            format!("{}5", "just ".repeat(128)),
2752            format!("{}5", "@i ".repeat(128)),
2753            format!("{}5", "uint32 ".repeat(128)),
2754        ] {
2755            assert!(
2756                refuse(&text).ends_with("variant nested too deeply"),
2757                "{text}"
2758            );
2759        }
2760    }
2761
2762    /// A signature value takes 129 levels, with the leaf counted.
2763    ///
2764    /// The reader checks a signature value as a type string on its own. Its
2765    /// levels are inside the string, so its level in the value does not
2766    /// narrow it. Measured against `ostree` 2026.1.
2767    #[test]
2768    fn a_signature_value_takes_129_levels() {
2769        let arrays = |count: usize| "a".repeat(count);
2770        for count in [0usize, 1, 65, 127, 128] {
2771            for text in [
2772                format!("signature '{}y'", arrays(count)),
2773                format!("@g '{}y'", arrays(count)),
2774            ] {
2775                assert!(from_text(&text).is_ok(), "{count} arrays was refused");
2776            }
2777        }
2778        assert_eq!(
2779            refuse(&format!("signature '{}y'", arrays(129))),
2780            "10-142:not a valid signature"
2781        );
2782        assert_eq!(
2783            refuse(&format!("@g '{}y'", arrays(129))),
2784            "3-135:not a valid signature"
2785        );
2786        // The deepest signature stands at the deepest level that a value
2787        // reaches.
2788        let deep = format!(
2789            "{}signature '{}y'{}",
2790            "[".repeat(100),
2791            arrays(128),
2792            "]".repeat(100)
2793        );
2794        assert!(from_text(&deep).is_ok());
2795    }
2796
2797    /// A declaration takes the levels of its type, up to 128 levels in all.
2798    ///
2799    /// The count starts at the level where the declaration stands. A leaf is
2800    /// one level, and a container adds one over its deepest member. The empty
2801    /// tuple carries no level. A dict entry measures its value.
2802    ///
2803    /// A type string past 129 levels is invalid. The invalid refusal comes
2804    /// before the depth refusal. The depth refusal comes before the
2805    /// definiteness refusal. Measured against `ostree` 2026.1.
2806    #[test]
2807    fn a_declaration_takes_128_levels_from_where_it_stands() {
2808        let arrays = |count: usize| "a".repeat(count);
2809        for text in [
2810            format!("@{}y []", arrays(127)),
2811            format!("@{}() []", arrays(128)),
2812            format!("@{}(y) []", arrays(126)),
2813            format!("@{}(()) []", arrays(127)),
2814            format!("@{}{{sy}} []", arrays(126)),
2815            format!("@{}{{s()}} []", arrays(127)),
2816            format!("@{}(y()) []", arrays(126)),
2817            format!("@{}((y)y) []", arrays(125)),
2818            format!("[@{}y []]", arrays(126)),
2819            format!("[[@{}y []]]", arrays(125)),
2820        ] {
2821            assert!(from_text(&text).is_ok(), "{text} was refused");
2822        }
2823        let deep = "type declaration recurses too deeply";
2824        let invalid = "invalid type declaration";
2825        let indefinite = "type declarations must be definite";
2826        let cases: &[(String, String)] = &[
2827            (format!("@{}y []", arrays(128)), format!("0-130:{deep}")),
2828            (format!("@{}y []", arrays(129)), format!("0-131:{invalid}")),
2829            (format!("@{}(y) []", arrays(127)), format!("0-131:{deep}")),
2830            (format!("@{}() []", arrays(129)), format!("0-132:{invalid}")),
2831            (
2832                format!("@{}{{sy}} []", arrays(127)),
2833                format!("0-132:{deep}"),
2834            ),
2835            (
2836                format!("@{}(()) []", arrays(128)),
2837                format!("0-133:{invalid}"),
2838            ),
2839            (format!("@{}(y()) []", arrays(127)), format!("0-133:{deep}")),
2840            (
2841                format!("@{}((y)y) []", arrays(126)),
2842                format!("0-133:{deep}"),
2843            ),
2844            // The reader reports the definiteness only inside the cap.
2845            (format!("@{}r 5", arrays(66)), format!("0-68:{indefinite}")),
2846            (
2847                format!("@{}r 5", arrays(127)),
2848                format!("0-129:{indefinite}"),
2849            ),
2850            (format!("@{}r 5", arrays(128)), format!("0-130:{deep}")),
2851            (format!("@{}r 5", arrays(129)), format!("0-131:{invalid}")),
2852            (
2853                format!("@{}* 5", arrays(127)),
2854                format!("0-129:{indefinite}"),
2855            ),
2856            (format!("@{}* 5", arrays(128)), format!("0-130:{deep}")),
2857            (
2858                format!("@{}(r) 5", arrays(126)),
2859                format!("0-130:{indefinite}"),
2860            ),
2861            (format!("@{}(r) 5", arrays(127)), format!("0-131:{deep}")),
2862            // A declaration inside a container starts from that level.
2863            (format!("[@{}y []]", arrays(127)), format!("1-130:{deep}")),
2864            (format!("[[@{}y []]]", arrays(126)), format!("2-130:{deep}")),
2865        ];
2866        for (text, expected) in cases {
2867            assert_eq!(refuse(text), *expected, "refusing {text}");
2868        }
2869    }
2870
2871    /// The reader parses, types, and builds the value before the trailing check.
2872    ///
2873    /// If the value has a fault, the error names that fault.
2874    #[test]
2875    fn a_fault_in_the_value_stands_ahead_of_trailing_input() {
2876        let cases: &[(&str, &str)] = &[
2877            ("@i 'x' 5", "3-6:can not parse as value of type 'i'"),
2878            ("3000000000 5", "0-10:number out of range for type 'i'"),
2879            ("@d 5e-324 5", "3-9:number too big for any type"),
2880            ("objectpath 'bad' 5", "11-16:not a valid object path"),
2881            ("nothing 5", "0-7:unable to infer type"),
2882            ("(1) 5", "2:expected ',' after first tuple element"),
2883            // A value with no fault of its own reports the trailing token.
2884            ("42 43", "3:expected end of input"),
2885            ("nan(0x1)", "3:expected end of input"),
2886        ];
2887        for (input, expected) in cases {
2888            assert_eq!(refuse(input), *expected, "refusing {input:?}");
2889        }
2890    }
2891
2892    /// The depth limit of the parser bounds the node tree.
2893    ///
2894    /// The reader refuses a text far past the cap, and the stack does not
2895    /// overflow. This applies to the parser, type inference, construction, and
2896    /// the drop of the tree.
2897    #[test]
2898    fn deep_nesting_does_not_overflow_the_stack() {
2899        for text in [
2900            "[".repeat(50_000),
2901            format!("{}1{}", "[".repeat(50_000), "]".repeat(50_000)),
2902            format!("{}1{}", "(".repeat(50_000), ")".repeat(50_000)),
2903            format!("{}1{}", "<".repeat(50_000), ">".repeat(50_000)),
2904            format!("{}1", "just ".repeat(50_000)),
2905            format!("{}1{}", "{'a': ".repeat(20_000), "}".repeat(20_000)),
2906            format!("{}5", "@i ".repeat(50_000)),
2907            format!("@{}i 5", "a".repeat(50_000)),
2908        ] {
2909            assert!(from_text(&text).is_err(), "{:.20} was accepted", text);
2910        }
2911    }
2912
2913    /// Every text that the printer writes reads back.
2914    ///
2915    /// A value can go out through `to_text` and come back in through
2916    /// `from_text`.
2917    #[test]
2918    fn the_printers_output_reads_back() {
2919        let cases = [
2920            "nan",
2921            "-nan",
2922            "inf",
2923            "-inf",
2924            "1.5",
2925            "-0.0",
2926            "0.10000000000000001",
2927            "1.7976931348623157e+308",
2928            "uint32 42",
2929            "byte 0x41",
2930            "@ms nothing",
2931            "b'bytes'",
2932            "{'x': 'y'}",
2933            "('a', 5)",
2934            "<'x'>",
2935            "objectpath '/a/b'",
2936            "signature 'ay'",
2937            "(1,)",
2938            "[byte 0x01, 0x02]",
2939            "@a{sv} {}",
2940            "[@ms 'a', nothing]",
2941            "{'a', 5}",
2942            "int64 -5",
2943            "handle 5",
2944            // Every escape that the string printer writes, its quote for a
2945            // string that holds a quote, and one character that it writes
2946            // unchanged.
2947            "'a\\ab'",
2948            "'a\\bb'",
2949            "'a\\fb'",
2950            "'a\\nb'",
2951            "'a\\rb'",
2952            "'a\\tb'",
2953            "'a\\vb'",
2954            "'a\\\\b'",
2955            "'a\\u001bb'",
2956            "'a\\u007fb'",
2957            "\"a'b\"",
2958            "'a\"b'",
2959            "\"a'\\\"b\"",
2960            "'héllo'",
2961            // Every escape that the bytestring printer writes, and the quote
2962            // that it selects for content with a single quote in it.
2963            "b'a\\tb'",
2964            "b'a\\nb'",
2965            "b'a\\rb'",
2966            "b'a\\bb'",
2967            "b'a\\fb'",
2968            "b'a\\vb'",
2969            "b'a\\\\b'",
2970            "b'a\\\"b'",
2971            "b\"a'b\"",
2972            "b\"a'\\\"b\"",
2973            "b'\\377'",
2974            "b'h\\303\\251'",
2975            // A nested maybe. The `just ` prefixes that the printer writes are
2976            // the only record of the number of set levels. If these prefixes do
2977            // not survive, the text reads back as a different value.
2978            "@mmi 5",
2979            "@mmi just nothing",
2980            "@mmi nothing",
2981            "@mmmi just just nothing",
2982            "@mmmi just nothing",
2983            "@mmmmi just just just nothing",
2984            "@mms just nothing",
2985            "@mmv just nothing",
2986            "@mmv <5>",
2987            "@mmay just nothing",
2988            "@mm() just nothing",
2989            "@mammi [just nothing]",
2990            "[@mmi just nothing, nothing, 5]",
2991            "[@mmmi just just nothing, just nothing, nothing, 5]",
2992            "{'a': @mmi just nothing, 'b': nothing, 'c': 5}",
2993            "{'a', @mmi just nothing}",
2994            "(@mmi just nothing,)",
2995            "(@mmi just nothing, @mmi nothing, @mmi 5)",
2996        ];
2997        for text in cases {
2998            let (ty, value) = from_text(text).unwrap_or_else(|e| panic!("{text}: {e}"));
2999            let printed = to_text(&ty, &value).unwrap();
3000            assert_eq!(printed, text, "printing {text}");
3001            let (again_ty, again_value) =
3002                from_text(&printed).unwrap_or_else(|e| panic!("{printed}: {e}"));
3003            assert_eq!(again_ty, ty, "type of {text}");
3004            assert_eq!(again_value, value, "value of {text}");
3005        }
3006        // The reader refuses one text that the printer writes, a subnormal.
3007        // The `ostree` command also refuses a subnormal on the way in.
3008        let printed = to_text(&Type::Double, &Value::double(f64::from_bits(1))).unwrap();
3009        assert_eq!(printed, "4.9406564584124654e-324");
3010        assert_eq!(
3011            refuse(&printed),
3012            "0-23:number too big for any type",
3013            "the subnormal the printer writes"
3014        );
3015    }
3016
3017    /// Every maybe chain that the printer writes reads back as the same value.
3018    ///
3019    /// If every level of a chain is set, the printer writes the value alone.
3020    /// Then the type states the level count. A chain that ends at `nothing`
3021    /// states its set levels, with one `just ` for each. Both readings must
3022    /// survive the trip. If not, the printed text names a different value.
3023    #[test]
3024    fn every_maybe_chain_the_printer_writes_reads_back() {
3025        let leaves: &[(&str, Value)] = &[
3026            ("i", Value::I32(5)),
3027            ("s", Value::Str("x".into())),
3028            ("v", Value::variant(Type::I32, Value::I32(5))),
3029            ("ay", Value::Bytes(vec![0x01])),
3030            ("()", Value::Tuple(Vec::new())),
3031            ("ai", Value::Array(vec![Value::I32(1)])),
3032            (
3033                "(is)",
3034                Value::Tuple(vec![Value::I32(1), Value::Str("x".into())]),
3035            ),
3036            (
3037                "a{si}",
3038                Value::Array(vec![Value::Tuple(vec![
3039                    Value::Str("k".into()),
3040                    Value::I32(1),
3041                ])]),
3042            ),
3043        ];
3044        for (element, leaf) in leaves {
3045            for depth in 1..=4usize {
3046                let signature = format!("{}{element}", "m".repeat(depth));
3047                let ty = Type::parse(&signature).unwrap();
3048                for set in 0..=depth {
3049                    let mut value = if set == depth {
3050                        leaf.clone()
3051                    } else {
3052                        Value::Maybe(None)
3053                    };
3054                    for _ in 0..set {
3055                        value = Value::Maybe(Some(Box::new(value)));
3056                    }
3057                    let printed = to_text(&ty, &value).unwrap();
3058                    let (again_ty, again_value) = from_text(&printed)
3059                        .unwrap_or_else(|e| panic!("{signature} set {set}: {printed}: {e}"));
3060                    assert_eq!(again_ty, ty, "type of {printed}");
3061                    assert_eq!(again_value, value, "value of {printed}");
3062                }
3063            }
3064        }
3065    }
3066
3067    /// A value serializes to the bytes that the `ostree` command stores.
3068    ///
3069    /// The bytes of a `u` and a `d` are little-endian.
3070    #[test]
3071    fn serializes_in_host_byte_order() {
3072        let (ty, value) = from_text("uint32 42").unwrap();
3073        assert_eq!(ty.signature(), "u");
3074        assert_eq!(to_bytes(&ty, &value).unwrap(), 42u32.to_le_bytes());
3075        let (ty, value) = from_text("1.5").unwrap();
3076        assert_eq!(ty.signature(), "d");
3077        assert_eq!(to_bytes(&ty, &value).unwrap(), 1.5f64.to_le_bytes());
3078    }
3079}