stet-core 0.8.1

Core type system, arena storage, tokenizer, and VM context for the stet PostScript interpreter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
// stet - A PostScript Interpreter
// Copyright (c) 2026 Scott Bowman
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Save/restore stack for PostScript VM persistence.
//!
//! Implements copy-on-write save/restore: `save` records a level, mutations
//! create COW copies, and `restore` swaps offsets to revert changes.

use crate::graphics_state::{GraphicsState, GstateEntry};
use crate::object::EntityId;

/// Which store type a save record refers to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StoreType {
    String,
    Array,
    Dict,
}

/// Records one COW copy made during a save level.
#[derive(Debug, Clone)]
pub struct SaveRecord {
    /// The original entity that was COW-copied.
    pub src: EntityId,
    /// The backup entity holding the pre-mutation data.
    pub copy: EntityId,
    /// Which store the entities belong to.
    pub store_type: StoreType,
}

/// High-water marks of **local** VM at the moment of a `save`.
///
/// `restore` truncates each local store back to these marks, which is what
/// makes the memory a save level allocated actually available again. Global VM
/// is never affected by save/restore, so it has no marks here.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct VmMarks {
    pub string_data: usize,
    pub string_entities: usize,
    pub array_data: usize,
    pub array_entities: usize,
    pub dict_slots: usize,
    pub dict_entities: usize,
}

/// Interpreter state captured by `save` and reinstated by `restore`.
///
/// Grouped into a struct rather than passed positionally: every field is
/// state the interpreter has to rewind, and the set grows as more of the
/// interpreter learns to participate in save/restore.
pub struct SaveSnapshot {
    /// `d_stack` length at save time (for restore validation).
    pub d_stack_depth: usize,
    /// Packing mode (`setpacking`/`currentpacking`).
    pub packing_mode: bool,
    /// VM allocation mode (`setglobal`/`currentglobal`).
    pub vm_alloc_mode: bool,
    /// Binary object format (`setobjectformat`/`currentobjectformat`).
    pub object_format: i32,
    /// Graphics state and graphics state stack.
    pub gstate: GraphicsState,
    pub gstate_stack: Vec<GstateEntry>,
    /// `Context::gstate_store` length at save time.
    ///
    /// `gstate_store` backs `PsValue::Gstate`, and a `gstate` object is a
    /// composite in local VM, so `restore` has to reclaim the ones created
    /// after the save. Without this the store would grow monotonically and
    /// each stale slot would keep naming entities the restore released.
    pub gstate_store_len: usize,
    /// Local-VM high-water marks, for reclamation on restore.
    pub marks: VmMarks,
}

/// One save level's state.
pub struct SaveLevel {
    /// Numeric level (1-based, 0 = no save active).
    pub level: u16,
    /// Unique save id for invalidation tracking.
    pub save_id: u32,
    /// COW records accumulated during this save level.
    pub records: Vec<SaveRecord>,
    /// Whether this save level is still valid (becomes false on restore).
    pub valid: bool,
    /// Snapshot of d_stack length at save time (for restore validation).
    pub d_stack_depth: usize,
    /// Saved packing mode (`setpacking`/`currentpacking`).
    pub packing_mode: bool,
    /// Saved VM allocation mode (`setglobal`/`currentglobal`).
    pub vm_alloc_mode: bool,
    /// Saved binary object format (`setobjectformat`/`currentobjectformat`).
    pub object_format: i32,
    /// Saved graphics state and graphics state stack.
    pub gstate: GraphicsState,
    pub gstate_stack: Vec<GstateEntry>,
    /// `Context::gstate_store` length at save time.
    ///
    /// `gstate_store` backs `PsValue::Gstate`, and a `gstate` object is a
    /// composite in local VM, so `restore` has to reclaim the ones created
    /// after the save. Without this the store would grow monotonically and
    /// each stale slot would keep naming entities the restore released.
    pub gstate_store_len: usize,
    /// Local-VM high-water marks, for reclamation on restore.
    pub marks: VmMarks,
}

/// The save/restore stack.
pub struct SaveStack {
    levels: Vec<SaveLevel>,
    next_save_id: u32,
}

impl SaveStack {
    /// Create an empty save stack.
    pub fn new() -> Self {
        Self {
            levels: Vec::new(),
            next_save_id: 1,
        }
    }

    /// Push a new save level. Returns `(level, save_id)`.
    pub fn save(&mut self, snapshot: SaveSnapshot) -> (u16, u32) {
        let SaveSnapshot {
            d_stack_depth,
            packing_mode,
            vm_alloc_mode,
            object_format,
            gstate,
            gstate_stack,
            gstate_store_len,
            marks,
        } = snapshot;
        let level = (self.levels.len() + 1) as u16;
        let save_id = self.next_save_id;
        self.next_save_id += 1;
        self.levels.push(SaveLevel {
            level,
            save_id,
            records: Vec::new(),
            valid: true,
            d_stack_depth,
            packing_mode,
            vm_alloc_mode,
            object_format,
            gstate,
            gstate_stack,
            gstate_store_len,
            marks,
        });
        (level, save_id)
    }

    /// Add a COW record to the current save level.
    pub fn add_record(&mut self, record: SaveRecord) {
        if let Some(level) = self.levels.last_mut() {
            level.records.push(record);
        }
    }

