rustyfi-lang 0.1.4

Abstract syntax tree, elaboration, evaluator, and primitives for SATySFi
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
//! Interpreter state and beta-reduction.
//!
//! Expression evaluation lives entirely in `crate::compile`; what remains
//! here is genuinely runtime: the [`Interp`] state every primitive threads
//! (images, hooks, cross-references, decorations, …), function application,
//! and pattern matching. Follows `evaluator.cppo.ml`'s naive interpreter, not
//! its bytecode VM, which was deliberately not ported.

use crate::ast::{Ast, Pattern};
use crate::crossref::CrossRefs;
use crate::value::{BaseEnv, Env, Value};
use rustyfi_backend::{DocInfo, FontMetrics, ImageResource, MathCmdId};
use rustyfi_syntax::{RustyfiVersion, Span};
use std::cell::RefCell;
use std::rc::Rc;

/// See [`Interp::decos`].
///
/// Each entry records the `interp.version` active when the deco closure was
/// CAPTURED ([`DecoEntry::version`]). Reading `interp.version` at FIRE time
/// instead is wrong: the consumer (`primitives::apply_deco`, called only from
/// `lib.rs`'s post-page-break hook-firing pass) always runs outside every
/// `VersionScope`'s save/restore window, so in a cross-version program the
/// flag there is the ENTRY's generation, never the deco author's — concretely,
/// `uline`, `enumitem` and `figbox` are ordinary 0.0.6 packages with their own
/// 0.0.6 `graphics list` decos; they register while `interp.version` is
/// `V0_0` and get fired while it is `V0_1`, so `coerce_graphics_result`
/// demanded a single `graphics` and got a list.
#[derive(Clone, Debug)]
pub enum DecoEntry {
    Inline {
        deco: Value,
        version: RustyfiVersion,
    },
    Block {
        pads: rustyfi_backend::Paddings,
        /// The frame's OUTER width (the wrapping context's paragraph_width).
        width: rustyfi_backend::Length,
        /// `(decoS, decoH, decoM, decoT)` — evalUtil.ml:169 `get_decoset`.
        decoset: [Value; 4],
        version: RustyfiVersion,
    },
    /// `inline-frame-breakable`'s deco set, behind a
    /// `PureHorzBox::InlineFrameMarker` pair. The inline twin of `Block`
    /// above: the frame may split across LINE breaks rather than page breaks,
    /// so `fire_hooks` picks `decoS`/`decoH`/`decoM`/`decoT` per line
    /// fragment the same way. `pads` is kept for the vertical half only —
    /// `paddingL`/`paddingR` are already spliced into the box stream as
    /// `FixedEmpty` (upstream `append_horz_padding`), so only `t`/`b` are
    /// read back here, to size each fragment's rect.
    InlineBreakable {
        pads: rustyfi_backend::Paddings,
        decoset: [Value; 4],
        version: RustyfiVersion,
    },
}

impl DecoEntry {
    pub fn version(&self) -> RustyfiVersion {
        match self {
            DecoEntry::Inline { version, .. }
            | DecoEntry::Block { version, .. }
            | DecoEntry::InlineBreakable { version, .. } => *version,
        }
    }
}

#[derive(Debug, thiserror::Error)]
#[error("{}{msg}", .span.map(|s| format!("{s}: ")).unwrap_or_default())]
pub struct EvalError {
    pub span: Option<Span>,
    pub msg: String,
}

pub(crate) fn eval_error<T>(msg: impl Into<String>) -> Result<T, EvalError> {
    Err(EvalError {
        span: None,
        msg: msg.into(),
    })
}

/// Comma-separated, sorted field names of a record — the "(available fields:
/// …)" hint shared by the field-access and field-update error messages.
pub(crate) fn available_fields(map: &std::collections::BTreeMap<String, Value>) -> String {
    let mut keys: Vec<&str> = map.keys().map(|s| s.as_str()).collect();
    keys.sort();
    keys.join(", ")
}

