Skip to main content

latexml_core/binding/
store_setters.rs

1//! K11's table of title-page setters (`latexml_engine/src/frontmatter_stores.rs` reroutes a raw
2//! class's — or package's — stores through it), and which of them a binding defined: a setter whose definition
3//! changed while a binding loaded is the binding's own (acmart.cls's `\copyrightyear`, ported as the
4//! class's store), never a raw class's store, though a raw class that loads the binding
5//! (`\LoadClass[nonacm]{acmart}` in a wrapper class) ends with it defined. `input_definitions`
6//! snapshots the setters around each binding load; the snapshot is a Rust local, so nested loads
7//! pair by the call stack and nothing transient enters the State (or a format dump). So: raw TeX a
8//! binding loads itself (`noltxml`) counts as the binding's, a raw class a binding loads still
9//! reroutes at its own end, and a raw class's later redefinition of a binding's setter is the raw
10//! class's. Only loads through `input_definitions` are tracked (a plain-TeX `.tex` binding loaded
11//! by `load_binding` directly is not).
12use std::{cell::Cell, rc::Rc};
13
14use crate::{
15  common::{arena, error::Result, store::Stored},
16  state::{Scope, assign_value, lookup_definition, lookup_definition_stored, lookup_value},
17  token::{Catcode, Token},
18};
19
20/// Setter name (no backslash) → the frontmatter API body for its kind, with
21/// `#1` the setter's argument (an `[optional]{mandatory}` setter's `#2`). Kinds and roles follow OmniBus.cls.ltxml and
22/// the kernel (`\lx@add@date[role=…]`, latex_constructs.pool.ltxml:1066).
23pub const STORE_SETTERS: &[(&str, &str)] = &[
24  ("subtitle", "\\lx@add@subtitle{#1}"),
25  ("shorttitle", "\\lx@add@toctitle{#1}"),
26  ("toctitle", "\\lx@add@toctitle{#1}"),
27  ("titlerunning", "\\lx@add@toctitle{#1}"),
28  ("email", "\\lx@add@email{#1}"),
29  ("emailaddr", "\\lx@add@email{#1}"),
30  ("ead", "\\lx@add@email{#1}"),
31  ("address", "\\lx@add@address{#1}"),
32  ("affaddr", "\\lx@add@address{#1}"),
33  ("affil", "\\lx@add@store@affiliations{affil}{#1}"),
34  (
35    "affiliation",
36    "\\lx@add@store@affiliations{affiliation}{#1}",
37  ),
38  // aaai21-aaai2027's labelled lines (aaai25.sty:72 `\long\gdef\affiliations #1{ \def \affiliations_{…#1…}}`)
39  (
40    "affiliations",
41    "\\lx@add@store@affiliations{affiliations}{#1}",
42  ),
43  ("inst", "\\lx@add@store@affiliations{inst}{#1}"),
44  ("department", "\\lx@add@store@affiliations{department}{#1}"),
45  ("institute", "\\lx@add@store@affiliations{institute}{#1}"),
46  (
47    "institution",
48    "\\lx@add@store@affiliations{institution}{#1}",
49  ),
50  ("keywords", "\\lx@add@keywords{#1}"),
51  ("keyword", "\\lx@add@keywords{#1}"),
52  ("kword", "\\lx@add@keywords{#1}"),
53  ("kwd", "\\lx@add@keywords{#1}"),
54  ("terms", "\\lx@add@keywords{#1}"),
55  ("pacs", "\\lx@add@classification[scheme=pacs]{#1}"),
56  ("abst", "\\lx@add@abstract{#1}"),
57  ("resumen", "\\lx@add@abstract{#1}"),
58  ("received", "\\lx@add@date[role=received]{#1}"),
59  ("recdate", "\\lx@add@date[role=received]{#1}"),
60  ("revised", "\\lx@add@date[role=revised]{#1}"),
61  // medima.sty:300-312 (and the other Elsevier journal styles papers ship under elsarticle: jcomp, prletters, ycviu,
62  // yjvci, cag, jasr) keeps a five-line "Article history" — received, received in final form, accepted, available
63  // online, communicated —, in the roles revtex4_support and aipproc give those dates (2307.16262).
64  ("finalform", "\\lx@add@date[role=revised]{#1}"),
65  ("accepted", "\\lx@add@date[role=accepted]{#1}"),
66  ("availableonline", "\\lx@add@date[role=published]{#1}"),
67  ("pubyear", "\\lx@add@date[role=publication]{#1}"),
68  ("copyrightyear", "\\lx@add@copyrightyear{#1}"),
69  ("communicated", "\\lx@add@date[role=communicated]{#1}"),
70  ("presented", "\\lx@add@date[role=presented]{#1}"),
71  ("preprint", "\\lx@add@pubnote[role=preprint]{#1}"),
72  ("journal", "\\lx@add@pubnote[role=journal]{#1}"),
73  ("jname", "\\lx@add@pubnote[role=journal]{#1}"),
74  ("volume", "\\lx@add@pubnote[role=volume]{#1}"),
75  ("issue", "\\lx@add@pubnote[role=issue]{#1}"),
76  ("pubinfo", "\\lx@add@pubnote{#1}"),
77  ("origin", "\\lx@add@pubnote{#1}"),
78  // A DOI is a string, as the classes print it (sig-alternate-05-2015.cls:1639-1641 `\def\doi#1{\def\@doi{#1}}`,
79  // `\printdoi` = `\url`): its `_` was digested as a subscript in the pubnote (1610.03579, 1710.01977; OXIDIZED_DESIGN
80  // #551). It is set as ASCII text, as `\lx@address@textfont` sets an address. Guard
81  // `perfect_kernel_batch65m::raw_class_doi_is_a_string`.
82  (
83    "doi",
84    "\\lx@add@pubnote[role=doi]{\\lx@address@textfont{\\detokenize{#1}}}",
85  ),
86  ("conferenceinfo", "\\lx@add@pubnote[role=conference]{#1}"),
87  ("articletype", "\\lx@add@pubnote[role=type]{#1}"),
88  // wiley-article.cls:213-214 (nbdt-article.cls too): the article type and the journal section its `\maketitle`
89  // (:420-466) prints above the title (1911.06213 "Research article", 1808.01384 "Original Article", 2012.13110).
90  ("papertype", "\\lx@add@pubnote[role=type]{#1}"),
91  ("paperfield", "\\lx@add@pubnote{#1}"),
92  ("orcid", "\\lx@add@orcid{#1}"),
93  ("orcidID", "\\lx@add@orcid{#1}"),
94  ("editor", "\\lx@add@editor{#1}"),
95  ("editors", "\\lx@add@editor{#1}"),
96  ("speaker", "\\lx@add@creator[role=speaker]{#1}"),
97  // The correspondence block, e-mail and funding line wiley-article.cls:206-209 stores (nbdt-article.cls too), which
98  // only its own abstract environment prints (`\wiley@affilmetadata`, :416-433, in the margin beside the abstract,
99  // :470): the kernel's locked `{abstract}` refuses that environment, so they were lost (1808.01384
100  // "pantelis@ucdavis.edu" and its funding line, 1911.06213; 13 papers of the 3,000-paper sample). The e-mail is the
101  // correspondence block's, not a named author's: a note, as OmniBus's `\printead` makes it.
102  (
103    "corraddress",
104    "\\lx@add@frontmatter{ltx:note}[role=correspondence]{#1}",
105  ),
106  (
107    "corremail",
108    "\\lx@add@frontmatter{ltx:note}[role=email]{#1}",
109  ),
110  (
111    "fundinginfo",
112    "\\lx@add@frontmatter{ltx:note}[role=funding]{#1}",
113  ),
114  // CSML.cls:227-229 `\def\ACMCCS#1{\def\@ACMCCS{#1}}`, "2012 ACM CCS", printed by its `\@setACMCCS` (:285-286) at
115  // the title page's foot (LMCS: 1608.04592 "Theory of computation", 1602.00476).
116  ("ACMCCS", "\\lx@add@classification[scheme=ACMCCS]{#1}"),
117  // The author note a title page prints under its heading (apa6.cls:779 `\authornote` → `\@acks`, printed by its
118  // `\maketitle` only; 68 of 188 apa/apa6 papers), as apa7's binding makes it (apa7_cls.rs).
119  (
120    "authornote",
121    "\\lx@add@frontmatter{ltx:note}[role=authornote]{#1}",
122  ),
123  // The corresponding-author note a class keeps in a token register (`\newtoks\correspondingauthor`) and prints only in
124  // its title page's footer (googlecloud.cls:80/:110-114, 2607.06973; cmu.cls, 2608.26053; deepseek.cls, 2401.14196;
125  // K11's toks stores, `frontmatter_stores.rs` `toks_store`), or in a macro store its title page prints.
126  (
127    "correspondingauthor",
128    "\\lx@add@frontmatter{ltx:note}[role=corresponding]{#1}",
129  ),
130];
131
132/// Table setters only the displaced-setter route takes (`reroute_displaced_setters`): K11's in-place reroute skips
133/// them and its off-table survey reads them as off the table. A pure `\affiliations` store is the creators' where the
134/// title page prints it (rlj.sty:72, 2605.26012), the class's where only its page foot does (lpor2014.cls:1229-1230,
135/// numbered by `\and`: 1601.06956, 1912.03045).
136pub const DISPLACED_ONLY_SETTERS: &[&str] = &["affiliations"];
137
138/// The setter `\name`'s current definition, as stored; none when it is undefined, `\let` to an
139/// undefined control sequence, or `\let` to a character (for which `lookup_definition_stored`
140/// makes a new definition on each call).
141fn setter_definition(name: &str) -> Result<Option<Stored>> {
142  // A name never interned has no definition: probe without formatting or pinning (two snapshots per binding load).
143  let Some(cs_sym) = arena::get_suffixed("\\", name) else {
144    return Ok(None);
145  };
146  let cs = Token!(sym cs_sym, Catcode::CS);
147  if lookup_definition(&cs)?.is_none() {
148    return Ok(None);
149  }
150  lookup_definition_stored(&cs)
151}
152
153/// Whether two stored definitions are the same definition (not merely equal ones).
154fn same_definition(a: &Stored, b: &Stored) -> bool {
155  match (a, b) {
156    (Stored::Expandable(a), Stored::Expandable(b)) => Rc::ptr_eq(a, b),
157    (Stored::Primitive(a), Stored::Primitive(b)) => Rc::ptr_eq(a, b),
158    (Stored::Constructor(a), Stored::Constructor(b)) => Rc::ptr_eq(a, b),
159    (Stored::MathPrimitive(a), Stored::MathPrimitive(b)) => Rc::ptr_eq(a, b),
160    (Stored::Conditional(a), Stored::Conditional(b)) => Rc::ptr_eq(a, b),
161    (Stored::Register(a), Stored::Register(b)) => Rc::ptr_eq(a, b),
162    _ => false,
163  }
164}
165
166/// Each table setter's definition before a binding loads.
167pub fn snapshot() -> Result<Vec<Option<Stored>>> {
168  STORE_SETTERS
169    .iter()
170    .map(|(name, _)| setter_definition(name))
171    .collect()
172}
173
174/// The table setters whose definition changed since `before`, with their new definitions.
175fn changed_since(before: &[Option<Stored>]) -> Result<Vec<(&'static str, Stored)>> {
176  let mut changed = Vec::new();
177  for ((name, _), before) in STORE_SETTERS.iter().zip(before) {
178    let Some(after) = setter_definition(name)? else {
179      continue;
180    };
181    if !before
182      .as_ref()
183      .is_some_and(|before| same_definition(before, &after))
184    {
185      changed.push((*name, after));
186    }
187  }
188  Ok(changed)
189}
190
191/// After a binding loaded: mark each table setter whose definition changed since `before` as the
192/// binding's — unless a raw file read during the load defined it ([`mark_raw`]): bfhlayout_sty.rs
193/// reads bfhlayout.sty, whose `\institution`/`\department`/`\institute` stay the raw stores the
194/// class's title page reads (DEMO-BFHThesis lost its affiliations).
195pub fn mark_bound(before: &[Option<Stored>]) -> Result<()> {
196  for (name, after) in changed_since(before)? {
197    let raw =
198      lookup_value(&s!("lx_raw_setter_{name}")).is_some_and(|raw| same_definition(&raw, &after));
199    if !raw {
200      assign_value(&s!("lx_bound_setter_{name}"), after, Some(Scope::Global));
201    }
202  }
203  Ok(())
204}
205
206/// After a raw file was read: record each table setter it defined as the raw file's.
207pub fn mark_raw(before: &[Option<Stored>]) -> Result<()> {
208  for (name, after) in changed_since(before)? {
209    assign_value(&s!("lx_raw_setter_{name}"), after, Some(Scope::Global));
210  }
211  Ok(())
212}
213
214/// Whether the setter's current definition is the one a raw file made ([`mark_raw`]): not a binding's, nor the K11
215/// reroute's of a raw file's store.
216pub fn defined_by_a_raw_file(name: &str) -> Result<bool> {
217  let Some(current) = setter_definition(name)? else {
218    return Ok(false);
219  };
220  Ok(lookup_value(&s!("lx_raw_setter_{name}")).is_some_and(|raw| same_definition(&raw, &current)))
221}
222
223/// Whether the setter's current definition is one a binding made.
224pub fn defined_by_a_binding(name: &str) -> Result<bool> {
225  let Some(current) = setter_definition(name)? else {
226    return Ok(false);
227  };
228  Ok(
229    lookup_value(&s!("lx_bound_setter_{name}"))
230      .is_some_and(|bound| same_definition(&bound, &current)),
231  )
232}
233
234thread_local! {
235  /// The raw class reads in progress (`content.rs`, around a `.cls` read raw).
236  static RAW_CLASS_READS: Cell<usize> = const { Cell::new(0) };
237}
238
239/// Counts a raw class read while it lasts ([`in_a_raw_class_read`]).
240pub struct RawClassRead;
241
242impl RawClassRead {
243  /// Enter a raw class read.
244  #[must_use]
245  pub fn begin() -> Self {
246    RAW_CLASS_READS.with(|n| n.set(n.get() + 1));
247    RawClassRead
248  }
249}
250
251impl Drop for RawClassRead {
252  fn drop(&mut self) { RAW_CLASS_READS.with(|n| n.set(n.get().saturating_sub(1))); }
253}
254
255/// Is a raw class being read? A raw package it loads is then the class's: its table setters are rerouted at the
256/// class's end, where its title page is known (`latexml_engine/src/frontmatter_stores.rs` `reroute_raw_package_stores`).
257pub fn in_a_raw_class_read() -> bool { RAW_CLASS_READS.with(Cell::get) > 0 }