Skip to main content

latexml_core/
parameter.rs

1use std::{
2  cell::{Cell, RefCell},
3  fmt,
4  rc::Rc,
5  sync::LazyLock,
6};
7
8#[cfg(feature = "codegen")]
9use proc_macro2::TokenStream;
10#[cfg(feature = "codegen")]
11use quote::{ToTokens, quote};
12use regex::Regex;
13
14use crate::{
15  BoxOps, Digested,
16  common::{
17    arena::{self, SymStr},
18    error::{emit_warn, *},
19    object::Object,
20  },
21  definition::{
22    BeforeDigestClosure, Definition, DigestionClosure,
23    argument::ArgWrap,
24    constructor::Constructor,
25    register::{RegisterType, RegisterValue},
26  },
27  gullet,
28  mouth::Mouth,
29  pin,
30  state::*,
31  token::{Catcode, Token},
32  tokens::Tokens,
33  whatsit::Whatsit,
34};
35
36pub type ReaderFn = dyn Fn(Option<&Parameters>, &[Tokens]) -> Result<ArgWrap>;
37pub type ReaderPredigestFn = dyn Fn(ArgWrap, &[Tokens]) -> Result<Option<Digested>>;
38pub type ReaderPredigestClosure = Rc<ReaderPredigestFn>;
39pub type ReaderClosure = Rc<ReaderFn>;
40
41// Rust Note:
42// the reversion functions initially had "&mut Gullet" as a parameter.
43// This turned out to be infeasible if we are to maintain the latexml code flow
44// as we have calls into reversions from arbitrary binding closures, at ALL phases.
45// Compromise: use the gated Stomach in state::whenever you need gullet in reversion, as in
46// let mut stomach = state::stomach.borrow_mut();
47//
48//
49pub type ReversionClosure =
50  Rc<dyn Fn(Vec<Token>, Option<&Parameters>, &[Tokens]) -> Result<Tokens>>;
51
52/// A reversion closure that operates on the original Digested argument,
53/// enabling access to structured data (e.g., KeyVals) for custom reversion formatting.
54/// Perl equivalent: the `reversion` option on DefParameterType, which receives the raw value.
55pub type DigestedReversionClosure = Rc<dyn Fn(&Digested) -> Result<Tokens>>;
56
57/// `LXML_TRACE_ARGS=\cs`, read ONCE: both argument readers below run on every
58/// macro, primitive, conditional and constructor invocation, and
59/// `std::env::var` takes the process environment lock and byte-scans the
60/// environment each call — 14 % of a pgf/TikZ conversion (tikz-network's
61/// 887 M token reads per picture; symbolized profile
62/// `~/data/pk_agents/w23/perf_pgf/NOTES.md`), the same trap gullet.rs's
63/// `TRACE_GROUP_END` records. A debug switch set before launch never changes.
64static TRACE_ARGS: LazyLock<Option<String>> =
65  LazyLock::new(|| std::env::var("LXML_TRACE_ARGS").ok());
66
67static LAST_WCHAR_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\w$").unwrap());
68static FIRST_WCHAR_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\w").unwrap());
69
70#[derive(Clone)]
71pub struct Parameter {
72  pub novalue:            bool,
73  /// A `\newcommand`-family optional argument: latex.ltx reads it through
74  /// `\@protected@testopt` → `\@testopt` → `\kernel@ifnextchar[` (1249, 1261,
75  /// 1259-1260), a futurelet peek, so its macro
76  /// [`peeks_by_futurelet`](crate::definition::Definition::peeks_by_futurelet).
77  pub testopt:            bool,
78  /// The `\@protected@testopt` call its command is in LaTeX, where the command's definer made the internal it names
79  /// ([`TestoptCall`]).
80  pub testopt_call:       Option<Rc<TestoptCall>>,
81  /// A size argument latex.ltx evaluates with the box already set, so that
82  /// `\width`/`\height`/`\depth`/`\totalheight` measure it (`\@begin@tempboxa`,
83  /// latex.ltx:16085-16094): `TempboxaDimension`, graphics' `GraphixDimension`. See
84  /// [`Parameters::read_arguments_and_digest`].
85  pub after_box:          bool,
86  pub semiverbatim:       Option<Vec<char>>,
87  pub optional:           bool,
88  pub name:               SymStr,
89  pub spec:               SymStr,
90  pub extra:              Vec<Tokens>,
91  pub inner:              Option<Parameters>,
92  pub reader:             ReaderClosure,
93  pub predigest:          Option<ReaderPredigestClosure>,
94  pub reversion:          Option<ReversionClosure>,
95  /// Reversion closure that operates on the original Digested argument.
96  /// Takes precedence over `reversion` when the argument is a digested value.
97  /// Perl equivalent: `reversion` option on DefParameterType with `undigested => 1`.
98  pub digested_reversion: Option<DigestedReversionClosure>,
99  pub before_digest:      Vec<BeforeDigestClosure>,
100  pub after_digest:       Vec<DigestionClosure>,
101  /// `(OptionalMatch…, Until…)` of `name`, worked out on the first read (lazily: `name` is set
102  /// by struct update after `Default`), so a read pays no interner lookup.
103  pub name_kind:          Cell<Option<(bool, bool)>>,
104  /// A braced or bracketed argument's tokens as the source states them (`{0.48\textwidth}`), kept for the reader that
105  /// asked for them ([`Parameters::read_arguments_and_digest`] under [`KEEP_STATED_LENGTHS`]): `Some` while asked
106  /// for, holding them once [`Parameters::reparse_argument`] has read them.
107  pub stated:             RefCell<Option<Tokens>>,
108}
109
110/// The state value that asks a constructor to keep the tokens its braced or bracketed typed arguments state
111/// (`{Dimension}`, `[TempboxaDimension]`, `{SetlengthDimension}`, …) on its whatsit ([`STATED_LENGTHS`]), and a
112/// `KeyVals` the tokens of its typed length values (`KeyVals::stated_entry`): what the source states, which a reader
113/// may evaluate again under other register values (latexml_engine's panel rows, a float's panels set against the
114/// class's real line; OXIDIZED_DESIGN_DIVERGENCES #885). Assigned in a group (a float's), so it ends with it.
115pub const KEEP_STATED_LENGTHS: &str = "lx@keep@stated@lengths";
116
117/// The whatsit property holding the tokens its typed arguments state ([`KEEP_STATED_LENGTHS`]): a
118/// `Stored::VecDequeStored` aligned with the whatsit's arguments, `Stored::Tokens` for a kept one, else `Stored::None`.
119pub const STATED_LENGTHS: &str = "stated_lengths";
120
121/// The state value with which a binding that sizes a box of its own accord withholds the tokens of the lengths it
122/// gives a constructor ([`KEEP_STATED_LENGTHS`] off in its group; latexml_engine's `\lx@panel@unstated`, subcaption's
123/// `\subfloat`): the source states no such length, which differs from one given where none are kept (a box built
124/// outside a float). Assigned in a group, so it ends with it.
125pub const WITHHOLD_STATED_LENGTHS: &str = "lx@withhold@stated@lengths";
126
127/// The whatsit property marking a constructor whose length arguments' tokens were withheld
128/// ([`WITHHOLD_STATED_LENGTHS`]): it states none.
129pub const STATED_LENGTHS_WITHHELD: &str = "stated_lengths_withheld";
130
131/// A command with an optional argument is `\@protected@testopt\cs\\cs{<default>}` in LaTeX (latex.ltx:1245-1257
132/// `\@xargdef`; twoopt.sty:51-55; xargs.sty:205-212, whose `head` is `\@protected@testopt@xargs` where an argument
133/// after the first is optional). Ours reads its arguments itself, and `Expandable::testopt_call` makes this call, the
134/// default its parameter's, only once `head` is no longer `kernel`, the copy its definer saved (hyperref.sty:548-549
135/// in a PDF string).
136#[derive(Clone, Debug)]
137pub struct TestoptCall {
138  pub head:     Token,
139  pub kernel:   Token,
140  /// `\cs`, `\csname\string\cs\endcsname`, which the definer defined
141  pub internal: Token,
142}
143
144impl TestoptCall {
145  /// latex.ltx's `\@protected@testopt`, against its copy `\lx@kernel@protected@testopt` (sect13.rs).
146  pub fn kernel(internal: Token) -> Self {
147    TestoptCall {
148      head: crate::T_CS!("\\@protected@testopt"),
149      kernel: crate::T_CS!("\\lx@kernel@protected@testopt"),
150      internal,
151    }
152  }
153}
154
155impl Default for Parameter {
156  fn default() -> Self {
157    Parameter {
158      novalue:            false,
159      testopt:            false,
160      testopt_call:       None,
161      after_box:          false,
162      semiverbatim:       None,
163      optional:           false,
164      name:               pin!("parameter_default"),
165      spec:               pin!(""),
166      extra:              Vec::new(),
167      inner:              None,
168      reader:             Rc::new(|_args, _extra| {
169        Warn!(
170          "Parameter",
171          "mock_reader",
172          "Please define a real reader, this is a mock fallback!"
173        );
174        Ok(ArgWrap::None)
175      }),
176      predigest:          None,
177      reversion:          None,
178      digested_reversion: None,
179      before_digest:      Vec::new(),
180      after_digest:       Vec::new(),
181      name_kind:          Cell::new(None),
182      stated:             RefCell::new(None),
183    }
184  }
185}
186impl fmt::Debug for Parameter {
187  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
188    writeln!(
189      f,
190      "Parameter(\n\t name:{:?}, novalue:{:?}, semiverbatim:{:?},",
191      self.name, self.novalue, self.semiverbatim,
192    )?;
193    writeln!(f, "\t optional:{:?}, spec:{:?}", self.optional, self.spec)?;
194    writeln!(f, "\t inner: {:?}", self.inner)?;
195    writeln!(
196      f,
197      "\t extra: {:?}\n\t reversion: {:?}, before_digest: {:?}, after_digest: {:?} )",
198      self.extra,
199      self.reversion.is_some(),
200      self.before_digest.len(),
201      self.after_digest.len()
202    )
203  }
204}
205impl fmt::Display for Parameter {
206  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
207    arena::with(self.name, |name| write!(f, "{name}"))
208  }
209}
210
211impl PartialEq for Parameter {
212  fn eq(&self, other: &Parameter) -> bool { self.name == other.name }
213}
214impl Object for Parameter {
215  fn stringify(&self) -> String { arena::to_string(self.spec) }
216}
217
218static OPTIONAL_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^Optional(.+)$").unwrap());
219static SKIP_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^Skip(.+)$").unwrap());
220
221/// A `{}` argument that is exactly one token whose MEANING is `{` (an
222/// implicit begin-group such as `\bgroup`, not a literal brace): the `{}`
223/// reader takes the single token, so the group body is still in the gullet.
224fn is_implicit_begin_group(arg: &ArgWrap) -> bool {
225  match arg {
226    ArgWrap::Tokens(toks) => {
227      let list = toks.unlist_ref();
228      list.len() == 1
229        && list[0].get_catcode() != Catcode::BEGIN
230        && list[0].defined_as(&crate::T_BEGIN!())
231    },
232    _ => false,
233  }
234}
235
236impl Parameter {
237  pub fn new<T: AsRef<str>>(name: T, spec: T, extra: Option<Vec<Tokens>>) -> Result<Self> {
238    Parameter {
239      name: arena::pin(name),
240      spec: arena::pin(spec),
241      extra: extra.unwrap_or_default(),
242      ..Parameter::default()
243    }
244    .init()
245  }
246  pub fn init(mut self) -> Result<Self> {
247    // Create a parameter reading object for a specific type.
248    // If either a declared entry or a function Read<Type> accessible from LaTeXML::Package::Pool
249    // is defined.
250    let mut descriptor: Option<Rc<Parameter>> =
251      with_mapping_sym(pin!("PARAMETER_TYPES"), self.name, |looked_up_mapping| {
252        if let Some(Stored::Parameter(d_lookup)) = looked_up_mapping {
253          Some(Rc::clone(d_lookup))
254        } else {
255          None
256        }
257      });
258    if descriptor.is_none() {
259      // TODO: see discussion on line 168
260      let basetype_opt = arena::with(self.name, |name| {
261        OPTIONAL_REGEX
262          .captures(name)
263          .map(|captures| captures.get(1).map_or("", |m| m.as_str()).to_string())
264      })
265      .map(arena::pin);
266      if let Some(basetype) = basetype_opt {
267        descriptor = with_mapping_sym(pin!("PARAMETER_TYPES"), basetype, |basetype_param_opt| {
268          match basetype_param_opt {
269            Some(Stored::Parameter(d_lookup)) => Ok(Some(d_lookup.clone())),
270            _ => match Parameter::check_reader_function(&arena::with(self.name, |name| {
271              s!("Read{name}")
272            })) {
273              Some(reader) => Ok(Some(Rc::new(Parameter {
274                reader,
275                optional: true,
276                ..Parameter::default()
277              }))),
278              None => match Parameter::check_reader_function(&arena::with(basetype, |type_str| {
279                s!("Read{type_str}")
280              })) {
281                Some(reader) => Ok(Some(Rc::new(Parameter {
282                  reader,
283                  optional: true,
284                  novalue: true,
285                  ..Parameter::default()
286                }))),
287                None => fatal!(
288                  Parameter,
289                  Init,
290                  s!("Can't initialize parameter {:?}, unknown?", self.name)
291                ),
292              },
293            },
294          }
295        })?;
296        self.optional = true;
297      } else {
298        // TODO: This looks like a code smell. Do we need a new arena method?
299        // We start with a ticket, do a non-allocation operation on the underlying &str,
300        // Then want to ping the newly acquired &str slice in the arena. Clearly that is only
301        // possible *AFTER* the original &str is released, but how do we avoid allocating?
302        // Is this a use for unsafe{} or is there a more idiomatic way?
303        // Maybe, with_mut... which allows an inner pin?
304        let basetype_opt = arena::with(self.name, |name| {
305          SKIP_REGEX
306            .captures(name)
307            .map(|captures| captures.get(1).map_or("", |m| m.as_str()).to_string())
308        })
309        .map(arena::pin);
310        if let Some(basetype) = basetype_opt {
311          descriptor = with_mapping_sym(pin!("PARAMETER_TYPES"), basetype, |basetype_param_opt| {
312            match basetype_param_opt {
313              Some(Stored::Parameter(d_lookup)) => Some(d_lookup.clone()),
314              _ => match arena::with(self.name, |name| Parameter::check_reader_function(name)) {
315                Some(reader) => Some(Rc::new(Parameter {
316                  reader,
317                  optional: true,
318                  novalue: true,
319                  ..Parameter::default()
320                })),
321                None => Parameter::check_reader_function(&arena::with(basetype, |type_str| {
322                  s!("Read{type_str}")
323                }))
324                .map(|reader| {
325                  Rc::new(Parameter {
326                    reader,
327                    optional: true,
328                    novalue: true,
329                    ..Parameter::default()
330                  })
331                }),
332              },
333            }
334          });
335          if let Some(ref _desc) = descriptor {
336            self.novalue = true;
337            self.optional = true;
338          }
339        } else {
340          descriptor =
341            Parameter::check_reader_function(&arena::with(self.name, |name| s!("Read{name}")))
342              .map(|reader| Rc::new(Parameter { reader, ..Parameter::default() }));
343        }
344      }
345    }
346    match descriptor {
347      Some(descriptor) => {
348        // descriptor needs to get integrated into Self
349        //  except `spec` and `name` which are always preserved!
350        self.reader = descriptor.reader.clone(); // What else?
351        if descriptor.novalue {
352          self.novalue = true;
353        }
354        if descriptor.after_box {
355          self.after_box = true;
356        }
357        self.semiverbatim.clone_from(&descriptor.semiverbatim);
358        // Also doing optional setting on the fly, so don't override unless true
359        // self.optional = descriptor.optional;
360        if descriptor.optional {
361          self.optional = true;
362        }
363        self.reversion.clone_from(&descriptor.reversion);
364        self
365          .digested_reversion
366          .clone_from(&descriptor.digested_reversion);
367        self.before_digest.clone_from(&descriptor.before_digest);
368        self.after_digest.clone_from(&descriptor.after_digest);
369        self.predigest.clone_from(&descriptor.predigest);
370      },
371      None => fatal!(
372        Parameter,
373        Unknown,
374        arena::with2(self.name, self.spec, |name, spec| s!(
375          "Unrecognized parameter type with name {:?}, spec {:?}",
376          name,
377          spec
378        ))
379      ),
380    }
381    // Last but not least, initialize any "inner" parameters
382    self.inner = self.inner.map(|inner_ps| match inner_ps.clone().init() {
383      Ok(ps) => ps,
384      Err(e) => {
385        emit_warn(
386          "internal",
387          "parameter",
388          &format!("inner parameter init failed: {e}"),
389        );
390        inner_ps
391      },
392    });
393    Ok(self)
394  }
395
396  /// Obtain the reader of a given parameter name, if available
397  pub fn check_reader_function(name: &str) -> Option<ReaderClosure> {
398    // TODO: This function doesn't have a direct Rust equivalent, since the metaprogramming isn't
399    // possible But what is the exact purpose of seeking through the pool namespace? Wouldn't
400    // any parameter be already assigned in the state::
401    with_mapping("PARAMETER_TYPES", name, |param_opt| {
402      if let Some(Stored::Parameter(param)) = param_opt {
403        Some(param.reader.clone())
404      } else {
405        None
406      }
407    })
408  }
409
410  /// ExpandedSemiverbatim wants the semiverbatim DIGESTION protection
411  /// (Parameter::digest's neutralize-under-ASCII branch — without it an
412  /// OTHER `_` font-decodes to the OT1 dot-above in the constructor's
413  /// output) but must NOT flip catcodes at READ time: its whole point is
414  /// tokenizing the argument at the CALLER's catcodes so an expl3
415  /// `\l_..._tl` file name stays one control sequence.
416  #[inline]
417  fn semiverbatim_read_setup(&self) -> bool {
418    self.semiverbatim.is_some() && self.semiverbatim_set_up_at_read()
419  }
420
421  /// [`Self::semiverbatim_read_setup`] of a semiverbatim parameter, apart: this runs twice per argument of every macro.
422  #[inline(never)]
423  fn semiverbatim_set_up_at_read(&self) -> bool {
424    !arena::with(self.name, |n| n == "ExpandedSemiverbatim")
425  }
426
427  /// Whether a semiverbatim argument is expanded before it is digested (Perl Parameter.pm:124-132, "Expand (before
428  /// digest), so tokens can be neutralized"): every one but the Rust-only `UnexpandedSemiverbatim`, whose tokens are
429  /// neutralized as read and digested in order, as a macro's `#1` is — `\afterassignment\remove@to@nnil`, the kernel
430  /// `\fontsize`'s `\@defaultunits` (latex.ltx:10537), expanded ahead of its assignment missed its `\@nnil` delimiter
431  /// and `\@nil` ran undefined (1802.01191's `\email{\fontsize{11pt}{12pt}\selectfont …}`).
432  #[inline(never)]
433  fn semiverbatim_expands_before_digest(&self) -> bool {
434    !arena::with(self.name, |n| n == "UnexpandedSemiverbatim")
435  }
436
437  #[inline]
438  pub fn setup_catcodes(&self) {
439    if self.semiverbatim_read_setup() {
440      begin_semiverbatim(self.semiverbatim.as_deref());
441    }
442  }
443
444  #[inline]
445  pub fn revert_catcodes(&self) -> Result<()> {
446    if self.semiverbatim_read_setup() {
447      end_semiverbatim()?;
448    }
449    Ok(())
450  }
451
452  pub fn read(&self, fordefn: Option<&dyn Definition>) -> Result<ArgWrap> {
453    self.read_with(self.inner.as_ref(), fordefn)
454  }
455
456  /// A braced or bracketed argument whose one inner parameter is read with the
457  /// box already set (`after_box`): see [`Parameters::read_arguments_and_digest`].
458  fn measures_the_box(&self) -> bool {
459    self
460      .inner
461      .as_ref()
462      .is_some_and(|inner| matches!(inner.0.as_slice(), [only] if only.after_box))
463  }
464
465  /// [`Self::read`] with `inner` for the reader: `None` reads a braced or
466  /// bracketed argument's raw tokens, to be re-parsed later.
467  fn read_with(
468    &self,
469    inner: Option<&Parameters>,
470    fordefn: Option<&dyn Definition>,
471  ) -> Result<ArgWrap> {
472    // For semiverbatim, I had messed with catcodes, but there are cases
473    // (eg. \caption(...\label{badchars}}) where you really need to
474    // cleanup after the fact!
475    // Hmmm, seem to still need it...
476    self.setup_catcodes();
477
478    let closure = &self.reader;
479    let value_from_reader: ArgWrap = closure(inner, &self.extra)?;
480    // Direct enum destructure: was `is_tokens() then owned_tokens()`
481    // which matched twice (once for the is_tokens check, again for
482    // the owned_tokens dispatch over all ArgWrap variants). This
483    // function fires on every parameter read of every macro call —
484    // ~2M times on si.tex per callgrind.
485    let value_arg = match value_from_reader {
486      ArgWrap::Tokens(mut value) => {
487        if let Some(ref semi_chars) = self.semiverbatim {
488          value = neutralize_keeping_definition_names(value, semi_chars);
489        }
490        ArgWrap::Tokens(value)
491      },
492      other => other,
493    };
494    self.revert_catcodes()?;
495
496    // Perl: experiment: skip spaces after a successful OptionalMatch read
497    // (not when the call is being abandoned: nothing more is read).
498    if self.optional && !value_arg.is_none() && self.name_kind_of().0 && !gullet::argument_runaway()
499    {
500      gullet::skip_spaces()?;
501    }
502
503    // A `\def` parameter text's leading delimiter (`\def\lp\x{…}`) is a
504    // value-less required `Match`: its miss IS an improper macro call (below).
505    if value_arg.is_none()
506      && !self.optional
507      && (!self.novalue || self.is_macro_delimiter())
508      && self.predigest.is_none()
509      // A call being abandoned (tex.web §392) has nothing more to report.
510      && !gullet::argument_runaway()
511    {
512      self.read_missing_value(value_arg, fordefn)
513    } else {
514      Ok(value_arg)
515    }
516  }
517
518  /// Whether this parameter's name is an `OptionalMatch` and an `Until` one, found once.
519  #[inline]
520  fn name_kind_of(&self) -> (bool, bool) {
521    match self.name_kind.get() {
522      Some(kind) => kind,
523      None => {
524        let kind = arena::with(self.name, |name| {
525          (name.starts_with("OptionalMatch"), name.starts_with("Until"))
526        });
527        self.name_kind.set(Some(kind));
528        kind
529      },
530    }
531  }
532
533  /// [`Self::read_with`] of a required parameter that read no value.
534  #[cold]
535  #[inline(never)]
536  fn read_missing_value(
537    &self,
538    value_arg: ArgWrap,
539    fordefn: Option<&dyn Definition>,
540  ) -> Result<ArgWrap> {
541    let is_until = self.name_kind_of().1;
542    Ok({
543      // `Until:` readers return a DISTINGUISHABLE EOF (read_until → None
544      // when the delimiter never appeared; a matched-but-empty arg is
545      // Some(empty)). Real TeX's runaway-argument ERROR applies to REAL
546      // file ends — but many of our mouth ends are ARTIFICIAL (isolated
547      // constructor-argument mouths, reading_from_mouth), where real TeX
548      // would keep scanning the enclosing stream and find the delimiter
549      // (l3tl replace sentinels: spath3/litetable/zref-check — a
550      // per-iteration Error here regressed 63 corpus docs, sweep 23).
551      // So: stay QUIET for Until misses; zero-progress delimited-scan
552      // loops terminate via the stomach cycle guard instead. Perl errors
553      // here (Parameter.pm L93-97) and equally mis-fires on the
554      // artificial-EOF shapes. (The `Until` reader itself never yields
555      // None — it maps a miss to an empty argument, and reports the one
556      // REAL runaway, a miss at `gullet::at_end_of_all_input`, itself.)
557      // A `\def` delimiter missed because an ISOLATED token list ran out (an
558      // index phrase digested at `\index` time, a constructor argument) is the
559      // same artificial end: real TeX would read on — manyind.sty:98
560      // `\def\mgobblepgeref, #1 {}` eats makeindex's `, <page>`, which never
561      // follows here. Quiet, and the call proceeds as before. Only a present,
562      // different token is TeX's improper call (tex.web §398).
563      let ran_out = self.is_macro_delimiter()
564        && match gullet::read_token()? {
565          Some(next) => {
566            gullet::unread_one(next);
567            false
568          },
569          None => true,
570        };
571      if ran_out && gullet::argument_ran_off_a_file()? {
572        // At a file's end the call is abandoned instead (tex.web §392).
573        value_arg
574      } else if ran_out {
575        ArgWrap::Tokens(Tokens::new(Vec::new()))
576      } else if !is_until {
577        let fordefn_str = fordefn.map(|fdefn| fdefn.stringify()).unwrap_or_default();
578        Error!(
579          "expected",
580          self,
581          s!("Missing argument {} for {}", self.stringify(), fordefn_str)
582        );
583        if self.novalue {
584          ArgWrap::None
585        } else {
586          ArgWrap::Tokens(Tokens!(T_OTHER!("missing")))
587        }
588      } else {
589        value_arg
590      }
591    })
592  }
593
594  /// The leading delimiter of a `\def` parameter text (`\def\lp\x{…}`,
595  /// base_utilities.rs `parse_def_parameters`): a required `Match` that carries
596  /// no value. Binding `Match:to`-style parameters carry their value.
597  fn is_macro_delimiter(&self) -> bool {
598    self.novalue && !self.optional && self.name == crate::pin!("Match")
599  }
600
601  pub fn digest(
602    &self,
603    mut value_arg: ArgWrap,
604    _fordefn: Option<&Constructor>,
605  ) -> Result<Option<Digested>> {
606    // Perl Parameter.pm lines 122,139-141: capture MODE, check after digest
607    let mode = lookup_mode();
608    // If semiverbatim, Expand (before digest), so tokens can be neutralized; BLECH!!!!
609    if self.semiverbatim.is_some() {
610      // Digest-time protection applies to ExpandedSemiverbatim too (its
611      // read-time carve-out lives in semiverbatim_read_setup) — use the
612      // raw begin, not setup_catcodes.
613      begin_semiverbatim(self.semiverbatim.as_deref());
614      if value_arg.is_tokens() && !self.semiverbatim_expands_before_digest() {
615        value_arg = value_arg
616          .owned_tokens()
617          .map_or_else(ArgWrap::default, |value| {
618            ArgWrap::Tokens(Tokens::new(
619              value
620                .unlist()
621                .into_iter()
622                .map(|t| t.neutralize(&[]))
623                .collect(),
624            ))
625          });
626      } else if value_arg.is_tokens() {
627        if let Some(value) = value_arg.owned_tokens() {
628          let neutralized = gullet::reading_from_mouth(Mouth::default(), move || {
629            gullet::unread(value);
630            // Each token with whether it is neutralized: the name a definition primitive reads is
631            // read unexpanded and kept as it is (tex.web §1215 `get_r_token`), as are a definition's
632            // parameter text and a `\def`'s body (§473), `\let`'s `=` and target (§1221) and the token
633            // `\afterassignment`/`\aftergroup` save; `\futurelet`'s two peeked tokens TeX puts back, to
634            // be read (and expanded) as usual. Expanded, a font switch in the
635            // argument (`\textbf` → `\fontseries` → `\edef\f@series{…}`) defined the letter `m`,
636            // and a `\def~{…}` had its active `~` neutralized ("Missing control sequence
637            // inserted"; stopped full-arXiv run 329: 1212.6174 natbib `\cite` notes, 1303.4395 and
638            // 1711.09355 JHEP `\href` link text, 1011.4121 amsart `\urladdr{\def~…}`).
639            let mut tokens: Vec<(Token, bool)> = Vec::new();
640            loop {
641              match gullet::get_pending_comment() {
642                Some(token) => tokens.push((token, true)),
643                None => match gullet::read_x_token(Some(true), false, None) {
644                  Ok(token_opt) => match token_opt {
645                    Some(token) => {
646                      let kind = definition_reads_names(&token);
647                      tokens.push((token, true));
648                      read_definition_names(kind, &mut tokens)?;
649                    },
650                    None => break,
651                  },
652                  Err(x) => return Err(x),
653                },
654              }
655            }
656            Ok(Tokens::new(
657              tokens
658                .into_iter()
659                .map(|(t, neutralize)| if neutralize { t.neutralize(&[]) } else { t })
660                .collect(),
661            ))
662          })?;
663          value_arg = ArgWrap::Tokens(neutralized);
664        } else {
665          value_arg = ArgWrap::default();
666        }
667      }
668    }
669
670    for pre in self.before_digest.iter() {
671      // Done for effect only.
672      pre()?; // maybe pass extras?
673    }
674    let digested_value = if let Some(closure) = &self.predigest {
675      closure(value_arg, &self.extra)?
676    } else {
677      // Note: we have an open question for the type interface.
678      //  What happens when a wrapped "None" value,
679      // (such as the missing value of an Optional [] argument)
680      // gets digested?
681      //
682      // currently a `Digested::default` gets returned, which has an empty TBox and also gets
683      // returned for e.g. empty mandatory Plain arguments {}.
684      // But we need *different* values, as the explicit "\foo[]" is an override to empty, while
685      // "\foo" will use the default value for the Optional.
686      if self.optional && value_arg.is_none() {
687        None
688      } else if self.reads_plain() && is_implicit_begin_group(&value_arg) {
689        // `\mbox\bgroup A … B\egroup` (syntax.sty:158 `\syn@assist`, whose
690        // `\egroup` is even inserted by `\readupto`'s `\aftergroup`; the
691        // newcommand manual): TeX hands `\bgroup` to `\mbox#1` as its one-token
692        // argument, and the `\hbox{` that `\mbox` opens is then closed by the
693        // `\egroup`, its own `}` having closed the `\bgroup` — so the box runs to
694        // the `\egroup`. A `\bgroup`-only argument therefore reads its group by
695        // DIGESTION from the live gullet until the frame closes (the `{`
696        // primitive: `bgroup` + `digest_next_body`), tex.web §1063/§1068 pairing
697        // an implicit brace with whatever closes the group. Perl reads the lone
698        // `\bgroup`, opens a boxing frame inside the constructor's mode frame,
699        // and errors at `end_mode` (SHARED; pdflatex clean). Guard:
700        // `perfect_kernel_batch54::implicit_bgroup_argument_reads_its_group`.
701        crate::stomach::invoke_token(&crate::T_BEGIN!())?
702          .into_iter()
703          .next()
704      } else {
705        Some(value_arg.be_digested()?)
706      }
707    };
708    for post in self.after_digest.iter() {
709      // Done for effect only.
710      let mut w = Whatsit::default();
711      post(&mut w)?; // maybe pass extras?
712    }
713
714    // Pairs with the raw begin_semiverbatim at the top of digest().
715    if self.semiverbatim.is_some() {
716      end_semiverbatim()?;
717    }
718
719    // Perl Parameter.pm lines 139-141: avoid mode change leaking out of parameter digestion
720    if mode != lookup_mode() && mode != crate::pin!("horizontal") {
721      crate::stomach::leave_horizontal_internal();
722    }
723
724    Ok(digested_value)
725  }
726
727  pub fn revert(&self, value_opt: Option<Tokens>) -> Result<Option<Tokens>> {
728    if let Some(ref reverter) = self.reversion {
729      if let Some(value) = value_opt {
730        Ok(Some((reverter)(
731          value.unlist(),
732          self.inner.as_ref(),
733          &self.extra,
734        )?))
735      } else {
736        Ok(None)
737      }
738    } else if let Some(value) = value_opt {
739      Ok(Some(Tokens::new(value.revert())))
740    } else {
741      Ok(None)
742    }
743  }
744
745  /// Whether this parameter reads a plain braced argument: `Plain` (`{}`), `HBoxPlain` (a `{}` set in a box's braces),
746  /// or `Position`, a box's position keyword read as `{}` is (base_parameter_types.rs).
747  fn reads_plain(&self) -> bool {
748    self.name == pin!("Plain") || self.name == pin!("HBoxPlain") || self.name == pin!("Position")
749  }
750
751  /// This is needed by structured parameter types like KeyVals
752  /// where the argument may already have been tokenized before the KeyVals
753  /// (and the parameter types for the keys) had a chance to properly parse.
754  // Yuck!
755  pub fn reparse(&self, tokens: Tokens) -> Result<ArgWrap> {
756    // Needs neutralization, since the keyvals may have been tokenized already???
757    // perhaps a better test would involve whether $tokens is, in fact, Tokens?
758    if self.reads_plain() || self.predigest.is_some() {
759      // Gack!
760      Ok(ArgWrap::Tokens(tokens))
761    } else if self.semiverbatim.is_some() {
762      // Needs neutralization
763      // but maybe specific to catcodes
764      Ok(ArgWrap::Tokens(
765        tokens.neutralize(self.semiverbatim.as_ref().unwrap().as_slice()),
766      ))
767    } else {
768      gullet::reading_from_mouth(Mouth::default(), || {
769        // start with empty mouth
770        let mut tokens = tokens.unlist();
771        if !tokens.is_empty() // Strip outer braces from dimensions & friends
772          && arena::with(self.name,|name|
773              matches!(name, "Number"|"Dimension"|"Glue"|"MuDimension"|"MuGlue"
774                |"SetlengthDimension"|"SetlengthGlue"|"TempboxaDimension"))
775          && tokens.first().map(|t| t.get_catcode() == Catcode::BEGIN)
776              .unwrap_or(false)
777          && tokens.last().map(|t| t.get_catcode() == Catcode::END).unwrap_or(false)
778        {
779          tokens.remove(0);
780          tokens.pop();
781        }
782        gullet::unread_vec(tokens); // but put back tokens to be read
783        let value = self.read(None)?;
784        gullet::skip_spaces()?;
785        Ok(value)
786      })
787    }
788  }
789}
790
791#[derive(Clone, Debug, Default)]
792pub struct Parameters(Vec<Parameter>);
793
794impl PartialEq for Parameters {
795  fn eq(&self, other: &Parameters) -> bool { self.0 == other.0 }
796}
797impl Object for Parameters {
798  fn stringify(&self) -> String {
799    let mut result = String::new();
800    for parameter in self.0.iter() {
801      let s = parameter.stringify();
802      let lead_letter = match s.chars().next() {
803        Some(c) => c.is_alphanumeric(),
804        None => false,
805      };
806      let trail_letter = match result.chars().last() {
807        Some(c) => c.is_alphanumeric(),
808        None => false,
809      };
810      if lead_letter && trail_letter {
811        result.push(' ');
812      }
813      result.push_str(&s);
814    }
815    result
816  }
817}
818
819/// `LXML_TRACE_ARGS=\\cs`: whether `definition` is the one traced.
820#[cold]
821#[inline(never)]
822fn traced_definition(definition: &dyn Definition) -> bool {
823  TRACE_ARGS
824    .as_deref()
825    .is_some_and(|want| definition.get_cs().to_string() == want)
826}
827
828/// `LXML_TRACE_ARGS=\\cs`: print one argument.
829#[cold]
830#[inline(never)]
831fn trace_argument(definition: &dyn Definition, parameter: &Parameter, values: &ArgWrap) {
832  let shown = values.revert().map(|t| t.to_string()).unwrap_or_default();
833  eprintln!(
834    "ARGS {}: {} = {shown}",
835    definition.get_cs(),
836    parameter.stringify()
837  );
838}
839
840impl Parameters {
841  pub fn new(params: Vec<Parameter>) -> Self { Parameters(params) }
842  pub fn get_num_args(&self) -> usize { self.0.iter().filter(|&p| !p.novalue).count() }
843  pub fn get_parameters(&self) -> &[Parameter] { &self.0 }
844  pub fn take_parameters(self) -> Vec<Parameter> { self.0 }
845  /// The first parameter's [`Parameter::testopt_call`], where it is an optional one ([`Parameter::testopt`]).
846  pub fn with_testopt_call(mut self, call: TestoptCall) -> Self {
847    if let Some(first) = self.0.first_mut().filter(|first| first.testopt) {
848      first.testopt_call = Some(Rc::new(call));
849    }
850    self
851  }
852  /// Revert `args`, one per valued parameter: a novalue parameter (an
853  /// environment's leading `SkipSpaces`, a `Match` delimiter) stored no
854  /// argument and takes none here. Perl `Parameters::revertArguments`
855  /// (Parameters.pm:51-57) skips it before shifting an argument; pairing every
856  /// parameter with an argument shifted each one a slot left and dropped the
857  /// last (`\begin{minipage}[t]{3cm}` reverted as `\begin{minipage}[85.35826pt]`).
858  pub fn revert_arguments(&self, args: Vec<Option<Tokens>>) -> Result<Vec<Token>> {
859    let mut tokens = Vec::new();
860    for (parameter, arg) in self.0.iter().filter(|p| !p.novalue).zip(args) {
861      if let Some(reverted_tks) = parameter.revert(arg)? {
862        tokens.extend(reverted_tks.unlist());
863      }
864    }
865    Ok(tokens)
866  }
867
868  /// Revert arguments from their digested form, using `digested_reversion` when available.
869  /// This allows parameter types (like BoxSpecification) to control reversion formatting
870  /// based on the structured digested data rather than token-level reversion.
871  /// Perl equivalent: `$parameters->revertArguments($self->getArgs)`; one
872  /// argument per valued parameter, as [`Self::revert_arguments`].
873  pub fn revert_digested_arguments(
874    &self,
875    digested_args: &[Option<Digested>],
876  ) -> Result<Vec<Token>> {
877    let mut tokens = Vec::new();
878    for (parameter, arg_opt) in self.0.iter().filter(|p| !p.novalue).zip(digested_args) {
879      let reverted = if let Some(ref digested_rev) = parameter.digested_reversion {
880        // Use digested_reversion: operates on the raw Digested value
881        match arg_opt {
882          Some(arg) => Some(digested_rev(arg)?),
883          None => None,
884        }
885      } else {
886        // Fall back to standard reversion: Digested → Tokens → Parameter::revert
887        let token_reverted = match arg_opt {
888          Some(arg) => Some(arg.revert()?),
889          None => None,
890        };
891        parameter.revert(token_reverted)?
892      };
893      if let Some(tks) = reverted {
894        tokens.extend(tks.unlist());
895      }
896    }
897    Ok(tokens)
898  }
899  // Try to initialize each associated Parameter
900  pub fn init(mut self) -> Result<Self> {
901    let mut initialized = Vec::new();
902    for param in self.0.drain(..) {
903      initialized.push(param.init()?);
904    }
905    self.0 = initialized;
906    Ok(self)
907  }
908
909  pub fn read_arguments(&self, fordefn: Option<&dyn Definition>) -> Result<Vec<ArgWrap>> {
910    Ok(
911      self
912        .read_parameter_list(fordefn, false)?
913        .unwrap_or_default(),
914    )
915  }
916
917  /// `read_arguments` for a macro call: `None` when the call does not match its
918  /// definition — a `\def` parameter text's leading delimiter is not there
919  /// (tex.web §397-398 "Use of \x doesn't match its definition": reported, the
920  /// token backed up, the macro IGNORED). Perl reports it and expands the macro
921  /// anyway, so a self-calling `\def\lp\x{\lp}` met with `\lp\y` re-reports to
922  /// its error cap; the expansion loop has no cap and ran to the digestion fuse.
923  /// Arguments after the miss are not read (TeX stops at the mismatch).
924  /// OXIDIZED_DESIGN #295; guard
925  /// `perfect_kernel_batch56::macro_delimiter_mismatch_ignores_the_call`.
926  ///
927  /// `None` too when an argument ran off the end of a file
928  /// ([`gullet::argument_runaway`]): tex.web §392 "Report a runaway argument
929  /// and abort" abandons the call and drops the arguments read so far; the
930  /// caller that set the `matching` status consumes the mark
931  /// (`Expandable::read_call_arguments`). Guards: `scanner_status::*`.
932  pub fn read_macro_arguments(
933    &self,
934    fordefn: Option<&dyn Definition>,
935  ) -> Result<Option<Vec<ArgWrap>>> {
936    self.read_parameter_list(fordefn, true)
937  }
938
939  /// The parameter loop of [`Self::read_macro_arguments`] (`macro_call`) and
940  /// [`Self::read_arguments`]. Only a macro call stops at a runaway argument:
941  /// a nested re-parse of an argument already read (`reparse_argument`) must
942  /// deliver its values.
943  fn read_parameter_list(
944    &self,
945    fordefn: Option<&dyn Definition>,
946    macro_call: bool,
947  ) -> Result<Option<Vec<ArgWrap>>> {
948    let mut args = Vec::with_capacity(self.0.len());
949    // `LXML_TRACE_ARGS=\cs`: see `read_arguments_and_digest` (macros and
950    // primitives read their parameters here).
951    let traced = TRACE_ARGS.is_some() && fordefn.is_some_and(traced_definition);
952    let tails = self.may_defer_tails().then(ArgumentTails::open);
953    for parameter in &self.0 {
954      let values = parameter.read(fordefn)?;
955      if traced && let Some(d) = fordefn {
956        trace_argument(d, parameter, &values);
957      }
958      if parameter.predigest.is_some() {
959        // TODO: Sometimes we legitimately want to use e.g. Number parameters without the predigest
960        // closure... so this shouldn't be an error, not even an info -- but leaving it here
961        // if something changes in the future. error!(
962        //   target: &s!("parameter:{}", parameter.name),
963        //   "parameter with predigest closure was invoked in an expandable context. Parameter
964        // digestion won't execute." );
965      }
966      if macro_call && gullet::argument_runaway() {
967        return Ok(None);
968      }
969      if parameter.is_macro_delimiter() && values.is_none() {
970        return Ok(None);
971      }
972      if !parameter.novalue {
973        args.push(values);
974      }
975    }
976    if let Some(tails) = tails {
977      tails.hand_back(fordefn);
978    }
979    Ok(Some(args))
980  }
981
982  /// The tokens its one parameter reads ([`Parameter::stated`]), when this is the inner spec of a braced or bracketed
983  /// argument (`{Dimension}`, `[TempboxaDimension]`, `{GraphixDimension}`).
984  fn stated_argument_cell(&self) -> Option<&RefCell<Option<Tokens>>> {
985    match self.0.as_slice() {
986      [only] => Some(&only.stated),
987      _ => None,
988    }
989  }
990
991  /// Read and digest a constructor's arguments into `args` (on an `Err`, the ones read before it). Under
992  /// [`KEEP_STATED_LENGTHS`], `stated` receives the tokens each braced or bracketed typed argument states (a length's
993  /// `{0.48\textwidth}`), with its index among the arguments; `withheld` is set when it has such an argument and a
994  /// binding withheld their tokens ([`WITHHOLD_STATED_LENGTHS`]).
995  pub fn read_arguments_and_digest(
996    &self,
997    fordefn: &Constructor,
998    stated: &mut Vec<(usize, Tokens)>,
999    withheld: &mut bool,
1000    args: &mut Vec<Option<Digested>>,
1001  ) -> Result<()> {
1002    args.reserve(self.0.len());
1003    // `LXML_TRACE_ARGS=\cs` prints every argument this constructor reads, as
1004    // reverted tokens, before it is digested — a bisect aid for "which tokens
1005    // did the `{}` scan swallow" questions (examdesign's version-loop
1006    // re-execution; wave 14). Off by default.
1007    let traced = TRACE_ARGS
1008      .as_deref()
1009      .is_some_and(|want| fordefn.get_cs().to_string() == want);
1010    let tails = self.may_defer_tails().then(ArgumentTails::open);
1011    // Size arguments read with the box set (`after_box`): their raw tokens wait
1012    // in their slot until the box, the last argument, is digested.
1013    let mut after_box: Vec<(usize, &Parameter, ArgWrap)> = Vec::new();
1014    let last = self.0.len().saturating_sub(1);
1015    // whether the lengths' stated tokens are kept, looked up at the first such parameter
1016    let mut keep: Option<bool> = None;
1017    for (index, parameter) in self.0.iter().enumerate() {
1018      let measures = parameter.measures_the_box();
1019      let stated_cell = parameter
1020        .inner
1021        .as_ref()
1022        .and_then(Parameters::stated_argument_cell)
1023        .filter(|_| *keep.get_or_insert_with(|| lookup_bool(KEEP_STATED_LENGTHS)));
1024      if let Some(cell) = stated_cell {
1025        cell.replace(Some(Tokens::new(Vec::new())));
1026      }
1027      let value = if measures {
1028        parameter.read_with(None, Some(fordefn))?
1029      } else {
1030        parameter.read(Some(fordefn))?
1031      };
1032      // (a size read with the box set is re-parsed below, and its tokens taken there)
1033      if !measures
1034        && let Some(tokens) = stated_cell.and_then(|cell| cell.take())
1035        && !tokens.is_empty()
1036        && !parameter.novalue
1037      {
1038        stated.push((args.len(), tokens));
1039      }
1040      if traced {
1041        let shown = value.revert().map(|t| t.to_string()).unwrap_or_default();
1042        eprintln!(
1043          "ARGS {}: {} = {shown}",
1044          fordefn.get_cs(),
1045          parameter.stringify()
1046        );
1047      }
1048      if parameter.novalue {
1049        continue;
1050      }
1051      if measures {
1052        after_box.push((args.len(), parameter, value));
1053        args.push(None);
1054        continue;
1055      }
1056      // TeX sets the box in a group (`\hbox{`), before the sizes are read: its
1057      // font changes do not reach them (`\resizebox{2em}{!}{\Large x}`).
1058      let digested_value = if index == last && !after_box.is_empty() && parameter.reads_plain() {
1059        crate::stomach::begingroup();
1060        let mut digested = parameter.digest(value, Some(fordefn));
1061        // The box's size is fixed as its group closes, in the box's own font:
1062        // a `[c]` tabular's axis (`\resizebox{6cm}{!}{\footnotesize\begin{tabular}…}`).
1063        if let Ok(Some(body)) = &mut digested
1064          && after_box.iter().any(|(_, _, raw)| !raw.is_none())
1065          && let Err(error) = body.get_size(None)
1066        {
1067          digested = Err(error);
1068        }
1069        crate::stomach::endgroup()?;
1070        digested?
1071      } else {
1072        parameter.digest(value, Some(fordefn))?
1073      };
1074      args.push(digested_value);
1075    }
1076    debug_assert!(
1077      after_box.is_empty() || self.0.last().is_some_and(|last| !last.measures_the_box()),
1078      "{}: a size argument read after the box needs the box as the last argument",
1079      fordefn.get_cs()
1080    );
1081    if after_box.iter().any(|(_, _, raw)| !raw.is_none()) {
1082      let content = args.last().cloned().flatten();
1083      within_tempboxa(content.as_ref(), || {
1084        for (slot, parameter, raw) in after_box {
1085          let inner = parameter.inner.as_ref().expect("measures_the_box");
1086          let cell = inner.stated_argument_cell().filter(|_| keep == Some(true));
1087          if let Some(cell) = cell {
1088            cell.replace(Some(Tokens::new(Vec::new())));
1089          }
1090          let mut values = inner.reparse_argument(raw)?;
1091          if let Some(tokens) = cell.and_then(|cell| cell.take())
1092            && !tokens.is_empty()
1093          {
1094            stated.push((slot, tokens));
1095          }
1096          let value = if values.is_empty() {
1097            ArgWrap::None
1098          } else {
1099            values.remove(0)
1100          };
1101          args[slot] = parameter.digest(value, Some(fordefn))?;
1102        }
1103        Ok(())
1104      })?;
1105    }
1106    if let Some(tails) = tails {
1107      tails.hand_back(Some(fordefn));
1108    }
1109    // (looked up only for a constructor with a length argument whose tokens were not kept)
1110    *withheld = keep == Some(false) && lookup_bool(WITHHOLD_STATED_LENGTHS);
1111    Ok(())
1112  }
1113
1114  /// Re-read an argument already read as tokens (`{Dimension}`, `[Number]`,
1115  /// `CommaList:Number`: a braced or bracketed argument whose inner spec gives
1116  /// its type). Perl `Parameters::reparseArgument` (Parameters.pm:78-85).
1117  ///
1118  /// What follows the value inside the braces is NOT dropped (Perl's
1119  /// `readingFromMouth` closes the argument's mouth unread, Gullet.pm:131-135;
1120  /// KNOWN_PERL_ERRORS #275): TeX leaves it in the input — `\setlength#1#2{#1
1121  /// #2\relax}` (latex.ltx:10253), through which latex.ltx passes every such
1122  /// length — so `A\hspace{1em\foo}B` typesets the `x` of `\def\foo{x}`. The
1123  /// tail is handed back at the end of the command's argument list
1124  /// (`ArgumentTails`). With calc loaded, a length is evaluated as a whole
1125  /// expression ([`gullet::braced_length_evaluator`]). OXIDIZED_DESIGN #317.
1126  pub fn reparse_argument(&self, value: ArgWrap) -> Result<Vec<ArgWrap>> {
1127    if value.is_none() {
1128      return Ok(Vec::new());
1129    }
1130    let length = self.braced_length_type();
1131    let calc = length.and_then(|_| gullet::braced_length_evaluator());
1132    let tokens = value.revert()?;
1133    // the tokens the source states, for a reader that asked for them (`Parameter::stated`)
1134    if let [only] = self.0.as_slice()
1135      && let Ok(mut stated) = only.stated.try_borrow_mut()
1136      && stated.is_some()
1137    {
1138      *stated = Some(tokens.clone());
1139    }
1140    let (values, tail) = read_braced(tokens, || {
1141      if let Some((kind, true)) = length
1142        && let Some(value) = read_through_redefined_setlength(kind)?
1143      {
1144        return Ok(vec![ArgWrap::from(value)]);
1145      }
1146      match (length, calc) {
1147        (Some((kind, _)), Some(evaluate)) => {
1148          Ok(vec![ArgWrap::from(coerce_length(evaluate(kind)?, kind))])
1149        },
1150        _ => self.read_arguments(None),
1151      }
1152    })?;
1153    ArgumentTails::defer(tail);
1154    Ok(values)
1155  }
1156
1157  /// Whether reading these parameters can defer a tail: only a parameter with
1158  /// an inner spec re-parses its argument ([`Self::reparse_argument`]). The
1159  /// others open no `ArgumentTails` scope, which every macro call would pay for.
1160  fn may_defer_tails(&self) -> bool { self.0.iter().any(|parameter| parameter.inner.is_some()) }
1161
1162  /// The register type of a lone `Dimension`/`Glue` inner spec, the braced
1163  /// lengths calc evaluates whole (see [`gullet::BracedLengthFn`]), and whether
1164  /// it is declared a `\setlength` operand (`SetlengthDimension`/`SetlengthGlue`,
1165  /// read through a redefined `\setlength`: [`read_through_redefined_setlength`]).
1166  fn braced_length_type(&self) -> Option<(RegisterType, bool)> {
1167    let [only] = self.0.as_slice() else {
1168      return None;
1169    };
1170    let name = only.name;
1171    if name == pin!("Dimension") {
1172      Some((RegisterType::Dimension, false))
1173    } else if name == pin!("Glue") {
1174      Some((RegisterType::Glue, false))
1175    } else if name == pin!("SetlengthDimension") || name == pin!("TempboxaDimension") {
1176      Some((RegisterType::Dimension, true))
1177    } else if name == pin!("SetlengthGlue") {
1178      Some((RegisterType::Glue, true))
1179    } else {
1180      None
1181    }
1182  }
1183
1184  pub fn as_keysets(&self) -> Vec<String> { self.0.iter().map(|p| p.stringify()).collect() }
1185}
1186
1187/// latex.ltx's `\@begin@tempboxa` … `\@end@tempboxa` (16085-16094) around a
1188/// box command's size arguments: in a group, `\@tempboxa` holds `content` and
1189/// `\width`/`\height`/`\depth`/`\totalheight` measure it (`\lx@tempboxa@sizes`,
1190/// latex.ltx:16088-16093; internal dimensions, so `-.5\height` is exact to the
1191/// sp, tex.web §455), then `evaluate` reads the sizes. Without `\@tempboxa`
1192/// (plain TeX) `evaluate` runs unbound.
1193pub fn within_tempboxa<R>(
1194  content: Option<&Digested>,
1195  evaluate: impl FnOnce() -> Result<R>,
1196) -> Result<R> {
1197  let tempboxa = crate::T_CS!("\\@tempboxa");
1198  let sizes = crate::T_CS!("\\lx@tempboxa@sizes");
1199  if lookup_definition(&tempboxa)?.is_none() || lookup_definition(&sizes)?.is_none() {
1200    return evaluate();
1201  }
1202  crate::stomach::begingroup();
1203  let result = (|| {
1204    let number = gullet::reading_from_mouth(Mouth::default(), || {
1205      gullet::unread_one(tempboxa);
1206      gullet::read_number()
1207    })?;
1208    let stored = content.map_or(Stored::None, |content| Stored::Digested(content.clone()));
1209    assign_value(
1210      &format!(
1211        "box{}",
1212        crate::common::numeric_ops::NumericOps::value_of(number)
1213      ),
1214      stored,
1215      None,
1216    );
1217    crate::stomach::digest(Tokens::new(vec![sizes]))?;
1218    evaluate()
1219  })();
1220  crate::stomach::endgroup()?;
1221  result
1222}
1223
1224/// Read a value from a braced argument's `tokens`, in a mouth of their own,
1225/// and return it with the argument's TAIL: whatever `read` left unread — what
1226/// an expanding scan looked ahead at and put back, and the rest of the
1227/// argument. Perl `readingFromMouth` (Gullet.pm:108-146) drops the tail; TeX
1228/// has never seen braces here and leaves it in the input, so every caller hands
1229/// it back (`ArgumentTails`, or [`read_braced_value`]'s callers).
1230pub fn read_braced<R>(tokens: Tokens, read: impl FnOnce() -> Result<R>) -> Result<(R, Vec<Token>)> {
1231  let init_if_depth = crate::definition::conditional::if_stack_depth();
1232  gullet::reading_from_mouth(Mouth::new("", None)?, || {
1233    gullet::unread(tokens);
1234    let value = {
1235      let _braced = BracedRead::enter();
1236      read()?
1237    };
1238    // A conditional opened inside the argument and cut by the scan
1239    // (`\hspace{\ifx\a\b\Lreg\else\a\U\fi}`, read_dimension stops at `\U`)
1240    // is expanded to its `\fi` HERE, as TeX's `get_x_token` after `scan_dimen`
1241    // (tex.web §448/§461) meets it next — the conditional must not outlive the
1242    // argument's mouth (OXIDIZED_DESIGN #193; witness typog-example,
1243    // `parbox_dimen_conditional_double.tex`). What the taken branch still
1244    // holds heads the tail. One expansion at a time, stopping as the frame
1245    // closes: what follows the `\fi` is expanded where TeX expands it, after
1246    // the command (`\setlength\x{\ifx…\U\fi\the\x}` reads `\x`'s new value).
1247    let mut tail = Vec::new();
1248    while crate::definition::conditional::if_stack_depth() > init_if_depth {
1249      match gullet::read_token()? {
1250        Some(token) => {
1251          if !gullet::expand_once_partial(token)? {
1252            tail.push(token);
1253          }
1254        },
1255        None => {
1256          if crate::definition::conditional::if_stack_depth() > init_if_depth {
1257            // A genuinely unbalanced argument (`\hspace{\iftrue 3pt}`):
1258            // pdflatex reports "\iftrue … was incomplete", Perl warns at
1259            // `\end{document}`; say so here, then drop the orphaned frames so
1260            // they cannot leak outward.
1261            Warn!(
1262              "expected",
1263              "\\fi",
1264              "Missing \\fi: conditional opened inside an argument fell off its end"
1265            );
1266            while crate::definition::conditional::if_stack_depth() > init_if_depth {
1267              pop_if_frame();
1268            }
1269          }
1270          break;
1271        },
1272      }
1273    }
1274    if tail.is_empty() {
1275      gullet::skip_spaces()?;
1276    }
1277    tail.extend(gullet::take_rest_of_mouth());
1278    strip_scanned_error_stubs(&mut tail);
1279    Ok((value, tail))
1280  })
1281}
1282
1283/// Read a `kind` value from a braced argument's `tokens` the way LaTeX's
1284/// assignments scan it — `\setlength#1#2{#1 #2\relax}`, `\addtolength`,
1285/// `\setcounter`, `\addtocounter` (latex.ltx:10253-10254, 10115-10122): by
1286/// the register's own type, a length through calc when it is loaded (see
1287/// [`gullet::BracedLengthFn`]). Returns the value and the argument's tail; the
1288/// caller assigns, then puts the tail back (`gullet::unread_vec`) — exactly
1289/// where TeX leaves it, after the assignment.
1290pub fn read_braced_value(
1291  tokens: Tokens,
1292  kind: RegisterType,
1293) -> Result<(RegisterValue, Vec<Token>)> {
1294  read_braced(tokens, || read_length_value(kind))
1295}
1296
1297/// A register value of type `kind` from the current mouth, as [`read_braced_value`] reads one: a length through
1298/// calc's evaluator when calc is loaded ([`gullet::braced_length_evaluator`]), else by TeX's scan for the type.
1299pub fn read_length_value(kind: RegisterType) -> Result<RegisterValue> {
1300  let calc = if matches!(kind, RegisterType::Dimension | RegisterType::Glue) {
1301    gullet::braced_length_evaluator()
1302  } else {
1303    None
1304  };
1305  match calc {
1306    Some(evaluate) => Ok(coerce_length(evaluate(kind)?, kind)),
1307    None => gullet::read_value(kind),
1308  }
1309}
1310
1311thread_local! {
1312  /// Set while [`read_through_redefined_setlength`] runs a redefined
1313  /// `\setlength`: a braced length read inside it takes the direct path.
1314  static THROUGH_SETLENGTH: Cell<bool> = const { Cell::new(false) };
1315}
1316
1317/// A `SetlengthDimension`/`SetlengthGlue` argument is the operand latex.ltx
1318/// hands to `\setlength` (see [`gullet::BracedLengthFn`]), so a package that
1319/// redefines `\setlength` as a macro changes how it reads. bxcalcux.sty's
1320/// `\bxcx@decl@patch\setlength` parses custom units (`\newcalcunit{tm}{0.05em}`
1321/// makes `\hspace{6tm}` 3pt; bxcalc manual), and pgf's pictures swap in
1322/// `\pgf@setlength` (pgfcorescopes.code.tex:238-242, 311-317). Then the length
1323/// is assigned as latex.ltx assigns it, `\setlength<register>{<argument>}`
1324/// digested (`\@hspace`, latex.ltx:9425; a dimen register for a `Dimension`, as
1325/// `\@tempdima` is, so a scan stops before `plus`), and the register read back.
1326/// Whatever the assignment left in the input is typeset there, before the
1327/// command's own output, as TeX typesets it for the boxes and `\hspace`; for
1328/// `\\[..]` TeX typesets it after the break (inside `\vadjust`, latex.ltx:9260).
1329/// `None` when `\setlength` is a primitive (the kernel's or calc's binding) or
1330/// is undefined (plain TeX: the registers are LaTeX-only). OXIDIZED_DESIGN #325.
1331///
1332/// Precondition: called directly inside [`read_braced`]'s reader, whose mouth
1333/// holds exactly the rest of the argument: the whole mouth is taken as the
1334/// operand. The reentrancy flag covers the whole digestion, the tail's included.
1335pub fn read_through_redefined_setlength(kind: RegisterType) -> Result<Option<RegisterValue>> {
1336  if THROUGH_SETLENGTH.with(Cell::get) || !in_braced_read() {
1337    return Ok(None);
1338  }
1339  let setlength = crate::T_CS!("\\setlength");
1340  let register = if matches!(kind, RegisterType::Glue) {
1341    crate::T_CS!("\\lx@braced@skip")
1342  } else {
1343    crate::T_CS!("\\lx@braced@dimen")
1344  };
1345  if !lookup_definition(&setlength)?.is_some_and(|defn| defn.is_expandable())
1346    || lookup_definition(&register)?.is_none()
1347  {
1348    return Ok(None);
1349  }
1350  struct Through;
1351  impl Drop for Through {
1352    fn drop(&mut self) { THROUGH_SETLENGTH.with(|through| through.set(false)); }
1353  }
1354  THROUGH_SETLENGTH.with(|through| through.set(true));
1355  let _through = Through;
1356  let mut call = vec![setlength, register, crate::T_BEGIN!()];
1357  call.extend(gullet::take_rest_of_mouth());
1358  call.push(crate::T_END!());
1359  let typeset = crate::stomach::digest(Tokens::new(call))?;
1360  crate::stomach::extend_box_list(typeset.unlist());
1361  let value = lookup_register_token(&register, Vec::new())?.unwrap_or_default();
1362  Ok(Some(coerce_length(value, kind)))
1363}
1364
1365/// A calc result (always a skip, calc.sty:56) as the `kind` of length read.
1366fn coerce_length(value: RegisterValue, kind: RegisterType) -> RegisterValue {
1367  match kind {
1368    RegisterType::Dimension => RegisterValue::Dimension(value.into()),
1369    RegisterType::Glue => RegisterValue::Glue(value.into()),
1370    _ => value,
1371  }
1372}
1373
1374thread_local! {
1375  /// Braced-argument tails ([`read_braced`]) waiting for their command's
1376  /// argument list to end, in reading order. See [`ArgumentTails`].
1377  static ARGUMENT_TAILS: RefCell<Vec<Token>> = const { RefCell::new(Vec::new()) };
1378  /// How many [`ArgumentTails`] scopes are open.
1379  static TAIL_SCOPES: Cell<usize> = const { Cell::new(0) };
1380  /// How many [`read_braced`] reads are running, for [`in_braced_read`].
1381  static BRACED_READS: Cell<usize> = const { Cell::new(0) };
1382  /// Why tails are dropped instead of handed back, innermost last
1383  /// ([`dropping_argument_tails`]).
1384  static DROPPING_TAILS: RefCell<Vec<&'static str>> = const { RefCell::new(Vec::new()) };
1385}
1386
1387/// One running [`read_braced`], counted for [`in_braced_read`]; the count is
1388/// restored on every exit, a caught panic included (cortex_worker reuses the
1389/// thread for the next paper).
1390struct BracedRead;
1391impl BracedRead {
1392  fn enter() -> Self {
1393    BRACED_READS.with(|reads| reads.set(reads.get() + 1));
1394    BracedRead
1395  }
1396}
1397impl Drop for BracedRead {
1398  fn drop(&mut self) { BRACED_READS.with(|reads| reads.set(reads.get().saturating_sub(1))); }
1399}
1400
1401/// Where a handed-back tail would be misread, so `invoke` runs with the tails
1402/// its commands leave DROPPED, and warned about, `why` naming what TeX does
1403/// with the text:
1404/// - a column type (`\NC@rewrite@p`, alignment.rs): the template reader would
1405///   read a tail as more column letters (`p{\textwidth-1pt}c` a second `p`
1406///   column of width `t`); TeX typesets it in every cell (array.sty:189-191
1407///   `\@startpbox` → `\setlength\hsize{#1}`);
1408/// - the head of an alignment row, between rows (tex_tables.rs
1409///   `digest_alignment_column`): a tail would open the next row with a cell
1410///   of its own, where `\noalign` then fails (`\cmidrule[lr]{1-2}
1411///   \cmidrule[lr]{3-4}` for `(lr)`: 2605.27476, 2605.25272; pdflatex prints
1412///   the `lr` between the rows, with 2 errors).
1413///
1414/// The drop scope is restored on every exit, a caught panic included.
1415/// OXIDIZED_DESIGN #317.
1416pub fn dropping_argument_tails<R>(
1417  why: &'static str,
1418  invoke: impl FnOnce() -> Result<R>,
1419) -> Result<R> {
1420  struct Dropping;
1421  impl Drop for Dropping {
1422    fn drop(&mut self) {
1423      DROPPING_TAILS.with(|stack| {
1424        stack.borrow_mut().pop();
1425      });
1426    }
1427  }
1428  DROPPING_TAILS.with(|stack| stack.borrow_mut().push(why));
1429  let _dropping = Dropping;
1430  invoke()
1431}
1432
1433/// TeX's treatment of a tail dropped between the rows of an alignment.
1434pub const BETWEEN_ALIGNMENT_ROWS: &str = "TeX typesets it between the rows";
1435/// TeX's treatment of a column type's tail.
1436pub const IN_EVERY_CELL: &str = "TeX typesets it in every cell of the column";
1437
1438/// Drop `tail`, the rest of an argument of `cs` that has no place to go,
1439/// with the warning `ArgumentTails` gives when it holds more than spaces and
1440/// `\relax`.
1441pub fn drop_argument_tail(cs: &Token, tail: Vec<Token>, why: &str) {
1442  if let Some(first) = tail.iter().find(|token| !is_inert_tail_token(token)) {
1443    Warn!(
1444      "unexpected",
1445      first.stringify(),
1446      s!(
1447        "Unexpected text after the value in an argument of {} ('{}'); it is dropped ({why})",
1448        cs,
1449        Tokens::new(tail.clone())
1450      )
1451    );
1452  }
1453}
1454
1455/// Whether a parameter reader runs on a braced argument's own mouth
1456/// ([`read_braced`]), where the rest of the current mouth is the rest of that
1457/// argument (`DefaultUnits`, base_parameter_types.rs).
1458pub fn in_braced_read() -> bool { BRACED_READS.with(|reads| reads.get() > 0) }
1459
1460/// One argument list's share of the deferred braced-argument tails.
1461///
1462/// TeX grabs a macro's arguments as token lists and scans a quantity out of one
1463/// only afterwards (`\@rule[#1]#2#3{… \setlength\@tempdimb{#2}…}`,
1464/// latex.ltx:16360-16366), so what follows the quantity never meets the next
1465/// argument. A binding reads each typed argument as it goes, so a tail waits
1466/// here until the list is complete and is then put back in the input: read
1467/// next, after the command. For an assignment that is TeX's place (those read
1468/// their value with [`read_braced_value`] instead, without a warning); a command
1469/// that outputs a box or space (`\hspace`, `\makebox`, `\parbox`, `\rule`,
1470/// `minipage`) scans its length BEFORE that output in TeX, so there the tail
1471/// lands one step late. Either way a tail with more than spaces and `\relax` is
1472/// almost always an authoring slip (a length expression without calc), and a
1473/// warning names it. OXIDIZED_DESIGN #317.
1474struct ArgumentTails {
1475  mark: usize,
1476}
1477
1478impl ArgumentTails {
1479  fn open() -> Self {
1480    TAIL_SCOPES.with(|scopes| scopes.set(scopes.get() + 1));
1481    ArgumentTails {
1482      mark: ARGUMENT_TAILS.with(|tails| tails.borrow().len()),
1483    }
1484  }
1485
1486  /// Hold `tail` for the argument list being read; with none open (a re-parse
1487  /// outside a definition's arguments) it goes back in the input at once.
1488  fn defer(tail: Vec<Token>) {
1489    if tail.is_empty() {
1490    } else if TAIL_SCOPES.with(|scopes| scopes.get()) == 0 {
1491      gullet::unread_vec(tail);
1492    } else {
1493      ARGUMENT_TAILS.with(|tails| tails.borrow_mut().extend(tail));
1494    }
1495  }
1496
1497  /// Put the tails deferred since [`Self::open`] back in the input. `fordefn`
1498  /// is the command whose output the tail now follows, and is warned about;
1499  /// None for a nested re-parse, whose tail travels on with its enclosing
1500  /// argument's.
1501  fn hand_back(self, fordefn: Option<&dyn Definition>) {
1502    let tail = ARGUMENT_TAILS.with(|tails| tails.borrow_mut().split_off(self.mark));
1503    if tail.is_empty() {
1504      return;
1505    }
1506    let Some(defn) = fordefn else {
1507      // A nested re-parse: the tail travels on with its enclosing argument's.
1508      gullet::unread_vec(tail);
1509      return;
1510    };
1511    if let Some(why) = DROPPING_TAILS.with(|stack| stack.borrow().last().copied()) {
1512      drop_argument_tail(&defn.get_cs(), tail, why);
1513      return;
1514    }
1515    if let Some(first) = tail.iter().find(|token| !is_inert_tail_token(token)) {
1516      Warn!(
1517        "unexpected",
1518        first.stringify(),
1519        s!(
1520          "Unexpected text after the value in an argument of {} ('{}'); it is read after {0}",
1521          defn.get_cs(),
1522          Tokens::new(tail.clone())
1523        )
1524      );
1525    }
1526    gullet::unread_vec(tail);
1527  }
1528}
1529
1530impl Drop for ArgumentTails {
1531  /// An argument list abandoned by an error or a mismatched macro call (tex.web
1532  /// §392/§398 drop its arguments) takes its tails with it.
1533  fn drop(&mut self) {
1534    ARGUMENT_TAILS.with(|tails| tails.borrow_mut().truncate(self.mark));
1535    TAIL_SCOPES.with(|scopes| scopes.set(scopes.get().saturating_sub(1)));
1536  }
1537}
1538
1539/// Drop the undefined control sequences at the head of `tail`: the scan's
1540/// look-ahead expanded them, which reported them and stubbed them as
1541/// `<ltx:ERROR>` (`generate_error_stub`), and TeX discards an undefined control
1542/// sequence it expands (tex.web §370) — it must not come back as text.
1543/// `\hspace{6\@p@t}` with USG.cls's `\@p@t` missing (2605.25073). Spaces the
1544/// look-ahead passed on the way go with them.
1545fn strip_scanned_error_stubs(tail: &mut Vec<Token>) {
1546  loop {
1547    let Some(first) = tail.iter().position(|t| t.get_catcode() != Catcode::SPACE) else {
1548      return;
1549    };
1550    if !is_error_stub(&tail[first]) {
1551      return;
1552    }
1553    tail.drain(..=first);
1554  }
1555}
1556
1557/// A tail token that does nothing when read: a space or `\relax` (`\stretch{1}`
1558/// = `0pt plus 1fill\relax` leaves its `\relax`, which TeX's own `\relax` after
1559/// `#2` would have ended the scan with).
1560fn is_inert_tail_token(token: &Token) -> bool {
1561  token.get_catcode() == Catcode::SPACE || token.defined_as(&crate::token::TOKEN_RELAX)
1562}
1563
1564impl fmt::Display for Parameters {
1565  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1566    let mut content = String::new();
1567    for parameter in &self.0 {
1568      let param_content = parameter.to_string();
1569      if LAST_WCHAR_RE.is_match(&content) && FIRST_WCHAR_RE.is_match(&param_content) {
1570        content.push(' ');
1571      }
1572      content.push_str(&param_content);
1573    }
1574    write!(f, "{content}")
1575  }
1576}
1577
1578impl From<Parameters> for Vec<Parameter> {
1579  fn from(ps: Parameters) -> Vec<Parameter> { ps.0 }
1580}
1581
1582// ToTokens impls gated by `codegen` feature — see comment in
1583// `tokens.rs` for rationale (audit DEP-14, 2026-05-18).
1584#[cfg(feature = "codegen")]
1585impl ToTokens for Parameters {
1586  fn to_tokens(&self, stream: &mut TokenStream) {
1587    let params = &self.0;
1588    stream.extend(quote! {
1589        Parameters::new(<[Parameter]>::into_vec(Box::new([ #(#params),* ])))
1590    });
1591  }
1592}
1593
1594#[cfg(feature = "codegen")]
1595impl ToTokens for Parameter {
1596  fn to_tokens(&self, stream: &mut TokenStream) {
1597    let name = arena::with(self.name, |name| quote!(arena::pin_static(#name)));
1598    let spec = arena::with(self.spec, |spec| quote!(arena::pin_static(#spec)));
1599    let extra = &self.extra;
1600    let inner = match &self.inner {
1601      None => quote!(None),
1602      Some(inner_ps) => quote!(Some(#inner_ps)),
1603    };
1604    stream.extend(quote! {
1605      Parameter {
1606        name: #name,
1607        spec: #spec,
1608        extra: <[Tokens]>::into_vec(Box::new([ #(#extra),* ])),
1609        inner: #inner,
1610        ..Parameter::default()
1611      }
1612    });
1613  }
1614}
1615
1616/// What a definition primitive reads unexpanded after itself (tex.web §1215 `get_r_token`).
1617#[derive(Clone, Copy, PartialEq, Eq)]
1618enum DefinitionNames {
1619  /// Not a definition primitive.
1620  None,
1621  /// One token: the name of the `\chardef` family and `\font` (§1257), the token `\afterassignment` and
1622  /// `\aftergroup` save (§1269, §1271), the name of `\futurelet`, whose two peeked tokens TeX puts back to be read as
1623  /// usual (§1221 `back_input`).
1624  Name,
1625  /// `\def`, `\gdef`: the name, the parameter text and the body, all unexpanded (§473 `scan_toks(true,false)`).
1626  Def,
1627  /// `\edef`, `\xdef`: the name and the parameter text unexpanded; the body is expanded (§473 `scan_toks(true,true)`).
1628  Edef,
1629  /// LaTeX's `\newcommand`, `\renewcommand`, `\providecommand`, `\DeclareRobustCommand` (`OptionalMatch:* DefToken
1630  /// [Number][]{}`): the star, the name, both options and the body, macro arguments TeX reads unexpanded.
1631  LatexDef,
1632  /// `\let`: a name, spaces, an optional `=` with one optional space, the target (§1221).
1633  Let,
1634  /// `\read`/`\readline`: a number, the keyword `to`, a name (§1225).
1635  ReadTo,
1636}
1637
1638/// The names `token` reads as a definition primitive: its meaning's own name, so a `\let` copy of `\def` reads as
1639/// `\def`, and a macro or an undefined name as none (one meaning lookup per token).
1640fn definition_reads_names(token: &Token) -> DefinitionNames {
1641  if !token.get_catcode().is_active_or_cs() {
1642    return DefinitionNames::None;
1643  }
1644  with_meaning(token, |meaning| match meaning {
1645    Some(Stored::Primitive(primitive)) => primitive.cs.with_cs_name(|name| match name {
1646      "\\def" | "\\gdef" => DefinitionNames::Def,
1647      "\\edef" | "\\xdef" => DefinitionNames::Edef,
1648      "\\newcommand" | "\\renewcommand" | "\\providecommand" | "\\DeclareRobustCommand" => {
1649        DefinitionNames::LatexDef
1650      },
1651      "\\chardef" | "\\mathchardef" | "\\countdef" | "\\dimendef" | "\\skipdef" | "\\muskipdef"
1652      | "\\toksdef" | "\\font" | "\\futurelet" | "\\afterassignment" | "\\aftergroup" => {
1653        DefinitionNames::Name
1654      },
1655      "\\let" => DefinitionNames::Let,
1656      "\\read" | "\\readline" => DefinitionNames::ReadTo,
1657      _ => DefinitionNames::None,
1658    }),
1659    _ => DefinitionNames::None,
1660  })
1661}
1662
1663/// Reads, unexpanded and kept from neutralizing, the tokens `kind` names as a definition's names, from the gullet.
1664fn read_definition_names(kind: DefinitionNames, tokens: &mut Vec<(Token, bool)>) -> Result<()> {
1665  take_definition_names(kind, &mut || gullet::read_token(), tokens)
1666}
1667
1668/// Takes from `next`, kept from neutralizing, the tokens `kind` names as a definition's names.
1669fn take_definition_names(
1670  kind: DefinitionNames,
1671  next: &mut dyn FnMut() -> Result<Option<Token>>,
1672  tokens: &mut Vec<(Token, bool)>,
1673) -> Result<()> {
1674  // The next token, kept as it is (`keep`) or left to neutralizing.
1675  let mut take = |tokens: &mut Vec<(Token, bool)>, keep: bool| -> Result<Option<Token>> {
1676    let token = next()?;
1677    if let Some(t) = token {
1678      tokens.push((t, !keep));
1679    }
1680    Ok(token)
1681  };
1682  let is_space = |t: &Option<Token>| t.is_some_and(|t| t.get_catcode() == Catcode::SPACE);
1683  match kind {
1684    DefinitionNames::None => {},
1685    DefinitionNames::Name => {
1686      take(tokens, true)?;
1687    },
1688    DefinitionNames::Def | DefinitionNames::Edef => {
1689      take(tokens, true)?;
1690      // The parameter text, through the body's `{` (not past the end of a malformed group).
1691      let mut token = take(tokens, true)?;
1692      while token.is_some_and(|t| !matches!(t.get_catcode(), Catcode::BEGIN | Catcode::END)) {
1693        token = take(tokens, true)?;
1694      }
1695      let token = token.filter(|t| t.get_catcode() == Catcode::BEGIN);
1696      // `\def`'s body, balanced; `\edef`'s is left to the expanding reader.
1697      if kind == DefinitionNames::Def && token.is_some() {
1698        take_rest_of_group(&mut take, tokens)?;
1699      }
1700    },
1701    DefinitionNames::LatexDef => {
1702      let mut token = take(tokens, true)?;
1703      while is_space(&token) {
1704        token = take(tokens, true)?;
1705      }
1706      if is_other_char(&token, "*") {
1707        token = take(tokens, true)?;
1708        while is_space(&token) {
1709          token = take(tokens, true)?;
1710        }
1711      }
1712      // The name: a token or a braced one.
1713      if is_begin(&token) {
1714        take_rest_of_group(&mut take, tokens)?;
1715      }
1716      token = take(tokens, true)?;
1717      while is_space(&token) {
1718        token = take(tokens, true)?;
1719      }
1720      // `[n]` and `[default]`, each through its `]` outside braces.
1721      for _ in 0..2 {
1722        if !is_other_char(&token, "[") {
1723          break;
1724        }
1725        let mut depth = 0;
1726        loop {
1727          match take(tokens, true)? {
1728            Some(t) if t.get_catcode() == Catcode::BEGIN => depth += 1,
1729            Some(t) if t.get_catcode() == Catcode::END => {
1730              depth -= 1;
1731              if depth < 0 {
1732                break;
1733              }
1734            },
1735            Some(t) if depth == 0 && is_other_char(&Some(t), "]") => break,
1736            Some(_) => {},
1737            None => break,
1738          }
1739        }
1740        token = take(tokens, true)?;
1741        while is_space(&token) {
1742          token = take(tokens, true)?;
1743        }
1744      }
1745      // The body.
1746      if is_begin(&token) {
1747        take_rest_of_group(&mut take, tokens)?;
1748      }
1749    },
1750    DefinitionNames::Let => {
1751      take(tokens, true)?;
1752      // Spaces, the optional `=` and one optional space, then the target.
1753      let mut token = take(tokens, true)?;
1754      while is_space(&token) {
1755        token = take(tokens, true)?;
1756      }
1757      if token.is_some_and(|t| t.get_catcode() == Catcode::OTHER && t.with_str(|s| s == "=")) {
1758        token = take(tokens, true)?;
1759        if is_space(&token) {
1760          take(tokens, true)?;
1761        }
1762      }
1763    },
1764    DefinitionNames::ReadTo => {
1765      // The number and the keyword pass through unexpanded and neutralizable; the name after `to` is kept.
1766      let mut previous_t = false;
1767      while let Some(token) = take(tokens, false)? {
1768        let letter = token.get_catcode() == Catcode::LETTER;
1769        let o = letter && token.with_str(|s| s.eq_ignore_ascii_case("o"));
1770        if previous_t && o {
1771          let mut name = take(tokens, true)?;
1772          while is_space(&name) {
1773            name = take(tokens, true)?;
1774          }
1775          break;
1776        }
1777        previous_t = letter && token.with_str(|s| s.eq_ignore_ascii_case("t"));
1778      }
1779    },
1780  }
1781  Ok(())
1782}
1783
1784/// A reader taking the next token into a Semiverbatim argument's tokens, kept as it is (`true`) or left to
1785/// neutralizing.
1786type TakeToken<'a> = dyn FnMut(&mut Vec<(Token, bool)>, bool) -> Result<Option<Token>> + 'a;
1787
1788/// Takes, kept as they are, the rest of a balanced group whose `{` was just taken.
1789fn take_rest_of_group(take: &mut TakeToken<'_>, tokens: &mut Vec<(Token, bool)>) -> Result<()> {
1790  let mut depth = 1;
1791  while depth > 0 {
1792    match take(tokens, true)? {
1793      Some(t) if t.get_catcode() == Catcode::BEGIN => depth += 1,
1794      Some(t) if t.get_catcode() == Catcode::END => depth -= 1,
1795      Some(_) => {},
1796      None => break,
1797    }
1798  }
1799  Ok(())
1800}
1801
1802fn is_other_char(token: &Option<Token>, c: &str) -> bool {
1803  token.is_some_and(|t| t.get_catcode() == Catcode::OTHER && t.with_str(|s| s == c))
1804}
1805
1806fn is_begin(token: &Option<Token>) -> bool {
1807  token.is_some_and(|t| t.get_catcode() == Catcode::BEGIN)
1808}
1809
1810/// A Semiverbatim argument's tokens neutralized as it is read, but for the names its definition primitives read
1811/// ([`take_definition_names`]): `\urladdr{\def~{…}…}` (amsart) keeps its active `~` (1011.4121).
1812fn neutralize_keeping_definition_names(value: Tokens, extraspecials: &[char]) -> Tokens {
1813  let mut source = value.unlist().into_iter();
1814  let mut tokens: Vec<(Token, bool)> = Vec::new();
1815  while let Some(token) = source.next() {
1816    let kind = definition_reads_names(&token);
1817    tokens.push((token, true));
1818    if kind != DefinitionNames::None {
1819      let _ = take_definition_names(kind, &mut || Ok(source.next()), &mut tokens);
1820    }
1821  }
1822  Tokens::new(
1823    tokens
1824      .into_iter()
1825      .map(|(t, neutralize)| {
1826        if neutralize {
1827          t.neutralize(extraspecials)
1828        } else {
1829          t
1830        }
1831      })
1832      .collect(),
1833  )
1834}
1835
1836#[cfg(test)]
1837mod tests {
1838  use super::*;
1839
1840  #[test]
1841  fn parameter_default_has_expected_fields() {
1842    let p = Parameter::default();
1843    assert!(!p.novalue);
1844    assert!(p.semiverbatim.is_none());
1845    assert!(!p.optional);
1846    assert!(p.inner.is_none());
1847    assert!(p.extra.is_empty());
1848    assert!(p.before_digest.is_empty());
1849    assert!(p.after_digest.is_empty());
1850    assert!(p.predigest.is_none());
1851    assert!(p.reversion.is_none());
1852    assert!(p.digested_reversion.is_none());
1853    assert_eq!(arena::to_string(p.name), "parameter_default");
1854    assert_eq!(arena::to_string(p.spec), "");
1855  }
1856
1857  #[test]
1858  fn parameter_display_is_name() {
1859    let p = Parameter {
1860      name: arena::pin("Plain"),
1861      ..Default::default()
1862    };
1863    assert_eq!(format!("{p}"), "Plain");
1864  }
1865
1866  #[test]
1867  fn parameter_stringify_is_spec() {
1868    let p = Parameter {
1869      spec: arena::pin("{}"),
1870      ..Default::default()
1871    };
1872    assert_eq!(p.stringify(), "{}");
1873  }
1874
1875  #[test]
1876  fn parameter_partial_eq_by_name() {
1877    // PartialEq compares by name only — Perl parity (closures can't
1878    // be structurally compared).
1879    let mut a = Parameter::default();
1880    let mut b = Parameter::default();
1881    a.name = arena::pin("x");
1882    b.name = arena::pin("x");
1883    assert_eq!(a, b);
1884    b.name = arena::pin("y");
1885    assert_ne!(a, b);
1886  }
1887
1888  #[test]
1889  fn parameters_new_and_take() {
1890    let p = Parameter::default();
1891    let ps = Parameters::new(vec![p]);
1892    let taken = ps.take_parameters();
1893    assert_eq!(taken.len(), 1);
1894  }
1895
1896  #[test]
1897  fn parameters_get_num_args_counts_valued() {
1898    // novalue=true parameters don't count toward num_args.
1899    let mut a = Parameter::default();
1900    let mut b = Parameter::default();
1901    let mut c = Parameter::default();
1902    a.novalue = false;
1903    b.novalue = true;
1904    c.novalue = false;
1905    let ps = Parameters::new(vec![a, b, c]);
1906    assert_eq!(ps.get_num_args(), 2);
1907  }
1908
1909  #[test]
1910  fn revert_arguments_skips_novalue_parameters() {
1911    // Perl Parameters.pm:51-57: a novalue parameter (an environment's leading SkipSpaces)
1912    // stores no argument, so the arguments pair with the valued parameters only.
1913    // Before, each argument moved a slot left: "a[b]" (the last one dropped).
1914    let wrapped = |open: &'static str, close: &'static str| Parameter {
1915      reversion: Some(Rc::new(
1916        move |tks: Vec<Token>, _: Option<&Parameters>, _: &[Tokens]| {
1917          let mut out = vec![T_OTHER!(open)];
1918          out.extend(tks);
1919          out.push(T_OTHER!(close));
1920          Ok(Tokens::new(out))
1921        },
1922      ) as ReversionClosure),
1923      ..Parameter::default()
1924    };
1925    let skip = Parameter {
1926      novalue: true,
1927      ..Parameter::default()
1928    };
1929    let ps = Parameters::new(vec![skip, wrapped("[", "]"), wrapped("(", ")")]);
1930    let args = vec![Some(Tokens!(T_OTHER!("a"))), Some(Tokens!(T_OTHER!("b")))];
1931    let reverted = ps.revert_arguments(args).unwrap();
1932    let expected = ["[", "a", "]", "(", "b", ")"].map(|s| T_OTHER!(s));
1933    assert_eq!(reverted, expected.to_vec());
1934  }
1935
1936  #[test]
1937  fn parameters_empty() {
1938    let ps = Parameters::new(vec![]);
1939    assert_eq!(ps.get_num_args(), 0);
1940    assert_eq!(ps.get_parameters().len(), 0);
1941  }
1942
1943  #[test]
1944  fn parameters_get_parameters_returns_refs_to_all() {
1945    // get_parameters returns ALL, including novalue ones (num_args
1946    // filters; get_parameters doesn't).
1947    let mut a = Parameter::default();
1948    let mut b = Parameter::default();
1949    a.novalue = false;
1950    b.novalue = true;
1951    let ps = Parameters::new(vec![a, b]);
1952    assert_eq!(ps.get_parameters().len(), 2);
1953  }
1954}