Skip to main content

saturnus_objects/
ram.rs

1//! A read-only view of a paused calculator's user memory: the HOME
2//! directory tree, the current directory, the data stack and the flags,
3//! read straight from RAM through the ROM's own system pointers. Nothing
4//! is written and the calculator does not change mode, so a host can show
5//! it at any time; the values are those the ROM left when it last went
6//! idle (in its outer loop, the stack showing), which is where a paused
7//! machine normally sits.
8//!
9//! Locations per model (48SX, 48GX, 49G) and the layouts: wiki:
10//! hardware/hp48-system-ram. The 38G, 39G and 40G keep aplets, not a HOME
11//! tree, and the 42S has no RPL user memory (its RAM holds HP-41-style
12//! programs and registers; wiki: hardware/hp42s); neither is covered.
13
14use saturnus_core::{Machine, Model};
15use serde::Serialize;
16
17use anyhow::{Context, Result, bail, ensure};
18
19use crate::decompile::Settings;
20use crate::names::NameTable;
21use crate::object::{Base, Memory, Object, Reader};
22use crate::prolog::{ObjectType, Record, records};
23
24/// Most stack levels read (the 49G's 256 KB of RAM holds about 50 000
25/// pointers; more means the pointers are not the ROM's).
26const MAX_LEVELS: usize = 100_000;
27/// Largest region read in one piece, in nibbles (the whole address space).
28const MAX_REGION: u32 = 1 << 20;
29
30impl Memory for Machine {
31    fn nibble(&self, addr: u32) -> Option<u8> {
32        (addr < MAX_REGION).then(|| self.peek(addr))
33    }
34}
35
36/// Where a model's ROM keeps its system pointers and flags in RAM (wiki:
37/// hardware/hp48-system-ram). Each `*_ptr` field is the address of a
38/// 5-nibble pointer.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub struct Layout {
41    /// The HOME directory object.
42    pub home_ptr: u32,
43    /// The nibble after HOME.
44    pub home_end_ptr: u32,
45    /// The current (context) directory object.
46    pub context_ptr: u32,
47    /// The saved data stack pointer (D1): level 1's entry.
48    pub stack_ptr: u32,
49    /// The nibble after the data stack's 0 end marker.
50    pub stack_end_ptr: u32,
51    /// The system flags -1, -2, ... (bit 0 of the first nibble is -1).
52    pub system_flags: u32,
53    /// The user flags 1, 2, ...
54    pub user_flags: u32,
55    /// 64-flag words of each kind: 1 on the 48, 2 on the 49G.
56    pub flag_words: usize,
57    /// Pointer to the menu the soft keys show: its definition (48SX) or an
58    /// XLIB name of the menu library's entry for it (48GX, 49G); wiki:
59    /// hardware/hp48-system-ram, "Menu".
60    pub menu_ptr: u32,
61}
62
63impl Layout {
64    /// 48SX (ROM J; the same addresses in the 1991 entry list of ROM E).
65    pub const HP48SX: Layout = Layout {
66        home_ptr: 0x70592,
67        home_end_ptr: 0x70597,
68        context_ptr: 0x7059C,
69        stack_ptr: 0x70579,
70        stack_end_ptr: 0x7057E,
71        system_flags: 0x706C5,
72        user_flags: 0x706D5,
73        flag_words: 1,
74        menu_ptr: 0x7061E,
75    };
76    /// 48GX (ROM R).
77    pub const HP48GX: Layout = Layout {
78        home_ptr: 0x80711,
79        home_end_ptr: 0x80716,
80        context_ptr: 0x8071B,
81        stack_ptr: 0x806F8,
82        stack_end_ptr: 0x806FD,
83        system_flags: 0x80843,
84        user_flags: 0x80853,
85        flag_words: 1,
86        menu_ptr: 0x8079D,
87    };
88    /// 49G (ROM 2.10).
89    pub const HP49G: Layout = Layout {
90        home_ptr: 0x80711,
91        home_end_ptr: 0x80716,
92        context_ptr: 0x8071B,
93        stack_ptr: 0x806F8,
94        stack_end_ptr: 0x806FD,
95        system_flags: 0x80F02,
96        user_flags: 0x80F22,
97        flag_words: 2,
98        menu_ptr: 0x807ED,
99    };
100
101    /// The layout of `model`, or `None` for the aplet models and the 42S.
102    pub fn of(model: Model) -> Option<Layout> {
103        match model {
104            Model::Hp48sx => Some(Self::HP48SX),
105            Model::Hp48gx => Some(Self::HP48GX),
106            Model::Hp49g => Some(Self::HP49G),
107            Model::Hp38g | Model::Hp39g | Model::Hp40g | Model::Hp42s => None,
108        }
109    }
110}
111
112/// A variable of a directory as the calculator lists it (`VARS` order,
113/// `BYTES` size and checksum).
114#[derive(Clone, Debug, PartialEq, Serialize)]
115pub struct Variable {
116    /// Name (HP characters as Unicode).
117    pub name: String,
118    /// The type name as `G D` prints it, e.g. `Real Number`, `Directory`.
119    #[serde(rename = "type")]
120    pub kind: String,
121    /// Size in bytes as `BYTES` reports it: the whole variable record
122    /// (name and object), so it can end in .5.
123    pub size: f64,
124    /// `BYTES`'s checksum: the CRC of the object's nibbles.
125    pub checksum: u16,
126    /// Address of the object in memory.
127    pub address: u32,
128    /// A directory's variables, newest first.
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub variables: Option<Vec<Variable>>,
131}
132
133/// The flags as 64-flag words, flag 1 (or -1) in bit 0 of the first.
134#[derive(Clone, Debug, PartialEq, Eq)]
135pub struct Flags {
136    /// System flags: -1..-64, then -65..-128 on the 49G.
137    pub system: Vec<u64>,
138    /// User flags: 1..64, then 65..128 on the 49G.
139    pub user: Vec<u64>,
140}
141
142impl Flags {
143    /// Whether flag `n` is set: negative for system flags, positive for
144    /// user flags; `None` for 0 or past the model's flags.
145    pub fn get(&self, n: i32) -> Option<bool> {
146        let (words, i) = match n {
147            0 => return None,
148            n if n < 0 => (&self.system, n.unsigned_abs() - 1),
149            n => (&self.user, n.unsigned_abs() - 1),
150        };
151        let word = words.get(usize::try_from(i / 64).ok()?)?;
152        Some(word >> (i % 64) & 1 == 1)
153    }
154
155    /// The binary integer display base (flags -11 and -12).
156    pub fn base(&self) -> Base {
157        match (self.get(-11), self.get(-12)) {
158            (Some(true), Some(true)) => Base::Hex,
159            (Some(true), _) => Base::Oct,
160            (_, Some(true)) => Base::Bin,
161            _ => Base::Dec,
162        }
163    }
164
165    /// The flags that are set, system flags first (-1, -2, ...), then user
166    /// flags (1, 2, ...).
167    pub fn set(&self) -> Vec<i32> {
168        let mut out = Vec::new();
169        for (words, sign) in [(&self.system, -1i32), (&self.user, 1)] {
170            for (w, word) in words.iter().enumerate() {
171                for bit in 0..64 {
172                    if word >> bit & 1 == 1 {
173                        let n = i32::try_from(w * 64 + bit + 1).unwrap_or(i32::MAX);
174                        out.push(sign * n);
175                    }
176                }
177            }
178        }
179        out
180    }
181}
182
183impl Serialize for Flags {
184    /// `{"system": ["0000000204010FF0"], "user": [...], "set": [-5, ...]}`:
185    /// words as 16 hex digits (a JSON number would lose bits), and the set
186    /// flags.
187    fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
188        use serde::ser::SerializeStruct;
189        let hex = |w: &Vec<u64>| w.iter().map(|v| format!("{v:016X}")).collect::<Vec<_>>();
190        let mut st = s.serialize_struct("Flags", 3)?;
191        st.serialize_field("system", &hex(&self.system))?;
192        st.serialize_field("user", &hex(&self.user))?;
193        st.serialize_field("set", &self.set())?;
194        st.end()
195    }
196}
197
198/// The calculator's CRC over `nibbles` (wiki: hardware/crc; `BYTES` zeroes
199/// the CRC register and reads the object).
200pub fn crc(nibbles: &[u8]) -> u16 {
201    let mut c: u32 = 0;
202    for &n in nibbles {
203        c = (c >> 4) ^ (((c ^ u32::from(n)) & 0xF) * 0x1081);
204    }
205    (c & 0xFFFF) as u16
206}
207
208/// User memory of a paused machine, read through `layout`.
209#[derive(Clone, Copy)]
210pub struct UserMemory<'a> {
211    mem: &'a dyn Memory,
212    layout: Layout,
213    /// The ROM's command names: with them, commands are named and
214    /// programs, algebraics and units get their text.
215    names: Option<&'a NameTable>,
216}
217
218impl std::fmt::Debug for UserMemory<'_> {
219    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220        f.debug_struct("UserMemory")
221            .field("layout", &self.layout)
222            .field("names", &self.names.is_some())
223            .finish_non_exhaustive()
224    }
225}
226
227/// HOME read in one piece.
228struct Home {
229    /// Address of the HOME object.
230    addr: u32,
231    /// Its nibbles.
232    nibbles: Vec<u8>,
233    /// Nibble of its last-variable offset field.
234    offset_at: usize,
235}
236
237impl<'a> UserMemory<'a> {
238    /// `mem` with the system pointers at `layout`.
239    pub fn new(mem: &'a dyn Memory, layout: Layout) -> Self {
240        Self {
241            mem,
242            layout,
243            names: None,
244        }
245    }
246
247    /// The same view, naming commands from `names` (the table of the ROM
248    /// this memory runs) and writing programs, algebraics and units as
249    /// text in the display mode of the flags.
250    pub fn with_names(self, names: &'a NameTable) -> Self {
251        Self {
252            names: Some(names),
253            ..self
254        }
255    }
256
257    /// The user memory of `machine` (48SX, 48GX, 49G).
258    pub fn of(machine: &'a Machine) -> Result<Self> {
259        let model = machine.model();
260        let layout = Layout::of(model).with_context(|| {
261            let why = if model == Model::Hp42s {
262                "has no RPL user memory (no HOME directory, no RPL stack)"
263            } else {
264                "keeps aplets, not a HOME directory"
265            };
266            format!("the {} {why}: no memory view", model.name().to_uppercase())
267        })?;
268        Ok(Self::new(machine, layout))
269    }
270
271    /// The layout in use.
272    pub fn layout(&self) -> Layout {
273        self.layout
274    }
275
276    fn nibble(&self, addr: u32) -> Result<u8> {
277        self.mem
278            .nibble(addr)
279            .with_context(|| format!("#{addr:05X} is not readable"))
280    }
281
282    /// The 5-nibble field at `addr`.
283    fn pointer(&self, addr: u32) -> Result<u32> {
284        let mut v = 0;
285        for i in (0..5).rev() {
286            v = (v << 4) | u32::from(self.nibble(addr + i)?);
287        }
288        Ok(v)
289    }
290
291    /// The nibbles from `from` up to `to`.
292    fn region(&self, from: u32, to: u32) -> Result<Vec<u8>> {
293        ensure!(
294            from <= to && to - from <= MAX_REGION,
295            "region #{from:05X}-#{to:05X} is not plausible"
296        );
297        (from..to).map(|a| self.nibble(a)).collect()
298    }
299
300    fn home(&self) -> Result<Home> {
301        let addr = self.pointer(self.layout.home_ptr)?;
302        let end = self.pointer(self.layout.home_end_ptr)?;
303        let nibbles = self.region(addr, end).context("reading HOME")?;
304        let prolog = crate::prolog::read_field(&nibbles, 0, 5);
305        ensure!(
306            prolog == Some(ObjectType::Directory.prolog()),
307            "no directory at HOME (#{addr:05X}): the ROM has not set up memory yet"
308        );
309        // HOME attaches a list of libraries where an ordinary directory has
310        // one library id: a 3-nibble count, then 13 nibbles per library.
311        let count = crate::prolog::read_field(&nibbles, 5, 3).context("HOME truncated")?;
312        let offset_at = 8 + 13 * usize::try_from(count)?;
313        Ok(Home {
314            addr,
315            nibbles,
316            offset_at,
317        })
318    }
319
320    /// The variables of the directory body in `n` whose offset field is at
321    /// `offset_at`, newest first, sub-directories expanded; `base` is the
322    /// address of `n[0]`.
323    fn variables(
324        &self,
325        n: &[u8],
326        base: u32,
327        offset_at: usize,
328        depth: usize,
329    ) -> Result<Vec<Variable>> {
330        let rs = records(n, offset_at, depth)?;
331        let mut out = Vec::with_capacity(rs.len());
332        for r in rs.iter().rev() {
333            // The empty name is HOME's hidden directory (user keys, alarms).
334            if r.name_len == 0 {
335                continue;
336            }
337            out.push(self.variable(n, base, r, depth)?);
338        }
339        Ok(out)
340    }
341
342    fn variable(&self, n: &[u8], base: u32, r: &Record, depth: usize) -> Result<Variable> {
343        let name_bytes: Vec<u8> = (0..r.name_len)
344            .map(|i| {
345                crate::prolog::read_field(n, r.name_at + 2 + 2 * i, 2)
346                    .map(|b| (b & 0xFF) as u8)
347                    .context("name truncated")
348            })
349            .collect::<Result<_>>()?;
350        let object = &n[r.object..r.end()];
351        let address = base + u32::try_from(r.object)?;
352        let prolog = crate::prolog::read_field(object, 0, 5).context("object truncated")?;
353        let ty = ObjectType::from_prolog(prolog);
354        let (kind, variables) = match ty {
355            Some(ObjectType::Directory) => (
356                ty.map(ObjectType::name),
357                Some(self.variables(n, base, r.object + 8, depth + 1)?),
358            ),
359            Some(t) => (Some(t.name()), None),
360            // A 5-nibble pointer to a ROM object (inferred: the ROM's STO
361            // copies objects, so this is rare); the target's type.
362            None => (
363                self.pointer(prolog)
364                    .ok()
365                    .and_then(ObjectType::from_prolog)
366                    .map(ObjectType::name),
367                None,
368            ),
369        };
370        Ok(Variable {
371            name: crate::charset::decode(&name_bytes),
372            kind: kind.unwrap_or("ROM Pointer").to_string(),
373            size: (r.end() - r.start) as f64 / 2.0,
374            checksum: crc(object),
375            address,
376            variables,
377        })
378    }
379
380    /// HOME's variables, newest first (as `VARS`), with every
381    /// sub-directory's variables. Needs no decode budget: the walk sizes
382    /// objects without following ROM pointers, so its work is linear in
383    /// HOME's nibbles (at most the address space).
384    pub fn tree(&self) -> Result<Vec<Variable>> {
385        let home = self.home()?;
386        let vars = self.variables(&home.nibbles, home.addr, home.offset_at, 0)?;
387        // The records must fill HOME exactly, else the layout is wrong.
388        let end = records(&home.nibbles, home.offset_at, 0)?
389            .last()
390            .map_or(home.offset_at + 5, Record::end);
391        ensure!(
392            end == home.nibbles.len(),
393            "HOME's variables end at #{:05X}, HOME at #{:05X}",
394            home.addr + u32::try_from(end)?,
395            home.addr + u32::try_from(home.nibbles.len())?
396        );
397        Ok(vars)
398    }
399
400    /// The current directory as a path from HOME, e.g. `["HOME", "A"]`.
401    pub fn current_path(&self) -> Result<Vec<String>> {
402        let context = self.pointer(self.layout.context_ptr)?;
403        let home = self.pointer(self.layout.home_ptr)?;
404        let mut path = vec!["HOME".to_string()];
405        if context == home {
406            return Ok(path);
407        }
408        if find(&self.tree()?, context, &mut path) {
409            Ok(path)
410        } else {
411            bail!("the current directory (#{context:05X}) is not under HOME")
412        }
413    }
414
415    /// The addresses of the objects on the data stack, level 1 first.
416    pub fn stack_addresses(&self) -> Result<Vec<u32>> {
417        let top = self.pointer(self.layout.stack_ptr)?;
418        let end = self.pointer(self.layout.stack_end_ptr)?;
419        let span = end
420            .checked_sub(top)
421            .filter(|s| s % 5 == 0 && *s >= 5)
422            .with_context(|| format!("stack pointers #{top:05X}-#{end:05X} are not plausible"))?;
423        let depth = usize::try_from(span / 5 - 1)?;
424        ensure!(depth <= MAX_LEVELS, "stack deeper than {MAX_LEVELS} levels");
425        ensure!(
426            self.pointer(end - 5)? == 0,
427            "no end marker at #{:05X}: the ROM is not idle",
428            end - 5
429        );
430        (0..depth)
431            .map(|i| {
432                let at = top + 5 * u32::try_from(i)?;
433                let p = self.pointer(at)?;
434                ensure!(p != 0, "stack level {} is 0 at #{at:05X}", i + 1);
435                Ok(p)
436            })
437            .collect()
438    }
439
440    /// The data stack as typed objects, level 1 first; binary integers
441    /// carry the display base of flags -11 and -12.
442    pub fn stack(&self) -> Result<Vec<Object>> {
443        let flags = self.flags()?;
444        let base = flags.base();
445        let settings = self.settings(&flags);
446        // One budget for the whole stack: the result is one document a
447        // host must hold, however many levels share an object.
448        let reader = self.reader(&settings);
449        self.stack_addresses()?
450            .into_iter()
451            .enumerate()
452            .map(|(i, addr)| {
453                let mut obj = reader
454                    .decode_at(addr)
455                    .with_context(|| format!("stack level {}", i + 1))?;
456                obj.set_base(base);
457                Ok(obj)
458            })
459            .collect()
460    }
461
462    /// The display settings `flags` select on this layout's model (the
463    /// 48SX and 48GX show objects alike).
464    fn settings(&self, flags: &Flags) -> Settings {
465        let model = if self.layout == Layout::HP49G {
466            Model::Hp49g
467        } else {
468            Model::Hp48gx
469        };
470        Settings::from_flags(flags, model)
471    }
472
473    fn reader(&self, settings: &Settings) -> Reader<'a> {
474        match self.names {
475            Some(names) => Reader::with_names(self.mem, names, *settings),
476            None => Reader::new(self.mem),
477        }
478    }
479
480    /// The object at `addr` (a variable's address from [`UserMemory::tree`]),
481    /// binary integers in the display base, text in the display mode.
482    pub fn object_at(&self, addr: u32) -> Result<Object> {
483        let flags = self.flags()?;
484        let mut obj = self.reader(&self.settings(&flags)).decode_at(addr)?;
485        obj.set_base(flags.base());
486        Ok(obj)
487    }
488
489    /// [`UserMemory::stack`] as JSON with the calculator's text on every
490    /// object ([`crate::decompile::described`]), in the display mode the
491    /// flags select; the texts of all levels together are capped at
492    /// [`crate::decompile::MAX_DESCRIBED_TEXT`].
493    pub fn stack_described(&self) -> Result<Vec<serde_json::Value>> {
494        let settings = self.settings(&self.flags()?);
495        let mut left = crate::decompile::MAX_DESCRIBED_TEXT;
496        self.stack()?
497            .iter()
498            .map(|o| crate::decompile::described_within(o, &settings, &mut left))
499            .collect()
500    }
501
502    /// The stack's depth and level 1 as JSON with its text
503    /// ([`crate::decompile::described`]), or `None` on an empty stack:
504    /// what an Edit button needs, without decoding the other levels.
505    pub fn stack_top(&self) -> Result<(usize, Option<serde_json::Value>)> {
506        let addresses = self.stack_addresses()?;
507        let top = match addresses.first() {
508            Some(&addr) => Some(self.object_described(addr).context("stack level 1")?),
509            None => None,
510        };
511        Ok((addresses.len(), top))
512    }
513
514    /// [`UserMemory::object_at`] as JSON with the calculator's text on
515    /// every object ([`crate::decompile::described`]).
516    pub fn object_described(&self, addr: u32) -> Result<serde_json::Value> {
517        let settings = self.settings(&self.flags()?);
518        crate::decompile::described(&self.object_at(addr)?, &settings)
519    }
520
521    /// The text to edit of the object at `addr` (a variable's address or a
522    /// stack level's, [`UserMemory::stack_addresses`]): decoded and written
523    /// in the display mode made fit for compiling again
524    /// ([`crate::decompile::edit_text`]).
525    pub fn edit_text_at(&self, addr: u32) -> Result<String> {
526        let flags = self.flags()?;
527        let settings = self.settings(&flags).for_editing();
528        let mut obj = self.reader(&settings).decode_at(addr)?;
529        obj.set_base(flags.base());
530        crate::decompile::edit_text(&obj, &settings)
531    }
532
533    /// What identifies the object at `addr` whatever the display mode:
534    /// its size in nibbles and `BYTES`'s checksum of them (`storeText`'s
535    /// check that the object a save replaces is the one that was opened).
536    pub fn identity_at(&self, addr: u32) -> Result<(usize, u16)> {
537        let n: Vec<u8> = (addr..MAX_REGION)
538            .map(|a| self.nibble(a))
539            .collect::<Result<_>>()?;
540        let size = crate::prolog::object_size(&n, 0)?;
541        Ok((size, crc(&n[..size])))
542    }
543
544    fn words(&self, at: u32) -> Result<Vec<u64>> {
545        (0..self.layout.flag_words)
546            .map(|w| {
547                let start = at + 16 * u32::try_from(w)?;
548                let mut v = 0u64;
549                for i in (0..16).rev() {
550                    v = (v << 4) | u64::from(self.nibble(start + i)?);
551                }
552                Ok(v)
553            })
554            .collect()
555    }
556
557    /// Where the current menu's pointer points (see [`Layout::menu_ptr`];
558    /// `crate::menus::Menus::number` turns it into a menu number).
559    pub fn menu_pointer(&self) -> Result<u32> {
560        self.pointer(self.layout.menu_ptr)
561    }
562
563    /// The system and user flags.
564    pub fn flags(&self) -> Result<Flags> {
565        Ok(Flags {
566            system: self.words(self.layout.system_flags)?,
567            user: self.words(self.layout.user_flags)?,
568        })
569    }
570
571    /// A number that changes whenever HOME (any variable anywhere in the
572    /// tree), the current directory, the stack or the flags change: an
573    /// FNV-1a hash of HOME's nibbles, the system pointers, the stack's
574    /// entries and the flag words. A host polls it and re-reads only when
575    /// it moves. Reads HOME once (up to the whole RAM). It hashes the stack's
576    /// pointers, not the objects they point to: an object rewritten in place
577    /// at the same address would not move it.
578    pub fn change_counter(&self) -> Result<u64> {
579        let mut h = Fnv::default();
580        let l = self.layout;
581        for p in [
582            l.home_ptr,
583            l.home_end_ptr,
584            l.context_ptr,
585            l.stack_ptr,
586            l.stack_end_ptr,
587        ] {
588            h.word(u64::from(self.pointer(p)?));
589        }
590        let home = self.pointer(l.home_ptr)?;
591        let end = self.pointer(l.home_end_ptr)?;
592        for n in self.region(home, end)? {
593            h.byte(n);
594        }
595        // Stack entries; garbage pointers are hashed as they are.
596        let top = self.pointer(l.stack_ptr)?;
597        let stack_end = self
598            .pointer(l.stack_end_ptr)?
599            .min(top + 5 * MAX_LEVELS as u32);
600        for a in (top..stack_end).step_by(5) {
601            h.word(u64::from(self.pointer(a)?));
602        }
603        let flags = self.flags()?;
604        for w in flags.system.iter().chain(&flags.user) {
605            h.word(*w);
606        }
607        Ok(h.0)
608    }
609}
610
611/// Extend `path` to the directory at `addr` under `vars`.
612fn find(vars: &[Variable], addr: u32, path: &mut Vec<String>) -> bool {
613    for v in vars {
614        let Some(children) = &v.variables else {
615            continue;
616        };
617        path.push(v.name.clone());
618        if v.address == addr || find(children, addr, path) {
619            return true;
620        }
621        path.pop();
622    }
623    false
624}
625
626/// 64-bit FNV-1a.
627struct Fnv(u64);
628
629impl Default for Fnv {
630    fn default() -> Self {
631        Fnv(0xCBF2_9CE4_8422_2325)
632    }
633}
634
635impl Fnv {
636    fn byte(&mut self, b: u8) {
637        self.0 = (self.0 ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01B3);
638    }
639
640    fn word(&mut self, w: u64) {
641        for b in w.to_le_bytes() {
642            self.byte(b);
643        }
644    }
645}
646
647/// HOME's variables of `machine`, newest first, with sub-directories.
648pub fn memory_tree(machine: &Machine) -> Result<Vec<Variable>> {
649    UserMemory::of(machine)?.tree()
650}
651
652/// The current directory of `machine`, e.g. `["HOME", "A"]`.
653pub fn current_path(machine: &Machine) -> Result<Vec<String>> {
654    UserMemory::of(machine)?.current_path()
655}
656
657/// The data stack of `machine`, level 1 first.
658pub fn stack_objects(machine: &Machine) -> Result<Vec<Object>> {
659    UserMemory::of(machine)?.stack()
660}
661
662/// The flags of `machine`.
663pub fn flags(machine: &Machine) -> Result<Flags> {
664    UserMemory::of(machine)?.flags()
665}
666
667/// See [`UserMemory::change_counter`].
668pub fn change_counter(machine: &Machine) -> Result<u64> {
669    UserMemory::of(machine)?.change_counter()
670}
671
672#[cfg(test)]
673mod tests {
674    use super::*;
675
676    /// The aplet models and the 42S have no layout, each with its own
677    /// reason.
678    #[test]
679    fn models_without_a_memory_view() {
680        for model in [Model::Hp38g, Model::Hp39g, Model::Hp40g, Model::Hp42s] {
681            assert!(Layout::of(model).is_none(), "{}", model.name());
682        }
683        let m = Machine::new(Model::Hp42s, &vec![0u8; Model::Hp42s.rom_bytes()]).unwrap();
684        let e = UserMemory::of(&m).err().unwrap().to_string();
685        assert!(e.contains("the 42S has no RPL user memory"), "{e}");
686        let m = Machine::new(Model::Hp38g, &vec![0u8; Model::Hp38g.rom_bytes()]).unwrap();
687        let e = UserMemory::of(&m).err().unwrap().to_string();
688        assert!(e.contains("keeps aplets"), "{e}");
689    }
690    use crate::object::{MAX_DECODED_OBJECTS, Real, decode_at};
691
692    /// RAM #70000-#7FFFF of a 48SX.
693    struct Ram(Vec<u8>);
694
695    impl Memory for Ram {
696        fn nibble(&self, addr: u32) -> Option<u8> {
697            let i = usize::try_from(addr.checked_sub(0x70000)?).ok()?;
698            self.0.get(i).copied()
699        }
700    }
701
702    impl Ram {
703        fn put(&mut self, addr: u32, hex: &str) {
704            let at = (addr - 0x70000) as usize;
705            for (i, c) in hex.chars().enumerate() {
706                self.0[at + i] = c.to_digit(16).unwrap() as u8;
707            }
708        }
709
710        fn put_ptr(&mut self, addr: u32, value: u32) {
711            let hex: String = (0..5)
712                .map(|i| format!("{:X}", value >> (4 * i) & 0xF))
713                .collect();
714            self.put(addr, &hex);
715        }
716    }
717
718    /// HOME of a 48SX (ROM J in saturnus, 2026-10-05) after `42 'X' STO
719    /// "HI" 'YY' STO 'DIRA' CRDIR DIRA 5 'Z' STO`, with IOPAR from the
720    /// Kermit server and the hidden directory; current directory DIRA.
721    fn sx() -> Ram {
722        let mut r = Ram(vec![0; 0x10000]);
723        r.put(
724            0x7FE9B,
725            concat!(
726                "69A20200200746228D356007EFD2200000501000",
727                "00000069A20FF7C500000000C055375627B45697",
728                "37E2342534C0E4A20900006E57A2000805537562",
729                "7B45697378047A20B2130E10006014C61627D637",
730                "6047A20B2130080005094F40514255047A201932",
731                "24B2A24B2A24B2A23F2A29C2A2B2130630001085",
732                "10339201000000000000240B100020959520C2A2",
733                "09000084946100040449425144069A20FF7A0000",
734                "0000010A51033920000000000000005",
735            ),
736        );
737        let l = Layout::HP48SX;
738        r.put_ptr(l.home_ptr, 0x7FE9B);
739        r.put_ptr(l.home_end_ptr, 0x7FFFB);
740        r.put_ptr(l.context_ptr, 0x7FFCE);
741        // Stack: "AB" (in RAM) on a ROM-free real 7 and a binary integer.
742        r.put(0x71000, "C2A2090000142433920000000000000007");
743        r.put(0x71030, "E4A2051000A200000000000000");
744        r.put_ptr(0x7F000, 0x71000);
745        r.put_ptr(0x7F005, 0x7100E);
746        r.put_ptr(0x7F00A, 0x71030);
747        r.put_ptr(l.stack_ptr, 0x7F000);
748        r.put_ptr(l.stack_end_ptr, 0x7F014);
749        // Flags -11 and -12 (HEX), -40; user flag 7.
750        r.put(l.system_flags, "0FF0000008000000");
751        r.put(l.user_flags, "0400000000000000");
752        r
753    }
754
755    #[test]
756    fn tree_sizes_and_checksums_match_the_calculator() {
757        let ram = sx();
758        let m = UserMemory::new(&ram, Layout::HP48SX);
759        let tree = m.tree().unwrap();
760        // Name, type, size, checksum as the calculator's `G D` listed them.
761        let flat: Vec<(&str, &str, f64, u16)> = tree
762            .iter()
763            .map(|v| (v.name.as_str(), v.kind.as_str(), v.size, v.checksum))
764            .collect();
765        assert_eq!(
766            flat,
767            [
768                ("DIRA", "Directory", 31.0, 44093),
769                ("YY", "String", 13.5, 5889),
770                ("X", "Real Number", 16.0, 59472),
771                ("IOPAR", "List", 29.5, 8861),
772            ]
773        );
774        let dira = tree[0].variables.as_ref().unwrap();
775        assert_eq!(dira.len(), 1);
776        assert_eq!(
777            (dira[0].name.as_str(), dira[0].size, dira[0].checksum),
778            ("Z", 16.0, 23381)
779        );
780        assert_eq!(dira[0].address, 0x7FFE6);
781        assert_eq!(m.current_path().unwrap(), ["HOME", "DIRA"]);
782        assert_eq!(
783            decode_at(tree[2].address, &ram).unwrap(),
784            Object::Real {
785                value: Real::parse("42").unwrap()
786            }
787        );
788    }
789
790    #[test]
791    fn stack_and_flags() {
792        let ram = sx();
793        let m = UserMemory::new(&ram, Layout::HP48SX);
794        let flags = m.flags().unwrap();
795        assert_eq!(flags.get(-40), Some(true));
796        assert_eq!(flags.get(7), Some(true));
797        assert_eq!(flags.get(8), Some(false));
798        assert_eq!(flags.get(65), None);
799        assert_eq!(flags.base(), Base::Hex);
800        assert_eq!(flags.set(), [-5, -6, -7, -8, -9, -10, -11, -12, -40, 7]);
801        let json = serde_json::to_value(&flags).unwrap();
802        assert_eq!(json["system"][0], "0000008000000FF0");
803        assert_eq!(json["user"][0], "0000000000000040");
804        let stack = m.stack().unwrap();
805        assert_eq!(stack.len(), 3);
806        assert_eq!(stack[0], Object::String { value: "AB".into() });
807        assert_eq!(
808            stack[1],
809            Object::Real {
810                value: Real::parse("7").unwrap()
811            }
812        );
813        assert_eq!(
814            serde_json::to_value(&stack[2]).unwrap(),
815            serde_json::json!({"type": "binary", "value": 42, "base": "hex", "text": "# 2Ah"})
816        );
817    }
818
819    #[test]
820    fn change_counter_moves_with_the_tree_and_the_stack() {
821        let mut ram = sx();
822        let c0 = UserMemory::new(&ram, Layout::HP48SX)
823            .change_counter()
824            .unwrap();
825        assert_eq!(
826            UserMemory::new(&ram, Layout::HP48SX)
827                .change_counter()
828                .unwrap(),
829            c0
830        );
831        // X = 42 becomes 43.
832        ram.put(0x7FF39 + 16, "3");
833        let c1 = UserMemory::new(&ram, Layout::HP48SX)
834            .change_counter()
835            .unwrap();
836        assert_ne!(c1, c0);
837        ram.put_ptr(Layout::HP48SX.stack_ptr, 0x7F005);
838        assert_ne!(
839            UserMemory::new(&ram, Layout::HP48SX)
840                .change_counter()
841                .unwrap(),
842            c1
843        );
844    }
845
846    /// Lists L0..L39 at #71000, each holding two pointers to the next (the
847    /// last empty): 2^39 objects if every pointer were decoded anew.
848    fn shared_pointers(levels: u32) -> Ram {
849        let mut r = sx();
850        let base = 0x71000;
851        for i in 0..levels {
852            let a = base + 20 * i;
853            r.put(a, "47A20");
854            if i + 1 < levels {
855                r.put_ptr(a + 5, a + 20);
856                r.put_ptr(a + 10, a + 20);
857                r.put(a + 15, "B2130");
858            } else {
859                r.put(a + 5, "B2130");
860            }
861        }
862        r.put_ptr(0x7F000, base);
863        r.put_ptr(0x7F005, 0);
864        r.put_ptr(Layout::HP48SX.stack_ptr, 0x7F000);
865        r.put_ptr(Layout::HP48SX.stack_end_ptr, 0x7F00A);
866        r
867    }
868
869    #[test]
870    fn shared_pointers_hit_the_decode_budget() {
871        let ram = shared_pointers(40);
872        let m = UserMemory::new(&ram, Layout::HP48SX);
873        let calls: [&dyn Fn() -> Result<()>; 2] = [&|| decode_at(0x71000, &ram).map(drop), &|| {
874            m.stack().map(drop)
875        }];
876        for call in calls {
877            // The budget error is the bound on the work: no wall-clock
878            // assertion here, a loaded CI runner would make it flaky.
879            let e = call().unwrap_err();
880            assert!(format!("{e:#}").contains("(MAX_DECODED_"), "{e:#}");
881        }
882        // 2^12 - 1 lists: shared, but within the budget, and exact.
883        let ram = shared_pointers(12);
884        let obj = decode_at(0x71000, &ram).unwrap();
885        fn count(o: &Object) -> usize {
886            match o {
887                Object::List { items } => 1 + items.iter().map(count).sum::<usize>(),
888                _ => 1,
889            }
890        }
891        assert_eq!(count(&obj), (1 << 12) - 1);
892        assert!(count(&obj) < MAX_DECODED_OBJECTS);
893    }
894
895    /// A stack of `levels` pointers to the object `hex` at #71000.
896    fn repeated(levels: u32, hex: &str) -> Ram {
897        let mut r = sx();
898        r.put(0x71000, hex);
899        for i in 0..levels {
900            r.put_ptr(0x7F000 + 5 * i, 0x71000);
901        }
902        r.put_ptr(0x7F000 + 5 * levels, 0);
903        r.put_ptr(Layout::HP48SX.stack_ptr, 0x7F000);
904        r.put_ptr(Layout::HP48SX.stack_end_ptr, 0x7F005 + 5 * levels);
905        r
906    }
907
908    /// A string of `chars` A's.
909    fn string(chars: usize) -> String {
910        let mut len = String::new();
911        for i in 0..5 {
912            len.push_str(&format!("{:X}", (5 + 2 * chars) >> (4 * i) & 0xF));
913        }
914        format!("C2A20{len}{}", "14".repeat(chars))
915    }
916
917    #[test]
918    fn repeated_large_objects_hit_the_nibble_budget() {
919        // 500 levels of one 40 K-nibble string (DUP copies the pointer):
920        // 20 M nibbles of copies, more than MAX_CLONED_NIBBLES.
921        let ram = repeated(500, &string(20_000));
922        let m = UserMemory::new(&ram, Layout::HP48SX);
923        for e in [m.stack().unwrap_err(), m.stack_described().unwrap_err()] {
924            assert!(format!("{e:#}").contains("MAX_CLONED_NIBBLES"), "{e:#}");
925        }
926        // A stack a calculator really builds by DUP: 100 levels, 4 M
927        // nibbles of copies, twice MAX_DECODED_NIBBLES, still decodes.
928        let ram = repeated(100, &string(20_000));
929        let stack = UserMemory::new(&ram, Layout::HP48SX).stack().unwrap();
930        assert_eq!(stack.len(), 100);
931        assert_eq!(
932            stack[99],
933            Object::String {
934                value: "A".repeat(20_000)
935            }
936        );
937    }
938
939    #[test]
940    fn nested_texts_hit_the_described_budget() {
941        // A string of 2000 characters in lists nested 60 deep: each list
942        // carries the string's text again, 120 K characters a level.
943        let hex = format!(
944            "{}{}{}",
945            "47A20".repeat(60),
946            string(2000),
947            "B2130".repeat(60)
948        );
949        let ram = repeated(100, &hex);
950        let m = UserMemory::new(&ram, Layout::HP48SX);
951        assert_eq!(m.stack().unwrap().len(), 100);
952        let e = m.stack_described().unwrap_err();
953        assert!(format!("{e:#}").contains("MAX_DESCRIBED_TEXT"), "{e:#}");
954        // One level fits.
955        let ram = repeated(1, &hex);
956        let level = &UserMemory::new(&ram, Layout::HP48SX)
957            .stack_described()
958            .unwrap()[0];
959        assert_eq!(
960            level["items"][0]["text"].as_str().map(str::len),
961            Some(2000 + 59 * 4 + 2)
962        );
963    }
964
965    #[test]
966    fn broken_pointers_are_errors() {
967        let mut ram = sx();
968        ram.put_ptr(Layout::HP48SX.home_end_ptr, 0x7FFF0);
969        assert!(UserMemory::new(&ram, Layout::HP48SX).tree().is_err());
970        let mut ram = sx();
971        ram.put_ptr(Layout::HP48SX.stack_end_ptr, 0x7F013);
972        assert!(UserMemory::new(&ram, Layout::HP48SX).stack().is_err());
973        ram.put_ptr(Layout::HP48SX.stack_end_ptr, 0x7F00F);
974        assert!(UserMemory::new(&ram, Layout::HP48SX).stack().is_err());
975    }
976}