/// Which callbacks a walk over placed geometry (`crate::fire_hooks` and the
/// helpers it shares with `page_break_core`) is allowed to invoke.
///
/// Upstream fires both halves in ONE pass, from `ops_of_evaled_vert_box_list`
/// (`handlePdf.ml:336` for `EvVertHookPageBreak`, `:325` for `EvVertFrame`'s
/// deco), and that pass runs per page INSIDE the page loop — page N's body
/// callbacks before page N's own `pagepartsf`. That ordering is load-bearing:
/// `stdjareport`'s `\figure` is a `hook-page-break` that pushes the figure
/// onto a `let-mutable` list which the page-parts callback drains onto a LATER
/// page, so a hook that fires after the loop registers into a list nobody
/// reads again.
///
/// This port cannot fire both halves there, because a decoration's rect needs
/// the frame's per-page top/bottom EXTENT, which is only known once the page's
/// header and footer are placed and the page is complete. So the walk runs
/// twice: `page_break_core` drives a [`FirePass::HooksOnly`] pass per column
/// (upstream's position, `pageBreak.ml:747-748`), and the post-run
/// `fire_hooks` drives a [`FirePass::DecosOnly`] one. Each callback still
/// fires exactly once.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum FirePass {
    /// One undivided pass — every hook and every decoration. What a
    /// hand-built `DocumentValue` handed straight to `fire_hooks` gets.
    #[default]
    All,
    /// `hook-page-break` closures only. Frame decorations are skipped, but
    /// the walk still descends through frames, tabular cells and graphics
    /// runs, so a hook nested in one of them fires here and nowhere else.
    HooksOnly,
    /// Frame decorations, `GraphicsElem::Destination` markers and everything
    /// else the walk records — but not one `hook-page-break`, which the
    /// preceding [`FirePass::HooksOnly`] pass already ran.
    DecosOnly,
}

