Skip to main content

latexml_core/common/
local_assignments.rs

1//! Perl-style local assignments (dynamic scope)
2//!
3//! This module provides stack-based dynamic scoping for global state,
4//! matching Perl's `local` mechanism. Each "localized" field uses a `Vec<T>`
5//! as a stack: push to shadow, pop to restore.
6//!
7//! ## RAII Guards
8//!
9//! Each localized variable has a corresponding `Guard` type that pushes on
10//! creation and pops on `Drop`. This prevents leaked state on early returns
11//! or panics:
12//!
13//! ```rust,no_run
14//! # use latexml_core::common::local_assignments::*;
15//! # use latexml_core::token::Token;
16//! # fn example(token: Token) {
17//! let _guard = local_current_token_guard(token);
18//! // ... do work ...
19//! // guard auto-pops when _guard goes out of scope
20//! # }
21//! ```
22//!
23//! The explicit `set_*/expire_*` pairs still exist for cases where
24//! RAII doesn't fit (e.g., cross-function push/pop with different lifetimes).
25
26use std::{cell::RefCell, rc::Rc, sync::LazyLock};
27
28use crate::{
29  Digested, alignment::template::Template, definition::conditional::IfFrame, token::Token,
30};
31
32/// These are fields realized via Perl's "local" mechanism in LaTeXML,
33/// but (for now) require explicit "expire" calls in Rust.
34/// Ideally their ergonomics gets improved, or we gradually phase them out.
35#[derive(Debug, Default)]
36pub struct Localized {
37  dual_branch:       Vec<&'static str>,
38  if_frames:         Vec<Option<Rc<RefCell<IfFrame>>>>,
39  current_token:     Vec<Token>,
40  align_group_count: Vec<i32>, // was $LaTeXML::ALIGN_STATE
41  reading_alignment: Vec<Digested>,
42  build_template:    Vec<Template>,
43  unlocked:          Vec<bool>,
44}
45
46macro_rules! locals {
47  () => {
48    (*LOCALIZED_VARS).borrow()
49  };
50}
51macro_rules! locals_mut {
52  () => {
53    (*LOCALIZED_VARS).borrow_mut()
54  };
55}
56
57thread_static! {
58  static LOCALIZED_VARS: RefCell<Localized> = RefCell::new(Localized::default());
59}
60
61/// Reset all localized variables to their default state.
62/// Must be called between conversion runs to prevent state pollution.
63pub fn initialize_localized() { *locals_mut!() = Localized::default(); }
64
65/// sets a (originally Perl-local) `IfFrame` that needs to be manually expired.
66pub fn set_ifframe(if_frame: Option<Rc<RefCell<IfFrame>>>) {
67  locals_mut!().if_frames.push(if_frame);
68}
69
70/// retrieves the most recent (originally Perl-local) `IfFrame`
71pub fn get_ifframe() -> Option<Rc<RefCell<IfFrame>>> {
72  match locals!().if_frames.last() {
73    Some(Some(frame)) => Some(Rc::clone(frame)),
74    _ => None,
75  }
76}
77/// expires the most recent (originally Perl-local) `IfFrame`
78pub fn expire_ifframe() { locals_mut!().if_frames.pop(); }
79/// Number of currently open conditional frames (`\if…` whose `\fi` has not
80/// been digested yet). Zero at any clean point between top-level constructs —
81/// the fragment-yield seam predicate requires exactly that.
82pub fn open_conditional_count() -> usize { locals!().if_frames.len() }
83/// localizes a new current token. see `Stomach::invoke_token`
84pub fn local_current_token(token: Token) { locals_mut!().current_token.push(token); }
85/// expires the most recent (localized) current token.
86pub fn expire_current_token() { locals_mut!().current_token.pop(); }
87/// gets the (localized) current token
88pub fn get_current_token() -> Option<Token> { locals!().current_token.last().cloned() }
89
90/// sets the (localized) flag for "dual branch"
91pub fn set_dual_branch(mode: &'static str) { locals_mut!().dual_branch.push(mode); }
92/// expire (localized) flag for "dual branch"
93pub fn expire_dual_branch() { locals_mut!().dual_branch.pop(); }
94/// get the current value for "dual branch"
95pub fn get_dual_branch() -> Option<&'static str> { locals!().dual_branch.last().cloned() }
96
97/// Cached snapshot of `LXML_TRACE_ALIGN_STATE`: print every change of the
98/// alignment ledger (tex.web `align_state`) with the current token and a
99/// short backtrace, to bisect a ledger drift (a cell-ending `&`/`\\` is only
100/// recognized at `align_group_count()==0`). Debug aid, off by default.
101static TRACE_ALIGN_STATE: LazyLock<bool> =
102  LazyLock::new(|| std::env::var("LXML_TRACE_ALIGN_STATE").is_ok());
103
104fn trace_align_state(what: &str, before: i32, after: i32) {
105  if *TRACE_ALIGN_STATE && !locals!().reading_alignment.is_empty() {
106    let tok = get_current_token()
107      .map(|t| t.to_string())
108      .unwrap_or_default();
109    let bt = std::backtrace::Backtrace::force_capture().to_string();
110    let frames: Vec<&str> = bt
111      .lines()
112      .filter(|l| l.contains("latexml_") && !l.contains("local_assignments"))
113      .take(4)
114      .map(str::trim)
115      .collect();
116    eprintln!(
117      "ALIGN_STATE {what}: {before} -> {after} at {tok} | {}",
118      frames.join(" < ")
119    );
120  }
121}
122
123/// Bump the current `align_state` by `delta` (tex.web §358: `left_brace:
124/// incr(align_state)`, `right_brace: decr(align_state)`), returning the new
125/// value. Every scanned `{`/`}` lands here, so it is one thread-local
126/// borrow; the trace's before/after read is behind the off-by-default switch.
127fn shift_align_group_count(delta: i32) -> i32 {
128  let mut locals = locals_mut!();
129  match locals.align_group_count.last_mut() {
130    Some(v) => {
131      *v += delta;
132      *v
133    },
134    None => {
135      locals.align_group_count.push(delta);
136      delta
137    },
138  }
139}
140pub fn increment_align_group_count() {
141  let after = shift_align_group_count(1);
142  if *TRACE_ALIGN_STATE {
143    trace_align_state("+1", after - 1, after);
144  }
145}
146pub fn decrement_align_group_count() {
147  let after = shift_align_group_count(-1);
148  if *TRACE_ALIGN_STATE {
149    trace_align_state("-1", after + 1, after);
150  }
151}
152
153pub fn state_is_unlocked() -> bool { locals!().unlocked.last().copied().unwrap_or(false) }
154pub fn local_state_unlocked(v: bool) { locals_mut!().unlocked.push(v); }
155/// Whether a reader re-locked the state explicitly: code that is not the document's own text, a raw file's or a hook's
156/// (`\AtBeginDocument`'s, run by `\begin{document}`), as Perl runs them under `$UNLOCKED=0`.
157pub fn state_is_relocked() -> bool { locals!().unlocked.last() == Some(&false) }
158pub fn expire_state_unlocked() { locals_mut!().unlocked.pop(); }
159
160pub fn align_group_count() -> i32 {
161  locals!()
162    .align_group_count
163    .last()
164    .copied()
165    .unwrap_or_default()
166}
167pub fn set_align_group_count(v: i32) {
168  trace_align_state("set", align_group_count(), v);
169  match locals_mut!().align_group_count.last_mut() {
170    Some(gc) => {
171      *gc = v;
172    },
173    _ => {
174      locals_mut!().align_group_count.push(v);
175    },
176  }
177}
178pub fn local_align_group_count(v: i32) { locals_mut!().align_group_count.push(v); }
179/// The alignment brace count as it stands (tex.web's `align_state`, with its stack of saved values), to be put back by
180/// [`restore_align_group_count`] after a digestion whose tokens are not the document's input.
181pub fn mark_align_group_count() -> (usize, Option<i32>) {
182  let locals = locals!();
183  (
184    locals.align_group_count.len(),
185    locals.align_group_count.last().copied(),
186  )
187}
188/// Puts back the alignment brace count [`mark_align_group_count`] read: the stack at its depth then, the current value
189/// as it was. A `{` the abandoned digestion scanned and never closed is no longer counted against the document's `&`s.
190pub fn restore_align_group_count(mark: (usize, Option<i32>)) {
191  let (depth, value) = mark;
192  trace_align_state("restore", align_group_count(), value.unwrap_or_default());
193  let mut locals = locals_mut!();
194  let stack = &mut locals.align_group_count;
195  stack.truncate(depth);
196  if let Some(value) = value {
197    if stack.len() < depth {
198      stack.resize(depth, value);
199    }
200    if let Some(top) = stack.last_mut() {
201      *top = value;
202    }
203  }
204}
205pub fn expire_align_group_count() -> Option<i32> { locals_mut!().align_group_count.pop() }
206
207/// Disables tab marks for the lifetime of the guard, restoring the previous
208/// count on drop — what ltcmd does around every argument it reads: latex.ltx:2103-2110
209/// (`\__cmd_start:nNNnnn`) opens `\group_align_safe_begin:` (closed at :2128), which raises `align_state`
210/// by the backquote-constant rule (tex.web §442), and physics.sty does it by hand around its fenced reads
211/// (`{\ifnum\z@=`}\fi`, physics.sty:35/74/141). TeX's own `macro_call` (§389-399) does NOT disable tab
212/// marks — the `{disable tab marks, etc.}` of `align_state:=1000000` is `read_toks`, behind `\read`
213/// (tex.web §482) — so a plain macro's delimited argument holding an `&` inside an alignment errs in TeX
214/// too ("Argument of \… has an extra }"); arming this in `Parameters::read_arguments` would be unfaithful.
215/// For an ltcmd/physics reader, without it a `&` in a **delimiter-fenced** argument reaches the alignment as a
216/// cell break: for
217/// `\mqty( b_0 &0 \\ 0 &b_1 )` (physics.sty, witness 2605.05903) the row splits
218/// mid-argument and the alignment then cannot close its own group —
219/// `Error:unexpected:\lx@begin@alignment Attempt to close a group that switched
220/// to mode restricted_horizontal` — truncating the rest of the document. The
221/// brace form `\mqty{…}` was always safe because cell scanning skips balanced
222/// groups; `(…)` is not a group. Perl raises the identical error (11 of them on
223/// the 14-line repro), so this is beyond-Perl and `pdflatex`, which renders the
224/// repro silently, is the ground truth.
225///
226/// Only armed inside an alignment: outside one there are no tab marks to
227/// suppress, which keeps this off the hot path for every ordinary macro call.
228/// 28 papers of the 2026-07-29 bibliography-absence residual truncate here.
229pub struct SuppressedTabMarks(Option<i32>);
230
231impl SuppressedTabMarks {
232  pub fn for_argument_scan() -> Self {
233    if has_reading_alignment() {
234      let saved = align_group_count();
235      set_align_group_count(1_000_000);
236      Self(Some(saved))
237    } else {
238      Self(None)
239    }
240  }
241}
242
243impl Drop for SuppressedTabMarks {
244  fn drop(&mut self) {
245    if let Some(saved) = self.0 {
246      set_align_group_count(saved);
247    }
248  }
249}
250
251pub fn get_reading_alignment() -> Option<Digested> { locals!().reading_alignment.last().cloned() }
252pub fn has_reading_alignment() -> bool { !locals!().reading_alignment.is_empty() }
253pub fn local_reading_alignment(alignment: &Digested) {
254  locals_mut!().reading_alignment.push(alignment.clone());
255}
256pub fn expire_reading_alignment() -> Option<Digested> { locals_mut!().reading_alignment.pop() }
257
258pub fn local_build_template(template: Template) { locals_mut!().build_template.push(template); }
259pub fn set_build_template(template: Template) {
260  *locals_mut!()
261    .build_template
262    .last_mut()
263    .expect("set_build_template should not be called before the first local_build_template") =
264    template;
265}
266pub fn take_build_template() -> Option<Template> { locals_mut!().build_template.pop() }
267
268pub fn with_current_build_template<R, FnR>(caller: FnR) -> R
269where FnR: FnOnce(Option<&mut Template>) -> R {
270  caller(locals_mut!().build_template.last_mut())
271}
272
273/// Runs `caller` on the alignment template being built, if one is. A column type's `\NC@rewrite@<c>` expanded outside
274/// a preamble (an `\edef` that meets it) builds nothing: in TeX it only yields tokens there (`\NC@find p{…}`), and
275/// unwrapping the missing template panicked (2605.18869: tabularx's `X`, current inside a tabularx since 61s, met by an
276/// `\edef` while an algorithm's unclosed group was open).
277pub fn with_building_template(caller: impl FnOnce(&mut Template)) {
278  if let Some(template) = locals_mut!().build_template.last_mut() {
279    caller(template);
280  }
281}
282
283// ============================================================
284// RAII Guards — auto-restore on Drop
285// ============================================================
286
287/// Generic RAII guard that calls an expire function on drop.
288/// Zero-cost when the expire function is a simple fn pointer.
289pub struct LocalGuard {
290  expire: fn(),
291}
292impl Drop for LocalGuard {
293  fn drop(&mut self) { (self.expire)(); }
294}
295
296/// Push a localized current token; returns guard that pops on drop.
297pub fn local_current_token_guard(token: Token) -> LocalGuard {
298  local_current_token(token);
299  LocalGuard { expire: expire_current_token }
300}
301
302/// Push a localized if-frame; returns guard that pops on drop.
303pub fn local_ifframe_guard(frame: Option<Rc<RefCell<IfFrame>>>) -> LocalGuard {
304  set_ifframe(frame);
305  LocalGuard { expire: expire_ifframe }
306}
307
308/// Push a localized dual branch; returns guard that pops on drop.
309pub fn local_dual_branch_guard(mode: &'static str) -> LocalGuard {
310  set_dual_branch(mode);
311  LocalGuard { expire: expire_dual_branch }
312}
313
314/// Push a localized align group count; returns guard that pops on drop.
315pub fn local_align_group_count_guard(v: i32) -> LocalGuard {
316  local_align_group_count(v);
317  LocalGuard {
318    expire: || {
319      expire_align_group_count();
320    },
321  }
322}
323
324/// Push a localized state unlocked flag; returns guard that pops on drop.
325pub fn local_state_unlocked_guard(v: bool) -> LocalGuard {
326  local_state_unlocked(v);
327  LocalGuard { expire: expire_state_unlocked }
328}
329
330/// Push a localized reading alignment; returns guard that pops on drop.
331pub fn local_reading_alignment_guard(alignment: &Digested) -> LocalGuard {
332  local_reading_alignment(alignment);
333  LocalGuard {
334    expire: || {
335      expire_reading_alignment();
336    },
337  }
338}
339
340// ============================================================
341// Unit tests
342// ============================================================
343
344#[cfg(test)]
345mod tests {
346  use super::*;
347
348  #[test]
349  fn test_dual_branch_push_pop() {
350    initialize_localized();
351    assert_eq!(get_dual_branch(), None);
352    set_dual_branch("true");
353    assert_eq!(get_dual_branch(), Some("true"));
354    set_dual_branch("false");
355    assert_eq!(get_dual_branch(), Some("false"));
356    expire_dual_branch();
357    assert_eq!(get_dual_branch(), Some("true"));
358    expire_dual_branch();
359    assert_eq!(get_dual_branch(), None);
360  }
361
362  #[test]
363  fn test_dual_branch_guard_auto_restore() {
364    initialize_localized();
365    assert_eq!(get_dual_branch(), None);
366    {
367      let _guard = local_dual_branch_guard("guarded");
368      assert_eq!(get_dual_branch(), Some("guarded"));
369    }
370    // Guard dropped — value restored
371    assert_eq!(get_dual_branch(), None);
372  }
373
374  #[test]
375  fn test_align_group_count() {
376    initialize_localized();
377    assert_eq!(align_group_count(), 0);
378    local_align_group_count(10);
379    assert_eq!(align_group_count(), 10);
380    increment_align_group_count();
381    assert_eq!(align_group_count(), 11);
382    decrement_align_group_count();
383    assert_eq!(align_group_count(), 10);
384    expire_align_group_count();
385    assert_eq!(align_group_count(), 0);
386  }
387
388  #[test]
389  fn test_align_group_count_guard() {
390    initialize_localized();
391    assert_eq!(align_group_count(), 0);
392    {
393      let _guard = local_align_group_count_guard(42);
394      assert_eq!(align_group_count(), 42);
395      increment_align_group_count();
396      assert_eq!(align_group_count(), 43);
397    }
398    // Guard dropped — outer value restored
399    assert_eq!(align_group_count(), 0);
400  }
401
402  #[test]
403  fn test_state_unlocked() {
404    initialize_localized();
405    assert!(!state_is_unlocked());
406    local_state_unlocked(true);
407    assert!(state_is_unlocked());
408    {
409      let _guard = local_state_unlocked_guard(false);
410      assert!(!state_is_unlocked());
411    }
412    assert!(state_is_unlocked());
413    expire_state_unlocked();
414    assert!(!state_is_unlocked());
415  }
416}