Skip to main content

hexicon_vm/
rebuild.rs

1//! Writing the program back out as an image, after it has run to set
2//! itself up: preinitialization.
3//!
4//! A build runs a program once before it writes the final image
5//! (preinitialization), and the image it writes is the program as that run left it: every object the program
6//! can still reach, in the image's own format, with the strings and
7//! lists among them made constants. The code and the constants the image
8//! had are kept, but for the code that only ran before the program
9//! started, which is gone with the list of what it was for.
10//!
11//! This follows the reference's rewriter step by step,
12//! so that the image is the same, byte for byte, for the same state.
13
14use std::collections::HashMap;
15
16use crate::error::{ErrParam, VmError, VmResult, code};
17use crate::meta::MetaKind;
18use crate::object::Object;
19use crate::value::{ObjId, Value};
20use crate::vm::Vm;
21
22/// An image, as the rewriter writes it.
23#[derive(Debug, Clone, Default)]
24pub struct RebuiltImage {
25    /// The image file.
26    pub bytes: Vec<u8>,
27    /// Stretches of it, as offset and length, that mean nothing: the
28    /// value bytes of `nil` and `true`, and the half of a property ID's
29    /// four bytes that it does not use. The reference writes them as
30    /// its memory had them.
31    pub unspecified: Vec<(usize, usize)>,
32}
33
34/// The size of the file header: the signature, the version, the
35/// compiler's own 32 bytes, and the time stamp.
36const HEADER_SIZE: usize = 11 + 2 + 32 + 24;
37
38/// The most data an object block holds before another is started.
39const OBJS_BLOCK_LIMIT: usize = 64000;
40
41/// Where the constants made of strings and lists go: new pages after
42/// the image's own, each item on one page.
43struct ConstMapper {
44    page_size: usize,
45    first_page: usize,
46    base: usize,
47    next_free: usize,
48    rem: usize,
49    /// Each object made a constant: its address in the pool.
50    addrs: HashMap<ObjId, u32>,
51    /// The pages, and how much of each is used.
52    pages: Vec<(Vec<u8>, usize)>,
53    /// For each page, the stretches that mean nothing.
54    page_unspecified: Vec<Vec<(usize, usize)>>,
55}
56
57impl ConstMapper {
58    fn new(page_size: usize, page_count: usize) -> Self {
59        let base = page_size * page_count;
60        Self {
61            page_size,
62            first_page: page_count,
63            base,
64            next_free: base,
65            rem: page_size,
66            addrs: HashMap::new(),
67            pages: Vec::new(),
68            page_unspecified: Vec::new(),
69        }
70    }
71
72    /// The address of an object made a constant. The reference cannot
73    /// tell an address of zero from none.
74    fn addr(&self, id: ObjId) -> Option<u32> {
75        self.addrs.get(&id).copied().filter(|&addr| addr != 0)
76    }
77
78    fn reserve(&mut self, id: ObjId, len: usize) {
79        // What does not fit on a page stays an object.
80        if len > self.page_size {
81            return;
82        }
83        if len > self.rem {
84            self.next_free += self.rem;
85            self.rem = self.page_size;
86        }
87        self.addrs.insert(id, self.next_free as u32);
88        self.next_free += len;
89        self.rem -= len;
90    }
91
92    fn prepare_to_store(&mut self) {
93        let used = self.next_free - self.base;
94        let count = used.div_ceil(self.page_size.max(1));
95        self.pages = (0..count).map(|_| (vec![0; self.page_size], 0)).collect();
96        self.page_unspecified = vec![Vec::new(); count];
97    }
98
99    fn store(&mut self, id: ObjId, data: &Data) {
100        let Some(addr) = self.addr(id) else {
101            return;
102        };
103        let at = addr as usize - self.base;
104        let (page, ofs) = (at / self.page_size, at % self.page_size);
105        let (bytes, used) = &mut self.pages[page];
106        bytes[ofs..ofs + data.bytes.len()].copy_from_slice(&data.bytes);
107        *used = (*used).max(ofs + data.bytes.len());
108        self.page_unspecified[page]
109            .extend(data.unspecified.iter().map(|&(at, len)| (ofs + at, len)));
110    }
111}
112
113/// An image file as the rewriter writes it, with the stretches that
114/// mean nothing.
115#[derive(Default)]
116struct ImageOut {
117    out: Vec<u8>,
118    unspecified: Vec<(usize, usize)>,
119}
120
121impl ImageOut {
122    fn u16(&mut self, value: usize) {
123        self.out.extend_from_slice(&(value as u16).to_le_bytes());
124    }
125
126    fn u32(&mut self, value: u32) {
127        self.out.extend_from_slice(&value.to_le_bytes());
128    }
129
130    /// A block: its type, its size, and its flags (1 for one the VM
131    /// has to understand).
132    fn block(&mut self, kind: &[u8; 4], data: &[u8], unspecified: &[(usize, usize)]) {
133        self.out.extend_from_slice(kind);
134        self.u32(data.len() as u32);
135        self.u16(1);
136        let at = self.out.len();
137        self.unspecified
138            .extend(unspecified.iter().map(|&(ofs, len)| (at + ofs, len)));
139        self.out.extend_from_slice(data);
140    }
141}
142
143/// Data for an object or a block, with the stretches that mean nothing.
144#[derive(Default)]
145struct Data {
146    bytes: Vec<u8>,
147    unspecified: Vec<(usize, usize)>,
148}
149
150impl Data {
151    fn u8(&mut self, value: u8) {
152        self.bytes.push(value);
153    }
154
155    fn u16(&mut self, value: usize) {
156        self.bytes.extend_from_slice(&(value as u16).to_le_bytes());
157    }
158
159    fn u32(&mut self, value: u32) {
160        self.bytes.extend_from_slice(&value.to_le_bytes());
161    }
162
163    fn raw(&mut self, bytes: &[u8]) {
164        self.bytes.extend_from_slice(bytes);
165    }
166
167    /// A value as five bytes. `nil` and `true` have no value, and a
168    /// property ID is two bytes of the four.
169    fn value(&mut self, value: Value) {
170        let at = self.bytes.len();
171        match value {
172            Value::Nil | Value::True | Value::Empty => self.unspecified.push((at + 1, 4)),
173            Value::Prop(_) => self.unspecified.push((at + 3, 2)),
174            _ => {}
175        }
176        self.bytes.extend_from_slice(&value.to_holder());
177    }
178
179    /// Another's data appended, with its stretches.
180    fn append(&mut self, other: Data) {
181        let at = self.bytes.len();
182        self.unspecified.extend(
183            other
184                .unspecified
185                .into_iter()
186                .map(|(ofs, len)| (at + ofs, len)),
187        );
188        self.bytes.extend(other.bytes);
189    }
190}
191
192/// What the rewriter needs of the image it was given: where its blocks
193/// are.
194struct Block<'a> {
195    kind: [u8; 4],
196    header: &'a [u8],
197    data: &'a [u8],
198    /// Where the block starts in the image.
199    at: usize,
200}
201
202fn blocks(image: &[u8]) -> VmResult<Vec<Block<'_>>> {
203    let bad = || VmError::new(code::NOT_AN_IMAGE_FILE);
204    let mut out = Vec::new();
205    let mut at = HEADER_SIZE;
206    while at + 10 <= image.len() {
207        let header = &image[at..at + 10];
208        let size = u32::from_le_bytes([header[4], header[5], header[6], header[7]]) as usize;
209        let data = image.get(at + 10..at + 10 + size).ok_or_else(bad)?;
210        let kind = [header[0], header[1], header[2], header[3]];
211        out.push(Block {
212            kind,
213            header,
214            data,
215            at,
216        });
217        at += 10 + size;
218        if &kind == b"EOF " {
219            break;
220        }
221    }
222    Ok(out)
223}
224
225impl Vm {
226    /// Give the program the compiler's table of global symbols and of
227    /// macros, for `globalSymbols`, as the compiler does for a
228    /// program it runs before writing the image. The order is the
229    /// order of the tables the program sees.
230    pub fn set_runtime_symbols(
231        &mut self,
232        symbols: Vec<hexicon_image::GlobalSymbol>,
233        macros: Vec<hexicon_image::Macro>,
234    ) {
235        self.debug.global_symbols = symbols;
236        self.debug.macros = macros;
237    }
238
239    /// Run the program as it is run before its image is written: with
240    /// `inPreinit()` true, and with the arguments given.
241    pub fn run_preinit(&mut self, args: &[String]) -> VmResult<()> {
242        self.preinit_mode = true;
243        let result = self.run(args);
244        self.preinit_mode = false;
245        result
246    }
247
248    /// Write the program as it now stands as an image, given the image
249    /// it was loaded from. This is what the reference does after
250    /// preinitialization.
251    pub fn rewrite_image(&mut self, original: &[u8]) -> VmResult<RebuiltImage> {
252        self.rewrite_image_keeping(original, &[])
253    }
254
255    /// The same, given the stretches of the image it was loaded from
256    /// that mean nothing: those in the parts that are copied are
257    /// carried over to where the parts go.
258    pub fn rewrite_image_keeping(
259        &mut self,
260        original: &[u8],
261        unspecified: &[(usize, usize)],
262    ) -> VmResult<RebuiltImage> {
263        if original.len() < HEADER_SIZE {
264            return Err(VmError::new(code::NOT_AN_IMAGE_FILE));
265        }
266        let blocks = blocks(original)?;
267
268        // What the image's pools are like, and where the code that only
269        // runs before the program starts begins.
270        let mut const_pages = (0usize, 0usize);
271        let mut static_code_offset = 0u32;
272        for block in &blocks {
273            match &block.kind {
274                b"CPDF" if block.data.len() >= 10 => {
275                    let pool = u16::from_le_bytes([block.data[0], block.data[1]]);
276                    let count = u32::from_le_bytes(block.data[2..6].try_into().unwrap());
277                    let size = u32::from_le_bytes(block.data[6..10].try_into().unwrap());
278                    if pool == 2 {
279                        const_pages = (count as usize, size as usize);
280                    }
281                }
282                b"SINI" if block.data.len() >= 8 => {
283                    static_code_offset = u32::from_le_bytes(block.data[4..8].try_into().unwrap());
284                }
285                _ => {}
286            }
287        }
288
289        // A time zone is written with its offsets as of now.
290        self.note_save_time();
291
292        // Nothing is left to undo, and nothing on the stack: what is
293        // still reachable is what goes in the image.
294        self.objects.drop_undo();
295        self.stack.clear();
296        self.frames.clear();
297        self.symbol_table = None;
298        self.macro_table = None;
299        self.collect_garbage(false);
300        let ids: Vec<ObjId> = self.objects.ids().collect();
301        for &id in &ids {
302            if let Some(kind) = self.kind_of(id) {
303                self.meta.add_if_new(kind);
304            }
305        }
306
307        // The strings and lists become constants, where they fit on a
308        // page; and every value that is one of them becomes the
309        // constant.
310        let (page_count, page_size) = const_pages;
311        let mut mapper = ConstMapper::new(page_size, page_count);
312        for &id in &ids {
313            match self.objects.get(id) {
314                Some(Object::String(text)) => mapper.reserve(id, 2 + text.len()),
315                Some(Object::List(items)) => {
316                    mapper.reserve(id, 2 + items.len() * Value::HOLDER_SIZE);
317                }
318                _ => {}
319            }
320        }
321        mapper.prepare_to_store();
322        for &id in &ids {
323            self.convert_to_const(id, &mut mapper)?;
324        }
325
326        // The new image: the header, and the blocks of the old one but
327        // for the objects, the classes, and the static initializers,
328        // which are written anew; and the code that ran before the
329        // program started, which is gone.
330        let mut out = ImageOut::default();
331        // What means nothing in a part that is copied as it is.
332        let copy_unspecified = |out: &mut ImageOut, from: usize, len: usize| {
333            let to = out.out.len();
334            for &(ofs, size) in unspecified {
335                if ofs >= from && ofs + size <= from + len {
336                    out.unspecified.push((ofs - from + to, size));
337                }
338            }
339        };
340        copy_unspecified(&mut out, 0, HEADER_SIZE);
341        out.out.extend_from_slice(&original[..HEADER_SIZE]);
342        let mut code_page_size = 0usize;
343        let mut xor_mask = 0xEFu8;
344        for block in &blocks {
345            match &block.kind {
346                b"OBJS" | b"MCLD" | b"SINI" => {}
347                b"CPDF" => {
348                    let mut data = block.data.to_vec();
349                    let pool = u16::from_le_bytes([data[0], data[1]]);
350                    let size = u32::from_le_bytes(data[6..10].try_into().unwrap());
351                    if pool == 2 {
352                        let count = page_count + mapper.pages.len();
353                        data[2..6].copy_from_slice(&(count as u32).to_le_bytes());
354                    }
355                    if pool == 1 && static_code_offset != 0 {
356                        let count = static_code_offset / size;
357                        data[2..6].copy_from_slice(&count.to_le_bytes());
358                        code_page_size = size as usize;
359                    }
360                    out.out.extend_from_slice(block.header);
361                    out.out.extend_from_slice(&data);
362                }
363                b"CPPG" => {
364                    let pool = u16::from_le_bytes([block.data[0], block.data[1]]);
365                    let index = u32::from_le_bytes(block.data[2..6].try_into().unwrap()) as usize;
366                    if pool == 2 {
367                        xor_mask = block.data[6];
368                    }
369                    let gone = pool == 1
370                        && static_code_offset != 0
371                        && index * code_page_size >= static_code_offset as usize;
372                    if !gone {
373                        copy_unspecified(&mut out, block.at, 10 + block.data.len());
374                        out.out.extend_from_slice(block.header);
375                        out.out.extend_from_slice(block.data);
376                    }
377                }
378                b"EOF " => {
379                    self.write_meta_table(&mut out);
380                    self.write_objects(&ids, &mapper, &mut out)?;
381                    for (index, (bytes, used)) in mapper.pages.iter().enumerate() {
382                        let mut data = Vec::with_capacity(7 + used);
383                        data.extend_from_slice(&2u16.to_le_bytes());
384                        data.extend_from_slice(&((mapper.first_page + index) as u32).to_le_bytes());
385                        data.push(xor_mask);
386                        data.extend(bytes[..*used].iter().map(|byte| byte ^ xor_mask));
387                        let unspecified: Vec<(usize, usize)> = mapper.page_unspecified[index]
388                            .iter()
389                            .map(|&(at, len)| (7 + at, len))
390                            .collect();
391                        out.block(b"CPPG", &data, &unspecified);
392                    }
393                    out.out.extend_from_slice(block.header);
394                    out.out.extend_from_slice(block.data);
395                }
396                _ => {
397                    copy_unspecified(&mut out, block.at, 10 + block.data.len());
398                    out.out.extend_from_slice(block.header);
399                    out.out.extend_from_slice(block.data);
400                }
401            }
402        }
403        Ok(RebuiltImage {
404            bytes: out.out,
405            unspecified: out.unspecified,
406        })
407    }
408
409    /// Make the values in an object that are strings and lists made
410    /// constants into the constants; and store a string or a list made
411    /// one.
412    fn convert_to_const(&mut self, id: ObjId, mapper: &mut ConstMapper) -> VmResult<()> {
413        let to_const = |value: Value, objects: &crate::object::ObjectTable| -> Value {
414            let Value::Obj(target) = value else {
415                return value;
416            };
417            let Some(addr) = mapper.addr(target) else {
418                return value;
419            };
420            match objects.get(target) {
421                Some(Object::String(_)) => Value::SString(addr),
422                Some(Object::List(_)) => Value::List(addr),
423                _ => value,
424            }
425        };
426        // The new values, worked out first, as the table is borrowed.
427        let mut store: Option<Data> = None;
428        let replacement: Option<Object> = match self.objects.get(id) {
429            Some(Object::Program(obj) | Object::IntClassMod(obj)) => {
430                let changes: Vec<(u16, Value)> = obj
431                    .props()
432                    .iter()
433                    .filter(|entry| entry.modified && !matches!(entry.value, Value::Empty))
434                    .filter_map(|entry| {
435                        let new = to_const(entry.value, &self.objects);
436                        (new != entry.value).then_some((entry.prop, new))
437                    })
438                    .collect();
439                if !changes.is_empty() {
440                    let mut object = self.objects.get(id).cloned().expect("the object");
441                    if let Object::Program(obj) | Object::IntClassMod(obj) = &mut object {
442                        for (prop, value) in changes {
443                            obj.set_value_in_place(prop, value);
444                        }
445                    }
446                    Some(object)
447                } else {
448                    None
449                }
450            }
451            Some(Object::List(items)) => {
452                let items: Vec<Value> = items.iter().map(|&v| to_const(v, &self.objects)).collect();
453                let mut data = Data::default();
454                data.u16(items.len());
455                for &item in &items {
456                    data.value(item);
457                }
458                store = Some(data);
459                Some(Object::List(items.into()))
460            }
461            Some(Object::String(text)) => {
462                let mut data = Data::default();
463                data.u16(text.len());
464                data.raw(text);
465                store = Some(data);
466                None
467            }
468            Some(Object::Vector(items)) => Some(Object::Vector(
469                items.iter().map(|&v| to_const(v, &self.objects)).collect(),
470            )),
471            Some(Object::AnonFn(items)) => Some(Object::AnonFn(
472                items.iter().map(|&v| to_const(v, &self.objects)).collect(),
473            )),
474            Some(Object::Map(table)) => {
475                let mut table = table.clone();
476                table.map_values(|value| to_const(value, &self.objects));
477                Some(Object::Map(table))
478            }
479            Some(Object::IndexedIter {
480                collection,
481                current,
482                first,
483                last,
484            }) => Some(Object::IndexedIter {
485                collection: to_const(*collection, &self.objects),
486                current: *current,
487                first: *first,
488                last: *last,
489            }),
490            Some(Object::Pattern { source, compiled }) => Some(Object::Pattern {
491                source: to_const(*source, &self.objects),
492                compiled: compiled.clone(),
493            }),
494            Some(Object::Dict(dictionary)) => {
495                // A dictionary's objects cannot be constants.
496                let fail = |text: &[u8]| {
497                    VmError::with(
498                        code::DICT_NO_CONST,
499                        vec![ErrParam::Str(String::from_utf8_lossy(text).into_owned())],
500                    )
501                };
502                if mapper.addr(dictionary.comparator).is_some() {
503                    return Err(fail(b"<comparator>"));
504                }
505                if let Some(word) = dictionary.words().find(|word| {
506                    word.entries
507                        .iter()
508                        .any(|&(obj, _)| mapper.addr(obj).is_some())
509                }) {
510                    return Err(fail(&word.text));
511                }
512                None
513            }
514            _ => None,
515        };
516        if let Some(object) = replacement {
517            self.objects.replace(id, object);
518        }
519        if let Some(data) = store {
520            mapper.store(id, &data);
521        }
522        Ok(())
523    }
524
525    /// The table of built-in classes: each by the name the image gave
526    /// it, with the properties the image gave its methods.
527    fn write_meta_table(&self, out: &mut ImageOut) {
528        let mut data = Data::default();
529        data.u16(self.meta.len());
530        for index in 0..self.meta.len() {
531            let Some(entry) = self.meta.get(index) else {
532                continue;
533            };
534            let name = entry.image_name.as_bytes();
535            let size = 2 + 1 + name.len() + 2 + 2 + 2 * entry.method_props.len();
536            data.u16(size);
537            data.u8(name.len() as u8);
538            data.raw(name);
539            data.u16(entry.method_props.len());
540            data.u16(2);
541            for &prop in &entry.method_props {
542                data.u16(prop.into());
543            }
544        }
545        out.block(b"MCLD", &data.bytes, &[]);
546    }
547
548    /// The objects, a class at a time in the order of the table of
549    /// classes, those that are saved before those that are not; and in
550    /// a class, in the order of their IDs. A block holds what fits in
551    /// 64,000 bytes, unless an object is larger than 65,535 bytes, which
552    /// starts blocks with a larger size for each object.
553    fn write_objects(
554        &self,
555        ids: &[ObjId],
556        mapper: &ConstMapper,
557        out: &mut ImageOut,
558    ) -> VmResult<()> {
559        let kinds: Vec<Option<MetaKind>> = ids.iter().map(|&id| self.kind_of(id)).collect();
560        for index in 0..self.meta.len() {
561            let Some(entry) = self.meta.get(index) else {
562                continue;
563            };
564            for transient in [false, true] {
565                let mut block = Data::default();
566                let mut count = 0usize;
567                let mut large = false;
568                let finish =
569                    |block: &mut Data, count: &mut usize, large: bool, out: &mut ImageOut| {
570                        if *count == 0 {
571                            return;
572                        }
573                        let mut head = Data::default();
574                        head.u16(*count);
575                        head.u16(index);
576                        head.u16(usize::from(large) | usize::from(transient) << 1);
577                        head.append(std::mem::take(block));
578                        out.block(b"OBJS", &head.bytes, &head.unspecified);
579                        *count = 0;
580                    };
581                for (&id, kind) in ids.iter().zip(&kinds) {
582                    if *kind != Some(entry.kind)
583                        || self.meta.index_of(entry.kind) != Some(index)
584                        || self.objects.is_transient(id) != transient
585                        || mapper.addr(id).is_some()
586                    {
587                        continue;
588                    }
589                    let data = self.image_data(id)?;
590                    if data.bytes.is_empty() {
591                        continue;
592                    }
593                    let size = data.bytes.len();
594                    if size > 65535 && !large {
595                        finish(&mut block, &mut count, large, out);
596                        large = true;
597                    }
598                    if block.bytes.len() + size + 6 > OBJS_BLOCK_LIMIT && count != 0 && !large {
599                        finish(&mut block, &mut count, large, out);
600                    }
601                    block.u32(id.0);
602                    if large {
603                        block.u32(size as u32);
604                    } else {
605                        block.u16(size);
606                    }
607                    block.append(data);
608                    count += 1;
609                }
610                finish(&mut block, &mut count, large, out);
611            }
612        }
613        Ok(())
614    }
615
616    /// An object's data as an image holds it.
617    fn image_data(&self, id: ObjId) -> VmResult<Data> {
618        let mut d = Data::default();
619        let Some(object) = self.objects.get(id) else {
620            return Ok(d);
621        };
622        match object {
623            Object::Program(obj) | Object::IntClassMod(obj) => {
624                // The superclasses, then the properties with values, in
625                // the order of their IDs.
626                let mut props: Vec<(u16, Value)> = obj
627                    .props()
628                    .iter()
629                    .filter(|entry| !matches!(entry.value, Value::Empty))
630                    .map(|entry| (entry.prop, entry.value))
631                    .collect();
632                props.sort_by_key(|(prop, _)| *prop);
633                d.u16(obj.superclasses.len());
634                d.u16(props.len());
635                d.u16(obj.load_flags.into());
636                for superclass in &obj.superclasses {
637                    d.u32(superclass.0);
638                }
639                for (prop, value) in props {
640                    d.u16(prop.into());
641                    d.value(value);
642                }
643            }
644            Object::String(text) => {
645                d.u16(text.len());
646                d.raw(text);
647            }
648            Object::List(items) => {
649                d.u16(items.len());
650                for &item in items.iter() {
651                    d.value(item);
652                }
653            }
654            Object::Vector(items) | Object::AnonFn(items) => {
655                d.u16(self.objects.vector_alloc(id).max(items.len()));
656                d.u16(items.len());
657                for &item in items {
658                    d.value(item);
659                }
660            }
661            Object::IndexedIter {
662                collection,
663                current,
664                first,
665                last,
666            } => {
667                d.value(*collection);
668                d.u32(*current as u32);
669                d.u32(*first as u32);
670                d.u32(*last as u32);
671                d.u32(0);
672            }
673            Object::Map(table) => {
674                let (buckets, slots, first_free) = table.save_parts();
675                d.u16(buckets.len());
676                d.u16(slots.len());
677                d.u16(first_free);
678                for bucket in buckets {
679                    d.u16(bucket);
680                }
681                for (key, value, next) in slots {
682                    d.value(key);
683                    d.value(value);
684                    d.u16(next);
685                }
686                d.value(table.default_value);
687            }
688            Object::MapIter { table, slot } => {
689                d.value(Value::Obj(*table));
690                d.u16(*slot as usize);
691                d.u16(0);
692            }
693            Object::CharSet { name, .. } => {
694                d.u16(name.len());
695                d.raw(name.as_bytes());
696            }
697            Object::FileName(name) => {
698                d.u32(name.special as u32);
699                if name.special == 0 {
700                    d.u16(name.path.len());
701                    d.raw(name.path.as_bytes());
702                }
703            }
704            Object::Date { dayno, daytime } => {
705                d.u32(*dayno as u32);
706                d.u32(*daytime as u32);
707            }
708            Object::TimeZone(zone) => {
709                let (gmtofs, save, abbr, name) = self.zone_saved_form(zone);
710                d.u32(gmtofs as u32);
711                d.u32(save as u32);
712                for text in [name, abbr] {
713                    let text = &text.as_bytes()[..text.len().min(255)];
714                    d.u8(text.len() as u8);
715                    d.raw(text);
716                }
717            }
718            Object::File(file) => {
719                d.u32(file.charset.0);
720                d.u8(file.mode);
721                d.u8(file.access);
722                d.u32(u32::from(file.out_of_sync));
723            }
724            // A temporary file has nothing to keep, and is left out.
725            Object::TempFile(_) => {}
726            Object::StrComp(comparator) => d.raw(&comparator.to_bytes()),
727            Object::GrammarRule(production) => d.raw(&production.to_bytes()),
728            Object::Dict(dictionary) => {
729                d.u32(dictionary.comparator.0);
730                let words: Vec<_> = dictionary.words().collect();
731                d.u16(words.len());
732                for word in words {
733                    let text = &word.text[..word.text.len().min(255)];
734                    d.u8(text.len() as u8);
735                    d.raw(&text.iter().map(|byte| byte ^ 0xBD).collect::<Vec<u8>>());
736                    d.u16(word.entries.len());
737                    for &(obj, prop) in &word.entries {
738                        d.u32(obj.0);
739                        d.u16(prop.into());
740                    }
741                }
742            }
743            Object::ByteArray(bytes) => {
744                d.u32(bytes.len() as u32);
745                d.raw(bytes);
746            }
747            Object::Decimal(big) => {
748                // The fifth byte has the sign and the kind of number in
749                // its low bits; the reference never sets the high ones.
750                d.unspecified.push((d.bytes.len() + 4, 1));
751                d.raw(&big.to_bytes());
752            }
753            // The length of the code, the number of objects it refers
754            // to, the method context, the source, the code, and where in
755            // it each object's number is.
756            Object::FrameRef(fref) => {
757                let vars = self.frame_vars(id).unwrap_or_else(|| fref.vars.clone());
758                d.u16(fref.nlocals);
759                d.u16(fref.nparams);
760                d.value(fref.entry);
761                d.value(fref.self_value);
762                d.u32(fref.definer.0);
763                d.u32(fref.target.0);
764                d.u16(fref.prop.into());
765                d.value(fref.invokee);
766                for index in 0..fref.nlocals + fref.nparams {
767                    d.value(vars.get(index).copied().unwrap_or(Value::Nil));
768                }
769            }
770            Object::FrameDesc(desc) => {
771                d.u32(desc.fref.0);
772                d.u16(desc.scope.into());
773                d.u16(desc.offset.into());
774            }
775            Object::CompiledCode(func) => {
776                d.u16(func.code.len());
777                d.u16(func.obj_refs.len());
778                d.value(func.method_ctx);
779                d.value(func.source);
780                d.raw(&func.code);
781                for &at in &func.obj_refs {
782                    d.u16(usize::from(at));
783                }
784            }
785            Object::StringBuilder(buffer) => {
786                // The room, the step it grows by, the length, and the
787                // characters, each in 16 bits, as the reference keeps them.
788                d.u32(buffer.room);
789                d.u32(buffer.step);
790                d.u32(buffer.len() as u32);
791                for &c in buffer.iter() {
792                    d.u16(u32::from(c) as usize & 0xffff);
793                }
794            }
795            Object::Pattern { source, .. } => d.value(*source),
796            Object::Class(class) => {
797                d.u16(2 + 2 + 4 + Value::HOLDER_SIZE);
798                d.u16(class.meta_index.into());
799                d.u32(class.modifier.0);
800                d.value(class.class_state);
801            }
802            Object::Opaque { data, .. } => d.raw(data),
803        }
804        Ok(d)
805    }
806}