/// Evaluation state threaded through every primitive: font metrics, images,
/// hooks, cross-references, and the per-trial accumulators below.
pub struct Interp<'a> {
    pub metrics: &'a dyn FontMetrics,
    /// The document-wide image table: `load-image` decodes eagerly and
    /// pushes here, returning the index as `Value::Image`;
    /// `use-image-by-width` looks the resource back up by it. `page-break`
    /// clones this into `DocumentValue::images` (a superset of what actually
    /// ends up placed on a page — the PDF writer itself filters down to the
    /// images a placed line actually references).
    pub images: Vec<ImageResource>,
    /// The document-wide page-break-hook closure table: `hook-page-break`
    /// pushes its closure and returns a `HookId` index
    /// (`PureHorzBox::HookPageBreak`) — the `images`-style seam, but for a
    /// deferred computation. Reset every trial (see `crossrefs`, the one
    /// exception); read back by `fire_hooks` once placement is known.
    pub hooks: Vec<Value>,
    /// Installed-math-command table (`get-initial-context`/
    /// `set-math-command` push here; `Context::math_command` holds the
    /// index) — needed because the backend `Context` cannot hold a lang-side
    /// `Value`. Read back by `read_inline`'s `EmbedMath` arm.
    pub math_commands: Vec<Value>,
    /// The cross-reference table, shared with the compile driver across
    /// every trial of the fixpoint loop — unlike `hooks`/`images`, this must
    /// *not* reset per trial, so the driver clones one `Rc<RefCell<
    /// CrossRefs>>` handle into each trial's fresh `Interp`.
    pub crossrefs: Rc<RefCell<CrossRefs>>,
    /// Accumulators: link annotations / named destinations / outline
    /// entries, plus the per-page deco-graphics overlays. All reset per
    /// trial; the FINAL trial's contents are moved into
    /// `DocumentValue::extras` by `compile_document_cst_with_trials`.
    pub annotations: Vec<rustyfi_backend::Annot>,
    pub destinations: Vec<rustyfi_backend::NamedDest>,
    pub outline: Vec<rustyfi_backend::OutlineEntry>,
    pub page_graphics: Vec<Vec<rustyfi_backend::GraphicsElem>>,
    /// `register-document-information`'s accumulator — LAST WRITE WINS,
    /// same reset-per-trial policy as `outline`/`annotations`/`destinations`.
    pub doc_info: Option<DocInfo>,
    /// `Some(0-based page)` only while a placed-geometry walk is on that page
    /// — the port of upstream's `State.during_page_break` + "current page"
    /// (`annotation.ml:15`, `namedDest.ml`'s `notify_pagebreak`). Both walks
    /// set it: `page_break_core`'s per-page hook pass and `fire_hooks`.
    pub current_page: Option<usize>,
    /// Which half of the placed-geometry walk is running right now. The walk
    /// happens TWICE per trial and each pass must fire exactly one half of it
    /// — see [`FirePass`].
    pub fire_pass: FirePass,
    /// Set by `page_break_core` once it has finished driving its per-page
    /// [`FirePass::HooksOnly`] pass, so the `fire_hooks` call that follows the
    /// page loop knows to run [`FirePass::DecosOnly`] and not fire every
    /// `hook-page-break` a second time. Stays `false` for a `DocumentValue`
    /// assembled by hand (unit tests drive `fire_hooks` directly), which then
    /// runs the undivided [`FirePass::All`].
    pub page_break_hooks_fired: bool,
    /// Links/metadata: the `DecoId` of the deco closure currently
    /// being fired by `fire_hooks`' two `apply_deco` call sites, `None`
    /// outside any such window. This is the STRUCTURAL link between a
    /// placed `Annot`/`NamedDest` (page-absolute, known only
    /// post-page-break) and the `PureHorzBox::Frame`/
    /// `VertBox::FrameStart`/`FrameEnd` marker that produced it in the
    /// PRE-page-break `DocumentValue::reflow_source` — both carry the SAME
    /// `DecoId`, so recording it here (into `link_decos`/`dest_decos`
    /// below) lets the reflow backend resolve "which Frame is this link"
    /// exactly, not by geometry/position.
    pub current_deco_id: Option<rustyfi_backend::DecoId>,
    /// `Some` only while an `inline-graphics` callback is being applied
    /// EAGERLY, outside any page-break window (`apply_graphics_callback`):
    /// `register-destination` appends its `(key, box-local point)` here
    /// instead of erroring, and the caller turns each into a
    /// `GraphicsElem::Destination` marker riding in the resulting box. Left
    /// `None` inside a page-break window, so the direct registration wins
    /// there.
    pub pending_dests: Option<Vec<(String, rustyfi_backend::Point)>>,
    /// One `(DecoId, action)` per `register-link-to-uri`/`-to-location`
    /// call made while `current_deco_id` was `Some`. Reset per trial,
    /// drained into `DocumentValue::reflow_links` by `eval_document_trials`
    /// alongside `extras`.
    pub link_decos: Vec<(rustyfi_backend::DecoId, rustyfi_backend::AnnotAction)>,
    /// Same idea as `link_decos`, for `register-destination`
    /// (`annot.satyh`'s `register-location-frame` idiom): `(DecoId, name)`.
    /// Drained into `DocumentValue::reflow_dests`.
    pub dest_decos: Vec<(rustyfi_backend::DecoId, String)>,
    /// Each block frame's own decoration at its natural size, box-local —
    /// see `rustyfi_backend::FrameDecoration`. Recorded by `fire_hooks` and
    /// drained into `DocumentValue::reflow_frame_decos`, so a renderer with
    /// no page grid can draw the frame the document actually asked for
    /// instead of nothing at all. Unread by the PDF path.
    pub frame_decos: Vec<(rustyfi_backend::DecoId, rustyfi_backend::FrameDecoration)>,
    /// `namedDest.ml`'s key -> "nameddest{N}" sanitizer table: arbitrary
    /// user keys become stable PDF name strings, shared by
    /// register-destination / register-link-to-location / register-outline
    /// within one trial.
    dest_names: std::collections::HashMap<String, String>,
    /// Deco-closure table (`DecoId` indexes here) — `hooks`' twin for
    /// decorations. `Inline` holds one `deco` closure
    /// (`point -> length -> length -> length -> graphics list`); `Block`
    /// holds a block frame's four-closure deco-set + the geometry the
    /// markers can't carry. Reset per trial.
    pub decos: Vec<DecoEntry>,
    /// Deferred `inline-graphics-outer` callbacks (`length -> point ->
    /// graphics list`), indexed by `GraphicsFnId` — the `hooks` pattern.
    /// Each entry also carries the generation it was registered under, for
    /// the same reason [`DecoEntry`] does: the callback's RESULT shape
    /// (`graphics list` vs one `graphics`) is a property of the code that
    /// wrote it, and `primitives::resolve_outer_graphics_in_contents` runs
    /// long after, from a line-breaking post-pass with no version context
    /// of its own.
    pub outer_graphics: Vec<(Value, RustyfiVersion)>,
    /// The target language version this evaluation run is checking against
    /// — consulted only by `read_inline`'s `IText::EmbedMath` FALLBACK arm
    /// (no installed math command; unit-test contexts only). Default
    /// `V0_0`; `lib.rs`'s `eval_document_trials` sets this to the real
    /// target version on every `Interp` it constructs.
    pub version: RustyfiVersion,
}

