Skip to main content

latexml_core/definition/
expandable.rs

1use std::{borrow::Cow, fmt};
2
3use libxml::tree::Node;
4
5use crate::{
6  Digested,
7  common::{error::*, locator::Locator, object::Object},
8  definition::{
9    BeforeDigestClosure, Definition, DigestionClosure, ExpansionBody, argument::ArgWrap,
10  },
11  state::*,
12};
13
14/// Returns true when `\protect` currently has no meaning, or is
15/// `\let`-equivalent to `\relax`. Used by the recursion guard in
16/// `Expandable::invoke` to distinguish `\def\foo{\protect\foo}`
17/// definitions under safe (`\@unexpandable@protect`/`\string`/…)
18/// vs. unsafe (`\relax`/undefined) `\protect` regimes. Only the
19/// unsafe regime actually runaways at full expansion.
20/// True when `\protect` currently means `\@typeset@protect` — i.e. normal
21/// typesetting, where real LaTeX's `\@protected@testopt` DOES expand an
22/// optional-argument `\newcommand`. Under any other regime
23/// (`\protected@edef` sets `\@unexpandable@protect`, `\protected@write`
24/// sets `\@unexpandable@protect`, etc.) the real macro emits
25/// `\protect\cs` unexpanded. Used by the gullet's partial-expansion gate
26/// for binding-defined optional-argument macros (see
27/// `wisdom_replayed_tokens_param_packing` sibling entry; titlecaps OOM,
28/// perfect-kernel sweep 16).
29pub fn protect_is_typeset() -> bool {
30  let protect = lookup_meaning(&T_CS!("\\protect"));
31  let typeset = lookup_meaning(&T_CS!("\\@typeset@protect"));
32  match (protect, typeset) {
33    (Some(p), Some(t)) => p == t,
34    // No \protect regime established yet (early bootstrap): behave as
35    // typesetting (expand), the historical behavior.
36    _ => true,
37  }
38}
39
40pub(crate) fn protect_is_relax_or_undefined() -> bool {
41  let protect = T_CS!("\\protect");
42  match lookup_meaning(&protect) {
43    None => true,
44    // Meaning equal to \relax's meaning ⇒ unsafe.
45    Some(stored) => match lookup_meaning(&T_CS!("\\relax")) {
46      None => false,
47      Some(relax) => stored == relax,
48    },
49  }
50}
51use crate::{
52  document::Document,
53  parameter::Parameters,
54  token::*,
55  tokens::{BodyPiece, NO_TOKENS, Tokens},
56  whatsit::Whatsit,
57};
58
59#[derive(Debug, Clone, Default)]
60pub struct ExpandableOptions {
61  pub locked:             bool,
62  pub protected:          bool,
63  pub outer:              bool,
64  pub long:               bool,
65  pub scope:              Option<Scope>,
66  pub alias:              Option<String>,
67  pub mathactive:         bool,
68  pub robust:             bool,
69  pub nopack_parameters:  bool,
70  /// See [`Definition::peeks_by_futurelet`].
71  pub peeks_by_futurelet: bool,
72  /// Declared with TeX's long-ness: the `\def` family, LaTeX's starred `\newcommand` family. Such a macro, made
73  /// by a format, a raw-loaded file or the document, checks its arguments for `\par` ([`Expandable::checks_par`]).
74  pub tex_declared:       bool,
75  /// A binding's port of a TeX macro that is not `\long`: it checks its arguments for `\par` as the original does
76  /// ([`Expandable::checks_par`]), wherever it is made. amsppt.sty:804/:814's `\footnote`/`\footnotetext`, whose
77  /// arguments stop at a paragraph's end (amsppt_sty.rs).
78  pub short:              bool,
79  /// Wraps the name's current meaning and delegates to it (OmniBus's `\bibitem`, which loads natbib for a
80  /// `[\protect\citeauthoryear…]` label and otherwise calls the `\bibitem` it saved): it extends the name rather
81  /// than replacing it, so a provide-only load installs it too (`state::provide_only_declines`).
82  pub extends:            bool,
83  /// The arguments (their numbers, `#n`) this binding macro drops by design: the real package or class prints nothing of
84  /// them (hyperref's `\texorpdfstring` #2, the PDF bookmark's text), or they are page furniture (FIDELITY_CHARTER §2).
85  /// The title-page check wants none of their words (`state::DocumentArgument::used`, OXIDIZED_DESIGN_DIVERGENCES #953
86  /// "106t"); the expansion is unchanged ([`Expandable::dropped_by_design`]).
87  pub drops:              &'static [u8],
88}
89
90/// A native answer to a macro's call, tried before its arguments are read ([`SpecialCall::Native`]).
91pub type NativeCall = fn() -> Result<Option<Tokens>>;
92
93thread_local! {
94  /// The one native call there is ([`SpecialCall::Native`], held here so that every macro does not pay for its pointer:
95  /// the size of an [`Expandable`], of which a format makes 24,000, is 0.16 % of an empty article's instructions).
96  static NATIVE_CALL: std::cell::Cell<Option<NativeCall>> = const { std::cell::Cell::new(None) };
97}
98
99/// The native call [`SpecialCall::Native`] runs.
100pub fn set_native_call(native: NativeCall) { NATIVE_CALL.with(|call| call.set(Some(native))); }
101
102#[cold]
103fn native_call() -> Result<Option<Tokens>> {
104  match NATIVE_CALL.with(std::cell::Cell::get) {
105    Some(native) => native(),
106    None => Ok(None),
107  }
108}
109
110/// A macro whose call is not simply its definition's run: one test per macro call for both kinds.
111#[derive(Clone, Copy, Default)]
112pub enum SpecialCall {
113  #[default]
114  None,
115  /// A document's parameterless override (a value) of a locked binding that owns its calls (`state::install_definition`):
116  /// a call — the next raw token an explicit `{`, or a `[`/`*` the binding's signature opens with — runs the binding,
117  /// kept as `\lx@locked@<cs>`; any other use expands this definition.
118  YieldsCalls,
119  /// A faster way to what this macro's own expansion comes to, tried when the gullet expands a call in full
120  /// ([`Definition::native_expansion`]) before any argument is read: `Some` is what the call leaves, the input it read
121  /// consumed; `None` leaves the input untouched and the macro runs as defined. The definition stays the macro's own:
122  /// `\meaning`, a one-step `\expandafter` and the prefixes see its body. `\__fp_parse_operand:Nw` (latexml_engine
123  /// `l3fp_native`).
124  Native,
125}
126
127#[derive(Clone)]
128pub struct Expandable {
129  pub is_protected:       bool,
130  /// See [`Definition::peeks_by_futurelet`]: set by the kernel's peeking
131  /// closures, and for every macro whose leading argument is a `\newcommand`
132  /// optional one ([`crate::parameter::Parameter::testopt`]).
133  pub peeks_by_futurelet: bool,
134  pub is_long:            bool,
135  /// tex.web §392/§399: reading this macro's arguments, a `\par` token ends the call — "Paragraph ended before
136  /// \x was complete" (§396). Only a non-`\long` macro whose long-ness is TeX's (`tex_declared`, made at a
137  /// Format, File or Document origin): LaTeXML's own `DefMacro!`s are non-long without meaning it (Perl stores
138  /// `isLong` and never reads it, Expandable.pm:46), so they are not checked. A `\let` copy keeps it (the meaning
139  /// carries the long-ness). Witness 1001.1670; guards `scanner_status::a_par_*`, DIVERGENCES #442.
140  pub checks_par:         bool,
141  pub is_outer:           bool,
142  pub has_cc_arg:         bool,
143  pub alias:              Option<String>,
144  pub locator:            Locator,
145  pub cs:                 Token,
146  pub paramlist:          Option<Parameters>,
147  pub expansion:          Option<ExpansionBody>,
148  pub origin:             crate::definition::origin::DefinitionOrigin,
149  /// See [`SpecialCall`]. Not part of the meaning (`PartialEq`).
150  pub special_call:       SpecialCall,
151  /// The token-list body's [`Tokens::substitution_plan`], built at the first call that substitutes.
152  pub plan:               std::cell::OnceCell<Box<[BodyPiece]>>,
153  /// The arguments the binding declares this macro drops by design ([`ExpandableOptions::drops`]), bit `n` for `#n`.
154  /// Not part of the meaning (`PartialEq`).
155  pub dropped_by_design:  u16,
156  /// Made while a raw class or a raw file of the document's own directory was read
157  /// ([`crate::definition::origin::reading_own_file`]), which the title-page check's third source reads
158  /// (`Self::watched_call`). Not part of the meaning (`PartialEq`).
159  pub made_in_own_file:   bool,
160  /// The body's [`StoredParameters`], read at the first call the store watch sees.
161  pub stored:             std::cell::OnceCell<Box<StoredParameters>>,
162}
163
164// By hand, for what `special_call` says without its address: a macro's text in a log is not to change with one.
165impl fmt::Debug for Expandable {
166  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167    f.debug_struct("Expandable")
168      .field("is_protected", &self.is_protected)
169      .field("peeks_by_futurelet", &self.peeks_by_futurelet)
170      .field("is_long", &self.is_long)
171      .field("checks_par", &self.checks_par)
172      .field("is_outer", &self.is_outer)
173      .field("has_cc_arg", &self.has_cc_arg)
174      .field("alias", &self.alias)
175      .field("locator", &self.locator)
176      .field("cs", &self.cs)
177      .field("paramlist", &self.paramlist)
178      .field("expansion", &self.expansion)
179      .field("origin", &self.origin)
180      .field("yields_calls", &self.yields_calls())
181      .field("plan", &self.plan)
182      .field("dropped_by_design", &self.dropped_by_design)
183      .field("made_in_own_file", &self.made_in_own_file)
184      .field("stored", &self.stored)
185      .finish()
186  }
187}
188
189impl Default for Expandable {
190  fn default() -> Self {
191    Expandable {
192      is_protected:       false,
193      peeks_by_futurelet: false,
194      is_long:            false,
195      checks_par:         false,
196      is_outer:           false,
197      has_cc_arg:         false,
198      alias:              None,
199      locator:            Locator::default(),
200      cs:                 T_CS!("Expandable"),
201      paramlist:          None,
202      expansion:          None,
203      origin:             crate::definition::origin::current_origin(),
204      special_call:       SpecialCall::None,
205      plan:               std::cell::OnceCell::new(),
206      made_in_own_file:   false,
207      stored:             std::cell::OnceCell::new(),
208      dropped_by_design:  0,
209    }
210  }
211}
212impl PartialEq for Expandable {
213  fn eq(&self, other: &Expandable) -> bool {
214    self.paramlist == other.paramlist && self.expansion == other.expansion
215  }
216}
217
218// impl fmt::Display for Expandable {
219//   fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
220//     todo!();
221//   }
222// }
223impl Object for Expandable {
224  fn is_definition(&self) -> bool { true }
225  fn is_expandable(&self) -> bool { true }
226  fn get_locator(&self) -> Option<Locator> { Some(self.locator) }
227  fn get_origin(&self) -> crate::definition::origin::DefinitionOrigin { self.origin }
228  fn stringify(&self) -> String { <Self as Definition>::stringify_type(self, "Expandable") }
229}
230impl Definition for Expandable {
231  fn is_protected(&self) -> bool { self.is_protected }
232  fn peeks_by_futurelet(&self) -> bool { self.peeks_by_futurelet }
233  fn get_parameters(&self) -> Option<&Parameters> { self.paramlist.as_ref() }
234  fn get_num_args(&self) -> usize {
235    match self.paramlist {
236      Some(ref params) => params.get_num_args(),
237      None => 0,
238    }
239  }
240  fn get_cs(&self) -> Cow<'_, Token> { Cow::Borrowed(&self.cs) }
241  fn get_cs_name(&self) -> Cow<'_, str> {
242    match self.alias {
243      Some(ref alias) => Cow::Borrowed(alias),
244      None => Cow::Owned(self.cs.with_cs_name(ToString::to_string)),
245    }
246  }
247  // fn with_cs_name<R, FnR>(&self, caller: FnR) -> R
248  // where FnR: FnOnce(&str) -> R {
249  //   match self.alias {
250  //     Some(ref alias) => caller(alias),
251  //     None => self.cs.with_cs_name(caller),
252  //   }
253  // }
254  fn get_expansion(&self) -> Option<&ExpansionBody> { self.expansion.as_ref() }
255  fn get_alias(&self) -> Option<&String> { self.alias.as_ref() }
256
257  /// Expand the expandable control sequence. This should be carried out by the Gullet.
258  fn invoke(&self, once_only: bool) -> Result<Tokens> {
259    if self.may_be_watched()
260      && let Some(watched) = self.watched_call()
261    {
262      return self.expand_watched(once_only, watched);
263    }
264    self.expand(once_only)
265  }
266
267  /// [`Self::invoke`] onto the input, a token-list body without building the expansion: the parameterless
268  /// body is pushed as stored, a body with parameters through its substitution plan
269  /// ([`crate::gullet::unread_substituted`]). Closures, argument-only definitions and a watched call (whose
270  /// arguments are kept, as [`Self::invoke`] keeps them) take the general path.
271  fn invoke_onto_input(&self, once_only: bool) -> Result<()> {
272    if self.may_be_watched()
273      && let Some(watched) = self.watched_call()
274    {
275      crate::gullet::unread_expansion(self.expand_watched(once_only, watched)?);
276      return Ok(());
277    }
278    if let Some(call) = self.testopt_call()? {
279      crate::gullet::unread_expansion(call);
280      return Ok(());
281    }
282    match self.special_call {
283      SpecialCall::None => {},
284      SpecialCall::YieldsCalls => {
285        if let Some(owner) = self.call_owner()? {
286          crate::gullet::unread_expansion(Tokens!(owner));
287          return Ok(());
288        }
289      },
290      SpecialCall::Native => {
291        if let Some(expansion) = native_call()? {
292          crate::gullet::unread_expansion(expansion);
293          return Ok(());
294        }
295      },
296    }
297    let Some(ExpansionBody::Tokens(tokens)) = &self.expansion else {
298      crate::gullet::unread_expansion(self.invoke(once_only)?);
299      return Ok(());
300    };
301    let Some(parms) = &self.paramlist else {
302      let body = self.parameterless_body(tokens, once_only)?;
303      crate::gullet::unread_substituted(body, &[BodyPiece::Run(0, body.len() as u32)], &[]);
304      return Ok(());
305    };
306    // A call that does not match its `\def` (tex.web §398) or whose argument ran off a file's end (§392)
307    // expands to nothing.
308    let Some(args) = self.read_call_arguments(parms)? else {
309      return Ok(());
310    };
311    if !self.has_cc_arg {
312      crate::gullet::unread_substituted(
313        tokens.unlist_ref(),
314        &[BodyPiece::Run(0, tokens.len() as u32)],
315        &[],
316      );
317      return Ok(());
318    }
319    self.substitute_onto_input(tokens, &args)
320  }
321
322  fn native_expansion(&self) -> Result<Option<Tokens>> {
323    match self.special_call {
324      SpecialCall::Native => native_call(),
325      _ => Ok(None),
326    }
327  }
328
329  // Not implemented for expandable
330  fn invoke_primitive(&self) -> Result<Vec<Digested>> { Ok(Vec::new()) }
331  fn before_digest(&self) -> Option<&Vec<BeforeDigestClosure>> { None }
332  fn after_digest(&self) -> Option<&Vec<DigestionClosure>> { None }
333  fn do_absorption(&self, _document: &mut Document, _whatsit: &Whatsit) -> Result<Vec<Node>> {
334    fatal!(
335      Definition,
336      Unexpected,
337      "do_absorption on Expandable should never be called!"
338    );
339  }
340}
341
342/// What a setter watch observes of a macro call ([`Expandable::watched_call`]).
343#[derive(Clone, Copy)]
344struct WatchedCall {
345  /// a document call's: its arguments kept ([`note_document_call`])
346  recorded: bool,
347  /// a binding macro's while the document's frontmatter entry is digested: the arguments it drops kept
348  /// ([`note_dropped_argument`])
349  dropping: bool,
350  /// a raw class's or own-directory file's setter's while the document's text is read: the arguments it stores kept
351  /// ([`note_store_call`])
352  stored:   bool,
353}
354
355impl Expandable {
356  /// Can a watch that is on see this call at all ([`crate::definition::origin::call_watch`])? [`Self::watched_call`] says
357  /// what it observes, on a cold path.
358  #[inline(always)]
359  fn may_be_watched(&self) -> bool {
360    crate::definition::origin::call_watch().is_some_and(|only_owned_with_parameters| {
361      !only_owned_with_parameters
362        || (self.paramlist.is_some() && (self.made_in_own_file || self.origin.is_latexml_owned()))
363    })
364  }
365
366  /// A `\newcommand` with an optional argument reads it itself (Perl's `convertLaTeXArgs`), where latex.ltx's is
367  /// `\@protected@testopt\cs\\cs{<default>}` (`\@xargdef`, :1245-1257; [`TestoptCall`]): when the head is not the
368  /// kernel's, the call is that body, for the redefinition to act on it (hyperref.sty:548-549 gobbles the command in a
369  /// PDF string, `\HyPsd@protected@testopt`; letltxmacro.sty:127). `None` otherwise, or where the definer made no
370  /// internal (`\@xargdef` itself, the internal's own optional).
371  ///
372  /// [`TestoptCall`]: crate::parameter::TestoptCall
373  fn testopt_call(&self) -> Result<Option<Tokens>> {
374    if !self.peeks_by_futurelet {
375      return Ok(None);
376    }
377    let Some(param) = self
378      .paramlist
379      .as_ref()
380      .and_then(|params| params.get_parameters().first())
381    else {
382      return Ok(None);
383    };
384    let Some(call) = param.testopt_call.as_deref() else {
385      return Ok(None);
386    };
387    if x_equals(&call.head, &call.kernel) {
388      return Ok(None);
389    }
390    Ok(Some(Tokens!(
391      call.head,
392      self.cs,
393      call.internal,
394      T_BEGIN!(),
395      param.extra.first().unwrap_or(&NO_TOKENS).clone(),
396      T_END!()
397    )))
398  }
399
400  /// [`SpecialCall::YieldsCalls`]?
401  #[inline]
402  pub fn yields_calls(&self) -> bool { matches!(self.special_call, SpecialCall::YieldsCalls) }
403
404  /// What a setter watch (`definition::origin::setter_watch`) observes of this call, if anything: a watched setter's
405  /// ([`note_setter_call`], a stand-in copy's default replaced), a call of LaTeXML's own macro that reads its arguments from the
406  /// document's text (`origin::document_call_watch`, [`crate::gullet::reading_document_text`]: its arguments kept,
407  /// [`note_document_call`]), and a binding's macro called while a frontmatter entry the document gave is digested
408  /// (`origin::dropped_argument_watch`, `DefinitionOrigin::is_binding_made`: the arguments it drops kept,
409  /// [`note_dropped_argument`]); and a setter a raw class or a file of the document's own directory made, while the
410  /// current mouth reads the document's text, before the title page (`origin::store_call_watch`, off from the title page
411  /// on: the arguments it writes into a store kept, [`note_store_call`]) — its arguments may come back through
412  /// `\@ifnextchar` (nj_style's `\ead`, CUP-JNL-DTM's `\address`), so no [`crate::gullet::reading_document_text`]: a class's
413  /// own literal is no word the document's source writes. Not while a raw class's setter replays or a speculative
414  /// run digests.
415  #[cold]
416  #[inline(never)]
417  fn watched_call(&self) -> Option<WatchedCall> {
418    if crate::definition::origin::copy_default_watch() {
419      note_setter_call(&self.cs);
420    }
421    let recorded = crate::definition::origin::document_call_watch()
422      && self.paramlist.is_some()
423      && self.origin.is_latexml_owned()
424      && crate::gullet::reading_document_text();
425    let dropping = crate::definition::origin::dropped_argument_watch()
426      && self.paramlist.is_some()
427      && self.origin.is_binding_made()
428      && !matches!(self.expansion, Some(ExpansionBody::Closure(_)));
429    let stored = crate::definition::origin::store_call_watch()
430      && self.paramlist.is_some()
431      && self.made_in_own_file
432      && self.stored_parameters().numbers != 0
433      && !lookup_bool("lx_replaying_class_setter")
434      && !lookup_bool("lx_depositing_class_maketitle");
435    (recorded || dropping || stored).then_some(WatchedCall { recorded, dropping, stored })
436  }
437
438  /// What this macro's token body writes into a store ([`stored_parameters`]), once per definition; nothing of a closure.
439  fn stored_parameters(&self) -> &StoredParameters {
440    self.stored.get_or_init(|| {
441      Box::new(match self.expansion.as_ref() {
442        Some(ExpansionBody::Tokens(body)) => stored_parameters(body.unlist_ref()),
443        _ => StoredParameters::default(),
444      })
445    })
446  }
447
448  /// [`Self::expand`] for a watched call ([`Self::watched_call`]): a document call's arguments kept, each with whether its parameter is optional and whether the body names it (the title-page
449  /// check); and the required arguments a binding's macro drops while a document's frontmatter entry is digested.
450  #[cold]
451  #[inline(never)]
452  fn expand_watched(&self, once_only: bool, watched: WatchedCall) -> Result<Tokens> {
453    let expansion = if watched.recorded || watched.dropping || watched.stored {
454      let mut captured = None;
455      let expansion = self.expand_capturing::<true>(once_only, &mut captured)?;
456      if let (Some(args), Some(parms)) = (captured, self.paramlist.as_ref()) {
457        let parameters = parms.get_parameters();
458        // (an optional argument, or one set in brackets by a `\def`'s parameter text, is a store's key or label:
459        // `\@@address[#1]#2`, `\cortext[cor1]{…}` of an elsarticle copy, 1603.09660, 1005.1545)
460        let keyed: Vec<bool> = parameters
461          .iter()
462          .filter(|parameter| !parameter.novalue)
463          .map(|parameter| parameter.optional || parameter.spec == crate::pin!("Until:]"))
464          .collect();
465        let optional = parameters
466          .iter()
467          .filter(|parameter| !parameter.novalue)
468          .map(|parameter| parameter.optional);
469        // (a parameter a token body never names, `#n`, is dropped by the call: quantumarticle's `\ead[]{}` →
470        // `\email{#1}` drops the address; a closure's use is unknown, so its arguments are taken as handed on; one the
471        // binding declares dropped by design is accounted for — hyperref's `\texorpdfstring` #2, 2306.06741; and only
472        // a binding's drop can lose what pdflatex prints: the kernel's is TeX's own, as the format's `\@firstoftwo{T}{F}`
473        // drops the branch ifthen's `\ifthenelse` does not take around a document's `\title`, 2202.08832)
474        let used = |at: usize| {
475          !self.origin.is_binding_made()
476            || self.dropped_by_design & (1 << at) != 0
477            || match self.expansion.as_ref() {
478              Some(ExpansionBody::Tokens(body)) => names_parameter(body, at),
479              Some(ExpansionBody::Closure(_)) => true,
480              None => false,
481            }
482        };
483        let args: Vec<DocumentArgument> = optional
484          .zip(args.iter())
485          .enumerate()
486          .filter_map(|(at, (optional, arg))| match arg {
487            ArgWrap::Tokens(tokens) => Some(DocumentArgument {
488              number: at + 1,
489              optional,
490              used: used(at + 1),
491              tokens: tokens.clone(),
492            }),
493            _ => None,
494          })
495          .collect();
496        if watched.dropping {
497          for arg in args.iter().filter(|arg| !arg.optional && !arg.used) {
498            note_dropped_argument(self.cs, arg);
499          }
500        }
501        if watched.stored {
502          let stored = self.stored_parameters();
503          let (keys, values): (Vec<_>, Vec<_>) = args
504            .iter()
505            .filter(|arg| stored.numbers & (1 << arg.number) != 0 && !arg.tokens.is_empty())
506            .partition(|arg| keyed.get(arg.number - 1).copied().unwrap_or(false));
507          let tokens =
508            |args: Vec<&DocumentArgument>| args.into_iter().map(|arg| arg.tokens.clone()).collect();
509          note_store_call(self.cs, stored, tokens(values), tokens(keys));
510        }
511        if watched.recorded {
512          note_document_call(self.cs, args);
513        }
514      }
515      expansion
516    } else {
517      self.expand(once_only)?
518    };
519    Ok(expansion)
520  }
521
522  /// The expansion of a call ([`Definition::invoke`]), its arguments read.
523  #[inline(always)]
524  fn expand(&self, once_only: bool) -> Result<Tokens> {
525    self.expand_capturing::<false>(once_only, &mut None)
526  }
527
528  /// [`Self::expand`], its arguments copied into `captured` when `CAPTURE` ([`Self::expand_watched`]).
529  #[inline(always)]
530  fn expand_capturing<const CAPTURE: bool>(
531    &self,
532    once_only: bool,
533    captured: &mut Option<Vec<ArgWrap>>,
534  ) -> Result<Tokens> {
535    // Perl shortcut for "trivial" macros that were tracing- or
536    // profiling-aware. Neither tracing nor profiling is implemented
537    // in the Rust port (the returned `_tracing` / `_profiled` values
538    // were discarded), so the two state lookups were pure overhead
539    // on every macro expansion (\~350k calls in si.tex alone per
540    // callgrind). Removed — re-introduce only alongside the actual
541    // tracing/profiling features if/when they land.
542    if self.yields_calls()
543      && let Some(owner) = self.call_owner()?
544    {
545      return Ok(Tokens!(owner));
546    }
547    if let Some(call) = self.testopt_call()? {
548      return Ok(call);
549    }
550    match &self.expansion {
551      Some(ExpansionBody::Closure(closure)) => {
552        // Harder to emulate \tracingmacros here.
553        let args = if let Some(ref parms) = self.paramlist {
554          // An argument that ran off a file's end abandons the call.
555          match self.read_call_arguments(parms)? {
556            Some(args) => args,
557            None => return Ok(Tokens!()),
558          }
559        } else {
560          Vec::new()
561        };
562        if CAPTURE {
563          *captured = Some(args.clone());
564        }
565        // Profiling: not implemented (Perl: startProfiling($profiled, 'expand'))
566        let result = closure(args)?;
567        // Tracing: Perl prints tracingCSName ==> tracetoString(result)
568        // Not implemented — silently skip to avoid panic on \tracingmacros=1
569        Ok(result)
570      },
571      Some(ExpansionBody::Tokens(tokens)) => {
572        let result = if self.paramlist.is_none() {
573          // Case: Trivial macro
574          // Profiling: not implemented (Perl: startProfiling($profiled, 'expand'))
575          // Tracing: Perl prints tracingCSName -> tracetoString(expansion)
576          // Not implemented — silently skip to avoid panic on \tracingmacros=1
577          Tokens::new(self.parameterless_body(tokens, once_only)?.to_vec())
578        } else {
579          let args = if let Some(ref parms) = self.paramlist {
580            // A call that does not match its `\def` (tex.web §398): reported,
581            // and the macro is ignored; so is one whose argument ran off a
582            // file's end (§392).
583            match self.read_call_arguments(parms)? {
584              Some(args) => args,
585              None => return Ok(Tokens!()),
586            }
587          } else {
588            Vec::new()
589          };
590          if CAPTURE {
591            *captured = Some(args.clone());
592          }
593          if self.has_cc_arg {
594            // Do we actually need to substitute the args in?
595            // Pre-size: one entry per argument; avoids Vec doublings on
596            // macros with many args.
597            let mut args_tks = Vec::with_capacity(args.len());
598            for arg in args.iter() {
599              args_tks.push(arg.as_tokens()?);
600            }
601            tokens.substitute_parameters(args_tks.as_slice())
602          } else {
603            tokens.clone()
604          }
605        };
606        // Profiling: Perl appends T_MARKER(profiled) for exclusive profiling
607        // Not implemented — silently skip
608        Ok(result)
609      },
610      None => {
611        // we always need to read the arguments, for e.g. things like \@gobble
612        if let Some(ref parms) = self.paramlist {
613          let args = self.read_call_arguments(parms)?;
614          if CAPTURE {
615            *captured = args;
616          }
617        }
618        Ok(NO_TOKENS)
619      },
620    }
621  }
622
623  /// For a [`SpecialCall::YieldsCalls`] override: `\lx@locked@<cs>`, the locked binding, when the next raw token opens a
624  /// call of it — an explicit catcode-1 `{`, or a `[`/`*` its signature opens with
625  /// ([`crate::state::call_openers`]) — and `None` for any other use, which expands the override. The peek reads
626  /// without expanding and puts the token back. Like TeX's argument scan it may read past the end of the macro body
627  /// the override was met in: `\def\wrap{\text}\wrap{x}` runs the binding on `{x}`. In an expansion-only context
628  /// (`\edef`, `\write`) the kept name `\lx@locked@<cs>` is what remains (OXIDIZED_DESIGN #500 residual).
629  fn call_owner(&self) -> Result<Option<Token>> {
630    let Some(next) = crate::gullet::peek_token()? else {
631      return Ok(None);
632    };
633    let owner = locked_binding_token(&self.cs);
634    let opens_call = next.get_catcode() == Catcode::BEGIN
635      || next.get_catcode() == Catcode::OTHER && call_openers(&owner).contains(&next);
636    Ok(opens_call.then_some(owner))
637  }
638
639  /// The expansion of a parameterless body: the body, or nothing when it expands into itself
640  /// ([`Self::expands_into_itself`]), with `Error:recursion` (Perl Expandable.pm L81-89). The one place for
641  /// both [`Definition::invoke`] and [`Definition::invoke_onto_input`].
642  fn parameterless_body<'a>(&self, tokens: &'a Tokens, once_only: bool) -> Result<&'a [Token]> {
643    // For trivial expansion, make sure we don't get \cs or
644    // \relax\cs direct recursion!  Perl: Expandable.pm L81-89.
645    //   if (!$onceonly && $$self{cs}) {
646    //     my ($t0, $t1) = ($$expansion[0], $$expansion[1]);
647    //     if ($t0 && ($t0->equals($$self{cs})
648    //         || ($t1 && $t1->equals($$self{cs})
649    //              && $t0->equals(T_CS('\protect'))))) {
650    //       Error('recursion', $$self{cs}, …,
651    //         "Token X expands into itself!", "defining as empty");
652    //       $expansion = TokensI(); } }
653    //
654    // Detect `\def\foo{\foo}` and `\def\foo{\protect\foo}`. Both
655    // are runaway-expansion landmines under any full-expansion
656    // context (`\edef`, `\xdef`, `\write`, `\message`). Perl
657    // reports an `Error:recursion` and substitutes an empty
658    // expansion for this invocation; the stored definition is
659    // unchanged (subsequent invocations re-detect and re-error).
660    //
661    // A previous Rust port tried to re-install the CS as
662    // `Stored::Token(self.cs)` to preserve `\ifx` identity for
663    // expl3 quarks (`\q_no_value`, `\q_nil`, …) and PGF keys
664    // (`\pgfkeys@mainstop`). That was a no-op: `assign_meaning`'s
665    // `token == mt` short-circuit (state.rs:1918-1922) rejects
666    // the `\foo → \foo` self-let, so the Expandable definition
667    // stayed in place and the recursion guard re-fired forever.
668    // Witness: cleveref × algorithmicx × hyperref on 2403.15855,
669    // where `\xdef\cref@currentprefix{\cref@currentprefix}` hung
670    // at the 60 s wall-clock guard.
671    //
672    // Identity for expl3 quarks is independent of this path: the
673    // quarks are defined `\cs_new_protected:Npn`, so they are
674    // protected expandables. Under partial expansion (the normal
675    // path) protected expandables aren't expanded at all — the
676    // recursion guard never fires, and the stored body keeps the
677    // CS as its first token, so `\ifx`-by-meaning comparisons
678    // remain distinct. Under full expansion the Error+empty
679    // recovery matches Perl exactly.
680    if self.expands_into_itself(tokens, once_only) {
681      Error!(
682        "recursion",
683        &self.cs.to_string(),
684        s!("Token {} expands into itself!", self.cs)
685      );
686      Ok(&[])
687    } else {
688      Ok(tokens.unlist_ref())
689    }
690  }
691
692  /// The substitution half of [`Definition::invoke_onto_input`], out of line: its argument arrays stay out of
693  /// the frame of the argument reading, which recurses through `read_x_token`.
694  #[inline(never)]
695  fn substitute_onto_input(&self, tokens: &Tokens, args: &[ArgWrap]) -> Result<()> {
696    // A macro's arguments are read as tokens, so they're there to read in place (tex.web §390).
697    if args.iter().all(|arg| matches!(arg, ArgWrap::Tokens(_))) {
698      let plan = self.plan.get_or_init(|| tokens.substitution_plan());
699      crate::gullet::unread_substituted_args(tokens.unlist_ref(), plan, args);
700      return Ok(());
701    }
702    // The arguments as token lists; TeX's nine at most (§476), so on the stack.
703    let mut owned: [Option<Cow<'_, Tokens>>; 9] = Default::default();
704    if args.len() > owned.len() {
705      crate::gullet::unread_expansion(
706        tokens.substitute_parameters(
707          &args
708            .iter()
709            .map(|arg| arg.as_tokens())
710            .collect::<Result<Vec<_>>>()?,
711        ),
712      );
713      return Ok(());
714    }
715    for (slot, arg) in owned.iter_mut().zip(args.iter()) {
716      *slot = arg.as_tokens()?;
717    }
718    let mut slices: [&[Token]; 9] = [&[]; 9];
719    for (slice, arg) in slices.iter_mut().zip(owned.iter()) {
720      if let Some(arg) = arg {
721        *slice = arg.unlist_ref();
722      }
723    }
724    let plan = self.plan.get_or_init(|| tokens.substitution_plan());
725    crate::gullet::unread_substituted(tokens.unlist_ref(), plan, &slices[..args.len()]);
726    Ok(())
727  }
728
729  /// A parameterless body that begins with the control sequence being expanded (or with `\protect` and it,
730  /// while `\protect` is `\relax`) expands into itself: `Error:recursion`, and the call expands to nothing
731  /// (Perl Expandable.pm L81-89; the cases below).
732  fn expands_into_itself(&self, tokens: &Tokens, once_only: bool) -> bool {
733    if !once_only {
734      let token_vec = tokens.unlist_ref();
735      let t0_opt = token_vec.first();
736      let t1_opt = token_vec.get(1);
737      // OXIDIZED_DESIGN #185: anchor on the token actually being
738      // expanded, not the definition's home CS: a `\let` alias shares the Expandable
739      // (`self.cs` = the original), and musixlyr.tex:709-722 legitimately
740      // stores a body beginning with `\cont@<verse>` that is invoked
741      // through the alias `\der@kontext` after the original was cleared
742      // (Perl Expandable.pm:84 uses `$$self{cs}` and errs the same way:
743      // recorder-fingering, undar-digitacion-doc). A genuine
744      // `\def\x{\x}` invoked as `\x` still fires; through an alias the
745      // loop is caught one step later when `\x` itself expands.
746      let invoker = get_current_token().unwrap_or(self.cs);
747      if let Some(t0) = t0_opt {
748        if t0 == &self.cs && *t0 == invoker {
749          true
750        } else if let Some(t1) = t1_opt {
751          // `\protect\foo` is only an actual runaway when
752          // `\protect` currently expands to `\relax` (or is
753          // undefined). Under `\protected@edef` it is `\let`
754          // to `\@unexpandable@protect`, which turns the body
755          // into `\noexpand\protect\noexpand\foo` — both tokens
756          // become un-expandable and the loop terminates after
757          // one expansion. msg.sty (loaded transitively from
758          // french.sty, czech.sty, … under INCLUDE_STYLES=true)
759          // uses exactly this idiom for `\msgheader`, so the
760          // earlier blanket `\protect\foo`-is-runaway check
761          // fired ~3 errors per language-style paper. Witness:
762          // math9903002, gr-qc9511021, alg-geom9611022,
763          // math9807030/.../math9810088 (8 papers).
764          t1 == &self.cs && t0 == &T_CS!("\\protect") && protect_is_relax_or_undefined()
765        } else {
766          false
767        }
768      } else {
769        false
770      }
771    } else {
772      false
773    }
774  }
775
776  /// Read this macro's arguments as tex.web §389-391 `macro_call` does, at
777  /// `matching` status naming the invoked token (an alias's own name, as
778  /// TeX's `warning_index:=cur_cs`). `None` abandons the call: a delimiter
779  /// that does not match (§398), or an argument that ran off the end of a file
780  /// ("File ended while scanning use of \foo", §338-339 and §392; or, for a
781  /// non-`\long` macro whose argument held a `\par`, "Paragraph ended before
782  /// \foo was complete", §396: [`crate::gullet::abandon_runaway_call`]).
783  /// Guards: `scanner_status::*`.
784  fn read_call_arguments(&self, parms: &Parameters) -> Result<Option<Vec<ArgWrap>>> {
785    let cs = get_current_token().unwrap_or(self.cs);
786    let matching = crate::gullet::set_scanner_status_checking_par(
787      crate::gullet::ScannerStatus::Matching,
788      Some(cs),
789      self.checks_par,
790    );
791    let args = parms.read_macro_arguments(Some(self))?;
792    match matching.end_taking_runaway_argument() {
793      None => Ok(args),
794      Some(runaway) => {
795        crate::gullet::abandon_runaway_call(cs, self.is_long, self.checks_par, runaway)?;
796        Ok(None)
797      },
798    }
799  }
800
801  pub fn new(
802    cs: Token,
803    paramlist: Option<Parameters>,
804    mut expansion_opt: Option<ExpansionBody>,
805    traits: Option<ExpandableOptions>,
806  ) -> Result<Self> {
807    let traits = traits.unwrap_or_default();
808    if !traits.nopack_parameters
809      && let Some(ExpansionBody::Tokens(expansion_tokens)) = expansion_opt
810    {
811      // Perl Core/Definition/Expandable.pm:35: FATAL if the expansion is
812      // unbalanced (mismatched {/}). An Error-and-store-as-is let
813      // jarticle.cls:94-97's `\ds@tate` (an ISO-2022-JP byte pair whose `%`
814      // eats `\message`'s closing brace) proceed into japanese-otf's kanji
815      // scanners, an aperiodic 250 s `\advance` loop the cycle guard cannot
816      // see (platexcheat sample/platexsheet; Perl aborts in 1.3 s). Fatal
817      // stays Fatal. Guard: `perfect_kernel_batch56::unbalanced_expansion_is_fatal`.
818      if !expansion_tokens.is_balanced() {
819        Fatal!(
820          Stomach,
821          Misdefined,
822          s!("Expansion of '{}' has unbalanced {{}}", cs)
823        );
824      } else {
825        expansion_opt = Some(ExpansionBody::Tokens(expansion_tokens.pack_parameters()?));
826      }
827    }
828    let has_cc_arg = match expansion_opt {
829      Some(ExpansionBody::Tokens(ref tks)) => tks
830        .unlist_ref()
831        .iter()
832        .any(|t| t.get_catcode() == Catcode::ARG),
833      _ => false,
834    };
835    // simplify: treat empty tokens as None
836    let expansion = match expansion_opt {
837      Some(ExpansionBody::Tokens(tks)) if tks.is_empty() => None,
838      real_body => real_body,
839    };
840
841    // A `\newcommand` optional argument is read by `\@protected@testopt` →
842    // `\kernel@ifnextchar` (latex.ltx:1249, 1259-1261), a futurelet peek.
843    let peeks_by_futurelet = traits.peeks_by_futurelet
844      || paramlist.as_ref().is_some_and(|params| {
845        params
846          .get_parameters()
847          .first()
848          .is_some_and(|param| param.testopt)
849      });
850    let is_long = traits.long || get_prefix_sym(crate::pin!("long"));
851    let reads_arguments = paramlist
852      .as_ref()
853      .is_some_and(|params| !params.get_parameters().is_empty());
854    Ok(Expandable {
855      cs,
856      paramlist,
857      peeks_by_futurelet,
858      expansion,
859      // locator           => $source->getLocator,
860      // Hot path: Expandable::new fires on every \def/\edef; pin!-cached keys
861      // skip the per-call arena probe (same policy as Conditional::invoke).
862      is_protected: traits.protected || get_prefix_sym(crate::pin!("protected")),
863      is_outer: traits.outer || get_prefix_sym(crate::pin!("outer")),
864      is_long,
865      checks_par: !is_long
866        && reads_arguments
867        && (traits.short
868          || traits.tex_declared
869            && matches!(
870              crate::definition::origin::current_origin(),
871              crate::definition::origin::DefinitionOrigin::Format
872                | crate::definition::origin::DefinitionOrigin::File
873                | crate::definition::origin::DefinitionOrigin::Document
874            )),
875      has_cc_arg,
876      alias: traits.alias,
877      dropped_by_design: traits.drops.iter().fold(0, |bits, &number| {
878        // (a macro's arguments are #1-#9: a bit each in the u16)
879        debug_assert!(number <= 9, "a dropped argument number past #9: {number}");
880        bits | 1 << number
881      }),
882      made_in_own_file: crate::definition::origin::reading_own_file(),
883      ..Expandable::default()
884    })
885  }
886}
887
888/// The kernel's commands that write a definition's name: the `\def` family, `\let`, `\g@addto@macro`. The unclaimed-text
889/// net's stores read these alone (latexml_engine `frontmatter_stores::stores_raw_code_writes`), which change the output
890/// where the check's cannot; the check reads [`ETOOLBOX_WRITERS_OF_NAMES`] too.
891pub const KERNEL_WRITERS_OF_NAMES: &[&str] = &[
892  "\\def",
893  "\\gdef",
894  "\\edef",
895  "\\xdef",
896  "\\let",
897  "\\protected@edef",
898  "\\protected@xdef",
899  "\\g@addto@macro",
900];
901
902/// The other commands that write a definition's name, the title-page check's alone (`stored_parameters`, latexml_engine
903/// `title_page_check::StoreReaders`): etoolbox's, and the kernel's `\@namedef`.
904pub const ETOOLBOX_WRITERS_OF_NAMES: &[&str] = &[
905  "\\@namedef",
906  "\\appto",
907  "\\gappto",
908  "\\eappto",
909  "\\xappto",
910  "\\preto",
911  "\\gpreto",
912  "\\epreto",
913  "\\xpreto",
914  "\\listadd",
915  "\\listgadd",
916  "\\listeadd",
917  "\\listxadd",
918  "\\csdef",
919  "\\csgdef",
920  "\\csedef",
921  "\\csxdef",
922  "\\csappto",
923  "\\csgappto",
924  "\\cseappto",
925  "\\csxappto",
926  "\\cspreto",
927  "\\csgpreto",
928  "\\csepreto",
929  "\\csxpreto",
930  "\\listcsadd",
931  "\\listcsgadd",
932  "\\listcseadd",
933  "\\listcsxadd",
934];
935
936/// The commands that write a definition's name: [`KERNEL_WRITERS_OF_NAMES`] and [`ETOOLBOX_WRITERS_OF_NAMES`], one list
937/// to search (`stored_parameters` asks for every control sequence of every definition's body).
938pub const WRITERS_OF_NAMES: [&str;
939  KERNEL_WRITERS_OF_NAMES.len() + ETOOLBOX_WRITERS_OF_NAMES.len()] = {
940  let mut all = [""; KERNEL_WRITERS_OF_NAMES.len() + ETOOLBOX_WRITERS_OF_NAMES.len()];
941  let mut at = 0;
942  while at < all.len() {
943    all[at] = if at < KERNEL_WRITERS_OF_NAMES.len() {
944      KERNEL_WRITERS_OF_NAMES[at]
945    } else {
946      ETOOLBOX_WRITERS_OF_NAMES[at - KERNEL_WRITERS_OF_NAMES.len()]
947    };
948    at += 1;
949  }
950  all
951};
952
953/// A writer of [`WRITERS_OF_NAMES`] whose value joins what its store holds, past `\g@addto@macro`.
954const APPENDERS: &[&str] = &[
955  "\\g@addto@macro",
956  "\\appto",
957  "\\gappto",
958  "\\eappto",
959  "\\xappto",
960  "\\preto",
961  "\\gpreto",
962  "\\epreto",
963  "\\xpreto",
964  "\\listadd",
965  "\\listgadd",
966  "\\listeadd",
967  "\\listxadd",
968  "\\csappto",
969  "\\csgappto",
970  "\\cseappto",
971  "\\csxappto",
972  "\\cspreto",
973  "\\csgpreto",
974  "\\csepreto",
975  "\\csxpreto",
976  "\\listcsadd",
977  "\\listcsgadd",
978  "\\listcseadd",
979  "\\listcsxadd",
980];
981
982/// The kernel's and the common classes' scratch names, which code writes and reads again at once: no store a setter fills,
983/// whatever else reads them later (`\subject{secondary}` through `\@tempa`, 1803.03153; `\newtheorem*` through
984/// `\reserved@a`, 1912.10847; 2505.24263). What they hold hands on to what they are written into (`stored_parameters`).
985const SCRATCH_NAMES: &[&str] = &[
986  "\\@tempa",
987  "\\@tempb",
988  "\\@tempc",
989  "\\@tempd",
990  "\\@tempe",
991  "\\@tempf",
992  "\\@gtempa",
993  "\\@temp",
994  "\\@tmp",
995  "\\@tmpa",
996  "\\@tmpb",
997  "\\@tmpc",
998  "\\temp",
999  "\\tempa",
1000  "\\tempb",
1001  "\\tempc",
1002  "\\tmp",
1003  "\\tmpa",
1004  "\\tmpb",
1005  "\\tmpc",
1006  "\\reserved@a",
1007  "\\reserved@b",
1008  "\\reserved@c",
1009  "\\reserved@d",
1010  "\\reserved@e",
1011  "\\reserved@f",
1012  "\\toks@",
1013  "\\@temptokena",
1014  "\\@toks",
1015];
1016
1017/// Is the control sequence named `name` a scratch name (`SCRATCH_NAMES`)?
1018pub fn is_scratch_name(name: &str) -> bool { SCRATCH_NAMES.contains(&name) }
1019
1020/// What a raw setter's body writes into a store (`stored_parameters`).
1021#[derive(Debug, Clone, Default)]
1022pub struct StoredParameters {
1023  /// a bit `n` for each `#n` written
1024  pub numbers:     u16,
1025  /// each write replaces a known store, and none reads a store written before it: a later call of the macro supersedes
1026  /// this one's text (`\def\@x{#1}`, as against `\g@addto@macro\@x{#1}`, `\xdef\@x{\@x #1}`, `\write`, a `\csname`
1027  /// store, `\def\@x{#1}\xdef\y{\y\@x}`)
1028  pub replaces:    bool,
1029  /// the stores written, by name (a `\csname…\endcsname` one has none: no reader of it can be told)
1030  pub stores:      Vec<Token>,
1031  /// one is written out (`\write`), whose reader is the next run
1032  pub written_out: bool,
1033}
1034
1035/// The parameters the token body `body` writes into a store: inside the value `{…}` of a writer of a named store
1036/// ([`WRITERS_OF_NAMES`] but `\let`, which takes one name; `\renewcommand`, `\newcommand`, `\providecommand`), of a token
1037/// register's assignment, or of a `\write` to a named stream. CUP-JNL-DTM.cls's `\g@addto@macro\auaddress{…#2…}`
1038/// (2305.00867), aeb_emulateapj's `\global\alt@affil@toks\expandafter{\the\alt@affil@toks … #2}` (1011.2770),
1039/// naverlabseurope.cls's `\def\@authors{#1}` (2408.05088), bosonai_techreport.sty's
1040/// `\renewcommand{\@affiliation}{#1}` (2605.02209), nj_style's `\immediate\write\@auxout{…{#1}…}` (1401.7920). A store the
1041/// body names by a parameter (`\gdef#1{#2}`) is a shorthand maker's, none; a `\csname` name is one, by no name. A name
1042/// written earlier in the body hands its parameters on to a value that names it (`\toks@{#1}\xdef\x{\the\toks@}`,
1043/// `\def\@tempa{#1}\global\let\x\@tempa`, SCIS2026.cls's temporary `\@authoremail`); a scratch name itself
1044/// ([`SCRATCH_NAMES`]) is no store.
1045fn stored_parameters(body: &[Token]) -> StoredParameters {
1046  const WRITERS_OF_COMMANDS: &[&str] = &["\\renewcommand", "\\newcommand", "\\providecommand"];
1047  let mut stored = StoredParameters {
1048    replaces: true,
1049    ..StoredParameters::default()
1050  };
1051  // (what each name written so far holds: its parameters, and every token of its value)
1052  let mut written: Vec<(Token, u16, Vec<Token>)> = Vec::new();
1053  let mut at = 0;
1054  while at < body.len() {
1055    let token = &body[at];
1056    at += 1;
1057    if token.get_catcode() != Catcode::CS {
1058      continue;
1059    }
1060    let is = |set: &[&str]| token.with_str(|name| set.contains(&name));
1061    let register = at >= 2 && body[at - 2].with_str(|name| name == "\\the");
1062    let is_let = token.with_str(|name| name == "\\let");
1063    // (the store's name, and from where the search for its value starts)
1064    let (store, value_search) = if is(WRITERS_OF_COMMANDS) || is(&WRITERS_OF_NAMES) {
1065      match written_store_name(body, at) {
1066        Some(found) => found,
1067        None => continue,
1068      }
1069    } else if token.with_str(|name| name == "\\write") {
1070      match body.get(at) {
1071        Some(stream) if stream.get_catcode() == Catcode::CS => (Some(*stream), at + 1),
1072        _ => continue,
1073      }
1074    } else if !register && is_token_register(token) {
1075      (Some(*token), at)
1076    } else {
1077      continue;
1078    };
1079    let scratch = store.is_some_and(|store| store.with_str(is_scratch_name));
1080    // (a value: a group's inside, or `\let`'s one token)
1081    let range = if is_let {
1082      let mut from = value_search;
1083      while body
1084        .get(from)
1085        .is_some_and(|t| t.get_catcode() == Catcode::SPACE || t.with_str(|text| text == "="))
1086      {
1087        from += 1;
1088      }
1089      (from < body.len()).then_some((from, from + 1))
1090    } else {
1091      value_group(body, value_search, token)
1092    };
1093    let Some((from, to)) = range else {
1094      continue;
1095    };
1096    let value = &body[from..to];
1097    // (a write that reads a store this body wrote first: `\gdef\@tmpz{#1}\g@addto@macro\x\@tmpz`, so a later call does
1098    // not supersede this one. Two stores side by side do: acm's `\conferenceinfo`'s `\global\conf={#1}\global\confinfo{#2}`,
1099    // called twice, 1612.06202)
1100    if value.iter().any(|inner| stored.stores.contains(inner)) {
1101      stored.replaces = false;
1102    }
1103    let mut named = 0u16;
1104    let mut holds: Vec<Token> = value.to_vec();
1105    for inner in value {
1106      if inner.get_catcode() == Catcode::ARG
1107        && let Some(number) = inner.with_str(|text| text.parse::<u16>().ok())
1108      {
1109        named |= 1 << number;
1110      } else if let Some((_, numbers, tokens)) = written.iter().find(|(name, ..)| name == inner) {
1111        named |= numbers;
1112        holds.extend_from_slice(tokens);
1113      }
1114    }
1115    if named != 0 && !scratch {
1116      stored.numbers |= named;
1117      let appends = is(APPENDERS) || token.with_str(|name| name == "\\write");
1118      match store {
1119        // (a `\csname` store: which one a later call writes, its counter's next, cannot be told)
1120        None => stored.replaces = false,
1121        Some(store) => {
1122          if appends || holds.contains(&store) {
1123            stored.replaces = false;
1124          }
1125          if token.with_str(|name| name == "\\write") {
1126            stored.written_out = true;
1127          } else {
1128            stored.stores.push(store);
1129          }
1130        },
1131      }
1132    }
1133    if let Some(store) = store
1134      && !(token.with_str(|name| name == "\\write"))
1135    {
1136      written.retain(|(name, ..)| *name != store);
1137      written.push((store, named, holds));
1138    }
1139    at = to;
1140  }
1141  stored
1142}
1143
1144/// The store a writer at `at - 1` names at `at` (`\x`, `{\x}`, `*\x`, `\expandafter\x`, a `\csname…\endcsname` or the
1145/// group `\@namedef` and etoolbox's `\csgdef` take: none known then), and where the search for its value starts; `None`
1146/// when it names no store (`\gdef#1{#2}`).
1147pub fn written_store_name(body: &[Token], mut at: usize) -> Option<(Option<Token>, usize)> {
1148  while let Some(token) = body.get(at)
1149    && (token.get_catcode() == Catcode::SPACE
1150      || token.with_str(|text| text == "*" || text == "\\expandafter"))
1151  {
1152    at += 1;
1153  }
1154  let token = body.get(at)?;
1155  match token.get_catcode() {
1156    Catcode::CS if token.with_str(|name| name == "\\csname") => {
1157      let end = body[at..]
1158        .iter()
1159        .position(|t| t.with_str(|name| name == "\\endcsname"))?;
1160      Some((None, at + end + 1))
1161    },
1162    Catcode::CS | Catcode::ACTIVE => Some((Some(*token), at + 1)),
1163    Catcode::BEGIN => {
1164      let name = body.get(at + 1)?;
1165      let close = body.get(at + 2)?;
1166      if name.get_catcode() == Catcode::CS && close.get_catcode() == Catcode::END {
1167        return Some((Some(*name), at + 3));
1168      }
1169      // (a name built in a group)
1170      let mut depth = 0usize;
1171      for (offset, token) in body[at..].iter().enumerate() {
1172        match token.get_catcode() {
1173          Catcode::BEGIN => depth += 1,
1174          Catcode::END => {
1175            depth -= 1;
1176            if depth == 0 {
1177              return Some((None, at + offset + 1));
1178            }
1179          },
1180          _ => {},
1181        }
1182      }
1183      None
1184    },
1185    _ => None,
1186  }
1187}
1188
1189/// The inside of the value group of `writer`, searched from `at`: the next `{…}`, balanced. A `\def`'s parameter text may
1190/// stand before it, a `\newcommand`'s `[n]`; a register's assignment or a `\write` has only `=`, spaces and `\expandafter`
1191/// there (`\toks@\the\x` assigns no group; `\@auxout\foo`).
1192pub fn value_group(body: &[Token], mut at: usize, writer: &Token) -> Option<(usize, usize)> {
1193  let by_group_only = !writer.with_str(|name| {
1194    WRITERS_OF_NAMES.contains(&name)
1195      || matches!(name, "\\renewcommand" | "\\newcommand" | "\\providecommand")
1196  });
1197  while let Some(token) = body.get(at) {
1198    match token.get_catcode() {
1199      Catcode::BEGIN => break,
1200      Catcode::END => return None,
1201      Catcode::SPACE => {},
1202      _ if !by_group_only => {},
1203      _ if token.with_str(|text| text == "=" || text == "\\expandafter") => {},
1204      _ => return None,
1205    }
1206    at += 1;
1207  }
1208  let from = at + 1;
1209  let mut depth = 0usize;
1210  for (offset, token) in body.get(at..)?.iter().enumerate() {
1211    match token.get_catcode() {
1212      Catcode::BEGIN => depth += 1,
1213      Catcode::END => {
1214        depth -= 1;
1215        if depth == 0 {
1216          return Some((from, at + offset));
1217        }
1218      },
1219      _ => {},
1220    }
1221  }
1222  None
1223}
1224
1225/// Does the token body `body` name its parameter `#number` (an argument token, `Catcode::ARG`)?
1226fn names_parameter(body: &Tokens, number: usize) -> bool {
1227  body.unlist_ref().iter().any(|token| {
1228    token.get_catcode() == Catcode::ARG && token.with_str(|text| text == number.to_string())
1229  })
1230}
1231
1232#[cfg(test)]
1233mod tests {
1234  use super::*;
1235
1236  #[test]
1237  fn expandable_default_flags_false() {
1238    let e = Expandable::default();
1239    assert!(!e.is_protected);
1240    assert!(!e.peeks_by_futurelet);
1241    assert!(!e.is_long);
1242    assert!(!e.is_outer);
1243    assert!(!e.has_cc_arg);
1244    assert!(e.alias.is_none());
1245    assert!(e.paramlist.is_none());
1246    assert!(e.expansion.is_none());
1247  }
1248
1249  #[test]
1250  fn expandable_default_has_default_cs() {
1251    let e = Expandable::default();
1252    // Default cs is a T_CS with empty text (produced by Token::default
1253    // or similar). We can at least confirm the code is CS.
1254    assert_eq!(e.cs.code, Catcode::CS);
1255  }
1256
1257  #[test]
1258  fn expandable_is_definition_and_expandable() {
1259    let e = Expandable::default();
1260    assert!(e.is_definition());
1261    assert!(e.is_expandable());
1262  }
1263
1264  #[test]
1265  fn expandable_partial_eq_by_paramlist_and_expansion() {
1266    // PartialEq ignores flags (protected/long/outer) and cs — it
1267    // compares paramlist and expansion only.
1268    let mut a = Expandable::default();
1269    let mut b = Expandable::default();
1270    // Both have paramlist=None, expansion=None → equal.
1271    assert_eq!(a, b);
1272    // Changing flags doesn't affect equality.
1273    a.is_protected = true;
1274    b.is_protected = false;
1275    assert_eq!(a, b);
1276  }
1277
1278  #[test]
1279  fn expandable_get_num_args_zero_without_paramlist() {
1280    let e = Expandable::default();
1281    assert_eq!(e.get_num_args(), 0);
1282  }
1283
1284  #[test]
1285  fn expandable_get_parameters_none_by_default() {
1286    let e = Expandable::default();
1287    assert!(e.get_parameters().is_none());
1288  }
1289
1290  #[test]
1291  fn expandable_options_default_all_false() {
1292    let o = ExpandableOptions::default();
1293    assert!(!o.locked);
1294    assert!(!o.protected);
1295    assert!(!o.outer);
1296    assert!(!o.long);
1297    assert!(o.scope.is_none());
1298    assert!(o.alias.is_none());
1299    assert!(!o.mathactive);
1300    assert!(!o.robust);
1301    assert!(!o.nopack_parameters);
1302    assert!(!o.peeks_by_futurelet);
1303  }
1304}