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 {
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 pub fn of(machine: &saturnus_core::Machine) -> NameTable {
257 Self::build(machine.model(), machine.rom_nibbles())
258 }
259
260 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 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 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 pub fn bank(&self) -> Option<usize> {
311 self.bank
312 }
313
314 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 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 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 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 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 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 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 Some(b) => a < 2 * b && t % b == a % b,
414 };
415 same.then_some((lib, c))
416 });
417 self.agreed(candidates)
418 }
419}
420
421fn 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 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 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
488fn 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#[derive(Clone, Copy, Debug)]
499struct Dispatch {
500 ck0: Option<usize>,
501 ck1: usize,
503 stride: usize,
504}
505
506impl Dispatch {
507 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 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 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
554fn first_object(rom: &[u8], t: usize) -> Option<usize> {
556 (f5(rom, t)? == ObjectType::Program.prolog() as usize).then(|| f5(rom, t + 5))?
557}
558
559fn 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 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
595fn 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 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 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 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 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 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 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 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 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 assert_eq!(
829 json(0x1000),
830 serde_json::json!({"type": "command", "name": "SIN", "address": 4096, "library": 2, "command": 0})
831 );
832 assert!(t.command_at(0x1100, &mem).unwrap().silent);
835 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 let cycle = format!("47A20{}B2130", ptr(0x3000));
853 let loose = "8BA2084E2010184E2010288E20B2130";
856 let short = format!("8BA20{}B2130", ptr(0x1040));
857 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 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 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 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 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 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 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 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 assert_eq!(libraries(MAX_LIBRARIES + 1, 100), 0);
981 assert_eq!(libraries(1, MAX_LIBRARY_COMMANDS + 1), 0);
983 assert_eq!(libraries(1, MAX_LIBRARY_COMMANDS), 1);
984 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 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}