impl<'a> Interp<'a> {
    pub fn new(metrics: &'a dyn FontMetrics) -> Self {
        Interp {
            metrics,
            images: Vec::new(),
            hooks: Vec::new(),
            math_commands: Vec::new(),
            crossrefs: Rc::new(RefCell::new(CrossRefs::new())),
            annotations: Vec::new(),
            destinations: Vec::new(),
            outline: Vec::new(),
            page_graphics: Vec::new(),
            doc_info: None,
            current_page: None,
            fire_pass: FirePass::All,
            page_break_hooks_fired: false,
            current_deco_id: None,
            pending_dests: None,
            link_decos: Vec::new(),
            dest_decos: Vec::new(),
            frame_decos: Vec::new(),
            dest_names: std::collections::HashMap::new(),
            decos: Vec::new(),
            outer_graphics: Vec::new(),
            version: RustyfiVersion::V0_0,
        }
    }

    /// Evaluate `ast` by compiling it against `env` and running the result.
    ///
    /// A thin shim: ~25 integration tests drive the evaluator through it, and
    /// it is precisely what their compiled counterpart already does — there
    /// is exactly one evaluator, since quoted text is compiled eagerly into
    /// [`crate::quoted`]'s name-free form.
    ///
    /// `base` is the COMPILE-time environment `ast`'s free names resolve
    /// against; the program itself runs in a fresh, empty runtime frame
    /// chain — `base` is NOT that chain's root, because nothing resolves a
    /// name at run time.
    pub fn eval(&mut self, base: &BaseEnv, ast: &Ast) -> Result<Value, EvalError> {
        crate::compile::compile_program(ast, base).run(&Env::root(), self)
    }

    /// Intern an installed math command, returning the handle a `Context`
    /// carries (`Context::math_command`).
    pub fn register_math_command(&mut self, cmd: Value) -> MathCmdId {
        self.math_commands.push(cmd);
        MathCmdId(self.math_commands.len() - 1)
    }

    /// `namedDest.ml:name_from_hash_table` — the stable PDF name for `key`,
    /// minting `nameddest{N}` on first sight. Also used by `register-outline`
    /// (upstream `Outline.make_entry` calls `NamedDest.get`, which mints too).
    pub fn dest_name(&mut self, key: &str) -> String {
        if let Some(n) = self.dest_names.get(key) {
            return n.clone();
        }
        let n = format!("nameddest{}", self.dest_names.len());
        self.dest_names.insert(key.to_string(), n.clone());
        n
    }

    pub fn apply(&mut self, func: Value, arg: Value) -> Result<Value, EvalError> {
        // A plain (0.0.6-shaped) application supplies no optional bundle; a
        // closure that *does* declare optional params defaults every one to
        // `None`, faithful to upstream's `reduce_beta_list`.
        self.apply_with_opts(func, Vec::new(), arg)
    }

