stet-core 0.8.0

Core type system, storage, tokenizer, and context for 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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
// stet - A PostScript Interpreter
// Copyright (c) 2026 Scott Bowman
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! PostScript object representation.
//!
//! `PsObject` is the fundamental unit — a tagged value with metadata flags.
//! Objects are `Clone + Copy` (value types with arena indices, not heap references).

/// Packed object metadata (1 byte).
///
/// Layout:
/// - Bits 0-2: access level (0-4)
/// - Bit 3: executable (0=literal, 1=executable)
/// - Bit 4: global (0=local, 1=global)
/// - Bit 5: composite (0=simple, 1=composite)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ObjFlags(u8);

impl ObjFlags {
    pub const LITERAL: u8 = 0;
    pub const EXECUTABLE: u8 = 1 << 3;

    pub const ACCESS_NONE: u8 = 0;
    pub const ACCESS_EXECUTE_ONLY: u8 = 1;
    pub const ACCESS_READ_ONLY: u8 = 2;
    pub const ACCESS_WRITE_ONLY: u8 = 3;
    pub const ACCESS_UNLIMITED: u8 = 4;

    const ACCESS_MASK: u8 = 0b0000_0111;
    const EXEC_BIT: u8 = 1 << 3;
    const GLOBAL_BIT: u8 = 1 << 4;
    const COMPOSITE_BIT: u8 = 1 << 5;
    const DEFERRED_BIT: u8 = 1 << 6;

    /// Create new flags with specified attributes.
    pub fn new(access: u8, executable: bool, global: bool, composite: bool) -> Self {
        let mut bits = access & Self::ACCESS_MASK;
        if executable {
            bits |= Self::EXEC_BIT;
        }
        if global {
            bits |= Self::GLOBAL_BIT;
        }
        if composite {
            bits |= Self::COMPOSITE_BIT;
        }
        Self(bits)
    }

    /// Convenience: literal simple object with unlimited access.
    pub fn literal() -> Self {
        Self::new(Self::ACCESS_UNLIMITED, false, false, false)
    }

    /// Convenience: executable simple object with unlimited access.
    pub fn executable() -> Self {
        Self::new(Self::ACCESS_UNLIMITED, true, false, false)
    }

    /// Convenience: literal composite object with unlimited access.
    pub fn literal_composite() -> Self {
        Self::new(Self::ACCESS_UNLIMITED, false, false, true)
    }

    /// Convenience: executable composite object with unlimited access.
    pub fn executable_composite() -> Self {
        Self::new(Self::ACCESS_UNLIMITED, true, false, true)
    }

    pub fn access(self) -> u8 {
        self.0 & Self::ACCESS_MASK
    }

    pub fn is_executable(self) -> bool {
        self.0 & Self::EXEC_BIT != 0
    }

    pub fn is_literal(self) -> bool {
        !self.is_executable()
    }

    pub fn is_global(self) -> bool {
        self.0 & Self::GLOBAL_BIT != 0
    }

    pub fn is_composite(self) -> bool {
        self.0 & Self::COMPOSITE_BIT != 0
    }

    pub fn set_executable(&mut self) {
        self.0 |= Self::EXEC_BIT;
    }

    pub fn set_literal(&mut self) {
        self.0 &= !Self::EXEC_BIT;
    }

    pub fn set_access(&mut self, access: u8) {
        self.0 = (self.0 & !Self::ACCESS_MASK) | (access & Self::ACCESS_MASK);
    }

    /// Check if this object is deferred (should be pushed to o_stack from e_stack).
    ///
    /// Used by `exec_procedure` to mark nested executable arrays that should be
    /// pushed to the operand stack rather than executed when encountered on the
    /// execution stack. The executable flag remains set so operators like `if`
    /// and `ifelse` still accept them.
    pub fn is_deferred(self) -> bool {
        self.0 & Self::DEFERRED_BIT != 0
    }

    /// Mark this object as deferred.
    pub fn set_deferred(&mut self) {
        self.0 |= Self::DEFERRED_BIT;
    }

    /// Clear the deferred flag.
    pub fn clear_deferred(&mut self) {
        self.0 &= !Self::DEFERRED_BIT;
    }

    /// Require read access (>= READ_ONLY). Returns InvalidAccess if not.
    #[inline]
    pub fn require_read(self) -> Result<(), crate::error::PsError> {
        if self.access() >= Self::ACCESS_READ_ONLY {
            Ok(())
        } else {
            Err(crate::error::PsError::InvalidAccess)
        }
    }

