Skip to main content

rustyfi_lang/
eval.rs

1//! Interpreter state and beta-reduction.
2//!
3//! Expression evaluation lives entirely in `crate::compile`; what remains
4//! here is genuinely runtime: the [`Interp`] state every primitive threads
5//! (images, hooks, cross-references, decorations, …), function application,
6//! and pattern matching. Follows `evaluator.cppo.ml`'s naive interpreter, not
7//! its bytecode VM, which was deliberately not ported.
8
9use crate::ast::{Ast, Pattern};
10use crate::crossref::CrossRefs;
11use crate::value::{BaseEnv, Env, Value};
12use rustyfi_backend::{DocInfo, FontMetrics, ImageResource, MathCmdId};
13use rustyfi_syntax::{RustyfiVersion, Span};
14use std::cell::RefCell;
15use std::rc::Rc;
16
17/// See [`Interp::decos`].
18///
19/// Each entry records the `interp.version` active when the deco closure was
20/// CAPTURED ([`DecoEntry::version`]). Reading `interp.version` at FIRE time
21/// instead is wrong: the consumer (`primitives::apply_deco`, called only from
22/// `lib.rs`'s post-page-break hook-firing pass) always runs outside every
23/// `VersionScope`'s save/restore window, so in a cross-version program the
24/// flag there is the ENTRY's generation, never the deco author's — concretely,
25/// `uline`, `enumitem` and `figbox` are ordinary 0.0.6 packages with their own
26/// 0.0.6 `graphics list` decos; they register while `interp.version` is
27/// `V0_0` and get fired while it is `V0_1`, so `coerce_graphics_result`
28/// demanded a single `graphics` and got a list.
29#[derive(Clone, Debug)]
30pub enum DecoEntry {
31    Inline {
32        deco: Value,
33        version: RustyfiVersion,
34    },
35    Block {
36        pads: rustyfi_backend::Paddings,
37        /// The frame's OUTER width (the wrapping context's paragraph_width).
38        width: rustyfi_backend::Length,
39        /// `(decoS, decoH, decoM, decoT)` — evalUtil.ml:169 `get_decoset`.
40        decoset: [Value; 4],
41        version: RustyfiVersion,
42    },
43    /// `inline-frame-breakable`'s deco set, behind a
44    /// `PureHorzBox::InlineFrameMarker` pair. The inline twin of `Block`
45    /// above: the frame may split across LINE breaks rather than page breaks,
46    /// so `fire_hooks` picks `decoS`/`decoH`/`decoM`/`decoT` per line
47    /// fragment the same way. `pads` is kept for the vertical half only —
48    /// `paddingL`/`paddingR` are already spliced into the box stream as
49    /// `FixedEmpty` (upstream `append_horz_padding`), so only `t`/`b` are
50    /// read back here, to size each fragment's rect.
51    InlineBreakable {
52        pads: rustyfi_backend::Paddings,
53        decoset: [Value; 4],
54        version: RustyfiVersion,
55    },
56}
57
58impl DecoEntry {
59    pub fn version(&self) -> RustyfiVersion {
60        match self {
61            DecoEntry::Inline { version, .. }
62            | DecoEntry::Block { version, .. }
63            | DecoEntry::InlineBreakable { version, .. } => *version,
64        }
65    }
66}
67
68#[derive(Debug, thiserror::Error)]
69#[error("{}{msg}", .span.map(|s| format!("{s}: ")).unwrap_or_default())]
70pub struct EvalError {
71    pub span: Option<Span>,
72    pub msg: String,
73}
74
75pub(crate) fn eval_error<T>(msg: impl Into<String>) -> Result<T, EvalError> {
76    Err(EvalError {
77        span: None,
78        msg: msg.into(),
79    })
80}
81
82/// Comma-separated, sorted field names of a record — the "(available fields:
83/// …)" hint shared by the field-access and field-update error messages.
84pub(crate) fn available_fields(map: &std::collections::BTreeMap<String, Value>) -> String {
85    let mut keys: Vec<&str> = map.keys().map(|s| s.as_str()).collect();
86    keys.sort();
87    keys.join(", ")
88}
89
90/// Evaluation state threaded through every primitive: font metrics, images,
91/// hooks, cross-references, and the per-trial accumulators below.
92pub struct Interp<'a> {
93    pub metrics: &'a dyn FontMetrics,
94    /// The document-wide image table: `load-image` decodes eagerly and
95    /// pushes here, returning the index as `Value::Image`;
96    /// `use-image-by-width` looks the resource back up by it. `page-break`
97    /// clones this into `DocumentValue::images` (a superset of what actually
98    /// ends up placed on a page — the PDF writer itself filters down to the
99    /// images a placed line actually references).
100    pub images: Vec<ImageResource>,
101    /// The document-wide page-break-hook closure table: `hook-page-break`
102    /// pushes its closure and returns a `HookId` index
103    /// (`PureHorzBox::HookPageBreak`) — the `images`-style seam, but for a
104    /// deferred computation. Reset every trial (see `crossrefs`, the one
105    /// exception); read back by `fire_hooks` once placement is known.
106    pub hooks: Vec<Value>,
107    /// Installed-math-command table (`get-initial-context`/
108    /// `set-math-command` push here; `Context::math_command` holds the
109    /// index) — needed because the backend `Context` cannot hold a lang-side
110    /// `Value`. Read back by `read_inline`'s `EmbedMath` arm.
111    pub math_commands: Vec<Value>,
112    /// The cross-reference table, shared with the compile driver across
113    /// every trial of the fixpoint loop — unlike `hooks`/`images`, this must
114    /// *not* reset per trial, so the driver clones one `Rc<RefCell<
115    /// CrossRefs>>` handle into each trial's fresh `Interp`.
116    pub crossrefs: Rc<RefCell<CrossRefs>>,
117    /// Accumulators: link annotations / named destinations / outline
118    /// entries, plus the per-page deco-graphics overlays. All reset per
119    /// trial; the FINAL trial's contents are moved into
120    /// `DocumentValue::extras` by `compile_document_cst_with_trials`.
121    pub annotations: Vec<rustyfi_backend::Annot>,
122    pub destinations: Vec<rustyfi_backend::NamedDest>,
123    pub outline: Vec<rustyfi_backend::OutlineEntry>,
124    pub page_graphics: Vec<Vec<rustyfi_backend::GraphicsElem>>,
125    /// `register-document-information`'s accumulator — LAST WRITE WINS,
126    /// same reset-per-trial policy as `outline`/`annotations`/`destinations`.
127    pub doc_info: Option<DocInfo>,
128    /// `Some(0-based page)` only while `fire_hooks` is walking that page —
129    /// the port of upstream's `State.during_page_break` + "current page"
130    /// (`annotation.ml:15`, `namedDest.ml`'s `notify_pagebreak`).
131    pub current_page: Option<usize>,
132    /// Links/metadata: the `DecoId` of the deco closure currently
133    /// being fired by `fire_hooks`' two `apply_deco` call sites, `None`
134    /// outside any such window. This is the STRUCTURAL link between a
135    /// placed `Annot`/`NamedDest` (page-absolute, known only
136    /// post-page-break) and the `PureHorzBox::Frame`/
137    /// `VertBox::FrameStart`/`FrameEnd` marker that produced it in the
138    /// PRE-page-break `DocumentValue::reflow_source` — both carry the SAME
139    /// `DecoId`, so recording it here (into `link_decos`/`dest_decos`
140    /// below) lets the reflow backend resolve "which Frame is this link"
141    /// exactly, not by geometry/position.
142    pub current_deco_id: Option<rustyfi_backend::DecoId>,
143    /// `Some` only while an `inline-graphics` callback is being applied
144    /// EAGERLY, outside any page-break window (`apply_graphics_callback`):
145    /// `register-destination` appends its `(key, box-local point)` here
146    /// instead of erroring, and the caller turns each into a
147    /// `GraphicsElem::Destination` marker riding in the resulting box. Left
148    /// `None` inside a page-break window, so the direct registration wins
149    /// there.
150    pub pending_dests: Option<Vec<(String, rustyfi_backend::Point)>>,
151    /// One `(DecoId, action)` per `register-link-to-uri`/`-to-location`
152    /// call made while `current_deco_id` was `Some`. Reset per trial,
153    /// drained into `DocumentValue::reflow_links` by `eval_document_trials`
154    /// alongside `extras`.
155    pub link_decos: Vec<(rustyfi_backend::DecoId, rustyfi_backend::AnnotAction)>,
156    /// Same idea as `link_decos`, for `register-destination`
157    /// (`annot.satyh`'s `register-location-frame` idiom): `(DecoId, name)`.
158    /// Drained into `DocumentValue::reflow_dests`.
159    pub dest_decos: Vec<(rustyfi_backend::DecoId, String)>,
160    /// Each block frame's own decoration at its natural size, box-local —
161    /// see `rustyfi_backend::FrameDecoration`. Recorded by `fire_hooks` and
162    /// drained into `DocumentValue::reflow_frame_decos`, so a renderer with
163    /// no page grid can draw the frame the document actually asked for
164    /// instead of nothing at all. Unread by the PDF path.
165    pub frame_decos: Vec<(rustyfi_backend::DecoId, rustyfi_backend::FrameDecoration)>,
166    /// `namedDest.ml`'s key -> "nameddest{N}" sanitizer table: arbitrary
167    /// user keys become stable PDF name strings, shared by
168    /// register-destination / register-link-to-location / register-outline
169    /// within one trial.
170    dest_names: std::collections::HashMap<String, String>,
171    /// Deco-closure table (`DecoId` indexes here) — `hooks`' twin for
172    /// decorations. `Inline` holds one `deco` closure
173    /// (`point -> length -> length -> length -> graphics list`); `Block`
174    /// holds a block frame's four-closure deco-set + the geometry the
175    /// markers can't carry. Reset per trial.
176    pub decos: Vec<DecoEntry>,
177    /// Deferred `inline-graphics-outer` callbacks (`length -> point ->
178    /// graphics list`), indexed by `GraphicsFnId` — the `hooks` pattern.
179    /// Each entry also carries the generation it was registered under, for
180    /// the same reason [`DecoEntry`] does: the callback's RESULT shape
181    /// (`graphics list` vs one `graphics`) is a property of the code that
182    /// wrote it, and `primitives::resolve_outer_graphics_in_contents` runs
183    /// long after, from a line-breaking post-pass with no version context
184    /// of its own.
185    pub outer_graphics: Vec<(Value, RustyfiVersion)>,
186    /// The target language version this evaluation run is checking against
187    /// — consulted only by `read_inline`'s `IText::EmbedMath` FALLBACK arm
188    /// (no installed math command; unit-test contexts only). Default
189    /// `V0_0`; `lib.rs`'s `eval_document_trials` sets this to the real
190    /// target version on every `Interp` it constructs.
191    pub version: RustyfiVersion,
192}
193
194impl<'a> Interp<'a> {
195    pub fn new(metrics: &'a dyn FontMetrics) -> Self {
196        Interp {
197            metrics,
198            images: Vec::new(),
199            hooks: Vec::new(),
200            math_commands: Vec::new(),
201            crossrefs: Rc::new(RefCell::new(CrossRefs::new())),
202            annotations: Vec::new(),
203            destinations: Vec::new(),
204            outline: Vec::new(),
205            page_graphics: Vec::new(),
206            doc_info: None,
207            current_page: None,
208            current_deco_id: None,
209            pending_dests: None,
210            link_decos: Vec::new(),
211            dest_decos: Vec::new(),
212            frame_decos: Vec::new(),
213            dest_names: std::collections::HashMap::new(),
214            decos: Vec::new(),
215            outer_graphics: Vec::new(),
216            version: RustyfiVersion::V0_0,
217        }
218    }
219
220    /// Evaluate `ast` by compiling it against `env` and running the result.
221    ///
222    /// A thin shim: ~25 integration tests drive the evaluator through it, and
223    /// it is precisely what their compiled counterpart already does — there
224    /// is exactly one evaluator, since quoted text is compiled eagerly into
225    /// [`crate::quoted`]'s name-free form.
226    ///
227    /// `base` is the COMPILE-time environment `ast`'s free names resolve
228    /// against; the program itself runs in a fresh, empty runtime frame
229    /// chain — `base` is NOT that chain's root, because nothing resolves a
230    /// name at run time.
231    pub fn eval(&mut self, base: &BaseEnv, ast: &Ast) -> Result<Value, EvalError> {
232        crate::compile::compile_program(ast, base).run(&Env::root(), self)
233    }
234
235    /// Intern an installed math command, returning the handle a `Context`
236    /// carries (`Context::math_command`).
237    pub fn register_math_command(&mut self, cmd: Value) -> MathCmdId {
238        self.math_commands.push(cmd);
239        MathCmdId(self.math_commands.len() - 1)
240    }
241
242    /// `namedDest.ml:name_from_hash_table` — the stable PDF name for `key`,
243    /// minting `nameddest{N}` on first sight. Also used by `register-outline`
244    /// (upstream `Outline.make_entry` calls `NamedDest.get`, which mints too).
245    pub fn dest_name(&mut self, key: &str) -> String {
246        if let Some(n) = self.dest_names.get(key) {
247            return n.clone();
248        }
249        let n = format!("nameddest{}", self.dest_names.len());
250        self.dest_names.insert(key.to_string(), n.clone());
251        n
252    }
253
254    pub fn apply(&mut self, func: Value, arg: Value) -> Result<Value, EvalError> {
255        // A plain (0.0.6-shaped) application supplies no optional bundle; a
256        // closure that *does* declare optional params defaults every one to
257        // `None`, faithful to upstream's `reduce_beta_list`.
258        self.apply_with_opts(func, Vec::new(), arg)
259    }
260
261    /// Beta-reduce `func` against a positional argument plus a SATySFi 0.1
262    /// labeled-optional bundle. For a closure, each of the closure's declared
263    /// optional params binds `Some v` when the bundle carries its label, else
264    /// `None`; a supplied label the closure does not declare is ignored
265    /// (upstream `reduce_beta` folds over the *closure's* map — the
266    /// typechecker rejects genuinely-wrong labels first). This
267    /// unknown-label-ignore is only sound because typecheck runs first.
268    pub fn apply_with_opts(
269        &mut self,
270        func: Value,
271        opt_vals: Vec<(String, Value)>,
272        arg: Value,
273    ) -> Result<Value, EvalError> {
274        match func {
275            Value::CompiledClosure {
276                opt_labels,
277                body,
278                env,
279            } => {
280                // Slot order: declared optional binders, then the positional
281                // parameter — what `Ast::LambdaOpt` pushed onto the
282                // compiler's scope stack.
283                let mut slots = Vec::with_capacity(opt_labels.len() + 1);
284                push_opt_slots(&mut slots, &opt_labels, &opt_vals);
285                slots.push(arg);
286                body.run(&env.child(slots), self)
287            }
288            Value::Prim { def, mut applied } => {
289                if !opt_vals.is_empty() {
290                    return eval_error(
291                        "labeled optional arguments to a primitive are roadmap phase 5",
292                    );
293                }
294                applied.push(arg);
295                if applied.len() == def.arity {
296                    (def.run)(self, applied)
297                } else {
298                    Ok(Value::Prim { def, applied })
299                }
300            }
301            other => eval_error(format!(
302                "cannot apply a value of type {} as a function",
303                other.type_name()
304            )),
305        }
306    }
307}
308
309/// Append one slot per declared SATySFi 0.1 labeled-optional parameter, in
310/// declaration order: `Some v` when `opt_vals` supplies that label, `None`
311/// otherwise (upstream `reduce_beta`'s fold over the closure's own label map).
312/// See `Interp::apply_with_opts` for why unknown labels are ignored.
313fn push_opt_slots(slots: &mut Vec<Value>, opt_labels: &[String], opt_vals: &[(String, Value)]) {
314    for label in opt_labels {
315        slots.push(match opt_vals.iter().find(|(l, _)| l == label) {
316            Some((_, v)) => Value::Ctor("Some".to_string(), Some(Box::new(v.clone()))),
317            None => Value::Ctor("None".to_string(), None),
318        });
319    }
320}
321
322/// Structural pattern matching against an already-evaluated scrutinee.
323/// Returns `true` (and appends every bound value, POSITIONALLY, in the order
324/// they were encountered) on a structural match; returns `false` (leaving
325/// `bindings` for this attempt unusable — callers must use a fresh `Vec` per
326/// arm) otherwise.
327///
328/// The push order here is the same left-to-right traversal
329/// `compile::pattern_vars` uses to collect the arm's names, so position `i`
330/// in `bindings` is slot `i` of the frame the arm runs in — keep the two in
331/// step. A pattern/value shape mismatch is simply "no match", never an
332/// error: this untyped evaluator relies on the separate exhaustiveness/type
333/// checker to rule out ill-typed matches ahead of time.
334pub fn match_pattern(pat: &Pattern, value: &Value, bindings: &mut Vec<Value>) -> bool {
335    match pat {
336        Pattern::Wild => true,
337        Pattern::Var(_) => {
338            bindings.push(value.clone());
339            true
340        }
341        Pattern::As(inner_pat, _) => {
342            if match_pattern(inner_pat, value, bindings) {
343                bindings.push(value.clone());
344                true
345            } else {
346                false
347            }
348        }
349        Pattern::Unit => matches!(value, Value::Unit),
350        Pattern::Bool(b) => matches!(value, Value::Bool(v) if v == b),
351        Pattern::Int(n) => matches!(value, Value::Int(v) if v == n),
352        Pattern::Str(s) => matches!(value, Value::Str(v) if v == s),
353        Pattern::Tuple(ps) => match value {
354            Value::Tuple(vs) if ps.len() == vs.len() => ps
355                .iter()
356                .zip(vs.iter())
357                .all(|(p, v)| match_pattern(p, v, bindings)),
358            _ => false,
359        },
360        Pattern::EmptyList => matches!(value, Value::List(vs) if vs.is_empty()),
361        Pattern::Cons(head_pat, tail_pat) => match value {
362            Value::List(vs) if !vs.is_empty() => {
363                if !match_pattern(head_pat, &vs[0], bindings) {
364                    return false;
365                }
366                let tail = Value::List(vs[1..].to_vec());
367                match_pattern(tail_pat, &tail, bindings)
368            }
369            _ => false,
370        },
371        Pattern::Ctor(name, parg) => match value {
372            Value::Ctor(vname, vpayload) if name == vname => match (parg, vpayload) {
373                (None, None) => true,
374                (Some(p), Some(v)) => match_pattern(p, v, bindings),
375                _ => false,
376            },
377            _ => false,
378        },
379    }
380}