    /// Beta-reduce `func` against a positional argument plus a SATySFi 0.1
    /// labeled-optional bundle. For a closure, each of the closure's declared
    /// optional params binds `Some v` when the bundle carries its label, else
    /// `None`; a supplied label the closure does not declare is ignored
    /// (upstream `reduce_beta` folds over the *closure's* map — the
    /// typechecker rejects genuinely-wrong labels first). This
    /// unknown-label-ignore is only sound because typecheck runs first.
    pub fn apply_with_opts(
        &mut self,
        func: Value,
        opt_vals: Vec<(String, Value)>,
        arg: Value,
    ) -> Result<Value, EvalError> {
        match func {
            Value::CompiledClosure {
                opt_labels,
                body,
                env,
            } => {
                // Slot order: declared optional binders, then the positional
                // parameter — what `Ast::LambdaOpt` pushed onto the
                // compiler's scope stack.
                let mut slots = Vec::with_capacity(opt_labels.len() + 1);
                push_opt_slots(&mut slots, &opt_labels, &opt_vals);
                slots.push(arg);
                body.run(&env.child(slots), self)
            }
            Value::Prim { def, mut applied } => {
                if !opt_vals.is_empty() {
                    return eval_error(
                        "labeled optional arguments to a primitive are roadmap phase 5",
                    );
                }
                applied.push(arg);
                if applied.len() == def.arity {
                    (def.run)(self, applied)
                } else {
                    Ok(Value::Prim { def, applied })
                }
            }
            other => eval_error(format!(
                "cannot apply a value of type {} as a function",
                other.type_name()
            )),
        }
    }
}

/// Append one slot per declared SATySFi 0.1 labeled-optional parameter, in
/// declaration order: `Some v` when `opt_vals` supplies that label, `None`
/// otherwise (upstream `reduce_beta`'s fold over the closure's own label map).
/// See `Interp::apply_with_opts` for why unknown labels are ignored.
fn push_opt_slots(slots: &mut Vec<Value>, opt_labels: &[String], opt_vals: &[(String, Value)]) {
    for label in opt_labels {
        slots.push(match opt_vals.iter().find(|(l, _)| l == label) {
            Some((_, v)) => Value::Ctor("Some".to_string(), Some(Box::new(v.clone()))),
            None => Value::Ctor("None".to_string(), None),
        });
    }
}

/// Structural pattern matching against an already-evaluated scrutinee.
/// Returns `true` (and appends every bound value, POSITIONALLY, in the order
/// they were encountered) on a structural match; returns `false` (leaving
/// `bindings` for this attempt unusable — callers must use a fresh `Vec` per
/// arm) otherwise.
///
/// The push order here is the same left-to-right traversal
/// `compile::pattern_vars` uses to collect the arm's names, so position `i`
/// in `bindings` is slot `i` of the frame the arm runs in — keep the two in
/// step. A pattern/value shape mismatch is simply "no match", never an
/// error: this untyped evaluator relies on the separate exhaustiveness/type
/// checker to rule out ill-typed matches ahead of time.
pub fn match_pattern(pat: &Pattern, value: &Value, bindings: &mut Vec<Value>) -> bool {
    match pat {
        Pattern::Wild => true,
        Pattern::Var(_) => {
            bindings.push(value.clone());
            true
        }
        Pattern::As(inner_pat, _) => {
            if match_pattern(inner_pat, value, bindings) {
                bindings.push(value.clone());
                true
            } else {
                false
            }
        }
        Pattern::Unit => matches!(value, Value::Unit),
        Pattern::Bool(b) => matches!(value, Value::Bool(v) if v == b),
        Pattern::Int(n) => matches!(value, Value::Int(v) if v == n),
        Pattern::Str(s) => matches!(value, Value::Str(v) if v == s),
        Pattern::Tuple(ps) => match value {
            Value::Tuple(vs) if ps.len() == vs.len() => ps
                .iter()
                .zip(vs.iter())
                .all(|(p, v)| match_pattern(p, v, bindings)),
            _ => false,
        },
        Pattern::EmptyList => matches!(value, Value::List(vs) if vs.is_empty()),
        Pattern::Cons(head_pat, tail_pat) => match value {
            Value::List(vs) if !vs.is_empty() => {
                if !match_pattern(head_pat, &vs[0], bindings) {
                    return false;
                }
                let tail = Value::List(vs[1..].to_vec());
                match_pattern(tail_pat, &tail, bindings)
            }
            _ => false,
        },
        Pattern::Ctor(name, parg) => match value {
            Value::Ctor(vname, vpayload) if name == vname => match (parg, vpayload) {
                (None, None) => true,
                (Some(p), Some(v)) => match_pattern(p, v, bindings),
                _ => false,
            },
            _ => false,
        },
    }
}