Skip to main content

saturnus_objects/
names.rs

1//! Command names, read at run time from the ROM's own library tables.
2//!
3//! The ROM's decompiler names a command from the 6-nibble XLIB body
4//! (library, command) that precedes every built-in command object, and
5//! from the library's hash table; the link table maps command numbers to
6//! objects (RPLMAN p. 13; layouts observed in the 48SX, 48GX and 49G ROMs:
7//! wiki: protocols/rpl-libraries). Nothing ROM-derived is compiled in: a
8//! [`NameTable`] is built from the ROM image the user loaded, once per ROM.
9//!
10//! What the table holds:
11//!
12//! - every library whose header, hash table and link table check out
13//!   (found by scanning the image, so the 49G's flash banks need no map),
14//!   with its command names and, where the command starts with one of the
15//!   argument-checking dispatchers, its argument count;
16//! - the five unit operator markers (`*`, `/`, `^`, prefix, end).
17//!
18//! Build cost: one pass over the image (512 K nibbles on the 48SX, 4 M on
19//! the 49G) and a few thousand table reads; see the ROM-gated test.
20
21use std::collections::HashMap;
22
23use saturnus::Model;
24
25use crate::charset;
26use crate::object::Memory;
27use crate::prolog::{ObjectType, SEMI, read_field};
28
29/// Nibbles in a 49G flash bank: one window (#00000-#3FFFF or
30/// #40000-#7FFFF) shows one bank (wiki: hardware/hp49g).
31const BANK_NIBBLES: usize = 0x40000;
32/// Library header: number (3), then offsets to the hash, message and link
33/// tables and the configuration object (5 each).
34const HEADER_NIBBLES: usize = 23;
35/// An empty list, the unit operator markers: prolog #02A74 and SEMI.
36const EMPTY_LIST: [u8; 10] = [4, 7, 0xA, 2, 0, 0xB, 2, 1, 3, 0];
37/// Distance between the unit operator markers.
38const MARKER_STRIDE: u32 = 10;
39/// Most elements of a ROM unit object read when looking for the markers.
40const MAX_UNIT_ELEMENTS: usize = 40;
41/// Most common dispatch objects considered when looking for CK1-CK4.
42const DISPATCH_CANDIDATES: usize = 12;
43/// Most commands in one library: command numbers are 3 nibbles (the XLIB
44/// body). The largest real library has 1444 (49G 2.10, library 788).
45const MAX_LIBRARY_COMMANDS: usize = 0x1000;
46/// Most libraries in an image, copies counted: 52 on the 49G 2.10 ROM,
47/// 42 on the 48GX, 2 on the 48SX.
48const MAX_LIBRARIES: usize = 256;
49/// Most commands of all libraries together: 5940 on the 49G 2.10 ROM.
50/// Without it a crafted image whose headers all share one large link
51/// table makes gigabytes of tables.
52const MAX_COMMANDS: usize = 1 << 15;
53
54/// The 5-nibble field at `at`, or `None` past the end.
55fn f5(n: &[u8], at: usize) -> Option<usize> {
56    read_field(n, at, 5).map(|v| v as usize)
57}
58
59/// The target of the self-relative offset field at `at` (offsets wrap at
60/// #100000 like addresses).
61fn rel(n: &[u8], at: usize) -> Option<usize> {
62    let off = f5(n, at)?;
63    let target = if off >= 0x80000 {
64        at.checked_sub(0x100000 - off)?
65    } else {
66        at.checked_add(off)?
67    };
68    (target < n.len()).then_some(target)
69}
70
71/// A hash table: where its number table starts, how many numbers it has,
72/// where it ends.
73#[derive(Clone, Copy, Debug)]
74struct Hash {
75    names_start: usize,
76    numbers: usize,
77    count: usize,
78}
79
80/// The hash table (hex string) at `t`, if its layout is valid.
81fn hash_at(n: &[u8], t: usize) -> Option<Hash> {
82    if f5(n, t)? != ObjectType::BinaryInteger.prolog() as usize {
83        return None;
84    }
85    let len = f5(n, t + 5)?;
86    let end = t.checked_add(5)?.checked_add(len)?;
87    let body = t + 10;
88    // 16 offsets by name length, the number table's offset, one name.
89    if len < 5 + 85 || end > n.len() {
90        return None;
91    }
92    for i in 0..16 {
93        let at = body + 5 * i;
94        if f5(n, at)? != 0 && rel(n, at)? >= end {
95            return None;
96        }
97    }
98    let numbers = rel(n, body + 80)?;
99    if numbers < body + 85 || numbers > end || (end - numbers) % 5 != 0 {
100        return None;
101    }
102    Some(Hash {
103        names_start: body + 85,
104        numbers,
105        count: (end - numbers) / 5,
106    })
107}
108
109/// The name of command `c` in `h`, if it has one.
110fn name_in(n: &[u8], h: &Hash, c: usize) -> Option<String> {
111    let at = h.numbers + 5 * c;
112    let back = f5(n, at)?;
113    if back == 0 {
114        return None;
115    }
116    let entry = at.checked_sub(back)?;
117    if entry < h.names_start {
118        return None;
119    }
120    let len = read_field(n, entry, 2)? as usize;
121    if len == 0 || entry + 2 + 2 * len + 3 > h.numbers {
122        return None;
123    }
124    let bytes: Option<Vec<u8>> = (0..len)
125        .map(|i| read_field(n, entry + 2 + 2 * i, 2).map(|b| b as u8))
126        .collect();
127    Some(charset::decode(&bytes?))
128}
129
130/// One library found in the ROM.
131#[derive(Clone, Debug)]
132struct Library {
133    id: u16,
134    /// Name by command number (shorter than `link` when the last commands
135    /// have none).
136    names: Vec<Option<String>>,
137    /// Image index of each command's object (`None`: outside the image).
138    link: Vec<Option<usize>>,
139    /// Argument count by command number, where the command starts with a
140    /// dispatcher (filled after all libraries are found).
141    arity: Vec<Option<u8>>,
142}
143
144/// A command as the name table knows it.
145#[derive(Clone, Copy, Debug, PartialEq, Eq)]
146pub struct CommandInfo<'a> {
147    /// Library number.
148    pub library: u16,
149    /// Command number in the library.
150    pub number: u16,
151    /// Its name, if the library's hash table has one.
152    pub name: Option<&'a str>,
153    /// Its argument count, if it starts with an argument dispatcher
154    /// (CK0-CK5).
155    pub arity: Option<u8>,
156    /// An unnamed command of the structure library (the one holding `«`),
157    /// such as the word that quotes a program inside a program: the ROM's
158    /// decompiler shows nothing for it.
159    pub silent: bool,
160}
161
162/// The unit operators: ROM pointers to five empty lists (wiki:
163/// protocols/rpl-libraries "Unit operators").
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub struct UnitMarkers {
166    /// `*`.
167    pub times: u32,
168    /// `/`.
169    pub divide: u32,
170    /// `^`.
171    pub power: u32,
172    /// A prefix (the character before the unit name).
173    pub prefix: u32,
174    /// The end of the unit expression.
175    pub end: u32,
176}
177
178/// What a built table holds, for reports and tests.
179#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
180pub struct NameStats {
181    /// Libraries found.
182    pub libraries: usize,
183    /// Command numbers with a name.
184    pub names: usize,
185    /// Commands with a known argument count.
186    pub arities: usize,
187}
188
189/// Command names and the other ROM facts the decompiler needs, built from
190/// one ROM image.
191#[derive(Clone, Default)]
192pub struct NameTable {
193    /// Libraries by number; a number can occur twice (a ROM can carry an
194    /// older copy), each is tried.
195    libraries: Vec<Library>,
196    index: HashMap<u16, Vec<usize>>,
197    /// Nibbles per bank when the image is banked (the 49G).
198    bank: Option<usize>,
199    units: Option<UnitMarkers>,
200    /// The library holding `«` and the other structure words.
201    structure: Option<u16>,
202}
203
204impl std::fmt::Debug for NameTable {
205    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206        f.debug_struct("NameTable")
207            .field("stats", &self.stats())
208            .field("units", &self.units)
209            .finish_non_exhaustive()
210    }
211}
212
213impl NameTable {
214    /// The table of `model`'s ROM image `rom` (one nibble per element, as
215    /// [`saturnus::Machine::rom_nibbles`] gives it). A ROM without
216    /// libraries gives an empty table (every command stays unnamed). Only
217    /// the 48SX, 48GX (mask ROM, image index = address) and 49G (flash
218    /// banks of 256 K nibbles) are handled; for the 38G, 39G, 40G and 42S,
219    /// whose ROM layout this does not know (banked differently, or no RPL
220    /// libraries at all on the 42S), the table is empty.
221    pub fn build(model: Model, rom: &[u8]) -> NameTable {
222        let bank = match model {
223            Model::Hp48sx | Model::Hp48gx => None,
224            Model::Hp49g => Some(BANK_NIBBLES),
225            Model::Hp38g | Model::Hp39g | Model::Hp40g | Model::Hp42s => {
226                return NameTable::default();
227            }
228        };
229        let mut libraries = scan(rom, bank);
230        let dispatch = Dispatch::find(rom, &libraries);
231        for lib in &mut libraries {
232            lib.arity = lib
233                .link
234                .iter()
235                .map(|t| dispatch.as_ref().zip(*t).and_then(|(d, t)| d.arity(rom, t)))
236                .collect();
237        }
238        let mut index: HashMap<u16, Vec<usize>> = HashMap::new();
239        for (i, lib) in libraries.iter().enumerate() {
240            index.entry(lib.id).or_default().push(i);
241        }
242        let structure = libraries
243            .iter()
244            .find(|l| l.names.iter().any(|n| n.as_deref() == Some("«")))
245            .map(|l| l.id);
246        NameTable {
247            libraries,
248            index,
249            bank,
250            units: unit_markers(rom, bank),
251            structure,
252        }
253    }
254
255    /// The table of `machine`'s ROM.
256    pub fn of(machine: &saturnus::Machine) -> NameTable {
257        Self::build(machine.model(), machine.rom_nibbles())
258    }
259
260    /// Counts for reports.
261    pub fn stats(&self) -> NameStats {
262        let mut s = NameStats {
263            libraries: self.libraries.len(),
264            ..NameStats::default()
265        };
266        for lib in &self.libraries {
267            s.names += lib.names.iter().flatten().count();
268            s.arities += lib.arity.iter().flatten().count();
269        }
270        s
271    }
272
273    /// The heap memory the table holds, in bytes (approximate: vector
274    /// and string capacities).
275    pub fn heap_bytes(&self) -> usize {
276        use std::mem::size_of;
277        let libs: usize = self
278            .libraries
279            .iter()
280            .map(|l| {
281                l.names.capacity() * size_of::<Option<String>>()
282                    + l.names
283                        .iter()
284                        .flatten()
285                        .map(String::capacity)
286                        .sum::<usize>()
287                    + l.link.capacity() * size_of::<Option<usize>>()
288                    + l.arity.capacity() * size_of::<Option<u8>>()
289            })
290            .sum();
291        let index: usize = self
292            .index
293            .values()
294            .map(|v| size_of::<(u16, Vec<usize>)>() + v.capacity() * size_of::<usize>())
295            .sum();
296        libs + self.libraries.capacity() * size_of::<Library>() + index
297    }
298
299    /// Every named command: (library, number, name).
300    pub fn names(&self) -> impl Iterator<Item = (u16, u16, &str)> + '_ {
301        self.libraries.iter().flat_map(|lib| {
302            lib.names
303                .iter()
304                .enumerate()
305                .filter_map(move |(c, n)| Some((lib.id, u16::try_from(c).ok()?, n.as_deref()?)))
306        })
307    }
308
309    /// Nibbles per bank when the image is banked (the 49G).
310    pub fn bank(&self) -> Option<usize> {
311        self.bank
312    }
313
314    /// The library and command number of the command called `name` (the
315    /// first library holding it).
316    pub fn find(&self, name: &str) -> Option<(u16, u16)> {
317        self.libraries.iter().find_map(|lib| {
318            let c = lib.names.iter().position(|n| n.as_deref() == Some(name))?;
319            Some((lib.id, u16::try_from(c).ok()?))
320        })
321    }
322
323    /// The commands of library `library` and how many of them have a name
324    /// (the first copy when the image holds it twice).
325    pub fn library_size(&self, library: u16) -> Option<(usize, usize)> {
326        let lib = &self.libraries[*self.index.get(&library)?.first()?];
327        Some((lib.link.len(), lib.names.iter().flatten().count()))
328    }
329
330    /// The image index of command `number` of `library`'s object, when
331    /// every copy of the library agrees on it.
332    pub fn object_index(&self, library: u16, number: u16) -> Option<usize> {
333        let c = usize::from(number);
334        let mut found = None;
335        for &i in self.index.get(&library)? {
336            let t = (*self.libraries[i].link.get(c)?)?;
337            match found {
338                None => found = Some(t),
339                Some(f) if f == t => {}
340                Some(_) => return None,
341            }
342        }
343        found
344    }
345
346    /// The unit operator markers, if the ROM's unit table revealed them.
347    pub fn unit_markers(&self) -> Option<UnitMarkers> {
348        self.units
349    }
350
351    fn info<'s>(&'s self, lib: &'s Library, c: usize) -> Option<CommandInfo<'s>> {
352        let name = lib.names.get(c).and_then(|n| n.as_deref());
353        Some(CommandInfo {
354            library: lib.id,
355            number: u16::try_from(c).ok()?,
356            name,
357            arity: lib.arity.get(c).copied().flatten(),
358            silent: name.is_none() && Some(lib.id) == self.structure,
359        })
360    }
361
362    /// The one answer of several candidate libraries (copies of a library
363    /// in two places of the image): accepted only when they all agree.
364    fn agreed<'s>(
365        &'s self,
366        candidates: impl Iterator<Item = (&'s Library, usize)>,
367    ) -> Option<CommandInfo<'s>> {
368        let mut found: Option<CommandInfo<'s>> = None;
369        for (lib, c) in candidates {
370            let info = self.info(lib, c)?;
371            match found {
372                None => found = Some(info),
373                Some(f) if f == info => {}
374                Some(_) => return None,
375            }
376        }
377        found
378    }
379
380    /// The command XLIB `library` `number` (an XLIB name object). When
381    /// the image holds the library twice, the copies must agree.
382    pub fn xlib(&self, library: u16, number: u16) -> Option<CommandInfo<'_>> {
383        let c = usize::from(number);
384        let candidates = self.index.get(&library)?.iter().filter_map(move |&i| {
385            let lib = &self.libraries[i];
386            (c < lib.link.len()).then_some((lib, c))
387        });
388        self.agreed(candidates)
389    }
390
391    /// The command whose object is at `addr` in `mem` (a ROM pointer), as
392    /// the ROM's decompiler finds it: the XLIB body in the six nibbles
393    /// before the object names a library and command whose link table
394    /// entry is this object. On a banked ROM the table does not know which
395    /// bank the CPU sees at `addr`: every copy of the library whose entry
396    /// lies at that offset of some bank must agree, else the command stays
397    /// unknown.
398    pub fn command_at(&self, addr: u32, mem: &dyn Memory) -> Option<CommandInfo<'_>> {
399        let start = addr.checked_sub(6)?;
400        let mut prefix = [0u8; 6];
401        for (i, p) in prefix.iter_mut().enumerate() {
402            *p = mem.nibble(start + i as u32)?;
403        }
404        let library = read_field(&prefix, 0, 3)? as u16;
405        let c = read_field(&prefix, 3, 3)? as usize;
406        let a = addr as usize;
407        let candidates = self.index.get(&library)?.iter().filter_map(move |&i| {
408            let lib = &self.libraries[i];
409            let t = (*lib.link.get(c)?)?;
410            let same = match self.bank {
411                None => t == a,
412                // The CPU sees a bank through one of two windows.
413                Some(b) => a < 2 * b && t % b == a % b,
414            };
415            same.then_some((lib, c))
416        });
417        self.agreed(candidates)
418    }
419}
420
421/// Every library header in `rom` whose hash and link tables check out;
422/// none when there are more than [`MAX_LIBRARIES`] or [`MAX_COMMANDS`]
423/// (not a ROM this knows).
424fn scan(rom: &[u8], bank: Option<usize>) -> Vec<Library> {
425    let hex = ObjectType::BinaryInteger.prolog() as usize;
426    let sysbin = ObjectType::SystemBinary.prolog() as usize;
427    let ext = ObjectType::ExtendedPointer.prolog() as usize;
428    let mut out = Vec::new();
429    let mut commands = 0;
430    let last = rom.len().saturating_sub(HEADER_NIBBLES);
431    for p in 0..last {
432        // Cheap rejections first: both offsets set, the link table a hex
433        // string, the hash table a hex string or an indirection.
434        if f5(rom, p + 3) == Some(0) || f5(rom, p + 13) == Some(0) {
435            continue;
436        }
437        let Some(tl) = rel(rom, p + 13) else { continue };
438        if f5(rom, tl) != Some(hex) {
439            continue;
440        }
441        let Some(th) = rel(rom, p + 3) else { continue };
442        let Some(ph) = f5(rom, th) else { continue };
443        if ph != hex && ph != sysbin && ph != ext {
444            continue;
445        }
446        let Some(len) = f5(rom, tl + 5) else { continue };
447        if len < 5 || (len - 5) % 5 != 0 || tl + 5 + len > rom.len() {
448            continue;
449        }
450        let count = (len - 5) / 5;
451        if count > MAX_LIBRARY_COMMANDS {
452            continue;
453        }
454        let hash = if ph == hex {
455            hash_at(rom, th)
456        } else {
457            // An indirection directly followed by the link table.
458            let size = if ph == sysbin { 10 } else { 15 };
459            if tl != th + size {
460                continue;
461            }
462            let Some(a) = f5(rom, th + 5) else { continue };
463            let mut found = candidates(a, bank, rom.len()).filter_map(|t| hash_at(rom, t));
464            match (found.next(), found.next()) {
465                (Some(h), None) => Some(h),
466                _ => None,
467            }
468        };
469        let Some(hash) = hash.filter(|h| h.count <= count) else {
470            continue;
471        };
472        commands += count;
473        if out.len() == MAX_LIBRARIES || commands > MAX_COMMANDS {
474            return Vec::new();
475        }
476        let link = (0..count).map(|c| rel(rom, tl + 10 + 5 * c)).collect();
477        let names = (0..hash.count).map(|c| name_in(rom, &hash, c)).collect();
478        out.push(Library {
479            id: read_field(rom, p, 3).unwrap_or(0) as u16,
480            names,
481            link,
482            arity: Vec::new(),
483        });
484    }
485    out
486}
487
488/// Image indexes that CPU address `a` can stand for: itself, or on a
489/// banked ROM the same offset in every bank.
490fn candidates(a: usize, bank: Option<usize>, len: usize) -> Box<dyn Iterator<Item = usize>> {
491    match bank {
492        None => Box::new((a < len).then_some(a).into_iter()),
493        Some(b) => Box::new((0..len / b).map(move |k| k * b + a % b)),
494    }
495}
496
497/// The argument dispatchers CK0-CK5 as ROM addresses.
498#[derive(Clone, Copy, Debug)]
499struct Dispatch {
500    ck0: Option<usize>,
501    /// CK1&Dispatch; CKn is `ck1 + (n - 1) * stride`.
502    ck1: usize,
503    stride: usize,
504}
505
506impl Dispatch {
507    /// The dispatchers, from the library that holds `+`: its commands'
508    /// first objects include four evenly spaced ones (CK1-CK4), `+`
509    /// starts with CK2, and the most common other one is CK0 (wiki:
510    /// protocols/rpl-libraries "Dispatchers").
511    fn find(rom: &[u8], libraries: &[Library]) -> Option<Dispatch> {
512        let (lib, plus) = libraries.iter().find_map(|l| {
513            let c = l.names.iter().position(|n| n.as_deref() == Some("+"))?;
514            Some((l, c))
515        })?;
516        let mut counts: HashMap<usize, usize> = HashMap::new();
517        for &t in lib.link.iter().flatten() {
518            if let Some(p) = first_object(rom, t) {
519                *counts.entry(p).or_default() += 1;
520            }
521        }
522        let ck2 = first_object(rom, (*lib.link.get(plus)?)?)?;
523        let mut common: Vec<(usize, usize)> = counts.into_iter().collect();
524        common.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
525        common.truncate(DISPATCH_CANDIDATES);
526        let has = |v: usize| common.iter().any(|&(p, _)| p == v);
527        // CK1 and CK3 around CK2, CK4 after: the smallest spacing that fits.
528        let stride = common
529            .iter()
530            .filter_map(|&(p, _)| p.checked_sub(ck2).filter(|s| *s > 0))
531            .filter(|&s| ck2 >= s && has(ck2 - s) && has(ck2 + 2 * s))
532            .min()?;
533        let ck1 = ck2 - stride;
534        let cks: Vec<usize> = (0..5).map(|k| ck1 + k * stride).collect();
535        let ck0 = common.iter().map(|&(p, _)| p).find(|p| !cks.contains(p));
536        Some(Dispatch { ck0, ck1, stride })
537    }
538
539    /// The argument count of the command whose object is at image index
540    /// `t`.
541    fn arity(&self, rom: &[u8], t: usize) -> Option<u8> {
542        let p = first_object(rom, t)?;
543        if Some(p) == self.ck0 {
544            return Some(0);
545        }
546        let k = p.checked_sub(self.ck1)?;
547        if k % self.stride != 0 || k / self.stride > 4 {
548            return None;
549        }
550        u8::try_from(k / self.stride + 1).ok()
551    }
552}
553
554/// The first element of the program at image index `t`, if it is one.
555fn first_object(rom: &[u8], t: usize) -> Option<usize> {
556    (f5(rom, t)? == ObjectType::Program.prolog() as usize).then(|| f5(rom, t + 5))?
557}
558
559/// The unit operator markers: the most common last element of the ROM's
560/// own unit objects is the end marker, the other four precede it.
561fn unit_markers(rom: &[u8], bank: Option<usize>) -> Option<UnitMarkers> {
562    let unit = ObjectType::Unit.prolog() as usize;
563    let mut ends: HashMap<usize, usize> = HashMap::new();
564    for p in 0..rom.len().saturating_sub(5) {
565        if f5(rom, p) != Some(unit) {
566            continue;
567        }
568        if let Some(e) = unit_end(rom, p + 5) {
569            *ends.entry(e).or_default() += 1;
570        }
571    }
572    let (&end, _) = ends.iter().max_by(|a, b| a.1.cmp(b.1).then(b.0.cmp(a.0)))?;
573    let end = u32::try_from(end).ok()?;
574    let first = end.checked_sub(4 * MARKER_STRIDE)? as usize;
575    // All five are empty lists, side by side, in one bank.
576    let is_block = |at: usize| {
577        (0..5).all(|k| {
578            let s = at + k * MARKER_STRIDE as usize;
579            rom.get(s..s + 10) == Some(&EMPTY_LIST[..])
580        })
581    };
582    if !candidates(first, bank, rom.len()).any(is_block) {
583        return None;
584    }
585    let m = |k: u32| end - (4 - k) * MARKER_STRIDE;
586    Some(UnitMarkers {
587        times: m(0),
588        divide: m(1),
589        power: m(2),
590        prefix: m(3),
591        end,
592    })
593}
594
595/// The last element (a ROM pointer) of the unit body at `at`, if the body
596/// holds only reals, strings, characters and pointers.
597fn unit_end(rom: &[u8], mut at: usize) -> Option<usize> {
598    let real = ObjectType::Real.prolog() as usize;
599    let string = ObjectType::String.prolog() as usize;
600    let chr = ObjectType::Character.prolog() as usize;
601    let mut last = None;
602    for _ in 0..MAX_UNIT_ELEMENTS {
603        let p = f5(rom, at)?;
604        if p == SEMI as usize {
605            return last;
606        }
607        if p == real {
608            at += 21;
609        } else if p == string {
610            at += 5 + f5(rom, at + 5)?;
611        } else if p == chr {
612            at += 7;
613        } else if (0x02600..=0x02FFF).contains(&p) {
614            return None;
615        } else {
616            last = Some(p);
617            at += 5;
618        }
619    }
620    None
621}
622
623#[cfg(test)]
624mod tests {
625    use super::*;
626
627    fn put(out: &mut Vec<u8>, at: usize, value: usize, width: usize) {
628        if out.len() < at + width {
629            out.resize(at + width, 0);
630        }
631        for i in 0..width {
632            out[at + i] = ((value >> (4 * i)) & 0xF) as u8;
633        }
634    }
635
636    fn put_rel(out: &mut Vec<u8>, at: usize, target: usize) {
637        let off = (target + 0x100000 - at) & 0xFFFFF;
638        put(out, at, off, 5);
639    }
640
641    /// A ROM of `size` nibbles with library `id` at #100: names `names`
642    /// (by command number), the commands' objects (programs starting with
643    /// the pointer in `first`) each preceded by their XLIB body.
644    fn synthetic(id: usize, names: &[Option<&str>], first: &[usize]) -> Vec<u8> {
645        let mut r = vec![0u8; 0x4000];
646        let header = 0x100;
647        let hash = 0x200;
648        let objects = 0x1000;
649        // Hash table: 16 length offsets, number table offset, names, numbers.
650        let body = hash + 10;
651        let mut at = body + 85;
652        let mut entries = vec![0usize; names.len()];
653        let mut first_of_len = [0usize; 16];
654        for len in 1..=16 {
655            for (c, n) in names.iter().enumerate() {
656                let Some(n) = n else { continue };
657                // HP characters: « and » are bytes #AB and #BB.
658                let bytes: Vec<u8> = n.chars().map(|c| c as u32 as u8).collect();
659                if bytes.len() != len {
660                    continue;
661                }
662                if first_of_len[len - 1] == 0 {
663                    first_of_len[len - 1] = at;
664                }
665                entries[c] = at;
666                put(&mut r, at, len, 2);
667                for (i, b) in bytes.iter().enumerate() {
668                    put(&mut r, at + 2 + 2 * i, usize::from(*b), 2);
669                }
670                put(&mut r, at + 2 + 2 * len, c, 3);
671                at += 2 + 2 * len + 3;
672            }
673        }
674        for (i, &e) in first_of_len.iter().enumerate() {
675            if e != 0 {
676                put_rel(&mut r, body + 5 * i, e);
677            }
678        }
679        let numbers = at;
680        put_rel(&mut r, body + 80, numbers);
681        for (c, &e) in entries.iter().enumerate() {
682            let field = numbers + 5 * c;
683            put(&mut r, field, if e == 0 { 0 } else { field - e }, 5);
684        }
685        let end = numbers + 5 * names.len();
686        put(&mut r, hash, 0x02A4E, 5);
687        put(&mut r, hash + 5, end - hash - 5, 5);
688        // Link table right after the hash table.
689        let link = end;
690        put(&mut r, link, 0x02A4E, 5);
691        put(&mut r, link + 5, 5 + 5 * names.len(), 5);
692        for c in 0..names.len() {
693            let obj = objects + 0x40 * c;
694            put(&mut r, obj - 6, id, 3);
695            put(&mut r, obj - 3, c, 3);
696            put(&mut r, obj, 0x02D9D, 5);
697            put(&mut r, obj + 5, first.get(c).copied().unwrap_or(0x3000), 5);
698            put(&mut r, obj + 10, SEMI as usize, 5);
699            put_rel(&mut r, link + 10 + 5 * c, obj);
700        }
701        put(&mut r, header, id, 3);
702        put_rel(&mut r, header + 3, hash);
703        put_rel(&mut r, header + 13, link);
704        r
705    }
706
707    struct Image<'a>(&'a [u8]);
708    impl Memory for Image<'_> {
709        fn nibble(&self, addr: u32) -> Option<u8> {
710            self.0.get(addr as usize).copied()
711        }
712    }
713
714    #[test]
715    fn names_resolve_by_number_and_by_address() {
716        // + is binary through "CK2" #2005; the others share "CK1" #2000,
717        // "CK3" #200A and "CK4" #200F appear once each.
718        let names = [
719            Some("SIN"),
720            Some("+"),
721            None,
722            Some("+"),
723            Some("IFTE"),
724            Some("INTG"),
725            Some("COS"),
726        ];
727        let first = [0x2000, 0x2005, 0x2000, 0x2005, 0x200A, 0x200F, 0x2000];
728        let rom = synthetic(0x2, &names, &first);
729        let t = NameTable::build(Model::Hp48sx, &rom);
730        assert_eq!(
731            t.stats(),
732            NameStats {
733                libraries: 1,
734                names: 6,
735                arities: 7
736            }
737        );
738        let sin = t.xlib(2, 0).unwrap();
739        assert_eq!((sin.name, sin.arity), (Some("SIN"), Some(1)));
740        assert_eq!(t.xlib(2, 3).unwrap().name, Some("+"));
741        assert_eq!(t.xlib(2, 2).unwrap().name, None);
742        assert_eq!(t.xlib(2, 4).unwrap().arity, Some(3));
743        assert_eq!(t.xlib(2, 5).unwrap().arity, Some(4));
744        assert_eq!(t.xlib(2, 7), None);
745        assert_eq!(t.xlib(3, 0), None);
746        let mem = Image(&rom);
747        let plus = t.command_at(0x1040, &mem).unwrap();
748        assert_eq!(
749            (plus.number, plus.name, plus.arity),
750            (1, Some("+"), Some(2))
751        );
752        // Not a command: no XLIB body before it, or one that lies.
753        assert_eq!(t.command_at(0x1041, &mem), None);
754        let mut liar = rom.clone();
755        put(&mut liar, 0x1040 - 3, 2, 3);
756        assert_eq!(t.command_at(0x1040, &Image(&liar)), None);
757        let all: Vec<&str> = t.names().map(|(_, _, n)| n).collect();
758        assert_eq!(all, ["SIN", "+", "+", "IFTE", "INTG", "COS"]);
759    }
760
761    /// The synthetic library's ROM with RAM objects at #3000.
762    fn with_ram(objects: &[(usize, &str)]) -> (Vec<u8>, NameTable) {
763        let names = [
764            Some("SIN"),
765            Some("+"),
766            Some("«"),
767            Some("»"),
768            None,
769            Some("IFTE"),
770            Some("INTG"),
771        ];
772        let first = [0x2000, 0x2005, 0x2000, 0x2000, 0x2000, 0x200A, 0x200F];
773        let mut rom = synthetic(0x2, &names, &first);
774        let t = NameTable::build(Model::Hp48sx, &rom);
775        for (at, hex) in objects {
776            for (i, c) in hex.chars().enumerate() {
777                let v = c.to_digit(16).unwrap() as usize;
778                put(&mut rom, at + i, v, 1);
779            }
780        }
781        (rom, t)
782    }
783
784    fn ptr(a: usize) -> String {
785        (0..5)
786            .map(|i| format!("{:X}", (a >> (4 * i)) & 0xF))
787            .collect()
788    }
789
790    #[test]
791    fn decoding_with_names() {
792        use crate::decompile::Settings;
793        use crate::object::{Object, Reader};
794        // { 1 SIN }, « 1 SIN » with « and » as commands, 'A+1'.
795        let one = "339200000000000000010";
796        let list = format!("47A20{one}{}B2130", ptr(0x1000));
797        let prog = format!(
798            "D9D20{}{one}{}{}B2130",
799            ptr(0x1080),
800            ptr(0x1000),
801            ptr(0x10C0)
802        );
803        let alg = format!("8BA2084E201014{one}{}B2130", ptr(0x1040));
804        let (rom, t) = with_ram(&[(0x3000, &list), (0x3100, &prog), (0x3200, &alg)]);
805        let mem = Image(&rom);
806        let r = Reader::with_names(&mem, &t, Settings::default());
807        let json = |a: u32| serde_json::to_value(r.decode_at(a).unwrap()).unwrap();
808        assert_eq!(
809            json(0x3000),
810            serde_json::json!({"type": "list", "items": [
811                {"type": "real", "value": 1.0},
812                {"type": "command", "name": "SIN", "address": 4096,
813                 "library": 2, "command": 0}]})
814        );
815        assert_eq!(
816            r.decode_at(0x3100).unwrap(),
817            Object::Program {
818                source: Some("« 1 SIN »".into())
819            }
820        );
821        assert_eq!(
822            r.decode_at(0x3200).unwrap(),
823            Object::Algebraic {
824                source: Some("'A+1'".into())
825            }
826        );
827        // A stack level that is a command's object is that command.
828        assert_eq!(
829            json(0x1000),
830            serde_json::json!({"type": "command", "name": "SIN", "address": 4096, "library": 2, "command": 0})
831        );
832        // An unnamed command of the structure library would be silent; this
833        // one is in the same library as « so it is.
834        assert!(t.command_at(0x1100, &mem).unwrap().silent);
835        // Without names: the pointer is still a command, not a program.
836        let plain = Reader::new(&mem);
837        assert_eq!(
838            serde_json::to_value(plain.decode_at(0x3000).unwrap()).unwrap()["items"][1],
839            serde_json::json!({"type": "command", "address": 4096})
840        );
841        assert_eq!(
842            plain.decode_at(0x3100).unwrap(),
843            Object::Program { source: None }
844        );
845    }
846
847    #[test]
848    fn garbage_ram_gives_errors_or_unknowns() {
849        use crate::decompile::Settings;
850        use crate::object::{Object, Reader};
851        // A list holding a pointer to itself: bounded by the nesting limit.
852        let cycle = format!("47A20{}B2130", ptr(0x3000));
853        // An algebraic whose elements do not form an expression, one whose
854        // operator lacks operands, a unit without its operators' operands.
855        let loose = "8BA2084E2010184E2010288E20B2130";
856        let short = format!("8BA20{}B2130", ptr(0x1040));
857        // A program pointing at itself: a ROM-style command, not followed.
858        let selfp = format!("D9D20{}B2130", ptr(0x3400));
859        let (rom, t) = with_ram(&[
860            (0x3000, &cycle),
861            (0x3100, loose),
862            (0x3200, &short),
863            (0x3400, &selfp),
864        ]);
865        let mem = Image(&rom);
866        let r = Reader::with_names(&mem, &t, Settings::default());
867        assert!(r.decode_at(0x3000).is_err());
868        assert!(matches!(
869            r.decode_at(0x3100),
870            Ok(Object::Algebraic { source: None }) | Err(_)
871        ));
872        assert_eq!(
873            r.decode_at(0x3200).unwrap(),
874            Object::Algebraic { source: None }
875        );
876        assert_eq!(
877            r.decode_at(0x3400).unwrap(),
878            Object::Program {
879                source: Some("External".into())
880            }
881        );
882    }
883
884    /// `copy` (a synthetic library image) at the start of each bank of
885    /// a two-bank 49G-style image.
886    fn two_banks(a: &[u8], b: &[u8]) -> Vec<u8> {
887        let mut r = vec![0u8; 2 * BANK_NIBBLES];
888        r[..a.len()].copy_from_slice(a);
889        r[BANK_NIBBLES..BANK_NIBBLES + b.len()].copy_from_slice(b);
890        r
891    }
892
893    #[test]
894    fn banked_copies_must_agree() {
895        let first = [0x2000, 0x2005, 0x2000];
896        let sin = synthetic(0x2, &[Some("SIN"), Some("+"), Some("X")], &first);
897        let cos = synthetic(0x2, &[Some("COS"), Some("+"), Some("X")], &first);
898        // The CPU sees bank 0's copy at #1000 (its first command).
899        let mem = Image(&sin);
900        let same = NameTable::build(Model::Hp49g, &two_banks(&sin, &sin));
901        assert_eq!(same.command_at(0x1000, &mem).unwrap().name, Some("SIN"));
902        assert_eq!(same.xlib(2, 0).unwrap().name, Some("SIN"));
903        let differ = NameTable::build(Model::Hp49g, &two_banks(&sin, &cos));
904        assert_eq!(differ.command_at(0x1000, &mem), None);
905        assert_eq!(differ.xlib(2, 0), None);
906        // Where they agree (command 1), the answer stands.
907        assert_eq!(differ.command_at(0x1040, &mem).unwrap().name, Some("+"));
908    }
909
910    #[test]
911    fn link_entries_outside_the_image_match_nothing() {
912        let mut lib = synthetic(0x2, &[Some("SIN"), Some("COS")], &[0x2000, 0x2000]);
913        // Command 1's link entry points past the end of the image.
914        let link = (0..lib.len() - 5)
915            .find(|&i| read_field(&lib, i, 5) == Some(0x02A4E) && i > 0x210)
916            .unwrap();
917        put(&mut lib, link + 15, 0x7FFFF, 5);
918        let image = two_banks(&lib, &[]);
919        let t = NameTable::build(Model::Hp49g, &image);
920        assert_eq!(t.xlib(2, 1).unwrap().name, Some("COS"));
921        // An address whose bank offset would equal the old sentinel's.
922        let mut ram = vec![0u8; 0x40000];
923        put(&mut ram, 0x3FFF9, 0x2, 3);
924        put(&mut ram, 0x3FFFC, 1, 3);
925        assert_eq!(t.command_at(0x3FFFF, &Image(&ram)), None);
926    }
927
928    #[test]
929    fn other_models_get_an_empty_table() {
930        let rom = synthetic(0x2, &[Some("SIN")], &[0x2000]);
931        assert_eq!(NameTable::build(Model::Hp48gx, &rom).stats().names, 1);
932        for model in [Model::Hp38g, Model::Hp39g, Model::Hp40g, Model::Hp42s] {
933            let t = NameTable::build(model, &rom);
934            assert_eq!(t.stats(), NameStats::default(), "{}", model.name());
935            assert_eq!(t.unit_markers(), None);
936        }
937    }
938
939    #[test]
940    fn garbage_gives_an_empty_table() {
941        let mut rom = vec![0u8; 0x10000];
942        for (i, n) in rom.iter_mut().enumerate() {
943            *n = ((i * 7919) >> 3) as u8 & 0xF;
944        }
945        let t = NameTable::build(Model::Hp49g, &rom);
946        assert_eq!(t.stats().names, 0);
947        assert_eq!(t.unit_markers(), None);
948        assert_eq!(t.command_at(5, &Image(&rom)), None);
949        assert_eq!(NameTable::build(Model::Hp48sx, &[]).stats().libraries, 0);
950    }
951
952    /// `headers` library headers every 20 nibbles, all sharing one empty
953    /// hash table and one link table of `commands` entries.
954    fn shared_tables(headers: usize, commands: usize) -> Vec<u8> {
955        let mut r = vec![0u8; 0x10000];
956        let (th, tl) = (0x2000, 0x3000);
957        put(&mut r, th, 0x02A4E, 5);
958        put(&mut r, th + 5, 90, 5);
959        // The number table's offset: right at the end, no names.
960        put(&mut r, th + 90, 5, 5);
961        put(&mut r, tl, 0x02A4E, 5);
962        put(&mut r, tl + 5, 5 + 5 * commands, 5);
963        for k in 0..headers {
964            put(&mut r, 20 * k, 0x700 + (k & 0xFF), 3);
965            put_rel(&mut r, 20 * k + 3, th);
966            put_rel(&mut r, 20 * k + 13, tl);
967        }
968        r
969    }
970
971    #[test]
972    fn crafted_link_tables_are_capped() {
973        let libraries = |h, c| {
974            NameTable::build(Model::Hp48gx, &shared_tables(h, c))
975                .stats()
976                .libraries
977        };
978        assert_eq!(libraries(10, 100), 10);
979        // More libraries than any ROM (the 49G has 52).
980        assert_eq!(libraries(MAX_LIBRARIES + 1, 100), 0);
981        // More commands than a 3-nibble command number can name.
982        assert_eq!(libraries(1, MAX_LIBRARY_COMMANDS + 1), 0);
983        assert_eq!(libraries(1, MAX_LIBRARY_COMMANDS), 1);
984        // More commands together than any ROM (the 49G has 5940).
985        assert_eq!(libraries(MAX_COMMANDS / 2000 + 1, 2000), 0);
986    }
987
988    #[test]
989    fn unit_markers_from_the_rom_units() {
990        let mut rom = vec![0u8; 0x2000];
991        let block = 0x400;
992        for k in 0..5 {
993            rom[block + 10 * k..block + 10 * k + 10].copy_from_slice(&EMPTY_LIST);
994        }
995        let end = block + 40;
996        // Three units 1_m ending in the end marker, one ending elsewhere.
997        for (u, last) in [(0x800, end), (0x900, end), (0xA00, end), (0xB00, 0x1234)] {
998            put(&mut rom, u, 0x02ADA, 5);
999            put(&mut rom, u + 5, 0x2A2C9, 5);
1000            put(&mut rom, u + 10, 0x02A2C, 5);
1001            put(&mut rom, u + 15, 7, 5);
1002            put(&mut rom, u + 20, 0x6D, 2);
1003            put(&mut rom, u + 22, last, 5);
1004            put(&mut rom, u + 27, SEMI as usize, 5);
1005        }
1006        let m = NameTable::build(Model::Hp48sx, &rom)
1007            .unit_markers()
1008            .unwrap();
1009        assert_eq!(
1010            (m.times, m.divide, m.power, m.prefix, m.end),
1011            (0x400, 0x40A, 0x414, 0x41E, 0x428)
1012        );
1013    }
1014}