1use std::collections::HashMap;
22
23use saturnus_core::Model;
24
25use crate::charset;
26use crate::object::Memory;
27use crate::prolog::{ObjectType, SEMI, read_field};
28
29const BANK_NIBBLES: usize = 0x40000;
32const HEADER_NIBBLES: usize = 23;
35const EMPTY_LIST: [u8; 10] = [4, 7, 0xA, 2, 0, 0xB, 2, 1, 3, 0];
37const MARKER_STRIDE: u32 = 10;
39const MAX_UNIT_ELEMENTS: usize = 40;
41const DISPATCH_CANDIDATES: usize = 12;
43const MAX_LIBRARY_COMMANDS: usize = 0x1000;
46const MAX_LIBRARIES: usize = 256;
49const MAX_COMMANDS: usize = 1 << 15;
53
54fn f5(n: &[u8], at: usize) -> Option<usize> {
56 read_field(n, at, 5).map(|v| v as usize)
57}
58
59fn 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#[derive(Clone, Copy, Debug)]
74struct Hash {
75 names_start: usize,
76 numbers: usize,
77 count: usize,
78}
79
80fn 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 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
109fn 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#[derive(Clone, Debug)]
132struct Library {
133 id: u16,
134 names: Vec<Option<String>>,
137 link: Vec<Option<usize>>,
139 arity: Vec<Option<u8>>,
142}
143
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
146pub struct CommandInfo<'a> {
147 pub library: u16,
149 pub number: u16,
151 pub name: Option<&'a str>,
153 pub arity: Option<u8>,
156 pub silent: bool,
160}
161
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub struct UnitMarkers {
166 pub times: u32,
168 pub divide: u32,
170 pub power: u32,
172 pub prefix: u32,
174 pub end: u32,
176}
177
178#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
180pub struct NameStats {
181 pub libraries: usize,
183 pub names: usize,
185 pub arities: usize,
187}
188
189#[derive(Clone, Default)]
192pub struct NameTable {
193 libraries: Vec<Library>,
196 index: HashMap<u16, Vec<usize>>,
197 bank: Option<usize>,
199 units: Option<UnitMarkers>,
200 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 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 return NameTable::default();
235 }
236 };
237 let mut libraries = scan(rom, bank);
238 let dispatch = Dispatch::find(rom, &libraries);
239 for lib in &mut libraries {
240 lib.arity = lib
241 .link
242 .iter()
243 .map(|t| dispatch.as_ref().zip(*t).and_then(|(d, t)| d.arity(rom, t)))
244 .collect();
245 }
246 let mut index: HashMap<u16, Vec<usize>> = HashMap::new();
247 for (i, lib) in libraries.iter().enumerate() {
248 index.entry(lib.id).or_default().push(i);
249 }
250 let structure = libraries
251 .iter()
252 .find(|l| l.names.iter().any(|n| n.as_deref() == Some("«")))
253 .map(|l| l.id);
254 NameTable {
255 libraries,
256 index,
257 bank,
258 units: unit_markers(rom, bank),
259 structure,
260 }
261 }
262
263 pub fn of(machine: &saturnus_core::Machine) -> NameTable {
265 Self::build(machine.model(), machine.rom_nibbles())
266 }
267
268 pub fn stats(&self) -> NameStats {
270 let mut s = NameStats {
271 libraries: self.libraries.len(),
272 ..NameStats::default()
273 };
274 for lib in &self.libraries {
275 s.names += lib.names.iter().flatten().count();
276 s.arities += lib.arity.iter().flatten().count();
277 }
278 s
279 }
280
281 pub fn heap_bytes(&self) -> usize {
284 use std::mem::size_of;
285 let libs: usize = self
286 .libraries
287 .iter()
288 .map(|l| {
289 l.names.capacity() * size_of::<Option<String>>()
290 + l.names
291 .iter()
292 .flatten()
293 .map(String::capacity)
294 .sum::<usize>()
295 + l.link.capacity() * size_of::<Option<usize>>()
296 + l.arity.capacity() * size_of::<Option<u8>>()
297 })
298 .sum();
299 let index: usize = self
300 .index
301 .values()
302 .map(|v| size_of::<(u16, Vec<usize>)>() + v.capacity() * size_of::<usize>())
303 .sum();
304 libs + self.libraries.capacity() * size_of::<Library>() + index
305 }
306
307 pub fn names(&self) -> impl Iterator<Item = (u16, u16, &str)> + '_ {
309 self.libraries.iter().flat_map(|lib| {
310 lib.names
311 .iter()
312 .enumerate()
313 .filter_map(move |(c, n)| Some((lib.id, u16::try_from(c).ok()?, n.as_deref()?)))
314 })
315 }
316
317 pub fn bank(&self) -> Option<usize> {
319 self.bank
320 }
321
322 pub fn find(&self, name: &str) -> Option<(u16, u16)> {
325 self.libraries.iter().find_map(|lib| {
326 let c = lib.names.iter().position(|n| n.as_deref() == Some(name))?;
327 Some((lib.id, u16::try_from(c).ok()?))
328 })
329 }
330
331 pub fn library_size(&self, library: u16) -> Option<(usize, usize)> {
334 let lib = &self.libraries[*self.index.get(&library)?.first()?];
335 Some((lib.link.len(), lib.names.iter().flatten().count()))
336 }
337
338 pub fn object_index(&self, library: u16, number: u16) -> Option<usize> {
341 let c = usize::from(number);
342 let mut found = None;
343 for &i in self.index.get(&library)? {
344 let t = (*self.libraries[i].link.get(c)?)?;
345 match found {
346 None => found = Some(t),
347 Some(f) if f == t => {}
348 Some(_) => return None,
349 }
350 }
351 found
352 }
353
354 pub fn unit_markers(&self) -> Option<UnitMarkers> {
356 self.units
357 }
358
359 fn info<'s>(&'s self, lib: &'s Library, c: usize) -> Option<CommandInfo<'s>> {
360 let name = lib.names.get(c).and_then(|n| n.as_deref());
361 Some(CommandInfo {
362 library: lib.id,
363 number: u16::try_from(c).ok()?,
364 name,
365 arity: lib.arity.get(c).copied().flatten(),
366 silent: name.is_none() && Some(lib.id) == self.structure,
367 })
368 }
369
370 fn agreed<'s>(
373 &'s self,
374 candidates: impl Iterator<Item = (&'s Library, usize)>,
375 ) -> Option<CommandInfo<'s>> {
376 let mut found: Option<CommandInfo<'s>> = None;
377 for (lib, c) in candidates {
378 let info = self.info(lib, c)?;
379 match found {
380 None => found = Some(info),
381 Some(f) if f == info => {}
382 Some(_) => return None,
383 }
384 }
385 found
386 }
387
388 pub fn xlib(&self, library: u16, number: u16) -> Option<CommandInfo<'_>> {
391 let c = usize::from(number);
392 let candidates = self.index.get(&library)?.iter().filter_map(move |&i| {
393 let lib = &self.libraries[i];
394 (c < lib.link.len()).then_some((lib, c))
395 });
396 self.agreed(candidates)
397 }
398
399 pub fn command_at(&self, addr: u32, mem: &dyn Memory) -> Option<CommandInfo<'_>> {
407 let start = addr.checked_sub(6)?;
408 let mut prefix = [0u8; 6];
409 for (i, p) in prefix.iter_mut().enumerate() {
410 *p = mem.nibble(start + i as u32)?;
411 }
412 let library = read_field(&prefix, 0, 3)? as u16;
413 let c = read_field(&prefix, 3, 3)? as usize;
414 let a = addr as usize;
415 let candidates = self.index.get(&library)?.iter().filter_map(move |&i| {
416 let lib = &self.libraries[i];
417 let t = (*lib.link.get(c)?)?;
418 let same = match self.bank {
419 None => t == a,
420 Some(b) => a < 2 * b && t % b == a % b,
422 };
423 same.then_some((lib, c))
424 });
425 self.agreed(candidates)
426 }
427}
428
429fn scan(rom: &[u8], bank: Option<usize>) -> Vec<Library> {
433 let hex = ObjectType::BinaryInteger.prolog() as usize;
434 let sysbin = ObjectType::SystemBinary.prolog() as usize;
435 let ext = ObjectType::ExtendedPointer.prolog() as usize;
436 let mut out = Vec::new();
437 let mut commands = 0;
438 let last = rom.len().saturating_sub(HEADER_NIBBLES);
439 for p in 0..last {
440 if f5(rom, p + 3) == Some(0) || f5(rom, p + 13) == Some(0) {
443 continue;
444 }
445 let Some(tl) = rel(rom, p + 13) else { continue };
446 if f5(rom, tl) != Some(hex) {
447 continue;
448 }
449 let Some(th) = rel(rom, p + 3) else { continue };
450 let Some(ph) = f5(rom, th) else { continue };
451 if ph != hex && ph != sysbin && ph != ext {
452 continue;
453 }
454 let Some(len) = f5(rom, tl + 5) else { continue };
455 if len < 5 || (len - 5) % 5 != 0 || tl + 5 + len > rom.len() {
456 continue;
457 }
458 let count = (len - 5) / 5;
459 if count > MAX_LIBRARY_COMMANDS {
460 continue;
461 }
462 let hash = if ph == hex {
463 hash_at(rom, th)
464 } else {
465 let size = if ph == sysbin { 10 } else { 15 };
467 if tl != th + size {
468 continue;
469 }
470 let Some(a) = f5(rom, th + 5) else { continue };
471 let mut found = candidates(a, bank, rom.len()).filter_map(|t| hash_at(rom, t));
472 match (found.next(), found.next()) {
473 (Some(h), None) => Some(h),
474 _ => None,
475 }
476 };
477 let Some(hash) = hash.filter(|h| h.count <= count) else {
478 continue;
479 };
480 commands += count;
481 if out.len() == MAX_LIBRARIES || commands > MAX_COMMANDS {
482 return Vec::new();
483 }
484 let link = (0..count).map(|c| rel(rom, tl + 10 + 5 * c)).collect();
485 let names = (0..hash.count).map(|c| name_in(rom, &hash, c)).collect();
486 out.push(Library {
487 id: read_field(rom, p, 3).unwrap_or(0) as u16,
488 names,
489 link,
490 arity: Vec::new(),
491 });
492 }
493 out
494}
495
496fn candidates(a: usize, bank: Option<usize>, len: usize) -> Box<dyn Iterator<Item = usize>> {
499 match bank {
500 None => Box::new((a < len).then_some(a).into_iter()),
501 Some(b) => Box::new((0..len / b).map(move |k| k * b + a % b)),
502 }
503}
504
505#[derive(Clone, Copy, Debug)]
507struct Dispatch {
508 ck0: Option<usize>,
509 ck1: usize,
511 stride: usize,
512}
513
514impl Dispatch {
515 fn find(rom: &[u8], libraries: &[Library]) -> Option<Dispatch> {
520 let (lib, plus) = libraries.iter().find_map(|l| {
521 let c = l.names.iter().position(|n| n.as_deref() == Some("+"))?;
522 Some((l, c))
523 })?;
524 let mut counts: HashMap<usize, usize> = HashMap::new();
525 for &t in lib.link.iter().flatten() {
526 if let Some(p) = first_object(rom, t) {
527 *counts.entry(p).or_default() += 1;
528 }
529 }
530 let ck2 = first_object(rom, (*lib.link.get(plus)?)?)?;
531 let mut common: Vec<(usize, usize)> = counts.into_iter().collect();
532 common.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
533 common.truncate(DISPATCH_CANDIDATES);
534 let has = |v: usize| common.iter().any(|&(p, _)| p == v);
535 let stride = common
537 .iter()
538 .filter_map(|&(p, _)| p.checked_sub(ck2).filter(|s| *s > 0))
539 .filter(|&s| ck2 >= s && has(ck2 - s) && has(ck2 + 2 * s))
540 .min()?;
541 let ck1 = ck2 - stride;
542 let cks: Vec<usize> = (0..5).map(|k| ck1 + k * stride).collect();
543 let ck0 = common.iter().map(|&(p, _)| p).find(|p| !cks.contains(p));
544 Some(Dispatch { ck0, ck1, stride })
545 }
546
547 fn arity(&self, rom: &[u8], t: usize) -> Option<u8> {
550 let p = first_object(rom, t)?;
551 if Some(p) == self.ck0 {
552 return Some(0);
553 }
554 let k = p.checked_sub(self.ck1)?;
555 if k % self.stride != 0 || k / self.stride > 4 {
556 return None;
557 }
558 u8::try_from(k / self.stride + 1).ok()
559 }
560}
561
562fn first_object(rom: &[u8], t: usize) -> Option<usize> {
564 (f5(rom, t)? == ObjectType::Program.prolog() as usize).then(|| f5(rom, t + 5))?
565}
566
567fn unit_markers(rom: &[u8], bank: Option<usize>) -> Option<UnitMarkers> {
570 let unit = ObjectType::Unit.prolog() as usize;
571 let mut ends: HashMap<usize, usize> = HashMap::new();
572 for p in 0..rom.len().saturating_sub(5) {
573 if f5(rom, p) != Some(unit) {
574 continue;
575 }
576 if let Some(e) = unit_end(rom, p + 5) {
577 *ends.entry(e).or_default() += 1;
578 }
579 }
580 let (&end, _) = ends.iter().max_by(|a, b| a.1.cmp(b.1).then(b.0.cmp(a.0)))?;
581 let end = u32::try_from(end).ok()?;
582 let first = end.checked_sub(4 * MARKER_STRIDE)? as usize;
583 let is_block = |at: usize| {
585 (0..5).all(|k| {
586 let s = at + k * MARKER_STRIDE as usize;
587 rom.get(s..s + 10) == Some(&EMPTY_LIST[..])
588 })
589 };
590 if !candidates(first, bank, rom.len()).any(is_block) {
591 return None;
592 }
593 let m = |k: u32| end - (4 - k) * MARKER_STRIDE;
594 Some(UnitMarkers {
595 times: m(0),
596 divide: m(1),
597 power: m(2),
598 prefix: m(3),
599 end,
600 })
601}
602
603fn unit_end(rom: &[u8], mut at: usize) -> Option<usize> {
606 let real = ObjectType::Real.prolog() as usize;
607 let string = ObjectType::String.prolog() as usize;
608 let chr = ObjectType::Character.prolog() as usize;
609 let mut last = None;
610 for _ in 0..MAX_UNIT_ELEMENTS {
611 let p = f5(rom, at)?;
612 if p == SEMI as usize {
613 return last;
614 }
615 if p == real {
616 at += 21;
617 } else if p == string {
618 at += 5 + f5(rom, at + 5)?;
619 } else if p == chr {
620 at += 7;
621 } else if (0x02600..=0x02FFF).contains(&p) {
622 return None;
623 } else {
624 last = Some(p);
625 at += 5;
626 }
627 }
628 None
629}
630
631#[cfg(test)]
632mod tests {
633 use super::*;
634
635 fn put(out: &mut Vec<u8>, at: usize, value: usize, width: usize) {
636 if out.len() < at + width {
637 out.resize(at + width, 0);
638 }
639 for i in 0..width {
640 out[at + i] = ((value >> (4 * i)) & 0xF) as u8;
641 }
642 }
643
644 fn put_rel(out: &mut Vec<u8>, at: usize, target: usize) {
645 let off = (target + 0x100000 - at) & 0xFFFFF;
646 put(out, at, off, 5);
647 }
648
649 fn synthetic(id: usize, names: &[Option<&str>], first: &[usize]) -> Vec<u8> {
653 let mut r = vec![0u8; 0x4000];
654 let header = 0x100;
655 let hash = 0x200;
656 let objects = 0x1000;
657 let body = hash + 10;
659 let mut at = body + 85;
660 let mut entries = vec![0usize; names.len()];
661 let mut first_of_len = [0usize; 16];
662 for len in 1..=16 {
663 for (c, n) in names.iter().enumerate() {
664 let Some(n) = n else { continue };
665 let bytes: Vec<u8> = n.chars().map(|c| c as u32 as u8).collect();
667 if bytes.len() != len {
668 continue;
669 }
670 if first_of_len[len - 1] == 0 {
671 first_of_len[len - 1] = at;
672 }
673 entries[c] = at;
674 put(&mut r, at, len, 2);
675 for (i, b) in bytes.iter().enumerate() {
676 put(&mut r, at + 2 + 2 * i, usize::from(*b), 2);
677 }
678 put(&mut r, at + 2 + 2 * len, c, 3);
679 at += 2 + 2 * len + 3;
680 }
681 }
682 for (i, &e) in first_of_len.iter().enumerate() {
683 if e != 0 {
684 put_rel(&mut r, body + 5 * i, e);
685 }
686 }
687 let numbers = at;
688 put_rel(&mut r, body + 80, numbers);
689 for (c, &e) in entries.iter().enumerate() {
690 let field = numbers + 5 * c;
691 put(&mut r, field, if e == 0 { 0 } else { field - e }, 5);
692 }
693 let end = numbers + 5 * names.len();
694 put(&mut r, hash, 0x02A4E, 5);
695 put(&mut r, hash + 5, end - hash - 5, 5);
696 let link = end;
698 put(&mut r, link, 0x02A4E, 5);
699 put(&mut r, link + 5, 5 + 5 * names.len(), 5);
700 for c in 0..names.len() {
701 let obj = objects + 0x40 * c;
702 put(&mut r, obj - 6, id, 3);
703 put(&mut r, obj - 3, c, 3);
704 put(&mut r, obj, 0x02D9D, 5);
705 put(&mut r, obj + 5, first.get(c).copied().unwrap_or(0x3000), 5);
706 put(&mut r, obj + 10, SEMI as usize, 5);
707 put_rel(&mut r, link + 10 + 5 * c, obj);
708 }
709 put(&mut r, header, id, 3);
710 put_rel(&mut r, header + 3, hash);
711 put_rel(&mut r, header + 13, link);
712 r
713 }
714
715 struct Image<'a>(&'a [u8]);
716 impl Memory for Image<'_> {
717 fn nibble(&self, addr: u32) -> Option<u8> {
718 self.0.get(addr as usize).copied()
719 }
720 }
721
722 #[test]
723 fn names_resolve_by_number_and_by_address() {
724 let names = [
727 Some("SIN"),
728 Some("+"),
729 None,
730 Some("+"),
731 Some("IFTE"),
732 Some("INTG"),
733 Some("COS"),
734 ];
735 let first = [0x2000, 0x2005, 0x2000, 0x2005, 0x200A, 0x200F, 0x2000];
736 let rom = synthetic(0x2, &names, &first);
737 let t = NameTable::build(Model::Hp48sx, &rom);
738 assert_eq!(
739 t.stats(),
740 NameStats {
741 libraries: 1,
742 names: 6,
743 arities: 7
744 }
745 );
746 let sin = t.xlib(2, 0).unwrap();
747 assert_eq!((sin.name, sin.arity), (Some("SIN"), Some(1)));
748 assert_eq!(t.xlib(2, 3).unwrap().name, Some("+"));
749 assert_eq!(t.xlib(2, 2).unwrap().name, None);
750 assert_eq!(t.xlib(2, 4).unwrap().arity, Some(3));
751 assert_eq!(t.xlib(2, 5).unwrap().arity, Some(4));
752 assert_eq!(t.xlib(2, 7), None);
753 assert_eq!(t.xlib(3, 0), None);
754 let mem = Image(&rom);
755 let plus = t.command_at(0x1040, &mem).unwrap();
756 assert_eq!(
757 (plus.number, plus.name, plus.arity),
758 (1, Some("+"), Some(2))
759 );
760 assert_eq!(t.command_at(0x1041, &mem), None);
762 let mut liar = rom.clone();
763 put(&mut liar, 0x1040 - 3, 2, 3);
764 assert_eq!(t.command_at(0x1040, &Image(&liar)), None);
765 let all: Vec<&str> = t.names().map(|(_, _, n)| n).collect();
766 assert_eq!(all, ["SIN", "+", "+", "IFTE", "INTG", "COS"]);
767 }
768
769 fn with_ram(objects: &[(usize, &str)]) -> (Vec<u8>, NameTable) {
771 let names = [
772 Some("SIN"),
773 Some("+"),
774 Some("«"),
775 Some("»"),
776 None,
777 Some("IFTE"),
778 Some("INTG"),
779 ];
780 let first = [0x2000, 0x2005, 0x2000, 0x2000, 0x2000, 0x200A, 0x200F];
781 let mut rom = synthetic(0x2, &names, &first);
782 let t = NameTable::build(Model::Hp48sx, &rom);
783 for (at, hex) in objects {
784 for (i, c) in hex.chars().enumerate() {
785 let v = c.to_digit(16).unwrap() as usize;
786 put(&mut rom, at + i, v, 1);
787 }
788 }
789 (rom, t)
790 }
791
792 fn ptr(a: usize) -> String {
793 (0..5)
794 .map(|i| format!("{:X}", (a >> (4 * i)) & 0xF))
795 .collect()
796 }
797
798 #[test]
799 fn decoding_with_names() {
800 use crate::decompile::Settings;
801 use crate::object::{Object, Reader};
802 let one = "339200000000000000010";
804 let list = format!("47A20{one}{}B2130", ptr(0x1000));
805 let prog = format!(
806 "D9D20{}{one}{}{}B2130",
807 ptr(0x1080),
808 ptr(0x1000),
809 ptr(0x10C0)
810 );
811 let alg = format!("8BA2084E201014{one}{}B2130", ptr(0x1040));
812 let (rom, t) = with_ram(&[(0x3000, &list), (0x3100, &prog), (0x3200, &alg)]);
813 let mem = Image(&rom);
814 let r = Reader::with_names(&mem, &t, Settings::default());
815 let json = |a: u32| serde_json::to_value(r.decode_at(a).unwrap()).unwrap();
816 assert_eq!(
817 json(0x3000),
818 serde_json::json!({"type": "list", "items": [
819 {"type": "real", "value": 1.0},
820 {"type": "command", "name": "SIN", "address": 4096,
821 "library": 2, "command": 0}]})
822 );
823 assert_eq!(
824 r.decode_at(0x3100).unwrap(),
825 Object::Program {
826 source: Some("« 1 SIN »".into())
827 }
828 );
829 assert_eq!(
830 r.decode_at(0x3200).unwrap(),
831 Object::Algebraic {
832 source: Some("'A+1'".into())
833 }
834 );
835 assert_eq!(
837 json(0x1000),
838 serde_json::json!({"type": "command", "name": "SIN", "address": 4096, "library": 2, "command": 0})
839 );
840 assert!(t.command_at(0x1100, &mem).unwrap().silent);
843 let plain = Reader::new(&mem);
845 assert_eq!(
846 serde_json::to_value(plain.decode_at(0x3000).unwrap()).unwrap()["items"][1],
847 serde_json::json!({"type": "command", "address": 4096})
848 );
849 assert_eq!(
850 plain.decode_at(0x3100).unwrap(),
851 Object::Program { source: None }
852 );
853 }
854
855 #[test]
856 fn garbage_ram_gives_errors_or_unknowns() {
857 use crate::decompile::Settings;
858 use crate::object::{Object, Reader};
859 let cycle = format!("47A20{}B2130", ptr(0x3000));
861 let loose = "8BA2084E2010184E2010288E20B2130";
864 let short = format!("8BA20{}B2130", ptr(0x1040));
865 let selfp = format!("D9D20{}B2130", ptr(0x3400));
867 let (rom, t) = with_ram(&[
868 (0x3000, &cycle),
869 (0x3100, loose),
870 (0x3200, &short),
871 (0x3400, &selfp),
872 ]);
873 let mem = Image(&rom);
874 let r = Reader::with_names(&mem, &t, Settings::default());
875 assert!(r.decode_at(0x3000).is_err());
876 assert!(matches!(
877 r.decode_at(0x3100),
878 Ok(Object::Algebraic { source: None }) | Err(_)
879 ));
880 assert_eq!(
881 r.decode_at(0x3200).unwrap(),
882 Object::Algebraic { source: None }
883 );
884 assert_eq!(
885 r.decode_at(0x3400).unwrap(),
886 Object::Program {
887 source: Some("External".into())
888 }
889 );
890 }
891
892 fn two_banks(a: &[u8], b: &[u8]) -> Vec<u8> {
895 let mut r = vec![0u8; 2 * BANK_NIBBLES];
896 r[..a.len()].copy_from_slice(a);
897 r[BANK_NIBBLES..BANK_NIBBLES + b.len()].copy_from_slice(b);
898 r
899 }
900
901 #[test]
902 fn banked_copies_must_agree() {
903 let first = [0x2000, 0x2005, 0x2000];
904 let sin = synthetic(0x2, &[Some("SIN"), Some("+"), Some("X")], &first);
905 let cos = synthetic(0x2, &[Some("COS"), Some("+"), Some("X")], &first);
906 let mem = Image(&sin);
908 let same = NameTable::build(Model::Hp49g, &two_banks(&sin, &sin));
909 assert_eq!(same.command_at(0x1000, &mem).unwrap().name, Some("SIN"));
910 assert_eq!(same.xlib(2, 0).unwrap().name, Some("SIN"));
911 let differ = NameTable::build(Model::Hp49g, &two_banks(&sin, &cos));
912 assert_eq!(differ.command_at(0x1000, &mem), None);
913 assert_eq!(differ.xlib(2, 0), None);
914 assert_eq!(differ.command_at(0x1040, &mem).unwrap().name, Some("+"));
916 }
917
918 #[test]
919 fn link_entries_outside_the_image_match_nothing() {
920 let mut lib = synthetic(0x2, &[Some("SIN"), Some("COS")], &[0x2000, 0x2000]);
921 let link = (0..lib.len() - 5)
923 .find(|&i| read_field(&lib, i, 5) == Some(0x02A4E) && i > 0x210)
924 .unwrap();
925 put(&mut lib, link + 15, 0x7FFFF, 5);
926 let image = two_banks(&lib, &[]);
927 let t = NameTable::build(Model::Hp49g, &image);
928 assert_eq!(t.xlib(2, 1).unwrap().name, Some("COS"));
929 let mut ram = vec![0u8; 0x40000];
931 put(&mut ram, 0x3FFF9, 0x2, 3);
932 put(&mut ram, 0x3FFFC, 1, 3);
933 assert_eq!(t.command_at(0x3FFFF, &Image(&ram)), None);
934 }
935
936 #[test]
937 fn other_models_get_an_empty_table() {
938 let rom = synthetic(0x2, &[Some("SIN")], &[0x2000]);
939 assert_eq!(NameTable::build(Model::Hp48gx, &rom).stats().names, 1);
940 for model in [Model::Hp38g, Model::Hp39g, Model::Hp40g, Model::Hp42s] {
941 let t = NameTable::build(model, &rom);
942 assert_eq!(t.stats(), NameStats::default(), "{}", model.name());
943 assert_eq!(t.unit_markers(), None);
944 }
945 }
946
947 #[test]
948 fn garbage_gives_an_empty_table() {
949 let mut rom = vec![0u8; 0x10000];
950 for (i, n) in rom.iter_mut().enumerate() {
951 *n = ((i * 7919) >> 3) as u8 & 0xF;
952 }
953 let t = NameTable::build(Model::Hp49g, &rom);
954 assert_eq!(t.stats().names, 0);
955 assert_eq!(t.unit_markers(), None);
956 assert_eq!(t.command_at(5, &Image(&rom)), None);
957 assert_eq!(NameTable::build(Model::Hp48sx, &[]).stats().libraries, 0);
958 }
959
960 fn shared_tables(headers: usize, commands: usize) -> Vec<u8> {
963 let mut r = vec![0u8; 0x10000];
964 let (th, tl) = (0x2000, 0x3000);
965 put(&mut r, th, 0x02A4E, 5);
966 put(&mut r, th + 5, 90, 5);
967 put(&mut r, th + 90, 5, 5);
969 put(&mut r, tl, 0x02A4E, 5);
970 put(&mut r, tl + 5, 5 + 5 * commands, 5);
971 for k in 0..headers {
972 put(&mut r, 20 * k, 0x700 + (k & 0xFF), 3);
973 put_rel(&mut r, 20 * k + 3, th);
974 put_rel(&mut r, 20 * k + 13, tl);
975 }
976 r
977 }
978
979 #[test]
980 fn crafted_link_tables_are_capped() {
981 let libraries = |h, c| {
982 NameTable::build(Model::Hp48gx, &shared_tables(h, c))
983 .stats()
984 .libraries
985 };
986 assert_eq!(libraries(10, 100), 10);
987 assert_eq!(libraries(MAX_LIBRARIES + 1, 100), 0);
989 assert_eq!(libraries(1, MAX_LIBRARY_COMMANDS + 1), 0);
991 assert_eq!(libraries(1, MAX_LIBRARY_COMMANDS), 1);
992 assert_eq!(libraries(MAX_COMMANDS / 2000 + 1, 2000), 0);
994 }
995
996 #[test]
997 fn unit_markers_from_the_rom_units() {
998 let mut rom = vec![0u8; 0x2000];
999 let block = 0x400;
1000 for k in 0..5 {
1001 rom[block + 10 * k..block + 10 * k + 10].copy_from_slice(&EMPTY_LIST);
1002 }
1003 let end = block + 40;
1004 for (u, last) in [(0x800, end), (0x900, end), (0xA00, end), (0xB00, 0x1234)] {
1006 put(&mut rom, u, 0x02ADA, 5);
1007 put(&mut rom, u + 5, 0x2A2C9, 5);
1008 put(&mut rom, u + 10, 0x02A2C, 5);
1009 put(&mut rom, u + 15, 7, 5);
1010 put(&mut rom, u + 20, 0x6D, 2);
1011 put(&mut rom, u + 22, last, 5);
1012 put(&mut rom, u + 27, SEMI as usize, 5);
1013 }
1014 let m = NameTable::build(Model::Hp48sx, &rom)
1015 .unit_markers()
1016 .unwrap();
1017 assert_eq!(
1018 (m.times, m.divide, m.power, m.prefix, m.end),
1019 (0x400, 0x40A, 0x414, 0x41E, 0x428)
1020 );
1021 }
1022}