    /// Require write access (>= UNLIMITED) for non-file composites. Returns InvalidAccess if not.
    #[inline]
    pub fn require_write(self) -> Result<(), crate::error::PsError> {
        if self.access() >= Self::ACCESS_UNLIMITED {
            Ok(())
        } else {
            Err(crate::error::PsError::InvalidAccess)
        }
    }

    /// Require file write access (>= WRITE_ONLY). Returns InvalidAccess if not.
    #[inline]
    pub fn require_file_write(self) -> Result<(), crate::error::PsError> {
        if self.access() >= Self::ACCESS_WRITE_ONLY {
            Ok(())
        } else {
            Err(crate::error::PsError::InvalidAccess)
        }
    }
}

/// Index into the name interning table.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NameId(pub u32);

/// Index into an arena store (strings, arrays, dicts, loop states).
///
/// Bit 31 is the global VM tag: set = global, clear = local.
/// Bits 0-30 are the index into the store's entity table.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct EntityId(pub u32);

impl EntityId {
    const GLOBAL_BIT: u32 = 1 << 31;
    const INDEX_MASK: u32 = !(1 << 31);

    /// Create a local VM entity ID.
    pub fn local(index: u32) -> Self {
        debug_assert!(
            index & Self::GLOBAL_BIT == 0,
            "index overflows into tag bit"
        );
        EntityId(index)
    }

    /// Create a global VM entity ID.
    pub fn global(index: u32) -> Self {
        debug_assert!(
            index & Self::GLOBAL_BIT == 0,
            "index overflows into tag bit"
        );
        EntityId(index | Self::GLOBAL_BIT)
    }

    /// Check if this entity is in global VM.
    #[inline]
    pub fn is_global(self) -> bool {
        self.0 & Self::GLOBAL_BIT != 0
    }

    /// Get the raw index (bits 0-30) for indexing into a store's entity table.
    #[inline]
    pub fn raw_index(self) -> usize {
        (self.0 & Self::INDEX_MASK) as usize
    }
}

/// Index into the operator dispatch table.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct OpCode(pub u16);

/// Save/restore nesting level.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SaveLevel(pub u32);

/// The value payload of a PostScript object.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PsValue {
    // Simple types (no arena allocation)
    Null,
    Mark,
    /// Dict mark from `<<` — distinguished from `Mark` so `]` only matches `[`-marks.
    DictMark,
    Bool(bool),
    /// A PostScript integer.
    ///
    /// 64-bit, matching Ghostscript. PLRM Appendix B's 32-bit range is stated
    /// as a limit "typical of PostScript implementations from Adobe Systems"
    /// running "on 32-bit machines", which "do not necessarily apply to all
    /// PostScript implementations" — not a conformance requirement. 32 bits
    /// breaks the standard LCG idiom
    /// (`seed 1103515245 mul 12345 add 2147483648 mod`) that PostScript
    /// programs use for pseudo-randomness: the product overflows, promotes to
    /// `Real`, and `mod` then raises `typecheck`. Widening the fallback is not
    /// an option — the product needs 55 bits and `f64` carries 53, so the
    /// sequence would silently diverge from every other interpreter.
    ///
    /// Costs nothing: `Real(f64)` already forces an 8-byte payload.
    Int(i64),
    Real(f64),

    // Interned name (index into NameTable)
    Name(NameId),

    // Composite types (arena-backed)
    String {
        entity: EntityId,
        start: u32,
        len: u32,
    },
    Array {
        entity: EntityId,
        start: u32,
        len: u32,
    },
    PackedArray {
        entity: EntityId,
        start: u32,
        len: u32,
    },
    Dict(EntityId),

    // Executable types
    Operator(OpCode),

    // Special types
    File(EntityId),
    Save(SaveLevel),
    FontID(i32),
    /// Gstate object (index into Context.gstate_store)
    Gstate(u32),

    // Control flow (internal, not user-visible)
    Stopped,
    Loop(EntityId),
    HardReturn,
    /// Marker that conditionally pops the dict stack when reached (used by
    /// resource operators to clean up after dispatching to PS-defined category
    /// procedures). Carries the expected entity so we only pop if it's still
    /// on top — the PS procedure may have already called `end`.
    DictEnd(EntityId),

    /// Procedure cursor on the exec stack — tracks position within a procedure
    /// being executed. The eval loop advances `pos` one element at a time.
    ExecArray {
        entity: EntityId,
        start: u32,
        len: u32,
        pos: u32,
    },
}