    /// Pop the topmost save level, returning its records for restore processing.
    /// Returns `None` if the stack is empty.
    pub fn restore(&mut self) -> Option<SaveLevel> {
        self.levels.pop()
    }

    /// Pop all save levels from `save_id` upward (inclusive), returning them
    /// in stack order (target level first, newest level last).
    /// Per PLRM, `restore` can target any valid save — not just the topmost.
    /// All newer saves are invalidated and their COW records are also returned
    /// so they can be undone.
    pub fn restore_to(&mut self, save_id: u32) -> Option<Vec<SaveLevel>> {
        let idx = self.levels.iter().position(|l| l.save_id == save_id)?;
        let popped: Vec<SaveLevel> = self.levels.drain(idx..).collect();
        Some(popped)
    }

    /// Current save level (0 if no save active).
    pub fn current_level(&self) -> u16 {
        self.levels.last().map(|l| l.level).unwrap_or(0)
    }

    /// Save ID of the most recent save (0 if no save active).
    /// Used for entity creation tracking (invalidrestore).
    pub fn last_save_id(&self) -> u32 {
        self.levels.last().map(|l| l.save_id).unwrap_or(0)
    }

    /// Check if a save_id is valid (exists and not invalidated).
    pub fn is_valid(&self, save_id: u32) -> bool {
        self.levels.iter().any(|l| l.save_id == save_id && l.valid)
    }

    /// Number of active save levels.
    pub fn depth(&self) -> usize {
        self.levels.len()
    }

    /// Read-only access to the levels (for validation checks).
    pub fn levels_ref(&self) -> &[SaveLevel] {
        &self.levels
    }

    /// Invalidate all save levels newer than the given save_id.
    pub fn invalidate_newer(&mut self, save_id: u32) {
        let mut found = false;
        for level in &mut self.levels {
            if found {
                level.valid = false;
            }
            if level.save_id == save_id {
                found = true;
            }
        }
    }
}

impl Default for SaveStack {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_save_and_depth() {
        let mut ss = SaveStack::new();
        assert_eq!(ss.depth(), 0);
        assert_eq!(ss.current_level(), 0);

        let (level, id) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        assert_eq!(level, 1);
        assert_eq!(id, 1);
        assert_eq!(ss.depth(), 1);
        assert_eq!(ss.current_level(), 1);
    }

    #[test]
    fn test_nested_save() {
        let mut ss = SaveStack::new();
        let (l1, _) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        let (l2, _) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        assert_eq!(l1, 1);
        assert_eq!(l2, 2);
        assert_eq!(ss.depth(), 2);
        assert_eq!(ss.current_level(), 2);
    }

    #[test]
    fn test_restore() {
        let mut ss = SaveStack::new();
        let (_, id1) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        ss.add_record(SaveRecord {
            src: EntityId(0),
            copy: EntityId(1),
            store_type: StoreType::String,
        });

        let level = ss.restore().unwrap();
        assert_eq!(level.save_id, id1);
        assert_eq!(level.records.len(), 1);
        assert_eq!(ss.depth(), 0);
    }

    #[test]
    fn test_is_valid() {
        let mut ss = SaveStack::new();
        let (_, id1) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        assert!(ss.is_valid(id1));
        ss.restore();
        assert!(!ss.is_valid(id1));
    }

    #[test]
    fn test_invalidate_newer() {
        let mut ss = SaveStack::new();
        let (_, id1) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        let (_, id2) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        let (_, id3) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });

        ss.invalidate_newer(id1);
        assert!(ss.is_valid(id1));
        assert!(!ss.is_valid(id2));
        assert!(!ss.is_valid(id3));
    }

    #[test]
    fn test_add_record_to_current() {
        let mut ss = SaveStack::new();
        ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        ss.add_record(SaveRecord {
            src: EntityId(0),
            copy: EntityId(1),
            store_type: StoreType::Array,
        });
        ss.add_record(SaveRecord {
            src: EntityId(2),
            copy: EntityId(3),
            store_type: StoreType::Dict,
        });

        let level = ss.restore().unwrap();
        assert_eq!(level.records.len(), 2);
    }

    #[test]
    fn test_restore_empty() {
        let mut ss = SaveStack::new();
        assert!(ss.restore().is_none());
    }

    #[test]
    fn test_d_stack_depth_snapshot() {
        let mut ss = SaveStack::new();
        ss.save(SaveSnapshot {
            d_stack_depth: 5,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        let level = ss.restore().unwrap();
        assert_eq!(level.d_stack_depth, 5);
    }

    #[test]
    fn test_unique_save_ids() {
        let mut ss = SaveStack::new();
        let (_, id1) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        let (_, id2) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        ss.restore();
        let (_, id3) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        assert_ne!(id1, id2);
        assert_ne!(id2, id3);
        assert_ne!(id1, id3);
    }

    #[test]
    fn test_save_level_numbers() {
        let mut ss = SaveStack::new();
        let (l1, _) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        let (l2, _) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        ss.restore();
        // After restoring level 2, next save should be level 2 again
        let (l3, _) = ss.save(SaveSnapshot {
            d_stack_depth: 3,
            packing_mode: false,
            vm_alloc_mode: false,
            object_format: 0,
            gstate: GraphicsState::new(),
            gstate_stack: Vec::new(),
            gstate_store_len: 0,
            marks: VmMarks::default(),
        });
        assert_eq!(l1, 1);
        assert_eq!(l2, 2);
        assert_eq!(l3, 2);
    }
}