Skip to main content

satx_core/
reply.rs

1//! Parsers for the text a calculator in Kermit server mode returns: the
2//! stack display of a host command (`C`) and the directory listing (`G D`).
3//!
4//! Input is already translated from the HP character set
5//! ([`crate::charset::decode`]). The 48SX, 48GX and 49G differ in details:
6//! the 49G prints reals with a trailing dot (`10777.`), shows lists in
7//! algebraic form (`{9600.,0.,0.,0.,3.,1.}`), shows names without quotes and
8//! truncates long values at the display width. The stack parser is
9//! `saturnus-objects`' (the emulator's hosts read the same replies).
10
11use crate::{Error, Result};
12
13pub use saturnus_objects::transfer::{StackReply, parse_stack};
14
15/// A directory listing returned for `G D`.
16#[derive(Clone, Debug, PartialEq)]
17pub struct Listing {
18    /// The current directory path, e.g. `["HOME", "D1"]` (48GX and 49G only).
19    pub path: Option<Vec<String>>,
20    /// Free memory in bytes (48GX and 49G only).
21    pub free: Option<f64>,
22    /// The variables of the current directory, in calculator order.
23    pub entries: Vec<Entry>,
24}
25
26/// One variable in a [`Listing`].
27#[derive(Clone, Debug, PartialEq)]
28pub struct Entry {
29    /// The variable name.
30    pub name: String,
31    /// Size in bytes; can be a half (`29.5`).
32    pub size: f64,
33    /// The English type name, e.g. `Real Number`, `Directory`.
34    pub kind: String,
35    /// The calculator's 16-bit CRC of the object.
36    pub checksum: u16,
37}
38
39impl Entry {
40    /// True if the variable is a directory.
41    pub fn is_directory(&self) -> bool {
42        self.kind == "Directory"
43    }
44}
45
46/// Parse a `G D` directory listing.
47///
48/// An optional header starting with `{` holds the path and the free
49/// memory; the 49G wraps a long header over several lines (seen in
50/// `HOME/SATXAAAA/SATXBBBB`, 2026-10-05), so it runs to the line with the
51/// closing brace. Every other non-blank line is `NAME SIZE TYPE...
52/// CHECKSUM`. Returns [`Error::Reply`] for a line that does not fit.
53pub fn parse_listing(text: &str) -> Result<Listing> {
54    let mut listing = Listing {
55        path: None,
56        free: None,
57        entries: Vec::new(),
58    };
59    let mut lines = text
60        .lines()
61        .map(str::trim)
62        .filter(|l| !l.is_empty())
63        .peekable();
64    if lines.peek().is_some_and(|l| l.starts_with('{')) {
65        let mut header = String::new();
66        for line in lines.by_ref() {
67            if !header.is_empty() {
68                header.push(' ');
69            }
70            header.push_str(line);
71            if line.contains('}') {
72                break;
73            }
74        }
75        let bad = || Error::Reply(format!("bad directory header: {header:?}"));
76        let end = header.find('}').ok_or_else(bad)?;
77        let (list, rest) = header.split_at(end + 1);
78        listing.path = Some(parse_list(list).ok_or_else(bad)?);
79        if !rest.trim().is_empty() {
80            listing.free = Some(parse_real(rest).ok_or_else(bad)?);
81        }
82    }
83    for line in lines {
84        listing.entries.push(parse_entry(line)?);
85    }
86    Ok(listing)
87}
88
89fn parse_entry(line: &str) -> Result<Entry> {
90    let bad = || Error::Reply(format!("bad directory line: {line:?}"));
91    let tokens: Vec<&str> = line.split_whitespace().collect();
92    let [name, size, kind @ .., checksum] = tokens.as_slice() else {
93        return Err(bad());
94    };
95    if kind.is_empty() {
96        return Err(bad());
97    }
98    let size = parse_real(size).filter(|s| *s >= 0.0).ok_or_else(bad)?;
99    let checksum = parse_real(checksum)
100        .and_then(integer)
101        .and_then(|c| u16::try_from(c).ok())
102        .ok_or_else(bad)?;
103    Ok(Entry {
104        name: (*name).to_string(),
105        size,
106        kind: kind.join(" "),
107        checksum,
108    })
109}
110
111/// The integer value of `x`, if it has no fractional part.
112fn integer(x: f64) -> Option<i64> {
113    // The bounds keep the cast exact.
114    (x.fract() == 0.0 && x.abs() < 9.0e15).then_some(x as i64)
115}
116
117/// Parse a displayed real such as `127828.`, `1.5`, `-3` or `1.E-3`, in
118/// any display mode: FIX, SCI and ENG (`9600.0000`, `9.60E3`), digit
119/// groups (the 48 in FIX shows `9,600.0000`) and the fraction mark `,`
120/// (flag -51 set: `9.600,0000`, `1,5`, `1,23E4`). A lone `,` is the
121/// fraction mark; with both, the last one is. Leading and trailing
122/// whitespace is ignored.
123pub fn parse_real(s: &str) -> Option<f64> {
124    let s = s.trim();
125    // Rust also accepts `inf` and `NaN`; the calculator never prints those.
126    if s.is_empty()
127        || !s
128            .chars()
129            .all(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | 'E' | 'e' | '+' | '-'))
130    {
131        return None;
132    }
133    let mark = match (s.rfind('.'), s.rfind(',')) {
134        (Some(point), Some(comma)) if comma > point => ',',
135        (None, Some(_)) if s.matches(',').count() == 1 => ',',
136        (Some(_), None) if s.matches('.').count() > 1 => ',',
137        _ => '.',
138    };
139    let plain: String = s
140        .chars()
141        .filter_map(|c| match c {
142            '.' | ',' if c == mark => Some('.'),
143            '.' | ',' => None,
144            c => Some(c),
145        })
146        .collect();
147    plain.parse().ok()
148}
149
150/// Parse a displayed flat list into its items as text: `{ 9600 0 0 0 3 1 }`,
151/// `{9600.,0.,0.,0.,3.,1.}`, `{ HOME D1 }`, `{ }`.
152///
153/// Items are separated by whitespace, `,` or `;`. `None` if the text is not
154/// wrapped in `{ }` (a 49G truncated list lacks the closing brace) or holds
155/// nested braces or quotes.
156pub fn parse_list(s: &str) -> Option<Vec<String>> {
157    let inner = s.trim().strip_prefix('{')?.strip_suffix('}')?;
158    if inner.contains(['{', '}', '"', '\'']) {
159        return None;
160    }
161    Some(
162        inner
163            .split(|c: char| c.is_whitespace() || c == ',' || c == ';')
164            .filter(|item| !item.is_empty())
165            .map(str::to_string)
166            .collect(),
167    )
168}
169
170/// Parse a displayed string: `"Version HP48-R"` gives `Version HP48-R`.
171///
172/// A missing closing quote (the 49G truncates long values) is accepted and
173/// the rest is returned as is. `None` if the text does not start with `"`.
174pub fn parse_string(s: &str) -> Option<String> {
175    let s = s.trim();
176    let body = s.strip_prefix('"')?;
177    Some(body.strip_suffix('"').unwrap_or(body).to_string())
178}
179
180/// Parse a displayed string that arrived whole: as [`parse_string`], but
181/// `None` without the closing quote (a string the 49G cut at its display
182/// width).
183pub fn parse_whole_string(s: &str) -> Option<String> {
184    let s = s.trim();
185    let body = s.strip_prefix('"')?.strip_suffix('"')?;
186    Some(body.to_string())
187}
188
189/// Whether a displayed stack level ends inside an object: a string without
190/// its closing quote, an algebraic without its closing `'`, or a list,
191/// vector, program or complex number whose `{ } [ ] « » ( )` do not close.
192///
193/// The 49G sends each level only as wide as its display (20 characters on
194/// ROM 1.18, 22 on 2.x, delimiters included), with no marker, so a longer
195/// object arrives cut; the 48S/SX and 48G/GX send it whole. A 48 string
196/// that holds a `"` itself can look cut too.
197pub fn looks_cut(level: &str) -> bool {
198    let mut open: Vec<char> = Vec::new();
199    let mut in_string = false;
200    let mut in_algebraic = false;
201    for c in level.chars() {
202        if in_string {
203            in_string = c != '"';
204            continue;
205        }
206        match c {
207            '"' => in_string = true,
208            '\'' => in_algebraic = !in_algebraic,
209            '{' | '[' | '«' | '(' => open.push(c),
210            '}' | ']' | '»' | ')' => {
211                let opener = match c {
212                    '}' => '{',
213                    ']' => '[',
214                    '»' => '«',
215                    _ => '(',
216                };
217                if open.pop() != Some(opener) {
218                    // Not a cut: something this check does not know.
219                    return false;
220                }
221            }
222            _ => {}
223        }
224    }
225    in_string || in_algebraic || !open.is_empty()
226}
227
228/// The levels of `levels` (level 1 first, as in [`StackReply`]) that
229/// [`looks_cut`], as level numbers counted from 1.
230pub fn cut_levels(levels: &[String]) -> Vec<usize> {
231    levels
232        .iter()
233        .enumerate()
234        .filter(|(_, level)| looks_cut(level))
235        .map(|(i, _)| i + 1)
236        .collect()
237}
238
239/// Parse a quoted global name: `'NOSUCH'` gives `NOSUCH`.
240///
241/// `None` for anything else, including an unquoted name (the 49G in
242/// algebraic mode shows names without quotes) and quoted expressions.
243pub fn parse_name(s: &str) -> Option<String> {
244    let inner = s.trim().strip_prefix('\'')?.strip_suffix('\'')?;
245    let first = inner.chars().next()?;
246    let valid = !first.is_ascii_digit()
247        && first != '.'
248        && inner.chars().all(|c| {
249            !c.is_whitespace()
250                && !matches!(
251                    c,
252                    '+' | '-'
253                        | '*'
254                        | '/'
255                        | '^'
256                        | '='
257                        | '<'
258                        | '>'
259                        | '('
260                        | ')'
261                        | '{'
262                        | '}'
263                        | '['
264                        | ']'
265                        | '#'
266                        | ','
267                        | ';'
268                        | '\''
269                        | '"'
270                        | ':'
271                        | '«'
272                        | '»'
273                )
274        });
275    valid.then(|| inner.to_string())
276}
277
278/// The IOPAR list (wiki: protocols/iopar): baud, parity, receive pacing,
279/// transmit pacing, Kermit checksum type, translation code.
280#[derive(Clone, Copy, Debug, PartialEq, Eq)]
281pub struct Iopar {
282    /// Baud rate.
283    pub baud: u32,
284    /// Parity: 0 none, 1 odd, 2 even, 3 mark, 4 space; negative applies to
285    /// transmit only.
286    pub parity: i8,
287    /// XON/XOFF pacing when receiving.
288    pub receive_pacing: bool,
289    /// XON/XOFF pacing when transmitting.
290    pub transmit_pacing: bool,
291    /// Kermit block check type (1, 2 or 3).
292    pub checksum: u8,
293    /// Character translation code.
294    pub translate: u8,
295}
296
297impl Default for Iopar {
298    /// `{ 9600 0 0 0 3 1 }`, the settings of a fresh calculator.
299    fn default() -> Self {
300        Self {
301            baud: 9600,
302            parity: 0,
303            receive_pacing: false,
304            transmit_pacing: false,
305            checksum: 3,
306            translate: 1,
307        }
308    }
309}
310
311impl Iopar {
312    /// Parse a displayed IOPAR list in 48 (`{ 9600 0 0 0 3 1 }`) or 49G
313    /// (`{9600.,0.,0.,0.,3.,1.}`) form. `None` unless it has exactly six
314    /// integer items in range. Nonzero pacing values mean on.
315    pub fn parse(s: &str) -> Option<Self> {
316        Self::from_items(&parse_list(s)?)
317    }
318
319    /// The settings from the list's six items as displayed, e.g. `9600.`,
320    /// `0`, `3.0000`, in list order. `None` unless there are exactly six
321    /// integers in range.
322    pub fn from_items(items: &[impl AsRef<str>]) -> Option<Self> {
323        let values = items
324            .iter()
325            .map(|item| parse_real(item.as_ref()).and_then(integer))
326            .collect::<Option<Vec<i64>>>()?;
327        let [baud, parity, rx, tx, checksum, translate] = values.as_slice() else {
328            return None;
329        };
330        Some(Self {
331            baud: u32::try_from(*baud).ok()?,
332            parity: i8::try_from(*parity).ok()?,
333            receive_pacing: *rx != 0,
334            transmit_pacing: *tx != 0,
335            checksum: u8::try_from(*checksum).ok()?,
336            translate: u8::try_from(*translate).ok()?,
337        })
338    }
339
340    /// The list as RPL source with real numbers, `{ 9600. 0. 0. 0. 3. 1. }`.
341    /// The trailing dots matter on the 49G: in exact mode it parses `9600`
342    /// as an exact integer, and a list of integers stored as `IOPAR` makes
343    /// the Kermit server stop with "Invalid IOPAR". The 48 reads `9600.` as
344    /// the real 9600 too.
345    pub fn to_rpl(&self) -> String {
346        let [baud, parity, rx, tx, checksum, translate] = self.values();
347        format!("{{ {baud}. {parity}. {rx}. {tx}. {checksum}. {translate}. }}")
348    }
349
350    fn values(&self) -> [i64; 6] {
351        [
352            i64::from(self.baud),
353            i64::from(self.parity),
354            i64::from(self.receive_pacing),
355            i64::from(self.transmit_pacing),
356            i64::from(self.checksum),
357            i64::from(self.translate),
358        ]
359    }
360}
361
362impl std::fmt::Display for Iopar {
363    /// The list as the 48 displays it, `{ 9600 0 0 0 3 1 }`.
364    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
365        let [baud, parity, rx, tx, checksum, translate] = self.values();
366        write!(f, "{{ {baud} {parity} {rx} {tx} {checksum} {translate} }}")
367    }
368}
369
370#[cfg(test)]
371#[allow(clippy::unwrap_used, clippy::expect_used)]
372mod tests {
373    use super::*;
374    use crate::charset::decode;
375
376    macro_rules! fixture {
377        ($model:literal, $name:literal) => {
378            decode(include_bytes!(concat!(
379                "../fixtures/",
380                $model,
381                "-",
382                $name,
383                ".txt"
384            )))
385        };
386    }
387
388    macro_rules! all_models {
389        ($name:literal) => {
390            [
391                ("48sx", fixture!("48sx", $name)),
392                ("48gx", fixture!("48gx", $name)),
393                ("49g", fixture!("49g", $name)),
394            ]
395        };
396    }
397
398    fn entry<'a>(l: &'a Listing, name: &str) -> &'a Entry {
399        l.entries
400            .iter()
401            .find(|e| e.name == name)
402            .unwrap_or_else(|| panic!("no entry {name}"))
403    }
404
405    #[test]
406    fn dir() {
407        for (model, text) in all_models!("dir") {
408            let l = parse_listing(&text).unwrap();
409            if model == "48sx" {
410                assert_eq!(l.path, None);
411                assert_eq!(l.free, None);
412            } else {
413                assert_eq!(l.path, Some(vec!["HOME".to_string()]), "{model}");
414                assert!(l.free.unwrap() > 0.0, "{model}");
415            }
416            let d1 = entry(&l, "D1");
417            assert!(d1.is_directory(), "{model}");
418            let g = entry(&l, "G");
419            assert_eq!(
420                (g.size, g.kind.as_str(), g.checksum),
421                (1103.5, "Graphic", 3894)
422            );
423            let r = entry(&l, "R");
424            assert_eq!(
425                (r.size, r.kind.as_str(), r.checksum),
426                (16.0, "Real Number", 52870)
427            );
428            let b = entry(&l, "B");
429            assert_eq!(b.kind, "Binary Integer");
430            let iopar = entry(&l, "IOPAR");
431            assert_eq!((iopar.size, iopar.kind.as_str()), (29.5, "List"));
432            assert!(!iopar.is_directory());
433        }
434        let l = parse_listing(&fixture!("48gx", "dir")).unwrap();
435        assert_eq!(l.free, Some(126562.0));
436        assert_eq!(l.entries.len(), 11);
437        assert_eq!(entry(&l, "D1").checksum, 51467);
438        let l = parse_listing(&fixture!("49g", "dir")).unwrap();
439        assert_eq!(l.free, Some(244692.0));
440        assert_eq!(l.entries.len(), 12);
441        assert_eq!(entry(&l, "IOPAR").checksum, 10777);
442        assert_eq!(entry(&l, "D1").checksum, 65022);
443        assert!(entry(&l, "CASDIR").is_directory());
444        assert_eq!(entry(&l, "C").size, 24.0);
445    }
446
447    #[test]
448    fn dir_sub() {
449        for (model, text) in all_models!("dir-sub") {
450            let l = parse_listing(&text).unwrap();
451            assert_eq!(l.entries.len(), 1, "{model}");
452            assert_eq!(l.entries[0].name, "Z");
453            if model != "48sx" {
454                assert_eq!(l.path, Some(vec!["HOME".to_string(), "D1".to_string()]));
455            }
456        }
457        let l = parse_listing(&fixture!("49g", "dir-sub")).unwrap();
458        assert_eq!(
459            l.entries[0],
460            Entry {
461                name: "Z".into(),
462                size: 11.5,
463                kind: "Integer".into(),
464                checksum: 25035
465            }
466        );
467        assert_eq!(l.free, Some(244679.0));
468    }
469
470    #[test]
471    fn path() {
472        for (model, text) in all_models!("path") {
473            let s = parse_stack(&text);
474            assert_eq!(
475                parse_list(s.level(1).unwrap()).unwrap(),
476                ["HOME"],
477                "{model}"
478            );
479        }
480        for (model, text) in all_models!("path-sub") {
481            let s = parse_stack(&text);
482            assert_eq!(
483                parse_list(s.level(1).unwrap()).unwrap(),
484                ["HOME", "D1"],
485                "{model}"
486            );
487        }
488    }
489
490    #[test]
491    fn mem() {
492        for (model, text) in all_models!("mem") {
493            let s = parse_stack(&text);
494            assert!(parse_real(s.level(1).unwrap()).unwrap() > 0.0, "{model}");
495        }
496        let s = parse_stack(&fixture!("48sx", "mem"));
497        assert_eq!(parse_real(s.level(1).unwrap()), Some(28859.5));
498    }
499
500    #[test]
501    fn version() {
502        let s = parse_stack(&fixture!("48sx", "version"));
503        assert_eq!(s.levels.len(), 1);
504        assert_eq!(parse_name(s.level(1).unwrap()).as_deref(), Some("VERSION"));
505
506        let s = parse_stack(&fixture!("48gx", "version"));
507        assert_eq!(s.levels.len(), 2);
508        assert_eq!(
509            parse_string(s.level(2).unwrap()).as_deref(),
510            Some("Version HP48-R")
511        );
512        assert_eq!(
513            parse_string(s.level(1).unwrap()).as_deref(),
514            Some("Copyright HP 1993")
515        );
516
517        // The 49G cuts the two-line version string at the display width.
518        let s = parse_stack(&fixture!("49g", "version"));
519        assert_eq!(s.levels.len(), 2);
520        assert_eq!(
521            parse_string(s.level(2).unwrap()).as_deref(),
522            Some("Version HP48-C\nRevisi")
523        );
524        assert_eq!(
525            parse_string(s.level(1).unwrap()).as_deref(),
526            Some("Copyright HP 2009")
527        );
528    }
529
530    /// Levels the 49G cut at its display width (ROM 1.18 on a real 49G
531    /// and 2.15 on the emulated one, 2026-11-08) and whole ones.
532    #[test]
533    fn cut_levels_are_told() {
534        for cut in [
535            "{ 9600. 0. 0. 0. 3. ",
536            "{9600.0000,0.0000,0.00",
537            "\"Version HP49-C\nRevi",
538            "\"ABCDEFGHIJKLMNOPQRS",
539            "« 1 2 + DUP DUP DUP D",
540            "[[1.,2.],[3.,4.],[5.",
541            "'X+Y+Z+SIN(X+Y+Z+X+Y",
542            "{ \"a}\" 'X' { 1 2 } 3",
543            "(1.,2.",
544        ] {
545            assert!(looks_cut(cut), "{cut:?}");
546        }
547        for whole in [
548            "42.",
549            "\"Copyright HP 2009\"",
550            "{9600.,0.,0.,0.,3.,1.}",
551            "{ 9600 0 0 0 3 1 }",
552            "« 1 2 + »",
553            "[[ 1 2 ][ 3 4 ]]",
554            "'SIN(X)'",
555            "{ \"a{\" 'X' }",
556            "(1.,2.)",
557            ":TAG: 5",
558            "# 10d",
559            "Graphic 131 × 64",
560            "",
561        ] {
562            assert!(!looks_cut(whole), "{whole:?}");
563        }
564        let levels = vec!["\"AB".to_string(), "1.".to_string(), "{ 1".to_string()];
565        assert_eq!(cut_levels(&levels), [1, 3]);
566        assert_eq!(parse_whole_string("\"AB\""), Some("AB".to_string()));
567        assert_eq!(parse_whole_string("\"AB"), None);
568        assert_eq!(parse_whole_string("\""), None);
569        assert_eq!(parse_whole_string("AB"), None);
570        // IOPAR's items as `LIST→` leaves them, in list order.
571        assert_eq!(
572            Iopar::from_items(&["9600.", "0.", "0.", "0.", "3.", "1."]),
573            Some(Iopar::default())
574        );
575        assert_eq!(Iopar::from_items(&["9600", "0", "0", "0", "3"]), None);
576    }
577
578    #[test]
579    fn iopar() {
580        for (model, text) in all_models!("iopar") {
581            let s = parse_stack(&text);
582            let iopar = Iopar::parse(s.level(1).unwrap());
583            assert_eq!(iopar, Some(Iopar::default()), "{model}");
584        }
585        let d = Iopar::default();
586        assert_eq!(d.to_string(), "{ 9600 0 0 0 3 1 }");
587        // Reals, not 49G exact integers (which the server rejects).
588        assert_eq!(d.to_rpl(), "{ 9600. 0. 0. 0. 3. 1. }");
589        let other = Iopar {
590            baud: 2400,
591            parity: -2,
592            receive_pacing: true,
593            transmit_pacing: false,
594            checksum: 1,
595            translate: 3,
596        };
597        assert_eq!(Iopar::parse(&other.to_rpl()), Some(other));
598        assert_eq!(other.to_rpl(), "{ 2400. -2. 1. 0. 1. 3. }");
599        assert_eq!(Iopar::parse(&other.to_string()), Some(other));
600        assert_eq!(Iopar::parse("{ 9600 0 0 0 3 }"), None);
601        assert_eq!(Iopar::parse("{ 9600 0 0 0 3 1.5 }"), None);
602        assert_eq!(Iopar::parse("{ 9600 0 0 0 300 1 }"), None);
603    }
604
605    #[test]
606    fn vars() {
607        for model in ["48sx", "48gx"] {
608            let text = if model == "48sx" {
609                fixture!("48sx", "vars")
610            } else {
611                fixture!("48gx", "vars")
612            };
613            let items = parse_list(parse_stack(&text).level(1).unwrap()).unwrap();
614            assert!(items.iter().any(|i| i == "D1"), "{model}");
615            assert!(items.iter().any(|i| i == "IOPAR"), "{model}");
616        }
617        // The 49G truncates the list at the display width: no closing brace.
618        let s = parse_stack(&fixture!("49g", "vars"));
619        assert_eq!(s.level(1), Some("{D1,G,TG,B,C,A,P,L,S,R"));
620        assert_eq!(parse_list(s.level(1).unwrap()), None);
621    }
622
623    #[test]
624    fn error() {
625        for model in ["48sx", "48gx"] {
626            let text = if model == "48sx" {
627                fixture!("48sx", "error")
628            } else {
629                fixture!("48gx", "error")
630            };
631            let s = parse_stack(&text);
632            assert_eq!(s.error.as_deref(), Some("Infinite Result"), "{model}");
633            assert_eq!(s.levels, ["0", "1"]);
634        }
635        // 1/0 is not an error on the 49G: it returns infinity.
636        let s = parse_stack(&fixture!("49g", "error"));
637        assert_eq!(s.error, None);
638        assert_eq!(s.level(1), Some("∞"));
639    }
640
641    #[test]
642    fn error_undefined() {
643        for (model, text) in all_models!("error-undefined") {
644            let s = parse_stack(&text);
645            assert_eq!(s.error.as_deref(), Some("Undefined Name"), "{model}");
646            assert_eq!(s.levels.len(), 1);
647            if model == "49g" {
648                // Shown unquoted in algebraic mode.
649                assert_eq!(s.level(1), Some("NOSUCH"));
650                assert_eq!(parse_name(s.level(1).unwrap()), None);
651            } else {
652                assert_eq!(parse_name(s.level(1).unwrap()).as_deref(), Some("NOSUCH"));
653            }
654        }
655    }
656
657    #[test]
658    fn error_syntax() {
659        for (model, text) in all_models!("error-syntax") {
660            let s = parse_stack(&text);
661            assert_eq!(s.error.as_deref(), Some("Invalid Syntax"), "{model}");
662            assert_eq!(s.levels.len(), 2);
663            assert_eq!(
664                parse_string(s.level(1).unwrap()).as_deref(),
665                Some("CLEAR \\->LIST")
666            );
667        }
668    }
669
670    #[test]
671    fn stack() {
672        for (model, text) in all_models!("stack") {
673            let s = parse_stack(&text);
674            assert_eq!(s.error, None);
675            assert_eq!(s.levels.len(), 3, "{model}");
676            assert_eq!(s.level(3), Some("\"a\nb\""));
677            assert_eq!(s.level(2), Some("1.5"));
678            assert_eq!(parse_list(s.level(1).unwrap()).unwrap(), ["1", "2"]);
679            assert_eq!(s.level(0), None);
680            assert_eq!(s.level(4), None);
681        }
682        let s = parse_stack(&fixture!("49g", "stack"));
683        assert_eq!(s.level(1), Some("{1,2}"));
684    }
685
686    #[test]
687    fn empty() {
688        for (model, text) in all_models!("empty") {
689            let s = parse_stack(&text);
690            assert!(s.is_empty(), "{model}");
691            assert_eq!(s.error, None);
692        }
693    }
694
695    #[test]
696    fn flag() {
697        for (model, text) in all_models!("flag") {
698            let s = parse_stack(&text);
699            assert_eq!(parse_real(s.level(1).unwrap()), Some(1.0), "{model}");
700        }
701    }
702
703    #[test]
704    fn stack_edge_cases() {
705        let s = parse_stack("Error: X\r\nEmpty Stack");
706        assert_eq!(s.error.as_deref(), Some("X"));
707        assert!(s.is_empty());
708
709        // "2:" inside a continuation line is not the expected next level.
710        let s = parse_stack("2:  5\r\n1:  \"x\r\n2: y\"\r\n");
711        assert_eq!(s.levels, ["\"x\n2: y\"", "5"]);
712
713        // Only the next lower level number starts a new level.
714        let s = parse_stack("2: \"a\r\n3: b\"\r\n1: 7");
715        assert_eq!(s.levels, ["7", "\"a\n3: b\""]);
716
717        // Trailing spaces inside a value are kept.
718        let s = parse_stack("1:   \"a \r\n b \"\r\n");
719        assert_eq!(s.level(1), Some("\"a \n b \""));
720
721        // Junk before the first level is ignored, never an error.
722        let s = parse_stack("garbage\r\n1: 3");
723        assert_eq!(s.levels, ["3"]);
724        assert_eq!(parse_stack(""), StackReply::default());
725        assert_eq!(parse_stack("noise"), StackReply::default());
726    }
727
728    #[test]
729    fn listing_edge_cases() {
730        let l = parse_listing("").unwrap();
731        assert_eq!(l.entries, []);
732        assert_eq!(l.path, None);
733        assert!(parse_listing("\r\n\r\n").unwrap().entries.is_empty());
734        assert!(matches!(parse_listing("X 16 Real"), Err(Error::Reply(_))));
735        assert!(matches!(
736            parse_listing("X big Real Number 12"),
737            Err(Error::Reply(_))
738        ));
739        assert!(matches!(
740            parse_listing("X 16 Real Number 70000"),
741            Err(Error::Reply(_))
742        ));
743        assert!(matches!(
744            parse_listing("X 16 Real Number 12.5"),
745            Err(Error::Reply(_))
746        ));
747        // A header the 49G wrapped over two lines (seen in HOME/SATXAAAA/
748        // SATXBBBB, 2026-10-05).
749        let l =
750            parse_listing("{ HOME SATXAAAA\r\nSATXBBBB } 244872.\r\nX 10.5 Real Number 1234\r\n")
751                .unwrap();
752        assert_eq!(
753            l.path.as_deref(),
754            Some(&["HOME".to_string(), "SATXAAAA".into(), "SATXBBBB".into()][..])
755        );
756        assert_eq!((l.free, l.entries.len()), (Some(244872.0), 1));
757        // A header that never closes is an error.
758        assert!(matches!(parse_listing("{ HOME 12"), Err(Error::Reply(_))));
759        // A complete header with garbage after it is still an error.
760        assert!(matches!(
761            parse_listing("{ HOME } lots"),
762            Err(Error::Reply(_))
763        ));
764        let l = parse_listing("{ HOME }\r\n").unwrap();
765        assert_eq!((l.path.unwrap().len(), l.free), (1, None));
766    }
767
768    #[test]
769    fn scalars() {
770        for (s, v) in [
771            ("127828.", 127828.0),
772            ("1.5", 1.5),
773            ("-3", -3.0),
774            ("30001", 30001.0),
775            (" 245966.5 ", 245966.5),
776            ("1.E-3", 0.001),
777            ("-1.5E12", -1.5e12),
778            // FIX 4 on the 48 and the 49G, then with flag -51 (fraction
779            // mark ,), SCI 2 with it (emulated 48SX and 49G, 2026-11-08).
780            ("9,600.0000", 9600.0),
781            ("9600.0000", 9600.0),
782            ("30.129,5000", 30129.5),
783            ("245951,5000", 245951.5),
784            ("-95,0000", -95.0),
785            ("1,5", 1.5),
786            ("1,23E4", 12300.0),
787            ("1,000,000.", 1.0e6),
788        ] {
789            assert_eq!(parse_real(s), Some(v), "{s}");
790        }
791        for s in ["", "inf", "NaN", "abc", ".", ",", "1.5.3,2,1"] {
792            assert_eq!(parse_real(s), None, "{s}");
793        }
794
795        assert_eq!(parse_list("{ }").unwrap(), Vec::<String>::new());
796        assert_eq!(parse_list("{}").unwrap(), Vec::<String>::new());
797        assert_eq!(parse_list("{1;2}").unwrap(), ["1", "2"]);
798        assert_eq!(parse_list("1 2"), None);
799        assert_eq!(parse_list("{ { 1 } }"), None);
800        assert_eq!(parse_list("{ \"a\" }"), None);
801
802        assert_eq!(parse_string("\"\"").as_deref(), Some(""));
803        assert_eq!(parse_string("\"abc").as_deref(), Some("abc"));
804        assert_eq!(parse_string("abc"), None);
805
806        assert_eq!(parse_name("'X1'").as_deref(), Some("X1"));
807        assert_eq!(parse_name("'→A'").as_deref(), Some("→A"));
808        assert_eq!(parse_name("NOSUCH"), None);
809        assert_eq!(parse_name("''"), None);
810        assert_eq!(parse_name("'X+1'"), None);
811        assert_eq!(parse_name("'1X'"), None);
812    }
813}