/// A PostScript object: a tagged value with metadata flags.
///
/// `PsObject` is `Clone + Copy` — it's a value type containing indices
/// into arena stores, not heap references.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PsObject {
    pub value: PsValue,
    pub flags: ObjFlags,
}

impl PsObject {
    // --- Convenience constructors ---

    /// Build an integer object.
    ///
    /// Generic over anything that widens losslessly to `i64` so the many
    /// `i32`/`u8`/`u16` call sites need no cast.
    pub fn int(v: impl Into<i64>) -> Self {
        let v: i64 = v.into();
        Self {
            value: PsValue::Int(v),
            flags: ObjFlags::literal(),
        }
    }

    pub fn real(v: f64) -> Self {
        Self {
            value: PsValue::Real(v),
            flags: ObjFlags::literal(),
        }
    }

    pub fn bool(v: bool) -> Self {
        Self {
            value: PsValue::Bool(v),
            flags: ObjFlags::literal(),
        }
    }

    pub fn null() -> Self {
        Self {
            value: PsValue::Null,
            flags: ObjFlags::literal(),
        }
    }

    pub fn mark() -> Self {
        Self {
            value: PsValue::Mark,
            flags: ObjFlags::literal(),
        }
    }

    /// Dict mark from `<<` — distinct from `[`/`mark` marks.
    pub fn dict_mark() -> Self {
        Self {
            value: PsValue::DictMark,
            flags: ObjFlags::literal(),
        }
    }

    /// Literal name: `/foo`
    pub fn name_lit(id: NameId) -> Self {
        Self {
            value: PsValue::Name(id),
            flags: ObjFlags::literal(),
        }
    }

    /// Executable name: `foo`
    pub fn name_exec(id: NameId) -> Self {
        Self {
            value: PsValue::Name(id),
            flags: ObjFlags::executable(),
        }
    }

    pub fn operator(op: OpCode) -> Self {
        Self {
            value: PsValue::Operator(op),
            flags: ObjFlags::executable(),
        }
    }

    /// Literal string.
    pub fn string(entity: EntityId, len: u32) -> Self {
        Self {
            value: PsValue::String {
                entity,
                start: 0,
                len,
            },
            flags: ObjFlags::literal_composite(),
        }
    }

    /// Literal array.
    pub fn array(entity: EntityId, len: u32) -> Self {
        Self {
            value: PsValue::Array {
                entity,
                start: 0,
                len,
            },
            flags: ObjFlags::literal_composite(),
        }
    }

    /// Executable array (procedure body).
    pub fn procedure(entity: EntityId, len: u32) -> Self {
        Self {
            value: PsValue::Array {
                entity,
                start: 0,
                len,
            },
            flags: ObjFlags::executable_composite(),
        }
    }

    /// Dict object.
    pub fn dict(entity: EntityId) -> Self {
        Self {
            value: PsValue::Dict(entity),
            flags: ObjFlags::literal_composite(),
        }
    }

    /// Stopped marker (internal).
    pub fn stopped_mark() -> Self {
        Self {
            value: PsValue::Stopped,
            flags: ObjFlags::executable(),
        }
    }

    /// Loop marker (internal).
    pub fn loop_mark(entity: EntityId) -> Self {
        Self {
            value: PsValue::Loop(entity),
            flags: ObjFlags::executable(),
        }
    }

    /// HardReturn marker (internal).
    pub fn hard_return() -> Self {
        Self {
            value: PsValue::HardReturn,
            flags: ObjFlags::executable(),
        }
    }

    /// DictEnd marker (internal) — conditionally pops the dict stack when reached.
    pub fn dict_end(entity: EntityId) -> Self {
        Self {
            value: PsValue::DictEnd(entity),
            flags: ObjFlags::executable(),
        }
    }

    // --- Type queries ---

    pub fn is_numeric(&self) -> bool {
        matches!(self.value, PsValue::Int(_) | PsValue::Real(_))
    }

    pub fn is_int(&self) -> bool {
        matches!(self.value, PsValue::Int(_))
    }

    pub fn is_real(&self) -> bool {
        matches!(self.value, PsValue::Real(_))
    }

    pub fn is_bool(&self) -> bool {
        matches!(self.value, PsValue::Bool(_))
    }

    pub fn is_array_type(&self) -> bool {
        matches!(
            self.value,
            PsValue::Array { .. } | PsValue::PackedArray { .. }
        )
    }

