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