Skip to main content

latexml_core/definition/
origin.rs

1//! Definition provenance — K1 of the generalized kernel-capability program
2//! (`docs/perfect_kernel/KERNEL_CAPABILITIES.md`).
3//!
4//! Every definition records WHO made it: LaTeXML's own layers (the format
5//! dumps, the Rust pools, a compiled binding, the raw format files) or the
6//! document's world (a raw `.sty`/`.cls`/`.def` the document loaded, or the
7//! document itself). The origin is captured at construction from a
8//! thread-local set by the loader seams, the same moment a definition's
9//! locator is, and travels with the object through `\let`.
10//!
11//! Its first consumer is the l3/ltcmd "already defined" leniency
12//! (`\lx@if@pooldefined`): real LaTeX keeps `\section`, `\thepage`,
13//! `{figure}`… in article.cls, our pool pre-defines them for class-less
14//! robustness, so a standalone class redeclaring them is not an error —
15//! while a genuine double declaration between two raw files still is.
16use std::cell::{Cell, RefCell};
17
18/// Who made a definition.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum DefinitionOrigin {
21  /// Made before any loader seam set an origin (engine bootstrap) — ours.
22  Unknown,
23  /// The PLAIN layer: restored from the plain format dump (embedded or a
24  /// `plain.YYYY.dump.txt` on disk), or made by a plain pool (`plain_*`). Perl
25  /// tells the same layer by its definitions' source (`isDefinableLaTeX`,
26  /// latex_constructs.pool.ltxml:2512-2517: `getShortSource =~ /^plain/`): LaTeX's
27  /// `\newcommand`/`\@ifdefinable` may redefine what plain defined.
28  Plain,
29  /// Restored from the LaTeX format dump (`<embedded:latex>`).
30  LatexDump,
31  /// A Rust pool (`InnerPool!`/`LoadPool!`: TeX.pool, LaTeX.pool, constructs).
32  Pool,
33  /// A compiled binding's own code (`DefMacro!`/`RawTeX!` in a `*_sty.rs`).
34  Binding,
35  /// The guess of a fallback class — OmniBus, loaded for a class with no binding: what it defines is a
36  /// convenience the real class may not have, so a document's own `\newcommand` (and `\providecommand`,
37  /// `\newenvironment`, `\@ifdefinable`) of the name wins over it, unless it is locked
38  /// (`state::is_fallback_meaning`) — and as OmniBus's fallback, locked too (`state::document_redefines_guess`).
39  Fallback,
40  /// A kernel stand-in for a name a class or style defines only where the document cannot reach it (aaai's
41  /// `\equalcontrib`, set inside its `\@maketitle`): yields as `Fallback` does, and to a raw class's or package's own
42  /// `\newcommand` of the name too, since the real file does define it (copernicus.cls:1673 `\equalcontrib[1]`).
43  Stub,
44  /// What a binding borrows from a package the real one does not load (`binding::content::require_package_borrowed`:
45  /// theorem.sty's and ntheorem.sty's bindings borrow amsthm's): in LaTeX the names do not exist, so they yield as
46  /// `Fallback` does, and to every raw file's own definition too — TeX Live's or the author's (cc.cls's ccproof.sty:56
47  /// `\newenvironment{proof}` after theorem.sty; 1507.02955).
48  Borrowed,
49  /// A raw format file read as definitions (latex.ltx, plain.tex, expl3-code.tex).
50  Format,
51  /// A raw `.sty`/`.cls`/`.def`/`.tex` the document loaded as definitions.
52  File,
53  /// The document's own preamble or body.
54  Document,
55}
56
57impl DefinitionOrigin {
58  /// Is this definition LaTeXML's own — a pool, dump, binding or format layer —
59  /// rather than the document's? The l3/ltcmd declarators tolerate
60  /// redefinition of our own pre-definitions (the class-level names real
61  /// LaTeX keeps in article.cls) and report genuine double declarations.
62  pub fn is_latexml_owned(self) -> bool {
63    !matches!(self, DefinitionOrigin::File | DefinitionOrigin::Document)
64  }
65
66  /// Is this definition a binding's — its own code, a fallback class's guess, a stand-in, a borrowing — rather than the
67  /// kernel's (a pool, a dump, a format) or the document's (`state::note_dropped_argument`)?
68  pub fn is_binding_made(self) -> bool {
69    matches!(
70      self,
71      DefinitionOrigin::Binding
72        | DefinitionOrigin::Fallback
73        | DefinitionOrigin::Stub
74        | DefinitionOrigin::Borrowed
75    )
76  }
77}
78
79thread_local! {
80  static CURRENT_ORIGIN: Cell<DefinitionOrigin> = const { Cell::new(DefinitionOrigin::Document) };
81}
82
83/// The origin a definition constructed now will carry.
84pub fn current_origin() -> DefinitionOrigin { CURRENT_ORIGIN.with(|c| c.get()) }
85
86/// RAII guard: definitions made while it lives carry `origin`; the previous
87/// origin is restored on drop (loaders nest: a binding raw-loading its `.sty`
88/// yields `File` for that file's definitions and `Binding` for its own).
89pub struct OriginGuard(DefinitionOrigin);
90
91impl OriginGuard {
92  pub fn new(origin: DefinitionOrigin) -> Self {
93    OriginGuard(CURRENT_ORIGIN.with(|c| c.replace(origin)))
94  }
95}
96
97impl Drop for OriginGuard {
98  fn drop(&mut self) { CURRENT_ORIGIN.with(|c| c.set(self.0)); }
99}
100
101thread_local! {
102  static PROVIDE_ONLY: Cell<bool> = const { Cell::new(false) };
103}
104
105/// Is a provide-only load in progress ([`ProvideOnlyGuard`])?
106pub fn provide_only() -> bool { PROVIDE_ONLY.with(|c| c.get()) }
107
108/// RAII guard: while it lives, a load only provides — a binding's definition (the fallback class OmniBus, or any binding it
109/// requires) of a name defined before the guard began is dropped, as a `\providecommand` of it is
110/// (`state::provide_only_declines`); the previous mode is restored on drop.
111pub struct ProvideOnlyGuard(bool);
112
113impl ProvideOnlyGuard {
114  pub fn new() -> Self {
115    crate::state::reset_provide_only_assigned();
116    ProvideOnlyGuard(PROVIDE_ONLY.with(|c| c.replace(true)))
117  }
118}
119
120impl Default for ProvideOnlyGuard {
121  fn default() -> Self { Self::new() }
122}
123
124impl Drop for ProvideOnlyGuard {
125  fn drop(&mut self) {
126    PROVIDE_ONLY.with(|c| c.set(self.0));
127    if !self.0 {
128      crate::state::end_provide_only();
129    }
130  }
131}
132
133thread_local! {
134  /// The stand-in copy whose provides-mode is in force (`0`: none), and the modes it interrupted.
135  static COPY_PROVIDES: Cell<u32> = const { Cell::new(0) };
136  static COPY_PROVIDES_STACK: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
137}
138
139/// The stand-in copy whose read is in force — "a stand-in's copy provides" (`state::note_copy_provides_assignment`): the
140/// 1-based number of the paper's copy of an author file a stand-in binding answers
141/// (`binding::content::read_stand_in_copy`), while that copy is read, while a hook it registered runs, or `0`.
142pub fn copy_provides() -> u32 { COPY_PROVIDES.with(|c| c.get()) }
143
144/// Enter copy `id`'s provides-mode (`0`: suspend it, for a file the copy loads), until the matching
145/// [`leave_copy_provides`]. A stack, not a guard: the scope markers `\lx@copy@provides@begin{N}` and
146/// `\lx@copy@provides@end` wrapped around a hook the copy registers bracket a token run, not a Rust call. Entering
147/// from no mode (or leaving to none) puts `\AddToHook`'s registration seam in place (or back out,
148/// `state::swap_copy_provides_hook_seam`).
149pub fn enter_copy_provides(id: u32) {
150  let previous = COPY_PROVIDES.with(|c| c.get());
151  COPY_PROVIDES_STACK.with(|s| s.borrow_mut().push(previous));
152  crate::state::enter_copy_provides_frame(id, previous);
153  if (previous == 0) != (id == 0) {
154    crate::state::swap_copy_provides_hook_seam(id != 0);
155  }
156  // (the copy's code is a file's: locked, as a raw read is, `load_tex_definitions` — also when its
157  // `\AtEndOfClass` code runs inside `\documentclass`'s unlocked after-digestion)
158  if id != 0 {
159    crate::common::local_assignments::local_state_unlocked(false);
160  }
161  COPY_PROVIDES.with(|c| c.set(id));
162}
163
164/// Leave the provides-mode [`enter_copy_provides`] entered: the interrupted one is in force again. An unmatched leave
165/// is ignored.
166pub fn leave_copy_provides() {
167  let Some(previous) = COPY_PROVIDES_STACK.with(|s| s.borrow_mut().pop()) else {
168    return;
169  };
170  let current = COPY_PROVIDES.with(|c| c.replace(previous));
171  if current != 0 {
172    crate::common::local_assignments::expire_state_unlocked();
173  }
174  crate::state::leave_copy_provides_frame();
175  if (previous == 0) != (current == 0) {
176    crate::state::swap_copy_provides_hook_seam(previous != 0);
177  }
178}
179
180/// RAII form of [`enter_copy_provides`]/[`leave_copy_provides`], for a Rust-bracketed scope (the copy's read, a
181/// nested load's suspension).
182pub struct CopyProvidesGuard;
183
184impl CopyProvidesGuard {
185  pub fn new(id: u32) -> Self {
186    enter_copy_provides(id);
187    CopyProvidesGuard
188  }
189}
190
191impl Drop for CopyProvidesGuard {
192  fn drop(&mut self) { leave_copy_provides(); }
193}
194
195thread_local! {
196  static STAND_IN_LOADING: Cell<u32> = const { Cell::new(0) };
197  static STAND_IN_OWN_CODE: Cell<bool> = const { Cell::new(false) };
198  static STAND_IN_LOADER_OWN_CODE: Cell<bool> = const { Cell::new(false) };
199  static STAND_IN_BASE_CLASS: Cell<bool> = const { Cell::new(false) };
200  /// Which setter watches are on: [`COPY_DEFAULT_WATCH`] and the title-page check's (one flag, read at every macro call).
201  static SETTER_WATCH: Cell<u8> = const { Cell::new(0) };
202}
203
204/// [`watch_setter_calls`]' watch: a stand-in copy stored a default of the setters' fields.
205const COPY_DEFAULT_WATCH: u8 = 1;
206/// [`watch_document_calls`]' watch: the title-page check's (`state::note_document_call`).
207const DOCUMENT_CALL_WATCH: u8 = 4;
208/// [`watch_dropped_arguments`]' watch: the title-page check's (`state::note_dropped_argument`).
209const DROPPED_ARGUMENT_WATCH: u8 = 8;
210/// [`watch_store_calls`]' watch: the title-page check's (`state::note_store_call`).
211const STORE_CALL_WATCH: u8 = 16;
212
213/// Is a setter watch on ([`watch_setter_calls`], [`watch_document_calls`], [`watch_dropped_arguments`],
214/// [`watch_store_calls`])? Read at every macro call, so a flag.
215pub fn setter_watch() -> bool { SETTER_WATCH.with(|c| c.get()) != 0 }
216
217/// What a macro's call must be for one of the watches on to see it, read at every macro call: `None` when no watch is on,
218/// `Some(true)` when only [`watch_document_calls`]' and [`watch_store_calls`]' are, which see only a macro with parameters
219/// that LaTeXML or a raw class's own file made. Those two stay on from a conversion's start until its title page, or to
220/// its end in a document with none, so a package's macro calls in the document's text would otherwise all pay for the
221/// watch's cold path.
222#[inline(always)]
223pub fn call_watch() -> Option<bool> {
224  let watches = SETTER_WATCH.with(|c| c.get());
225  (watches != 0).then_some(watches & !(DOCUMENT_CALL_WATCH | STORE_CALL_WATCH) == 0)
226}
227
228/// Is [`watch_setter_calls`]' watch on?
229pub fn copy_default_watch() -> bool { SETTER_WATCH.with(|c| c.get()) & COPY_DEFAULT_WATCH != 0 }
230
231/// Is [`watch_document_calls`]' watch on?
232pub fn document_call_watch() -> bool { SETTER_WATCH.with(|c| c.get()) & DOCUMENT_CALL_WATCH != 0 }
233
234/// Is [`watch_dropped_arguments`]' watch on?
235pub fn dropped_argument_watch() -> bool {
236  SETTER_WATCH.with(|c| c.get()) & DROPPED_ARGUMENT_WATCH != 0
237}
238
239/// Is [`watch_store_calls`]' watch on, the gullet reading the document's text?
240pub fn store_call_watch() -> bool { SETTER_WATCH.with(|c| c.get()) & STORE_CALL_WATCH != 0 }
241
242/// Observe (`true`) or stop observing the required arguments a binding's macro drops (`state::note_dropped_argument`):
243/// while a frontmatter entry the document gave is digested (latexml_engine `title_page_check`); the watch it replaces.
244pub fn watch_dropped_arguments(on: bool) -> bool {
245  SETTER_WATCH.with(|c| {
246    let was = c.get() & DROPPED_ARGUMENT_WATCH != 0;
247    c.set(if on {
248      c.get() | DROPPED_ARGUMENT_WATCH
249    } else {
250      c.get() & !DROPPED_ARGUMENT_WATCH
251    });
252    was
253  })
254}
255
256thread_local! {
257  /// Whether [`watch_document_calls`] is on, and whether the gullet reads a mouth of the document's text now
258  /// ([`note_document_mouth`]): the watch flag is set only while both hold, so no macro a package, a class or a
259  /// binding's own text calls takes the watched path.
260  static DOCUMENT_CALLS_WATCHED: Cell<(bool, bool)> = const { Cell::new((false, false)) };
261  /// Whether [`watch_store_calls`] is on: the watch flag is set only while the gullet reads a mouth of the document's
262  /// text too, and it is off from the title page on, so a call in the body pays nothing.
263  static STORE_CALLS_WATCHED: Cell<bool> = const { Cell::new(false) };
264  /// Whether a raw class or a raw file of the document's own directory is being read ([`note_reading_own_file`]).
265  static READING_OWN_FILE: Cell<bool> = const { Cell::new(false) };
266}
267
268/// Set the watch flag of [`watch_document_calls`] from `DOCUMENT_CALLS_WATCHED`.
269fn sync_document_call_watch() {
270  let (on, document_mouth) = DOCUMENT_CALLS_WATCHED.with(Cell::get);
271  let stores = STORE_CALLS_WATCHED.with(Cell::get);
272  SETTER_WATCH.with(|c| {
273    let mut flags = c.get() & !(DOCUMENT_CALL_WATCH | STORE_CALL_WATCH);
274    if on && document_mouth {
275      flags |= DOCUMENT_CALL_WATCH;
276    }
277    if stores && document_mouth {
278      flags |= STORE_CALL_WATCH;
279    }
280    c.set(flags);
281  });
282}
283
284/// Observe (`true`) or stop observing the calls of LaTeXML's own macros the document's text makes, their arguments read
285/// from it (`state::note_document_call`): the title-page check's second source, what the document gave a binding's
286/// frontmatter commands (latexml_engine `base_utilities::frontmatter::title_page_check`). On from a conversion's
287/// start until its frontmatter is sealed; observed only while the gullet reads the document's text
288/// ([`note_document_mouth`]).
289pub fn watch_document_calls(on: bool) {
290  DOCUMENT_CALLS_WATCHED.with(|c| c.set((on, c.get().1)));
291  sync_document_call_watch();
292}
293
294/// Observe (`true`) or stop observing the calls of the setters a raw class or a raw file of the document's own directory
295/// made (`state::note_store_call`): the title-page check's third source (latexml_engine
296/// `base_utilities::frontmatter::title_page_check`). On from a conversion's start until the title page; observed only
297/// while the gullet reads the document's text ([`note_document_mouth`]).
298pub fn watch_store_calls(on: bool) {
299  STORE_CALLS_WATCHED.with(|c| c.set(on));
300  sync_document_call_watch();
301}
302
303/// A raw file starts being read as definitions: is it a class or a file of the document's own directory
304/// (`binding::content::load_tex_definitions`)? What it says before the load is read, for its end. What a `\def` makes
305/// meanwhile is such a file's ([`crate::definition::expandable::Expandable::made_in_own_file`]): definitions record no
306/// source file of their own (their `locator` is a stub, Expandable.pm's is unported).
307pub fn note_reading_own_file(own: bool) -> bool { READING_OWN_FILE.with(|c| c.replace(own)) }
308
309/// Is a raw class or a raw file of the document's own directory being read ([`note_reading_own_file`])?
310pub fn reading_own_file() -> bool { READING_OWN_FILE.with(Cell::get) }
311
312/// The gullet's current mouth changed: does it read the document's own text (`Mouth::is_document_text`)?
313pub fn note_document_mouth(document_text: bool) {
314  if DOCUMENT_CALLS_WATCHED.with(Cell::get).1 != document_text {
315    DOCUMENT_CALLS_WATCHED.with(|c| c.set((c.get().0, document_text)));
316    sync_document_call_watch();
317  }
318}
319
320/// Observe the calls of the setters `names` from now on (`state::note_setter_call`): a stand-in's copy stored a
321/// default of their field, which the document's own call replaces whatever its value.
322pub fn watch_setter_calls(names: &[&str]) {
323  crate::state::watch_setters(names);
324  SETTER_WATCH.with(|c| c.set(c.get() | COPY_DEFAULT_WATCH));
325}
326
327/// Is a binding that stands in for an author's file loading ([`StandInLoadGuard`]), itself or a file it loads?
328pub fn stand_in_loading() -> bool { STAND_IN_LOADING.with(|c| c.get()) != 0 }
329
330/// Is the code running now a stand-in binding's own ([`StandInLoadGuard::new`]), not a file it loads
331/// ([`StandInLoadGuard::suspend`])?
332pub fn stand_in_own_code() -> bool { STAND_IN_OWN_CODE.with(|c| c.get()) }
333
334/// Did a stand-in binding's own code request the file now loading ([`StandInLoadGuard::suspend`] keeps the flag it
335/// suspended)? A stand-in binding that file is joins the loading binding's command set only then
336/// ([`StandInLoadGuard::loaded_by`]).
337pub fn stand_in_loader_own_code() -> bool { STAND_IN_LOADER_OWN_CODE.with(|c| c.get()) }
338
339/// Is the code running now a class a stand-in binding loads ([`StandInLoadGuard::suspend_for`]: its base class, the
340/// pool's article, report or book, or the OmniBus guess built on them), not the binding's own code nor a package?
341/// The text defaults such a class assigns (`\refname`, `\bibname`, `\abstractname`) are not the binding's
342/// (`state::State::stand_in_base_defaults`).
343pub fn stand_in_base_class() -> bool { STAND_IN_BASE_CLASS.with(|c| c.get()) }
344
345/// RAII guard: while a binding that stands in for an author's file loads (`binding::content::input_definitions`),
346/// every name assigned is recorded as that binding's (`state::State::stand_in_meanings`), whatever made it — its
347/// `DefMacro!`s, its `Let!`s and `RawTeX`, the bindings it requires — so the paper's copy read after it only provides
348/// them (`state::note_copy_provides_assignment`). The names its own code assigns, not a file it loads
349/// ([`StandInLoadGuard::suspend`]: OmniBus, natbib, a nested stand-in's own), are also its command set
350/// (`state::State::stand_in_last_load`), which the copy must define to be the file the binding stands in for
351/// (`binding::content` `copy_is_the_stood_in_file`).
352pub struct StandInLoadGuard {
353  own_code: bool,
354  load:     bool,
355  /// (a load: its names join the stand-in binding loading it, whose own code requested it; a suspension: the loader
356  /// flag it replaced)
357  from_own: bool,
358  /// (the base-class flag replaced: [`stand_in_base_class`])
359  base:     bool,
360}
361
362impl StandInLoadGuard {
363  /// A stand-in binding the code running now requests (`binding::content::input`'s `.tex` route): it joins the command
364  /// set of a stand-in binding loading it when that is the binding's own code.
365  pub fn new() -> Self { Self::loaded_by(stand_in_own_code()) }
366
367  /// A stand-in binding loads, requested by a stand-in binding's own code when `from_own_code`
368  /// (`binding::content::input_definitions`, [`stand_in_loader_own_code`]): its names join that binding's command set
369  /// at its end (`state::end_stand_in_load`) — the diagrams binding's diagrams.tex (hep-ph9609379) —, and not when a
370  /// file the outer binding loads requested it: OmniBus's `RequirePackage!("aas_macros")` (omnibus_cls.rs:71) under
371  /// asme2ej (2309.12017), nature-pre (2102.01782, 2111.09589), cimart (2412.00032).
372  pub fn loaded_by(from_own_code: bool) -> Self {
373    STAND_IN_LOADING.with(|c| c.set(c.get() + 1));
374    crate::state::begin_stand_in_load();
375    StandInLoadGuard {
376      own_code: STAND_IN_OWN_CODE.with(|c| c.replace(true)),
377      load:     true,
378      from_own: from_own_code,
379      base:     STAND_IN_BASE_CLASS.with(|c| c.replace(false)),
380    }
381  }
382
383  /// A file a stand-in binding loads (`binding::content::input_definitions`): its names are the binding's to own, but
384  /// not the binding's command set, until the guard drops.
385  pub fn suspend() -> Self { Self::suspend_for(false) }
386
387  /// [`StandInLoadGuard::suspend`] for a file that is a class (`class`, a `.cls`) or not: a class the binding's own
388  /// code loads is its base class ([`stand_in_base_class`]), and so is every class that class loads; a package any of
389  /// them loads is not (the bindings a binding requires stay its own).
390  pub fn suspend_for(class: bool) -> Self {
391    let own_code = STAND_IN_OWN_CODE.with(|c| c.replace(false));
392    let base = STAND_IN_BASE_CLASS.with(|c| c.replace(class && (own_code || c.get())));
393    StandInLoadGuard {
394      own_code,
395      load: false,
396      from_own: STAND_IN_LOADER_OWN_CODE.with(|c| c.replace(own_code)),
397      base,
398    }
399  }
400}
401
402impl Default for StandInLoadGuard {
403  fn default() -> Self { Self::new() }
404}
405
406impl Drop for StandInLoadGuard {
407  fn drop(&mut self) {
408    STAND_IN_OWN_CODE.with(|c| c.set(self.own_code));
409    STAND_IN_BASE_CLASS.with(|c| c.set(self.base));
410    if self.load {
411      STAND_IN_LOADING.with(|c| c.set(c.get().saturating_sub(1)));
412      crate::state::end_stand_in_load(self.from_own);
413    } else {
414      STAND_IN_LOADER_OWN_CODE.with(|c| c.set(self.from_own));
415    }
416  }
417}
418
419/// Forget every provides-mode: a new conversion starts with none (`reset_thread_engine`).
420pub fn reset_copy_provides() {
421  STAND_IN_LOADING.with(|c| c.set(0));
422  STAND_IN_OWN_CODE.with(|c| c.set(false));
423  STAND_IN_LOADER_OWN_CODE.with(|c| c.set(false));
424  STAND_IN_BASE_CLASS.with(|c| c.set(false));
425  // (the title-page check's watches are its own, set at its resets: `watch_document_calls`, `watch_dropped_arguments`,
426  // `watch_store_calls`)
427  SETTER_WATCH
428    .with(|c| c.set(c.get() & (DOCUMENT_CALL_WATCH | DROPPED_ARGUMENT_WATCH | STORE_CALL_WATCH)));
429  COPY_PROVIDES.with(|c| c.set(0));
430  COPY_PROVIDES_STACK.with(|s| s.borrow_mut().clear());
431}
432
433/// Run `f` with `origin` as the current definition origin.
434pub fn with_origin<R>(origin: DefinitionOrigin, f: impl FnOnce() -> R) -> R {
435  let _guard = OriginGuard::new(origin);
436  f()
437}