    pub fn is_composite(&self) -> bool {
        self.flags.is_composite()
    }

    /// Check if this object is in global VM using authoritative entity tag bits
    /// for composite types, falling back to ObjFlags for simple types.
    pub fn is_global_vm(&self) -> bool {
        match self.value {
            PsValue::Dict(e) => e.is_global(),
            PsValue::Array { entity, .. } | PsValue::PackedArray { entity, .. } => {
                entity.is_global()
            }
            PsValue::String { entity, .. } => entity.is_global(),
            _ => self.flags.is_global(),
        }
    }

    /// PostScript type name as bytes (e.g. `b"integertype"`).
    pub fn type_name(&self) -> &'static [u8] {
        match self.value {
            PsValue::Int(_) => b"integertype",
            PsValue::Real(_) => b"realtype",
            PsValue::Bool(_) => b"booleantype",
            PsValue::Null => b"nulltype",
            PsValue::Mark | PsValue::DictMark => b"marktype",
            PsValue::Name(_) => b"nametype",
            PsValue::String { .. } => b"stringtype",
            PsValue::Array { .. } => b"arraytype",
            PsValue::PackedArray { .. } => b"packedarraytype",
            PsValue::Dict(_) => b"dicttype",
            PsValue::Operator(_) => b"operatortype",
            PsValue::File(_) => b"filetype",
            PsValue::Save(_) => b"savetype",
            PsValue::FontID(_) => b"fonttype",
            PsValue::Gstate(_) => b"gstatetype",
            _ => b"nulltype", // internal types
        }
    }

    // --- Numeric extraction ---

    /// Extract as `f64` (works for both Int and Real).
    pub fn as_f64(&self) -> Option<f64> {
        match self.value {
            PsValue::Int(v) => Some(v as f64),
            PsValue::Real(v) => Some(v),
            _ => None,
        }
    }

    /// Extract as `i32` (Int only), rejecting values outside `i32` range.
    ///
    /// PostScript integers are `i64` (see [`PsValue::Int`]), but many callers
    /// need an `i32` — array and string indices, character codes, operand
    /// counts. Those are all genuinely bounded, and a value too large to be
    /// one of them should fail the caller's range check rather than wrap
    /// silently, so this returns `None` instead of truncating.
    pub fn as_i32(&self) -> Option<i32> {
        match self.value {
            PsValue::Int(v) => i32::try_from(v).ok(),
            _ => None,
        }
    }

    /// Extract as `i64` (Int only) — the full PostScript integer range.
    pub fn as_i64(&self) -> Option<i64> {
        match self.value {
            PsValue::Int(v) => Some(v),
            _ => None,
        }
    }
}

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

    #[test]
    fn test_obj_flags_basic() {
        let f = ObjFlags::new(ObjFlags::ACCESS_UNLIMITED, true, false, true);
        assert_eq!(f.access(), ObjFlags::ACCESS_UNLIMITED);
        assert!(f.is_executable());
        assert!(!f.is_global());
        assert!(f.is_composite());
    }

    #[test]
    fn test_obj_flags_set_literal() {
        let mut f = ObjFlags::executable();
        assert!(f.is_executable());
        f.set_literal();
        assert!(f.is_literal());
    }

    #[test]
    fn test_ps_object_int() {
        let obj = PsObject::int(42);
        assert!(obj.is_int());
        assert!(obj.is_numeric());
        assert!(!obj.is_real());
        assert_eq!(obj.as_i32(), Some(42));
        assert_eq!(obj.as_f64(), Some(42.0));
        assert_eq!(obj.type_name(), b"integertype");
    }

    #[test]
    fn test_ps_object_real() {
        let obj = PsObject::real(2.5);
        assert!(obj.is_real());
        assert!(obj.is_numeric());
        assert_eq!(obj.as_f64(), Some(2.5));
        assert_eq!(obj.as_i32(), None);
        assert_eq!(obj.type_name(), b"realtype");
    }

    #[test]
    fn test_ps_object_copy_semantics() {
        let a = PsObject::int(10);
        let b = a; // Copy
        assert_eq!(a.as_i32(), Some(10));
        assert_eq!(b.as_i32(), Some(10));
    }

    #[test]
    fn test_ps_object_procedure() {
        let obj = PsObject::procedure(EntityId(0), 3);
        assert!(obj.flags.is_executable());
        assert!(obj.flags.is_composite());
        assert!(obj.is_array_type());
    }
}